/**
 * Copyright (c) 2006, ARC Technologies.
 * All Rights Reserved
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this application.
 *
 * File     $Id: InputControl.js 1104 2007-12-16 10:57:11Z emann $ <br>
 * Author   Ed Mann <ed.mann at arctechnologies dot net>
 * @package eve.foundations.javascript
 */
 
 /*
  * global values
  */
  var orig_bg_color = null;
  var error_color;
  var size = null;
 /**
  * checkNumbers
  * This function will block any input that is not a numeric character.
  * @param {object} field object usually "this"
  * @param {object} event action. "event"
  */
  function checkNumbers(myfield, e)
	{
	var key;
	var keychar;

	if (window.event) {
	   key = window.event.keyCode;
	} else if (e) {
	   key = e.which;
	} else {
	   return true;
	}
	keychar = String.fromCharCode(key);

//	 control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) ) {
	   return true;
     }
//	 numbers
	else if ((("0123456789.").indexOf(keychar) > -1)) {
	   return true;
	}
//	 decimal point jump
	else if (keychar == ".") {
	   return false;
	   } else {
	   return false;
	   }
	}
    
 /**
  * checkMoney
  * This function will block any input that is not a numeric character or $ for money.
  * @param {object} field object usually "this"
  * @param {object} event action. "event"
  */
  function checkMoney(myfield, e, dec)
	{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
//	 control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) ||(key==36) || (key==13) || (key==27) )
	   return true;

//	 numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
	   return true;

//	 decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
	}
	
	/**
	 * field copy
	 * 
	 * Function will take the values from a src field and copy it to a dest field. This field can either be
	 * an array of fields or just the field name. If you are going to pass an array name in the src of the page
	 * you are going to do the copy from you need to define the src and dest arrays. To do that add the following code
	 * to your page. Change the names in the arrays and add when needed.
	 * <code>
	 * <script LANGUAGE="JavaScript"  type="text/javascript">
	 * var src_arr = new Array("src_field1","src_field2", "src_field3");
	 * var dst_arr = new Array("dst_field1","dst_field2", "dst_field3");
	 * </script>
	 * </code>
	 * Fields must match array order. so field 1 in dst_arr will inherit the value from field 1 in src_arr 
	 * @param string src field name or name of src array
	 * @param string dest field name or name of dest array
	 * @param boolean TRUE if values are array name, FALSE if not
	 */
	function fieldCopy(src, dest, arr){
	    if(arr == "TRUE" || arr == "true" || arr == "True"){
	        try{
	        for(var i = 0; i < src.length; i++){
	          document.getElementById(dest[i]).value = document.getElementById(src[i]).value;
	        }
	        } catch(e){
	            alert(e+" Field is: "+src[i]);
	        }
	    } else {
	       document.getElementById(dest).value = document.getElementById(src).value;
	    }
	    
	}

/**
 * fill Id
 * 
 * Function will take a value and fill a field with the passed id.
 * 
 * @param {string} value to put in field
 * @param {string} name of field to fill value
 */
function fillId(val, field){
    document.getElementById(field).innerHTML = val;
}
  
 /**
  * checkInput
  * Function will check an imput box to insure that it is not empty. If the value is
  * empty it will change the color of the input box.
  * @param {string} input The input box name 
  */
  function checkInput(input, reset, size) {
  	var elm = document.getElementById(input);
  	var input_val = elm.value;
    
  	/*
  	 * check to see if our orig_bg_color has been set. I should make a function that works like
  	 * php is_null... i may just do that.
  	 * To make this work with more than 1 color make an associated array and put the orig values in it.
  	 */
  	if(orig_bg_color === null && on_focus_color === null){
  		/*
  		 * our 2 ways of doing this. 1. Firefox/Opera... 2. IE imagin that
  		 * found at http://www.quirksmode.org/dom/getstyles.html
  		 */
  		 if (elm.currentStyle) {
			orig_bg_color = elm.currentStyle['backgroundColor'];
  		 } else if (window.getComputedStyle) {
  			orig_bg_color = document.defaultView.getComputedStyle(elm,null).getPropertyValue('background-color');
  		 }
  		 
  	}
  	if(reset === true && input_val == ""){
  		elm.style.backgroundColor = orig_bg_color;
  		return;  		
  	}
  	if(input_val == "") {
  		elm.style.backgroundColor = error_color;
  		return false;
  	} else if (size != null && input_val.length < size) {
        elm.style.backgroundColor = error_color;
        return false;
     } else {
        elm.style.backgroundColor = orig_bg_color;
		return true;
  	}
  	return false;	
  }
  
  /**
  * checkDropDown
  * Function will check an imput box to insure that it is not empty. If the value is
  * empty it will change the color of the input box.
  * @param {string} input The input box name 
  */
  function checkSelect(input, reset) {
  	var elm = document.getElementById(input);
  	var index  = elm.selectedIndex
	var input_val = elm.options[index].value
  	/*
  	 * check to see if our orig_bg_color has been set. I should make a function that works like
  	 * php is_null... i may just do that.
  	 * To make this work with more than 1 color make an associated array and put the orig values in it.
  	 */
  	if(orig_bg_color === null){
  		/*
  		 * our 2 ways of doing this. 1. Firefox/Opera... 2. IE imagin that
  		 * found at http://www.quirksmode.org/dom/getstyles.html
  		 */
  		 if (elm.currentStyle) {
			orig_bg_color = elm.currentStyle['backgroundColor'];
  		 } else if (window.getComputedStyle) {
  			orig_bg_color = document.defaultView.getComputedStyle(elm,null).getPropertyValue('background-color');
  		 }
  	}
  	if(reset === true){
  		elm.style.backgroundColor = orig_bg_color;
  		return;  		
  	}
  	if(input_val == "") {

  		elm.style.backgroundColor = error_color;
  		return false;
  	} else {
		return true;
  	}
  	return false;	
  }
  
  /**
   * checkAction
   * 
   * Function will check the form action for a value. If the value matches it will return true. If not False
   * 
   * @param string value to match against the action form field
   * @return bool True if match False otherwise. 
   */
  function checkAction(value){
      field = document.getElementById('action').value;
      if(field == value){
          return true;
      } else {
          return false;
      }
  }
  
  /**
   * checkPassword
   * 
   * Function will check the password and insure that they match.
   * @param {string} input The name of the input box to get the password value.
   * @param {string} input The name of the input box to get the match password value.
   */
function checkPassword(pwd, pwd_match) {
	var pwd			= document.getElementById(pwd);
  	var pwd_match 	= document.getElementById(pwd_match);
  	
  	if(pwd.value !== pwd_match.value){
  		pwd.style.backgroundColor = error_color;
  		pwd_match.style.backgroundColor = error_color;
  		return false;
  	} else {
  		return true;
  	}
  	}

   /**
    * checkDates
    * @param {string} start_date 
    * @param {string} end_date
    */
    function checkDates(start_date, end_date) {
    	var start		= document.getElementById(start_date);
    	var end			= document.getElementById(end_date);
    	var start_date	= new Date(start.value);
    	var end_date	= new Date(end.value);
    	if(end_date < start_date){
    		start.style.backgroundColor = error_color;
  			end.style.backgroundColor = error_color;
  			return false;
    	} else {
    		return true;
    	}
    }
 

 /**
  * checkNumSize
  * Function will strip all non alpha characters and
  * check the remaning characters (which should only be numbers)
  * to insure that they don't excede the size passed in.
  * 
  * @param {string} field field name to get values from
  * @param {int}	size 
  */
  function checkNumSize(field, size) {
  		var str_input = document.getElementById(field);
  		var re = /\D/g;
  		var num_only = str_input.value.replace(re,'');
  		if(num_only.length > size || num_only.length < size){
  			str_input.style.backgroundColor = error_color;
  			return false;
  		} else {
  			return true;
  		}
  }

  /**
   * setOnOff
   * Function will set a text box to disabled, or readonly. It will default to disabled
   *
   * @param {string} field text input id.
   * @param {string} state It can either be readonly or disabled.
   */
   function setOnOff(field, state){
   	var input_field = document.getElementById(field);
   	if(state == "readonly"){
   		if(input_field.readOnly == true){
   		input_field.readOnly = false;
   		} else {
   			input_field.readOnly = true;
   			input_field.value = "";
   		}
   	} else {
   		if(input_field.disabled == true){
   		input_field.disabled = false;
   		} else {
   			input_field.disabled = true;
   			input_field.value = "";
   		}
   	}
   }
   
/**
 * resetRadio
 * Function will reset a radio button. If the value is true, it will set to false.
 * @param {string} field 
 * 
 */
 function resetRadio(field) {
 	alert(field.index);
 }
 
 /**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 * http://www.smartwebby.com/DHTML/date_validation.asp
 * modified for my needs.
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
   var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {
            return false;
        } 
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1){
             returnString += c;
        }
    }
    return returnString;
}

function daysInFebruary (year){
   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 31
      if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
      if (i==2) {this[i] = 29}
   } 
   return this
}

/**
 * do Field Reset
 * 
 * Function will reset the field to the original background color. 
 * This is the helper for the error color. The error color will set a field to a certain color, but
 * when you click on the box again it will not reset to the onClick color... this function will return that
 * ability.
 * 
 * @param {string} name of field to change color on.
 */
 function doFieldReset(field){
     var elm = document.getElementById(field);
     elm.style.backgroundColor = orig_bg_color;
     return;  		
 }
 
/**
 * do Check Date
 * 
 * Function will check the field passed in to insure that it's a date.
 * 
 * @param string field to check
 * @param bool Show alert prompt
 * @return bool Return True if success else False
 */
function doCheckDate(field, show_alert){
   var str_input = document.getElementById(field) 
   var dtStr = str_input.value;
   var daysInMonth = DaysArray(12)
   var pos1=dtStr.indexOf(dtCh)
   var pos2=dtStr.indexOf(dtCh,pos1+1)
   var strMonth=dtStr.substring(0,pos1)
   var strDay=dtStr.substring(pos1+1,pos2)
   var strYear=dtStr.substring(pos2+1)
   strYr=strYear
   if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
   if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
   for (var i = 1; i <= 3; i++) {
      if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
   }
   month=parseInt(strMonth)
   day=parseInt(strDay)
   year=parseInt(strYr)
   if (pos1==-1 || pos2==-1){
       str_input.style.backgroundColor = error_color;
       if(show_alert){
      alert("The date format should be : mm/dd/yyyy");
       }
      return false;
   }
   if (strMonth.length<1 || month<1 || month>12){
       str_input.style.backgroundColor = error_color;
       if(show_alert){
      alert("Please enter a valid month");
       }
      return false
   }
   if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
       str_input.style.backgroundColor = error_color;
       if(show_alert){
      alert("Please enter a valid day");
       }
      return false
   }
   if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
       str_input.style.backgroundColor = error_color;
       if(show_alert){
      alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
       }
      return false
   }
   if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
       str_input.style.backgroundColor = error_color;
       if(show_alert){
      alert("Please enter a valid date");
       }
      return false
   }
return true
}

/**
 * validate Email
 * Function will check email string to make sure it is correctly formated.
 * 
 * @param {string} input of field to check.
 * @return boolean True if valid False if not
 * @requires ajax Requires that the ajax js file is loaded.
 * @requires StringFormat Needs StringFormat js file loaded
 */
function validateEmail(input,reset){
    var elm = document.getElementById(input);
  	var input_val = elm.value;
    /*
  	 * check to see if our orig_bg_color has been set. I should make a function that works like
  	 * php is_null... i may just do that.
  	 * To make this work with more than 1 color make an associated array and put the orig values in it.
  	 */
  	if(orig_bg_color === null && on_focus_color === null){
  		/*
  		 * our 2 ways of doing this. 1. Firefox/Opera... 2. IE imagin that
  		 * found at http://www.quirksmode.org/dom/getstyles.html
  		 */
  		 if (elm.currentStyle) {
			orig_bg_color = elm.currentStyle['backgroundColor'];
  		 } else if (window.getComputedStyle) {
  			orig_bg_color = document.defaultView.getComputedStyle(elm,null).getPropertyValue('background-color');
  		 }
  		 
  	}
 	
  
  	if(reset === true){
  		elm.style.backgroundColor = orig_bg_color;
  		return;  		
  	}
  if (isEmpty(input_val)) {
      elm.style.backgroundColor = error_color;
      return false;
  }
 
    var t_field = trim(input_val);  // value of field with whitespace trimmed off
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ; 
  if (!email.test(t_field)) {
      elm.style.backgroundColor = error_color;
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  /*if (!email2.test(t_field)) {
      str_input.style.backgroundColor = error_color;
    msg (infofield, "warn", "Unusual e-mail address - check if correct");
  } else {
      str_input.style.backgroundColor = error_color;
    msg (infofield, "warn", "");
  }*/
  return true;
}
