/***********************************************
WARNING:
Do not edit this file unless you exactly what you are doing!!!
***********************************************/

// Declare Global variables
var gst;
var gstTotal;
var stampDutyTotal;
var fireLeveeTotal;
var liabYearAmt = new Array();
var liabStampDuty = new Array();
var liabFee;
var genYearAmt = new Array();
var genStampDuty = new Array();
var genFireLevee = new Array();
var genFee;
//var vehicleDriverAge = new Array();
//var vehicleStateModifier = new Array();
//var vehicleStampDuty = new Array();
//var vehicleNCBProtect, windscreen, vehicleTrailer, vehicleBaseFee, vehicleMinCharge, vehicleBaseMultiplier, vehicleFee, vehicleRating1Multiplier;
var incomeStampDuty = new Array();


// Functions

function prepQuestions(suffix, num) {
	/**********************************************	
		Hides all the questions
	**********************************************/
	for (var i=1; i <= num; i++) {
		if (isDefined(document.catwebformform67491.elements[suffix + i + 'text'] ) && document.catwebformform67491.elements[suffix + i].checked == false) {
			toggleLayer(suffix + i + 'text', 'hide');
		}
	}
}


function showForm() {
	/**********************************************	
		Shows the options on the form if checkboxes are set
	**********************************************/
	// Reset amount
	var liabAmount = 0;
	var liabFirstMonth = 0;
	var liabMonthly = 0;
	var genAmount = 0;
	var genFirstMonth = 0;
	var genMonthly = 0;
	//var vehicleAmount = 0;
	//var vehicleFirstMonth = 0;
	//var vehicleMonthly = 0;
	gstTotal = 0;
	stampDutyTotal = 0;
	fireLeveeTotal = 0;
	
	
	
	// What state?
	var myState = parseInt(document.catwebformform67491.CAT_Custom_136237.selectedIndex);

	if (myState < 0 || myState >8) {
		myState = 1;
	}

 	// Liability display and calculations...
	if (document.catwebformform67491.CAT_Custom_138196.checked) {
		toggleLayer('wrapLiab', 'show');
		toggleLayer('wrapLiabQuestions', 'show');
		document.catwebformform67491.CAT_Custom_138196.value ="Yes"
		//alert(document.catwebformform67491.CAT_Custom_138196.value);
		// Calculate
		
        /*
		var group = parseInt(document.catwebformform67491.CAT_Custom_136239.value);
        //If you are a victorian plumber, use the 4th array in the module, as youre more expensive
        var CAT_Custom_136267 = document.catwebformform67491.CAT_Custom_136239.value;
        if(myState=='3' && group=='1' && CAT_Custom_136267=='1Plumber'){
            group = '4';
        }
        
        
		if (!isNaN(group) && !isNaN(amt) && !isNaN(employee)) {
			liabAmount = liabYearAmt[group -1][amt][employee];
			gstTotal += ((liabAmount * gst) - liabAmount) + (liabFee - liabFee/1.1);
			stampDutyTotal += ((liabAmount * gst) * (1 + (liabStampDuty[myState -1]/100))) - (liabAmount * gst);
			liabAmount = (liabAmount * gst) * (1 + (liabStampDuty[myState -1]/100));
			liabAmount += liabFee;
			liabMonthly = (liabAmount - liabFee)/12;
			liabFirstMonth = liabMonthly + liabFee;
		}
        */
        
        var occupation = parseInt(document.catwebformform67491.CAT_Custom_136239.selectedIndex);
      	var amt = parseInt(document.catwebformform67491.CAT_Custom_136240.selectedIndex);
		var employee = parseInt(document.catwebformform67491.CAT_Custom_136241.selectedIndex);
        
        if (!isNaN(occupation) && !isNaN(amt) && !isNaN(employee)) {
			liabAmount = liabYearAmt[occupation-1][amt][employee];
			//gstTotal += ((liabAmount * gst) - liabAmount) + (liabFee - liabFee/1.1);
			//stampDutyTotal += ((liabAmount * gst) * (1 + (liabStampDuty[myState -1]/100))) - (liabAmount * gst);
			//liabAmount = ((liabAmount - liabFee) * gst); // * (1 + (liabStampDuty[myState -1]/100));
			//liabAmount += liabFee;
			liabMonthly = (liabAmount - liabFee)/12;
			liabFirstMonth = liabMonthly + liabFee;
		}
        
        
		document.getElementById("liabYear").innerHTML = num2dec(liabAmount, 2); 
		document.getElementById("liabFirstMonth").innerHTML = num2dec(liabFirstMonth, 2); 
		document.getElementById("liabMonthly").innerHTML = num2dec(liabMonthly, 2); 
		document.catwebformform67491.CAT_Custom_136242.value = num2dec(liabAmount, 2); 
		document.catwebformform67491.CAT_Custom_136243.value = num2dec(liabFirstMonth, 2); 
		document.catwebformform67491.CAT_Custom_136244.value = num2dec(liabMonthly, 2);
	} else {
		toggleLayer('wrapLiab', 'hide');	
		toggleLayer('wrapLiabQuestions', 'hide');	
		document.catwebformform67491.CAT_Custom_138196.value ="No"
		//alert(document.catwebformform67491.CAT_Custom_138196.value);
	}
	
	// General display and calculations...
	if (document.catwebformform67491.CAT_Custom_138409.checked) {
		toggleLayer('wrapGen', 'show');
		toggleLayer('wrapGenQuestions', 'show');
		document.catwebformform67491.CAT_Custom_138409.value="Yes";
		// Calculate
		var property = parseInt(document.catwebformform67491.CAT_Custom_136246.selectedIndex);
		if (property > 0) {
			genAmount = genYearAmt[property];
			fireLeveeTotal += genAmount * (genFireLevee[myState -1]/100);			
			genAmount += genAmount * (genFireLevee[myState -1]/100);
			gstTotal += ((genAmount * gst) - genAmount) + (genFee - genFee/1.1);
			stampDutyTotal += ((genAmount * gst) * (1 + (genStampDuty[myState -1]/100))) - (genAmount * gst);
			genAmount = (genAmount * gst) * (1 + (genStampDuty[myState -1]/100));
			genAmount += genFee;
			genMonthly = (genAmount - genFee)/12;
			genFirstMonth = genMonthly + genFee;
		}
		document.getElementById("genYear").innerHTML = num2dec(genAmount, 2); 
		document.getElementById("genFirstMonth").innerHTML = num2dec(genFirstMonth, 2); 
		document.getElementById("genMonthly").innerHTML = num2dec(genMonthly, 2); 
		document.catwebformform67491.CAT_Custom_136247.value = num2dec(genAmount, 2); 
		document.catwebformform67491.CAT_Custom_136248.value = num2dec(genFirstMonth, 2); 
		document.catwebformform67491.CAT_Custom_136249.value = num2dec(genMonthly, 2); 
	} else {
		toggleLayer('wrapGen', 'hide');	
		toggleLayer('wrapGenQuestions', 'hide');
		document.catwebformform67491.CAT_Custom_138409.value="No";	
	}
	
	// Vehicle display and calculations...
	if (document.catwebformform67491.CAT_Custom_138410.checked) {
		toggleLayer('wrapVehicle', 'show');
		toggleLayer('wrapVehicleQuestions', 'show');
		document.catwebformform67491.CAT_Custom_138410.value="Yes";
		/*
		Hidden because this is no longer calculated
		// Calculate
		var vehicleSumIns = parseInt(document.catwebformform67491.vehicleSumIns.value.replace(/[^.\d]/g, ""));
		var vehicleDrAge = parseInt(document.catwebformform67491.vehicleDriverAge.value);
		var vehicleNCBAmt = 0;
		//if (document.catwebformform67491.vehicleNCB.value != "") {
		//	vehicleNCBAmt = parseInt(document.catwebformform67491.vehicleNCB.value);
		//}
		var vehicleNCBProtectAmt = 0;
		if (document.catwebformform67491.vehicleNCBProtect.checked) {
			vehicleNCBProtectAmt = vehicleNCBProtect;
		}
		var windscreenOpt = 0;
		if (document.catwebformform67491.windscreen.checked) {
			windscreenOpt = windscreen;
		};
		var vehicleTrailerOpt = 0;
		if (document.catwebformform67491.trailer.checked) {
			vehicleTrailerOpt = vehicleTrailer;
		};
		if (!isNaN(vehicleSumIns) && !isNaN(vehicleDrAge) && !isNaN(vehicleNCBAmt)) {
			//vehicleNCBProtect, windscreen, vehicleBaseFee, vehicleBaseMultiplier
			vehicleAmount = vehicleBaseFee + (vehicleSumIns * vehicleBaseMultiplier);
			vehicleAmount *= (100 + vehicleStateMultiplier[myState -1])/100;
			vehicleAmount += vehicleAmount * vehicleDriverAge[vehicleDrAge]; // ??????
			vehicleAmount -= vehicleAmount * vehicleRating1Multiplier;
			vehicleAmount -= vehicleAmount * (vehicleNCBAmt / 100);
			vehicleAmount += vehicleNCBProtectAmt;
			vehicleAmount += windscreenOpt;
			vehicleAmount += vehicleTrailerOpt;
			gstTotal += ((vehicleAmount * gst) - vehicleAmount) + (vehicleFee - vehicleFee/1.1);
			stampDutyTotal += ((vehicleAmount * gst) * (1 + (vehicleStampDuty[myState -1]/100))) - (vehicleAmount * gst);
			vehicleAmount = (vehicleAmount * gst) * (1 + (vehicleStampDuty[myState -1]/100));
			vehicleAmount += vehicleFee;
			if (vehicleAmount < vehicleMinCharge) { vehicleAmount = vehicleMinCharge };
			vehicleMonthly = (vehicleAmount - vehicleFee)/12;
			vehicleFirstMonth = vehicleMonthly + genFee;
		}
		document.getElementById("CAT_Custom_136301").innerHTML = num2dec(vehicleAmount, 2); 
		document.getElementById("vehicleFirstMonth").innerHTML = num2dec(vehicleFirstMonth, 2); 
		document.getElementById("vehicleMonthly").innerHTML = num2dec(vehicleMonthly, 2); 
		document.catwebformform67491.hid_vehicleYear.value = num2dec(vehicleAmount, 2); 
		document.catwebformform67491.hid_vehicleFirstMonth.value = num2dec(vehicleFirstMonth, 2); 
		document.catwebformform67491.hid_vehicleMonthly.value = num2dec(vehicleMonthly, 2); 
		*/
	} else {
		toggleLayer('wrapVehicle', 'hide');	
		toggleLayer('wrapVehicleQuestions', 'hide');
		document.catwebformform67491.CAT_Custom_138410.value="No";	
	}

 	// Income Protection display and calculations...
	if (document.catwebformform67491.CAT_Custom_138412.checked) {
		toggleLayer('wrapIncome', 'show');
		document.catwebformform67491.CAT_Custom_138412.value="Yes";
	} else {
		toggleLayer('wrapIncome', 'hide');	
		document.catwebformform67491.CAT_Custom_138412.value="No";
	}

if (document.catwebformform67491.CAT_Custom_138312.checked) {
		toggleLayer('wrapIncome2', 'show');
		document.catwebformform67491.CAT_Custom_138312.value="Yes";
	} else {
		toggleLayer('wrapIncome2', 'hide');	
		document.catwebformform67491.CAT_Custom_138312.value="No";
	}
	
	// Display amount
	//document.getElementById("totalYear").innerHTML = num2dec(liabAmount + genAmount + vehicleAmount, 2);
	document.getElementById("totalYear").innerHTML = num2dec(liabAmount + genAmount, 2);
	//document.getElementById("totalFirstMnth").innerHTML = num2dec(liabFirstMonth + genFirstMonth + vehicleFirstMonth, 2);
	document.getElementById("totalFirstMnth").innerHTML = num2dec(liabFirstMonth + genFirstMonth, 2);
	//document.getElementById("totalMonthly").innerHTML = num2dec(liabMonthly + genMonthly + vehicleMonthly, 2);
	document.getElementById("totalMonthly").innerHTML = num2dec(liabMonthly + genMonthly, 2);
    
    /* CMENTCH 1/25/2012
	document.getElementById("totalGST").innerHTML = num2dec(gstTotal, 2);
	document.getElementById("totalStampDuty").innerHTML = num2dec(stampDutyTotal, 2);
	document.getElementById("totalFireLevee").innerHTML = num2dec(fireLeveeTotal, 2);
    */
    
	//document.catwebformform67491.CAT_Custom_136254.value = num2dec(liabAmount + genAmount + vehicleAmount, 2); 
	document.catwebformform67491.CAT_Custom_136254.value = num2dec(liabAmount + genAmount, 2); 
	//document.catwebformform67491.CAT_Custom_136255.value = num2dec(liabFirstMonth + genFirstMonth + vehicleFirstMonth, 2); 
	document.catwebformform67491.CAT_Custom_136255.value = num2dec(liabFirstMonth + genFirstMonth, 2); 
	//document.catwebformform67491.CAT_Custom_136256.value = num2dec(liabMonthly + genMonthly + vehicleMonthly, 2); 
	document.catwebformform67491.CAT_Custom_136256.value = num2dec(liabMonthly + genMonthly, 2); 
	
    /* CMENTCH 1/25/2012
    document.catwebformform67491.CAT_Custom_136257.value = num2dec(gstTotal, 2); 
	document.catwebformform67491.CAT_Custom_136258.value = num2dec(stampDutyTotal, 2); 
	document.catwebformform67491.CAT_Custom_136259.value = num2dec(fireLeveeTotal, 2); 
    */
}

function showFeedback() {
	if (document.catwebformform67491.CAT_Custom_136261.value == "...") {
		toggleLayer('feedbackWrapper', 'show');
	} else {
		toggleLayer('feedbackWrapper', 'hide');	
	}
}
function showOtherTrade()
{
	if (document.catwebformform67491.CAT_Custom_136239.value == "Other") {
		toggleLayer('TradeOtherChoose', 'show');
	} else {
		toggleLayer('TradeOtherChoose', 'hide');	
	}
	
}
function showDetails(checkBox) {
	if (isDefined(checkBox)) {
		if (checkBox.name == "CAT_Custom_136319") {
			if (document.catwebformform67491.CAT_Custom_136319.checked) document.catwebformform67491.CAT_Custom_136318.checked = false;
			if (!document.catwebformform67491.CAT_Custom_136319.checked) document.catwebformform67491.CAT_Custom_136318.checked = true;
		} else {
			if (document.catwebformform67491.CAT_Custom_136318.checked) document.catwebformform67491.CAT_Custom_136319.checked = false;
			if (!document.catwebformform67491.CAT_Custom_136318.checked) document.catwebformform67491.CAT_Custom_136319.checked = true;
		}
	}
	if (document.catwebformform67491.CAT_Custom_136319.checked) {
		toggleLayer('wrapDetails', 'show');
		document.getElementById('detailForm').value="yes";
		//alert(document.getElementById('detailForm').value);
	} else {
		toggleLayer('wrapDetails', 'hide');	
		document.getElementById('detailForm').value="no";
		//alert(document.getElementById('detailForm').value);
	}
}

function showCredit(checkBox) {
	if (isDefined(checkBox)) {
		switch(checkBox.name) {
			
			case "CAT_Custom_136306":
				if (checkBox.checked) {
					document.catwebformform67491.CAT_Custom_136305.checked = false;
					document.catwebformform67491.CAT_Custom_136306.checked = true;
					document.catwebformform67491.CAT_Custom_136307.checked = false;
				} else {
					document.catwebformform67491.CAT_Custom_136305.checked = true;
					document.catwebformform67491.CAT_Custom_136306.checked = false;
					document.catwebformform67491.CAT_Custom_136307.checked = false;
				}
				break;
			
			case "CAT_Custom_136307":
				if (checkBox.checked) {
					document.catwebformform67491.CAT_Custom_136305.checked = false;
					document.catwebformform67491.CAT_Custom_136306.checked = false;
					document.catwebformform67491.CAT_Custom_136307.checked = true;
				} else {
					document.catwebformform67491.CAT_Custom_136305.checked = true;
					document.catwebformform67491.CAT_Custom_136306.checked = false;
					document.catwebformform67491.CAT_Custom_136307.checked = false;
				}
				break;
				

			default:
				document.catwebformform67491.CAT_Custom_136305.checked = true;
				document.catwebformform67491.CAT_Custom_136306.checked = false;
				document.catwebformform67491.CAT_Custom_136307.checked = false;
				break;
		}
	}
	// Hide layers
	if (document.catwebformform67491.CAT_Custom_136306.checked) {
		toggleLayer('wrapCredit', 'show');
		toggleLayer('wrapWithdraw', 'hide');
		document.getElementById('PaymentMethodType_1').checkded=true;
		document.getElementById('PaymentMethodType_11').checked = false;
		document.getElementById('googleit').value="usmango";
		//alert("usman active");
	} else if (document.catwebformform67491.CAT_Custom_136307.checked) {
		toggleLayer('wrapCredit', 'hide');
		toggleLayer('wrapWithdraw', 'show');
		document.getElementById('PaymentMethodType_11').checked = true;
		document.getElementById('PaymentMethodType_1').checked = false;
		document.getElementById('googleit').value="usmanfail";
		//alert("usman deactive");
	} else {
		toggleLayer('wrapCredit', 'hide');
		toggleLayer('wrapWithdraw', 'hide');	
		document.getElementById('PaymentMethodType_11').checked = true;
		document.getElementById('PaymentMethodType_1').checked = false;
		document.getElementById('googleit').value="usmanfail";
		//alert("deactiveate from all");
	}
}

function toggleYesNo(box1, box2) {
	/**********************************************
		Toggles two checkboxes
		Box1 is the name of the checkbox that has been clicked.
		Box2 is the name of the checkbox that may need to be toggled.
	***********************************************/
	var box1obj = document.forms[0].elements[box1];
	var box2obj = document.forms[0].elements[box2];
	
	if (!isDefined(box1obj) || !isDefined(box2obj)) {
		// Form elements don't exist so return without changing.
		return;
	}
	
	if (box1obj.checked) {
		box2obj.checked = false;
	} else {
		box2obj.checked = true;
	}
}

function toggleText(checkBox) {
	// Variables
	var checkName = checkBox.id;
	var checkRoot, checkOther;
	
	// Find checkRoot and checkOther
	if (checkName.charAt(checkName.length - 1) == 'x') {
		// 'No' has been clicked
		checkRoot = checkName.substr(0, checkName.length - 1);
		checkOther = checkRoot;
	} else {
		// 'Yes' has been clicked
		checkRoot = checkName;
		checkOther = checkRoot + 'x';
	}

	// Toggle checkboxes
	toggleYesNo( checkName, checkOther );
	
	// Show textarea if 'Yes' checked
	if (document.forms[0].elements[checkRoot].checked) {
		toggleLayer(checkRoot + 'text', 'show');
	} else {
		toggleLayer(checkRoot + 'text', 'hide');	
	}
}

function toggleLayer(myLayer, override) {
	/**********************************************
		myLayer is div reference to be shown/hidden
		override can be 'show' to show the layer
			or 'hide' to hide the layer
			or anything else will toggle the layer
	**********************************************/
	// Establish the layer style...
	if (document.getElementById) {
		// this is the way the standards work
		var layerStyle = document.getElementById(myLayer).style;
	}
	else if (document.all) {
		// this is the way old msie versions work
		var layerStyle = document.all[myLayer].style;
	}
	else if (document.layers) {
		// this is the way nn4 works
		var layerStyle = document.layers[myLayer].style;
	}
	// Use override first
	if (override == "show") {
		layerStyle.display = "block";
	} else if (override == "hide") {
		layerStyle.display = "none";
	} else {
		layerStyle.display = layerStyle.display? "none":"block";
	}
}

function XXXvalidateXXX(element) {
	/**********************************************	
		Checks to see if the input box is a number or blank
	**********************************************/
	if (isNaN(parseInt(element.value)) && element.value != "") {
		window.alert ("You must type a number.")
		return false;
	} else {
		return true;
	}
}


function num2dec(num, decPlaces) {
	/**********************************************	
		Returns a number to set decimal places
	**********************************************/
	if (isNaN(num)) {
		return "-";
	} else {
		return num.toFixed(decPlaces); 
	}
}

function isDefined(variable) {
	/**********************************************	
		Tests that a variable exists
	**********************************************/
	return (!(!( variable||false )))
}

/************************************************
-------------------------------------------------
FORM VALIDATION FUNCTION
-------------------------------------------------
************************************************/

/*
function validateForm(form) {
	//*********************************************	
		Checks that required fields in form has been filled in
	//**********************************************
	// Blank error message
	var msg = "";
	if (form.testMode.value == "true" || form.name.value == "Test" || form.name.value == "test") {
			return true; // Don't validate if in test mode
	} else {
		// Details Validation
		if (form.CAT_Custom_128567.value == "0") {
			msg += "You must select which State you are located.\n\n";
		}
		if (form.FullName.value == null || form.name.value == "") {
			msg += "You have not writen your name.\n\n";
		}
		if (!form.EmailAddress.value.match(/\b[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,6}\b/)) {
			msg += "Your email CAT_Custom_136265 is not valid.\n\n";
		}
		if ((form.HomePhone.value == null || form.phone.value == "") && (form.CellPhone.value == null || form.CellPhone.value == "")) {
			msg += "You must include either a phone or mobile number.\n\n";
		}
		// Credit Card Validation...
		if (form.CAT_Custom_136306.checked) {
			msg += CheckCardNumber(form);
		}
		
		// Display Errors
		if (msg != "") {
			headMsg =  "________________________________________________\n\n";
			headMsg += "The form was not submitted because of the following:\n";
			headMsg += "________________________________________________\n\n";
			alert(headMsg + msg);
			return false;
		} else {
			return true;
		}
	}
}


/************************************************
-------------------------------------------------
CREDIT CARD VALIDATION FUNCTIONS
-------------------------------------------------
************************************************/

var Cards = new makeArray(8);
Cards[0] = new CardType("MasterCard", "51,52,53,54,55", "16");
var MasterCard = Cards[0];
Cards[1] = new CardType("VisaCard", "4", "13,16");
var VisaCard = Cards[1];
Cards[2] = new CardType("AmExCard", "34,37", "15");
var AmExCard = Cards[2];
Cards[3] = new CardType("DinersClubCard", "30,36,38", "14");
var DinersClubCard = Cards[3];
Cards[4] = new CardType("DiscoverCard", "6011", "16");
var DiscoverCard = Cards[4];
Cards[5] = new CardType("enRouteCard", "2014,2149", "15");
var enRouteCard = Cards[5];
Cards[6] = new CardType("JCBCard", "3088,3096,3112,3158,3337,3528", "16");
var JCBCard = Cards[6];
var LuhnCheckSum = Cards[7] = new CardType();

/*************************************************************************\
CheckCardNumber(form)
function called when users click the "check" button.
\*************************************************************************/
function CheckCardNumber(form) {
	var returnMsg = "";

	var tmpyear;
	if (form.CardNumber.value.length == 0) {
		returnMsg += "Please enter a Card Number.\n\n";
		form.CardNumber.focus();
		return returnMsg;
	}
	if (form.ExpYear.value.length == 0) {
		returnMsg += "Please enter the Expiration Year.\n\n";
		form.ExpYear.focus();
		return returnMsg;
	}
	if (form.ExpYear.value > 96)
	tmpyear = "19" + form.ExpYear.value;
	else if (form.ExpYear.value < 21)
	tmpyear = "20" + form.ExpYear.value;
	else {
		returnMsg += "The Expiration Year is not valid.\n\n";
		return returnMsg;
	}
	tmpmonth = form.ExpMon.options[form.ExpMon.selectedIndex].value;
	// The following line doesn't work in IE3, you need to change it
	// to something like "(new CardType())...".
	// if (!CardType().isExpiryDate(tmpyear, tmpmonth)) {
	if (!(new CardType()).isExpiryDate(tmpyear, tmpmonth)) {
		returnMsg += "This card has already expired.\n\n";
		return returnMsg;
	}
	card = form.CardType.options[form.CardType.selectedIndex].value;
	var retval = eval(card + ".checkCardNumber(\"" + form.CardNumber.value +
	"\", " + tmpyear + ", " + tmpmonth + ");");
	cardname = "";
	if (!retval) {
	// The cardnumber has the valid luhn checksum, but we want to know which
	// cardtype it belongs to.
		for (var n = 0; n < Cards.size; n++) {
			if (Cards[n].checkCardNumber(form.CardNumber.value, tmpyear, tmpmonth)) {
				cardname = Cards[n].getCardType();
				break;
			}
		}
		if (cardname.length > 0) {
			returnMsg += "This looks like a " + cardname + " number, not a " + card + " number.\n\n";
			return returnMsg;
		}
		else {
			returnMsg += "This card number is not valid.\n\n";
			return returnMsg;
    }
  }
}
/*************************************************************************\
Object CardType([String cardtype, String rules, String len, int year, 
                                        int month])
cardtype    : type of card, eg: MasterCard, Visa, etc.
rules       : rules of the cardnumber, eg: "4", "6011", "34,37".
len         : valid length of cardnumber, eg: "16,19", "13,16".
year        : year of expiry date.
month       : month of expiry date.
eg:
var VisaCard = new CardType("Visa", "4", "16");
var AmExCard = new CardType("AmEx", "34,37", "15");
\*************************************************************************/
function CardType() {
var n;
var argv = CardType.arguments;
var argc = CardType.arguments.length;

this.objname = "object CardType";

var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";
var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";
var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";

this.setCardNumber = setCardNumber;  // set CardNumber method.
this.setCardType = setCardType;  // setCardType method.
this.setLen = setLen;  // setLen method.
this.setRules = setRules;  // setRules method.
this.setExpiryDate = setExpiryDate;  // setExpiryDate method.

this.setCardType(tmpcardtype);
this.setLen(tmplen);
this.setRules(tmprules);
if (argc > 4)
this.setExpiryDate(argv[3], argv[4]);

this.checkCardNumber = checkCardNumber;  // checkCardNumber method.
this.getExpiryDate = getExpiryDate;  // getExpiryDate method.
this.getCardType = getCardType;  // getCardType method.
this.isCardNumber = isCardNumber;  // isCardNumber method.
this.isExpiryDate = isExpiryDate;  // isExpiryDate method.
this.luhnCheck = luhnCheck;// luhnCheck method.
return this;
}

/*************************************************************************\
boolean checkCardNumber([String cardnumber, int year, int month])
return true if cardnumber pass the luhncheck and the expiry date is
valid, else return false.
\*************************************************************************/
function checkCardNumber() {
var argv = checkCardNumber.arguments;
var argc = checkCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
var year = (argc > 1) ? argv[1] : this.year;
var month = (argc > 2) ? argv[2] : this.month;

this.setCardNumber(cardnumber);
this.setExpiryDate(year, month);

if (!this.isCardNumber())
return false;
if (!this.isExpiryDate())
return false;

return true;
}
/*************************************************************************\
String getCardType()
return the cardtype.
\*************************************************************************/
function getCardType() {
return this.cardtype;
}
/*************************************************************************\
String getExpiryDate()
return the expiry date.
\*************************************************************************/
function getExpiryDate() {
return this.month + "/" + this.year;
}
/*************************************************************************\
boolean isCardNumber([String cardnumber])
return true if cardnumber pass the luhncheck and the rules, else return
false.
\*************************************************************************/
function isCardNumber() {
var argv = isCardNumber.arguments;
var argc = isCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
if (!this.luhnCheck())
return false;

for (var n = 0; n < this.len.size; n++)
if (cardnumber.toString().length == this.len[n]) {
for (var m = 0; m < this.rules.size; m++) {
var headdigit = cardnumber.substring(0, this.rules[m].toString().length);
if (headdigit == this.rules[m])
return true;
}
return false;
}
return false;
}

/*************************************************************************\
boolean isExpiryDate([int year, int month])
return true if the date is a valid expiry date,
else return false.
\*************************************************************************/
function isExpiryDate() {
var argv = isExpiryDate.arguments;
var argc = isExpiryDate.arguments.length;

year = argc > 0 ? argv[0] : this.year;
month = argc > 1 ? argv[1] : this.month;

if (!isNum(year+""))
return false;
if (!isNum(month+""))
return false;
today = new Date();
expiry = new Date(year, month);
if (today.getTime() > expiry.getTime())
return false;
else
return true;
}

/*************************************************************************\
boolean isNum(String argvalue)
return true if argvalue contains only numeric characters,
else return false.
\*************************************************************************/
function isNum(argvalue) {
argvalue = argvalue.toString();

if (argvalue.length == 0)
return false;

for (var n = 0; n < argvalue.length; n++)
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;

return true;
}

/*************************************************************************\
boolean luhnCheck([String CardNumber])
return true if CardNumber pass the luhn check else return false.
Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
\*************************************************************************/
function luhnCheck() {
var argv = luhnCheck.arguments;
var argc = luhnCheck.arguments.length;

var CardNumber = argc > 0 ? argv[0] : this.cardnumber;

if (! isNum(CardNumber)) {
return false;
  }

var no_digit = CardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;

for (var count = 0; count < no_digit; count++) {
var digit = parseInt(CardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}

/*************************************************************************\
ArrayObject makeArray(int size)
return the array object in the size specified.
\*************************************************************************/
function makeArray(size) {
this.size = size;
return this;
}

/*************************************************************************\
CardType setCardNumber(cardnumber)
return the CardType object.
\*************************************************************************/
function setCardNumber(cardnumber) {
this.cardnumber = cardnumber;
return this;
}

/*************************************************************************\
CardType setCardType(cardtype)
return the CardType object.
\*************************************************************************/
function setCardType(cardtype) {
this.cardtype = cardtype;
return this;
}

/*************************************************************************\
CardType setExpiryDate(year, month)
return the CardType object.
\*************************************************************************/
function setExpiryDate(year, month) {
this.year = year;
this.month = month;
return this;
}

/*************************************************************************\
CardType setLen(len)
return the CardType object.
\*************************************************************************/
function setLen(len) {
// Create the len array.
if (len.length == 0 || len == null)
len = "13,14,15,16,19";

var tmplen = len;
n = 1;
while (tmplen.indexOf(",") != -1) {
tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);
n++;
}
this.len = new makeArray(n);
n = 0;
while (len.indexOf(",") != -1) {
var tmpstr = len.substring(0, len.indexOf(","));
this.len[n] = tmpstr;
len = len.substring(len.indexOf(",") + 1, len.length);
n++;
}
this.len[n] = len;
return this;
}

/*************************************************************************\
CardType setRules()
return the CardType object.
\*************************************************************************/
function setRules(rules) {
// Create the rules array.
if (rules.length == 0 || rules == null)
rules = "0,1,2,3,4,5,6,7,8,9";
  
var tmprules = rules;
n = 1;
while (tmprules.indexOf(",") != -1) {
tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);
n++;
}
this.rules = new makeArray(n);
n = 0;
while (rules.indexOf(",") != -1) {
var tmpstr = rules.substring(0, rules.indexOf(","));
this.rules[n] = tmpstr;
rules = rules.substring(rules.indexOf(",") + 1, rules.length);
n++;
}
this.rules[n] = rules;
return this;
}



// ********************************************
// Ajax Form Handlers
// ********************************************


//window.onload = attachFormHandlers;

var gShow; //variable holding the id where CAT_Custom_136261 will be sent to.
var gErrors = 0; //number of errors is set to none to begin with
var http = getHTTPObject();//don't worry about this


/*validateMe is the function called with onblur each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateMe(objInput) {

	sVal = objInput.value; //get value inside of input field
	
	sRules = objInput.className.split(' '); // get all the rules from the input box classname
	if (sRules.length >= 4) {
		sRequired = sRules[1]; // determines if field is required or not
		sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
		gShow = sRules[3]; //gShow is the id where feedback is sent to.
		
		//sends the rules and value to the php page to be validated
		http.open("GET", + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
		
		http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
		http.send(null);
	}
}


// Changes details inside ID
function handleHttpResponse() {
	//if the process is completed, decide to do with the returned data
	if (http.readyState == 4 && isDefined(gShow)) 
  	{
		
  		sResults = http.responseText.split(","); //results is now whatever the feedback from the php page was
		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever was returned by the php page. 
    	//document.getElementById(gShow).innerHTML = "";
			//document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
            sResults[0] = 'form_tick';
			document.getElementById(gShow).src="/images/" + sResults[0] +".gif";
  	}
}


function validate() {
	var imageList; 

	imageList = document.catwebformform67491.getElementsByTagName('img')

	for (i=0; i < imageList.length; i++)//loop through all the img elements 
	{
		// Is element hidden?
		var imageVisible = true;
		var imageRef = imageList[i];
		while ( imageRef.id != 'catwebformform67491') {
			// Loop through nodes to see if hidden
			if (isDefined(imageRef.id) && imageRef.style.display == "none") {
				imageVisible = false;
				break;
			}
			imageRef = imageRef.parentNode;
		}
		//alert (imageList[i].id + " - " + imageVisible);
		if (imageVisible) {
			// Does the form contain the error gif
			if (imageList[i].src.indexOf('form_error.gif') != -1 || imageList[i].src.indexOf('form_required.gif') != -1)
			{
				gErrors = gErrors + 1; //the error count increases by 1
			}
		}
	}
	
	var msg = "";
	if (document.catwebformform67491.CAT_Custom_136306.checked) {
		// msg += CheckCardNumber(document.catwebformform67491);
	}

	if (gErrors > 0 || msg != "")
	{
		//if there are any errors give a message
		//alert ("Please make sure all required fields are properly completed.\r\n\r\n" + msg);
		//gErrors = 0;// reset errors to 0
		//return false;
	}
	else return true;
}


function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try 
		{
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
		xmlhttp = false;
		}
	}
	return xmlhttp;
}
function showPool(){
document.getElementById("pool").style.display ="block";
}
function hidePool(){
document.getElementById("pool").style.display ="none";
}
