/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 *
 *   11/10/04: added isValidCreditCard routine to end of this list of functions
 * 		which is passed a string for type (Visa, MC, Disc, AmEx or Diners)
 * 		and the string for entered credit card number
 *   01/29/05 added showhidesect to enable dynamic showing/hidding of form sections  (expects "value:sect3,hide" or "value:sect3,show")
 *   05/13/05 moved definiation of min and max Year to ASP page so that it can be set dynamically
 *   10/27/05 added 'dat1' type Date function.  Displays Month, Day Year drop downs which are leap year "aware"
 *   12/08/05 added checkbox control in showhidesect ( now allows checkbox, radio and selection list)
 *   12/19/05 added ability to use either field objects or field numbers in showhidesect (for use with ChangeToImage)
 *   12/19/05 added routine ChangeToImage which will replace all radio buttons which include the word 'big' in their names
 *   12/19/05 added routine checkChange which changes the graphic value of a check box when a radio button changes (with above)
 *   11/20/05 fixed: isDate no longer fails when incoming string is empty - it immediately returns true
*    12/02/08 added: credit card #1234567890 will validate for test purposes
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
// var minYear=2004;
// var maxYear=2010;

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
}

function isDate(dtStr){
	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 (dtStr.length==0) { return true } // return if the incoming data string is empty
	
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month (mm/dd/yyyy)")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day (mm/dd/yyyy)")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		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){
		alert("Please enter a valid date (mm/dd/yyyy)")
		return false
	}
return true
}

function isValidCreditCard(type, ccnum) {
   if (ccnum == '1234567890') return true;
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }

   if (!re) return false; // no type or bad type - 're' not set
   if (!re.test(ccnum)) return false;
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

  function showhidesect(field) // 'value:sect3,hide' or 'value:sect3,show'
  {
    if (!field.options)  //	boolean checkbox or radio button
    {  
    	if (!inputs[field]) 		// must be an object, not a field number
		{
	       	if (field.checked)  var selectedValue=field.value + ',show';
			if (!field.checked) var selectedValue=field.value + ',hide';
		}
		else						// field number from Image replacement
		{	
	    	if (inputs[field].getAttribute('checked')) var selectedValue=inputs[field].getAttribute('value') + ',show';
			if (!inputs[field].getAttribute('checked')) var selectedValue=inputs[field].getAttribute('value') + ',hide';
		}
    }
    else		//	listbox
    {
       var selectedValue=field.options[field.selectedIndex].value;
    }
    var pos_hide = selectedValue.indexOf('hide');
    var pos_show = selectedValue.indexOf('show');
    var pos_start_sect = selectedValue.indexOf(':')+1;
    var pos_stop_sect = selectedValue.indexOf(',');
    var section = selectedValue.substring(pos_start_sect,pos_stop_sect);

//  alert('name:' + field.name + ' selectedValue:' + selectedValue + ' section:' + section);

    if (pos_show != -1) document.getElementById(section).style.display = "block";
    if (pos_hide != -1) document.getElementById(section).style.display = "none";
  }
/* Javascript Date Selector
   by Warren Brown (03/01/2004 Radiokop South Africa)
   Script to place Month/Day/Year drop-downs onto a web page, leap year enabled
*/

var date_arr = new Array;
var days_arr = new Array;


date_arr[0]=new Option("1-January",31);
date_arr[1]=new Option("2-February",28);
date_arr[2]=new Option("3-March",31);
date_arr[3]=new Option("4-April",30);
date_arr[4]=new Option("5-May",31);
date_arr[5]=new Option("6-June",30);
date_arr[6]=new Option("7-July",31);
date_arr[7]=new Option("8-August",30);
date_arr[8]=new Option("9-September",30);
date_arr[9]=new Option("10-October",31);
date_arr[10]=new Option("11-November",31);
date_arr[11]=new Option("12-December",30);

function update_days(fieldname) //  (NOTE, form1 is hardcoded)
{
        y=eval('document.form1.Y_' + fieldname);
        m=eval('document.form1.M_' + fieldname);
        d=eval('document.form1.D_' + fieldname);
        temp=d.selectedIndex; 
        for(x=days_arr.length;x>0;x--)
        {
                days_arr[x]=null;
                d.options[x]=null;
         }
        selection=parseInt(m[m.selectedIndex].value);
        ret_val = 0;

        if(m[m.selectedIndex].value == 28)
        {
        	year=parseInt(y.options[y.selectedIndex].value);
               if (year % 4 != 0 || year % 100 == 0 ) 
	             	 ret_val=0;
               else
                    if (year % 400 == 0)  
                      	ret_val=1;
                    else
	             ret_val=1;
        }
        d.options[0].text="Day";
        d.options[0].value = 0;
        selection = selection + ret_val;      
        for(x=1;x < selection+1;x++) 
        {
                days_arr[x-1]=new Option(x);            
                d.options[x]=days_arr[x-1];
        } 

        if (temp == -1 || temp >= x-1) 
       	d.options[0].selected=true;
        else
        	d.options[temp].selected=true;  
}
function update_dateField(fieldname) // set the 'real' field to mm/dd/yyyy (NOTE, form1 is hardcoded)
{        	
       temp = (m.selectedIndex+1) + "/" + (d.selectedIndex) + "/" + y[y.selectedIndex].value
       eval('document.form1.' + fieldname +'.value = temp')
} 
var inputs;
var imgFalse = 'images/form_check_box_unchecked.gif';
var imgTrue = 'images/form_check_box_checked.gif';
function ChangeToImage() 
{
	//get all the input fields on the page
	inputs = document.getElementsByTagName('input');

	//cycle trough the input fields
	for(var i=0; i < inputs.length; i++) 
	{
		//check if the input is a radio AND it's name includes "ChangeToImage"
		if(inputs[i].getAttribute('type') == 'radio' && inputs[i].getAttribute('name').indexOf('ChangeToImage')>0) 
		{
			//create a new image
			var img = document.createElement('img');
			
			//check if the checkbox is checked
			if(inputs[i].checked) {
				img.src = imgTrue;
			} else {
				img.src = imgFalse;
			}

			//set image ID and onclick action
			img.id = 'checkImage'+i;
			img.value=inputs[i].getAttribute('value'); // store the 'real' radio button's value here
			img.onclick = new Function('checkChange('+i+');showhidesect('+i+');');
			img.height=40;
			img.width= 50;

			//place image in front of the radio button
			inputs[i].parentNode.insertBefore(img, inputs[i]);
			
			//hide the radio button
			inputs[i].style.display='none';
		}
	}
}
//change this radio buttons status and all replacement images to follow the other radio buttons
function checkChange(i) 
{
	var fname = inputs[i].name
	if(inputs[i].checked)
	{
		inputs[i].checked = '';
		document.getElementById('checkImage'+i).src=imgFalse;
	} 
	else 	
	{
		inputs[i].checked = 'checked';
		document.getElementById('checkImage'+i).src=imgTrue;
	}

	//cycle trough the input fields
	for(var i=0; i < inputs.length; i++) 
	{
		//check if the input is a radio AND the name matches from above
		if(inputs[i].getAttribute('type') == 'radio' && inputs[i].getAttribute('name') == fname)
		{
			// enable/disable this fields section
			showhidesect(i);
			
			//check if the checkbox is checked
			if(inputs[i].checked) 
			  {document.getElementById('checkImage'+i).src=imgTrue;} 
			else 
			  {document.getElementById('checkImage'+i).src=imgFalse;}
		}
	}			
}

