

// MLCOM_FORMS v2.1.3   May 6, 2008
// Added: AJAX Tool-Tip

// MLCOM_FORMS v2.1.2   May 3, 2008
// Added: New File Upload Functions: addUploadFileToList, removeUploadFileFromList


// MLCOM_FORMS v2.1.1   May 1, 2008

/*==============================================================*/
/*===================  MLCOM :: 2/15/2008  =====================*/
/*==============================================================*/

var mlcom_form_validation_switch = false;
var mlcom_form_validation_file = false;
var MLCOM_FORMS = function() {	
	// Preload Images - Update Image Paths Before Using !!!
	validIcon = new Image();		
	invalidIcon = new Image();	
	validIcon.src = "/images/tick.png";
	invalidIcon.src = "/images/cross.png";	
	// Main Functions ::  
	return {		
		validateFormIDs : function(list) {
			mlcom_form_validation_switch = true;
			this.iconRemoveAll('img.errorIcon');
			var count = 0;
			for(var i=0; i<list.length; i++) {
				if(list[i].type != 'file') {
					if(list[i].type == 'radio') { var len = list[i].id.length; list[i].id = list[i].id.substr(0,len-2); }
					var valid = this.validateErrorTypes(list[i].id, list[i].type);
					if(valid) { count++; }
					valid ? this.iconValid(list[i].id, list[i].type) : this.iconInvalid(list[i].id, list[i].type);
				} else {
					if(mlcom_form_validation_file == true) {
						$(list[i].id).setValid();
						valid = true;
						if(valid) { count++; }
					} else {
						$(list[i].id).setInvalid();	
					}
				}
			}
			if(count == list.length) { mlcom_form_validation_switch = false; return true; } else { return false; };
		},		
		iconValid: function(id,type) {
			var spacer = 5;
			var element = $(id);
			if(type == 'radio') { element = $(id+'YN'); }
			if(type == 'date') { element = $(id).next(); spacer = 23; }
			new Insertion.After(element,'<img class="errorIcon" src="' + validIcon.src + '" height="16" width="16" border="0" align="absmiddle" style="margin-left:' + spacer + 'px" />'); 	
		},		
		iconInvalid : function(id,type) {
			var spacer = 5;
			var element = $(id);
			if(type == 'radio') { element = $(id+'YN'); }
			if(type == 'date') { element = $(id).next(); spacer = 23; }
			new Insertion.After(element,'<img class="errorIcon" src="' + invalidIcon.src + '" height="16" width="16" border="0" align="absmiddle" style="margin-left:' + spacer + 'px" />'); 
		},		
		iconRemove : function(id,type) {
			try { 
				if(type == 'date') { $(id).next(1).remove(); } else { $(id).next().remove(); } 
				if(type == 'file') { $(id).clearIcon(); };
			} catch(e) { return }
		},		
		iconRemoveAll : function(id) {
			try { el = $$(id); for(var i=0; i<el.length; i++) { el[i].remove(); } } catch(e) { return }	
		},		
		validateElement : function(id,type) {
			this.iconRemove(id,type);
			if(type == 'radio') { var len = id.length; id = id.substr(0,len-2);}					
			var valid = this.validateErrorTypes(id,type);
			if(mlcom_form_validation_switch == true) { valid ? this.iconValid(id,type) : this.iconInvalid(id,type); }			
			// Update DB
			try {
				if(__currentForm == 'activate') { if(typeof(id) == "object") { var field = id.id; } else { var field = id; }
					if(type == 'radio') { id = id + 'Y'; }
					var fVal=$F(id);
					if(fVal == null) { fVal=0 }
					if(type == 'currency' && (fVal == null || fVal == '')) { fVal=0 }
					new Ajax.Request('/CFCs/cfc_slp.cfc', { method:'get', parameters: {method:'updateActivationData', id:__currentActivationID, field:field, value:fVal} });
				}
			} catch(e) { return };
			return valid;
		},		
		validateErrorTypes : function(id,type) {
			var valid = false;	
			switch(type) {		
				case 'blank':
					if($F(id) != '') { valid = true };
					break;
				case 'currency':
					if($F(id) != '' && Number($F(id)) > 0 && $F(id).length > 5) { valid = true };
					break;	
				case 'date':			
					if($F(id).strip() != '') { valid = true };
					break;
				case 'email':
					var filter= /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
					if (filter.test($F(id))) { valid = true; }
					break;			
				case 'phone':			
					if($F(id).length == 12) { valid = true };
					break;		
				case 'radio':			
					var radioY = $F(id+'Y');
					var radioN = $F(id+'N');
					if( radioY != null || radioN != null) { valid = true }; 
					break;
				case 'file':
					//if(mlcom_form_validation_file == true) { valid = true };
					if($(id).style.display != 'none') { valid = true };
					
					break;				
			}			
			return valid;
		}
	};
}();

/*==============================================================*/
/*===================  MLCOM :: 4/7/2008  ======================*/
/*==============================================================*/

function parseExtraVars(val) {
	var data = {};
	var step1 = val.split(",");
	for(var i=0; i<step1.length; i++) {
		var step2 = step1[i].split(":");
		data[step2[0]] = step2[1];
	}
	return data;
}



/*==============================================================*/
/*===================  MLCOM :: 2/15/2008  =====================*/
/*==============================================================*/

if ( typeof(MLCOM_MASKS) === 'undefined' ) {
   MLCOM_MASKS = new Object();
}
MLCOM_MASKS.InputMask = {
   masks: {
      date_us: {
         name: 'date_us',
			format: '  /  /    ',
         regex:  /\d/
      },
      time: {
         name: 'time',
			format: '  :  :  ',
         regex:  /\d/
      },
      phone: {
         name: 'phone',
			format: '   -   -    ',
         regex:  /\d/
      },
		stateAbbrev: {
         name: 'stateAbbrev',
			format: '  ',
         regex:  /[a-zA-Z]/
      }
   },

   // Finds every element with class input_mask and applies masks to them.
   setupElementMasks: function() {
      if ( document.getElementsByClassName ) { // Requires the Prototype library
         document.getElementsByClassName('input_mask').each(function(item) {
            Event.observe(item, 'keypress',
               MLCOM_MASKS.InputMask.applyMask.bindAsEventListener(item), true);
         });
      }
   },

   // This is triggered when the key is pressed in the form input.  It is
   // bound to the element, so 'this' is the input element.
   applyMask: function(event) {
      var match = /mask_(\w+)/.exec(this.className);
      if ( match.length == 2 && MLCOM_MASKS.InputMask.masks[match[1]] ) {
         var mask = MLCOM_MASKS.InputMask.masks[match[1]];
         var key  = MLCOM_MASKS.InputMask.getKey(event);

         if ( MLCOM_MASKS.InputMask.isPrintable(key) ) {
            var ch      = String.fromCharCode(key);
            var str     = this.value + ch;
            var pos     = str.length;
            if ( mask.regex.test(ch) && pos <= mask.format.length ) {
               if ( mask.format.charAt(pos - 1) != ' ' ) {
                  str = this.value + mask.format.charAt(pos - 1) + ch;
               }
               if( mask.name == 'stateAbbrev' ) { str = str.toUpperCase() }  // MLCOM ::  Added 3/21/2008
					this.value = str;
            }
            Event.stop(event);
         }
      }
   },

   // Returns true if the key is a printable character.
   isPrintable: function(key) {
      return ( key >= 32 && key < 127 );
   },

   // Returns the key code associated with the event.
   getKey: function(e) {
      return window.event ? window.event.keyCode : e ? e.which : 0;
   }
};

document.observe( 'dom:loaded', function() { MLCOM_MASKS.InputMask.setupElementMasks(); } );



/*==============================================================*/
/*==============================================================*/
function numeralsOnly(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}
	return true;
};

function currencyOnly(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		if(charCode != 44)
			return false;
	}
	return true;
};

function lettersOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 65 || charCode > 90) && 
        (charCode < 97 || charCode > 122)) {
        return false;
    }
    return true;
};

function daysBetween(date1, date2) {
    var DSTAdjust = 0;
    // constants used for our calculations below
    oneMinute = 1000 * 60;
    var oneDay = oneMinute * 60 * 24;
    // equalize times in case date objects have them
    date1.setHours(0);
    date1.setMinutes(0);
    date1.setSeconds(0);
    date2.setHours(0);
    date2.setMinutes(0);
    date2.setSeconds(0);
    // take care of spans across Daylight Saving Time changes
    if (date2 > date1) {
        DSTAdjust = 
            (date2.getTimezoneOffset() - date1.getTimezoneOffset()) * oneMinute;
    } else {
        DSTAdjust = 
            (date1.getTimezoneOffset() - date2.getTimezoneOffset()) * oneMinute;    
    }
    var diff = Math.abs(date2.getTime() - date1.getTime()) - DSTAdjust;
    return Math.ceil(diff/oneDay);
};

/*==============================================================*/
/*==============================================================*/

/*
We can easily select different formatting by changing the values 
in the second through eighth parameters. The second parameter is 
the number of decimal places that the number should have. If the 
number contains more decimal places than required it will be rounded 
to the nearest number with that number of decimal places. If it has 
fewer decimal places than specified zeroes will be added to the end.

The third parameter is the thousands separator. In our example we 
used a space but a comma or period may be what is required for your location.

The fourth parameter is the decimal point. Either a period or comma is normal here.

The fifth and sixth parameters are used for monetary values and one
or other of them will contain the currency symbol when required. 
If your location uses a currency symbol hard against the left of numbers
then place that symbol by itself in the fifth parameter eg. '$'. 
If you normally have a space after the currency symbol then add it after the 
symbol in this '$ '. If your currency symbol comes after the amount instead 
of before then place it in the sixth parameter instead of the fifth parameter.

The seventh and eighth parameters define the symbols to place around the 
number when the value is negative. The usual values for these parameters 
would be '-','' but you may have a situation where you want to 
use '(',')' or even '',' CR'. 
*/


function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; 
	if (z<0) z--; 
	for(var i = z; i < 0; i++) y.unshift('0');
	y.splice(z, 0, pnt); 
	if(y[0] == pnt) y.unshift('0'); 
	while (z > 3) {z-=3; y.splice(z,0,thou);}
	var r = curr1+n1+y.join('')+n2+curr2;
	return r;
}

/*==============================================================*/
/*==================== UPLOAD FILE FUNCTIONS ===================*/
/*==============================================================*/

// FUNCTION :: Default Upload Error Method
function uploadError(error) { alert("File Upload Error: " + error); }

// FUNCTION :: Add Files to Upload List
function addUploadFileToList(uploadID, fileName, size, required) {
	if(required == undefined) { required = false; }
	mlcom_form_validation_file = true;
	eval(uploadID+'__fileListCount++');
	if(required) { if(mlcom_form_validation_switch) { $(uploadID+'_swf').setValid(); } }
	var __fileList = $(uploadID+'_files').innerHTML;
	__fileList += '<div class="fileUploadListItem" title="Remove File From Upload List"><img src="/images/icons/delete.png" onClick="removeUploadFileFromList(\'' + uploadID + '\',\'' + fileName + '\'); try{this.up().remove()} catch(e){}" style="cursor:pointer" align="absmiddle" border="0" width="16" height="16" alt="Remove File From Upload List" />&nbsp;&nbsp;&nbsp;' + fileName + '&nbsp;&nbsp;&nbsp;<small>(' + (Math.ceil(size/1000)) + 'KB)</small>';
	__fileList +=  '<input name="' + uploadID + '_file" id="' + uploadID + '_file" type="hidden" value="' + fileName + '" /></div>';
	$(uploadID+'_files').update(__fileList);
}

//  FUNCTION :: Remove Files from Upload Lists
function removeUploadFileFromList(uploadID, fileName, required) {
	if(required == undefined) { required = false; }
	$(uploadID+'_swf').removeFile(fileName);
	eval(uploadID+'__fileListCount--');
	if(eval(uploadID+'__fileListCount') == 0) {
		$(uploadID+'_files').update();
		if(required) {
			mlcom_form_validation_file = false;
			if(mlcom_form_validation_switch) { $(uploadID+'_swf').setInvalid(); }
		}
	}
}

/*==============================================================*/
/*======================= AJAX TOOL-TIP ========================*/
/*==============================================================*/

/* Custom variables */

/* Offset position of tooltip */
var x_offset_tooltip = -3;
var y_offset_tooltip = 5;

/* Don't change anything below here */
var ml_tooltip_width = 300;
var flickerflag = true;
var ajax_tooltipObj = false;
var ajax_tooltipObj_iframe = false;
var _SelectElements = [];

var ajax_tooltip_MSIE = false;
if(navigator.userAgent.indexOf('MSIE')>=0) ajax_tooltip_MSIE=true;

function ajax_showTooltip(externalFile,inputObj)
{
	// MatthewLuke.com :: Matthew Luke :: Added June 7, 2007
	// Hides <select> boxes in IE6.
	if(isIE6) {
		if($('filterDiv')) {
			var selectEl = $$("#filterDiv select");
			for(i=0; i<selectEl.length; i++) {
				new Insertion.After(selectEl[i],"<div id='_select_" + i + "' style='height:13px'>&nbsp;</div>");
				selectEl[i].hide();
			}
		}
	}

	if(!ajax_tooltipObj) {	/* Tooltip div not created yet ? */	
		ajax_tooltipObj = document.createElement('DIV');
		ajax_tooltipObj.style.position = 'absolute';
		ajax_tooltipObj.id = 'ajax_tooltipObj';		
		document.body.appendChild(ajax_tooltipObj);
		
		var leftDiv = document.createElement('DIV');	/* Create arrow div */
		leftDiv.className='ajax_tooltip_arrow';
		leftDiv.id = 'ajax_tooltip_arrow';
		ajax_tooltipObj.appendChild(leftDiv);
		
		var contentDiv = document.createElement('DIV'); /* Create tooltip content div */
		contentDiv.className = 'ajax_tooltip_content';
		ajax_tooltipObj.appendChild(contentDiv);
		contentDiv.id = 'ajax_tooltip_content';
		
		if(ajax_tooltip_MSIE){	/* Create iframe object for MSIE in order to make the tooltip cover select boxes */
			ajax_tooltipObj_iframe = document.createElement('<IFRAME frameborder="0">');
			ajax_tooltipObj_iframe.style.position = 'absolute';
			ajax_tooltipObj_iframe.border='0';
			ajax_tooltipObj_iframe.frameborder=0;
			ajax_tooltipObj_iframe.style.backgroundColor='#FFF';
			ajax_tooltipObj_iframe.src = 'about:blank';
			contentDiv.appendChild(ajax_tooltipObj_iframe);
			ajax_tooltipObj_iframe.style.left = '-3px';
			ajax_tooltipObj_iframe.style.top = '3px';
		}			
	}
	// Find position of tooltip
	ajax_tooltipObj.style.display='block';
	ajax_loadContent('ajax_tooltip_content',externalFile);
	if(ajax_tooltip_MSIE){
		ajax_tooltipObj_iframe.style.width = ajax_tooltipObj.clientWidth + 'px';
		ajax_tooltipObj_iframe.style.height = ajax_tooltipObj.clientHeight + 'px';
	}
	ajax_positionTooltip(inputObj);
}

function ajax_positionTooltip(inputObj)
{
	var leftPos = (ajaxTooltip_getLeftPos(inputObj) + inputObj.offsetWidth);
	var topPos = ajaxTooltip_getTopPos(inputObj);	
	var rightedge=ajax_tooltip_MSIE? document.body.clientWidth-leftPos : window.innerWidth-leftPos   //
	var bottomedge=ajax_tooltip_MSIE? document.body.clientHeight-topPos : window.innerHeight-topPos  //	
	var tooltipWidth = document.getElementById('ajax_tooltip_content').offsetWidth; 
	var offset =  ml_tooltip_width - rightedge;  // tooltipWidth	
	if(offset>0)leftPos = Math.max(0,leftPos - ml_tooltip_width -25);  //  -offset -5	
	ajax_tooltipObj.style.left = (leftPos -3) + 'px';
	ajax_tooltipObj.style.top = (topPos + 13)  + 'px';
}


function ajax_hideTooltip(off) {
	// MatthewLuke.com :: Added June 7, 2007
	// Hides <select> boxes in IE6.
	if(isIE6) {
		if($('filterDiv')) {
			var selectEl = $$("#filterDiv select");
			for(i=0; i<selectEl.length; i++) {			
				selectEl[i].show();
				$('_select_'+i).remove();
			}
		}
	}	
	// MatthewLuke.com :: Added May 10, 2007
	// Removes Flicker bug when Tool-Tip is viewed in Firefox
	if(off) {flickerflag=false;}
	if(!flickerflag) {
		ajax_tooltipObj.style.display='none';
		flickerflag = true;
	}
}

function ajaxTooltip_getTopPos(inputObj) {		
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null) {
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function ajaxTooltip_getLeftPos(inputObj) {
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null) {
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
  }
  return returnValue;
}
