// #################################
// Company Information
var Stry;

function ProcessForm() {
	/*  // Commented Out By AjW.  
	if(document.getElementById("Latitude").value.length == 0) {
		sAddress = document.getElementById("Street1").value + ', ' + document.getElementById("City").value + ', ' + document.getElementById("StateCode").value + ', ' + document.getElementById("ZipCode").value;
		document.getElementById("divResults").innerHTML = '<strong>Verifying Addres...</strong>';
		GetLonLat(sAddress)
	}	
	*/
// Form Required
	var co = window.document.CompanyInfo
	missinginfo = '';
	if(co.ContactName.value == '') {
	missinginfo += "\n     -  Contact Name";
	}
	if(co.ContactPhone.value == '') {
	missinginfo += "\n     -  Contact Phone Number";
	}
	//if(co.ContactEmail.value == '') {
	//missinginfo += "\n     -  Contact Email Address";
	//}
	if(co.Username.value.length < 6) {
	missinginfo += "\n     -  Username (Min. Length 6 Letters)";
	}
	if(co.Password.value != co.ConfirmPassword.value) {
	missinginfo += "\n     -  Password and Confirm Password Do Not Match";
	}
	if(co.Password.value.length < 6) {
	missinginfo += "\n     -  Password (Min. Length 6 Letters)";
	}
	if(co.CompanyName.value == '') {
	missinginfo += "\n     -  Company Name";
	}
	if(co.AreaCode.value == '' || co.PhonePrefix.value == '' || co.PhoneNumber.value == '' || (co.PhonePrefix.value.length + co.PhoneNumber.value.length) < 7) {
	missinginfo += "\n     -  Phone Number";
	}	
	//if(co.Street1.value == '') {
	//missinginfo += "\n     -  Street Address";
	//}	
	if(co.City.value == '') {
	missinginfo += "\n     -  City";
	}	
	if(co.CompanyState.value == '') {
	missinginfo += "\n     -  State";
	}			
	if(co.ZipCode.value == '') {
	missinginfo += "\n     -  ZipCode";
	}
	//if(co.CompanyEmail.value == '') {
	//missinginfo += "\n     -  Company Email Address";
	//}					
	
	if (missinginfo != '') {
		missinginfo ="_____________________________\n" +
		"You complete the following required fields:\n" +
		missinginfo + "\n_____________________________" +
		"\nPlease correct and submit again.";
		alert(missinginfo);
		return false;
	}
// End Form Required
	return true;
	//if(document.getElementById("Latitude").value.length > 0) {return true;} else { return false;}
}


function CheckAddress(){

	if(((document.getElementById("City").value != '' && document.getElementById("StateCode").value != '') || document.getElementById("ZipCode").value != '')) {
		sAddress = document.getElementById("Street1").value + ', ' + document.getElementById("City").value + ', ' + document.getElementById("StateCode").value + ', ' + document.getElementById("ZipCode").value;
		document.getElementById("divResults").innerHTML = '<strong>Verifying Address...</strong>';
		GetLonLat(sAddress);
	}
}

function GetLonLat(searchid) { 
	geocode.getLocations(searchid, addpoint); 
}

function addpoint(results){
	var place;
	var errcode;
	
	if(results.Status.code == 200) {
		/*
		http://www.google.com/apis/maps/documentation/reference.html#GGeoStatusCode
		G_GEO_SUCCESS (200) 	 No errors occurred; the address was successfully parsed and its geocode has been returned. (Since 2.55)
		G_GEO_SERVER_ERROR (500) 	A geocoding request could not be successfully processed, yet the exact reason for the failure is not known. (Since 2.55)
		G_GEO_MISSING_ADDRESS (601) 	The HTTP q parameter was either missing or had no value. (Since 2.55)
		G_GEO_UNKNOWN_ADDRESS (602) 	No corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect. (Since 2.55)
		G_UNAVAILABLE_ADDRESS (603) 	The geocode for the given address cannot be returned due to legal or contractual reasons. (Since 2.55)
		G_GEO_BAD_KEY (610) 	The given key is either invalid or does not match the domain for which it was given. (Since 2.55)
		*/

		place = results.Placemark[0];
		sLongitude = place.Point.coordinates[0];
		sLatitude = place.Point.coordinates[1];
		
		//document.getElementById("divResults").innerHTML = document.getElementById("divResults").innerHTML + '<br>Long: ' + sLongitude + '<br>Lat: ' + sLatitude;
		document.getElementById("Latitude").value = sLatitude
		document.getElementById("Longitude").value = sLongitude
		
		//alert(place.AddressDetails.Accuracy)
		document.getElementById("divResults").innerHTML = document.getElementById("divResults").innerHTML + place.address
		/*
		http://www.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
		4 	 Town (city, village) level accuracy. (Since 2.59)
		5 	Post code (zip code) level accuracy. (Since 2.59)
		6 	Street level accuracy. (Since 2.59)
		7 	Intersection level accuracy. (Since 2.59)
		8 	Address level accuracy. (Since 2.59)
		*/

		
		if(results.Placemark[0].AddressDetails.Accuracy > 5){
			document.getElementById("divResults").innerHTML = '<strong><font color=\"green\">Address Verified</font></strong>';
			document.getElementById("accuracy").value = results.Placemark[0].AddressDetails.Accuracy;			
		} else {
			document.getElementById("divResults").innerHTML = '<strong><font color=\"black\">Address Verified</font></strong>';
			document.getElementById("accuracy").value = results.Placemark[0].AddressDetails.Accuracy;
			//alert(document.getElementById("accuracy").value);
		}
	} else {
			if(sAddress.length > 5){
				
				//alert(document.getElementById("ZipCode").value);
				GetLonLat(document.getElementById("ZipCode").value)
			}else{
				document.getElementById("divResults").innerHTML = '<strong><font color=\"red\">Your Address May Be Invalid.  Please Check It.</font></strong>';			
			}

		//errcode = results.Status.code;
		//alert('Invalid Address.  Please Verify Your Address Is Entered Correctly. \n Error Code:' + errcode + '\n If your address is correct please call us for assistance.  877-444-6339')
		//document.getElementById("Street1").focus();
	}

}






//##################################
// LISTINGS
var TotalAmount = 0
var vStatus


// USED TO RESET THE FORM TO BLANK & AT START UP
function ChooseCatsSetUp() {
	//  Reset the form
	document.getElementById("TowingChk").checked = false;
	document.getElementById("RepairChk").checked = false;
	document.getElementById("StorageChk").checked = false;
	document.getElementById("RepoChk").checked = false;
	EnableChk("TowingChk", 0, 15);
	EnableChk("RepairChk", 0, 6);
	EnableChk('StorageChk', 0, 3);
	TotalAmount = 0;
}



// USED IN RESTART PROCESS

function RestartSetUp(){
	if(Categories.CategoryId.length > 0) {
		ResetReStartChk("TowingChk", varTowingMonthly, 15);
		ResetReStartChk("RepairChk", varRepairMonthly, 6);
		ResetReStartChk("StorageChk", varStorageMonthly, 3);		
		ResetReStartChk("RepoChk", varRepoMonthly, 0);			
	} else {
		//  No Categories Saved
		ChooseCatsSetUp();
	}
}

function ResetReStartChk(chkid, Cost, ChkCount) {
	
	//  Check All The Parents
	for(var ii = 0; ii < Categories.CategoryId.length + 1; ii++) {
		if(Categories.CategoryId[ii] == document.getElementById(chkid).value) { 
			if(!document.getElementById(chkid).checked) {
				document.getElementById(chkid).checked = true;
				EnableChk(chkid, Cost, ChkCount);
			}
		}
	};
	
	// Go through all Sub-Categories Categories
	for(var i = 1; i < ChkCount; i++) {
		// For each category go through Listings to see if the value matches.
		for(var ii = 0; ii < Categories.CategoryId.length + 1; ii++) {
		
		
			// IT MIGHT MATCH THE PARENT CATEGORY OR THE SUB-CAT
			if(Categories.CategoryId[ii] == document.getElementById(chkid + '-' + i).value) { 
				//  If it does:
				//  1.  Make sure the parent is checked adding the correct cost to the total.
				//  2.  Enable all of this categories check boxes.
				
			
				if(!document.getElementById(chkid).checked) {
					// Add Cost
					// Enable Sub Items
					document.getElementById(chkid).checked = true;
					EnableChk(chkid, Cost, ChkCount);
				}
			
				//  3.  Check that category.
				document.getElementById(chkid + '-' + i).checked = true
			}
	


		//  If not:
		//  1.  Disable if the parent id has not been checked.
		//  2.  Otherwise enable but do not check.
//		alert(Categories.CategoryId.length + '--' + ii);
		};
	};


}





function CheckMainChk(chkid){
	if(document.getElementById(chkid).checked) { 
		switch (chkid) {
			case 'TowingChk': {TempCost = varRegTowingMonthly - varTowingMonthly; break}	
			case 'RepairChk': {TempCost = varRegRepairMonthly - varRepairMonthly; break}	
			case 'StorageChk': {TempCost = varRegStorageMonthly - varStorageMonthly; break}	
			case 'RepoChk': {TempCost = varRegRepoMonthly - varRepoMonthly; break}		
		}
		varMainCat = chkid;
		EnableChk(chkid, TempCost, 0)
	}
}

function EnableChk(chkid, Cost, ChkCount) {

	if(varMainCat == ''){ varMainCat = chkid;}

	if(!document.getElementById(chkid).checked) {	//  DISABLE CHECK BOXES
		bStatus = true;
		HandleChks(chkid, bStatus, ChkCount)
	
		if(varMainCat == chkid) {
			CheckMainChk('TowingChk');	
			varTowingMonthly = varRegTowingMonthly;
			document.getElementById("spTowingMonthly").innerHTML = '<strong>' + formatCurrency(varTowingMonthly) + ' per month</strong>';
		}
		if(varMainCat == chkid) {
			CheckMainChk('RepairChk');	
			varRepairMonthly = varRegRepairMonthly;
			document.getElementById("spRepairMonthly").innerHTML = '<strong>' + formatCurrency(varRepairMonthly) + ' per month</strong>';
		}
		if(varMainCat == chkid) {
			CheckMainChk('StorageChk');	
			varStorageMonthly = varRegRepairMonthly;
			document.getElementById("spStorageMonthly").innerHTML = '<strong>' + formatCurrency(varStorageMonthly) + ' per month</strong>';
		}
		if(varMainCat == chkid) {
			CheckMainChk('RepoChk');		
			varRepoMonthly = varRegRepoMonthly;
			document.getElementById("spRepoMonthly").innerHTML = '<strong>' + formatCurrency(varRepoMonthly) + ' per month</strong>';		
	
			debugger;
		}


		
		if(varMainCat == chkid) { varMainCat = ''; }
		TotalAmount = TotalAmount - Cost;		
	} else { 
		bStatus = false;
		HandleChks(chkid, bStatus, ChkCount)
		
		/*
		1.  If this is the main chk then all others show discount.
				- If it is !checked then remove discounts for others.
			
			If this is NOT the main check then adjust Total Amount but not display.
		*/
		if(varMainCat != 'TowingChk') {
			varTowingMonthly = varDiscTowingMonthly;
			document.getElementById("spTowingMonthly").innerHTML = '<strong style="color: #CC0000;">Add For ' + formatCurrency(varDiscTowingMonthly) + ' per month</strong> <span style="text-decoration: line-through;">$' + varRegTowingMonthly + '</span> ';		
		}
		if(varMainCat != 'RepairChk') {
			varRepairMonthly = varDiscRepairMonthly;
			document.getElementById("spRepairMonthly").innerHTML = '<strong style="color: #CC0000;">Add For ' + formatCurrency(varDiscRepairMonthly) + ' per month</strong> <span style="text-decoration: line-through;">$' + varRegRepairMonthly + '</span> ';
		}
		if(varMainCat != 'StorageChk') {
			varStorageMonthly = varDiscRepairMonthly;
			document.getElementById("spStorageMonthly").innerHTML = '<strong style="color: #CC0000;">Add For ' + formatCurrency(varDiscStorageMonthly) + ' per month</strong> <span style="text-decoration: line-through;">$' + varRegStorageMonthly + '</span> ';
		}
		if(varMainCat != 'RepoChk') {
		varRepoMonthly = varDiscRepoMonthly;
		document.getElementById("spRepoMonthly").innerHTML = '<strong style="color: #CC0000;">Add For ' + formatCurrency(varDiscRepoMonthly) + ' per month</strong> <span style="text-decoration: line-through;">$' + varRegRepoMonthly + '</span> ';
		}
		TotalAmount = TotalAmount + Cost;
		debugger;
	};

	TotalCost(TotalAmount);
}

function HandleChks(chkid, bStatus, ChkCount) {
	//  Enable or disable the sub-category check boxes.
	for(var i = 1; i < ChkCount; i++) {
		document.getElementById(chkid + "-" + i).disabled = bStatus;
		if(bStatus){ document.getElementById(chkid + "-" + i).checked = false; };
		debugger;
	};
}



function AddRemoveCost(sChk, Cost) {
		if(!document.getElementById(sChk).checked) { 
			document.getElementById(sChk).checked = false;
			TotalAmount = TotalAmount - Cost;
		} else {
			TotalAmount = TotalAmount + Cost;
		}
		
	TotalCost(TotalAmount);
}

function TotalCost(Total){
	document.getElementById("divTotalCost").innerHTML = formatCurrency(Total);
	document.getElementById("divTotalCost2").innerHTML = formatCurrency(Total);  // divTotalCost2 is for display only.
	document.getElementById("hidTotalCost").value = Total;
	if(document.getElementById("divTotalCost").innerHTML == "-$0.00") {document.getElementById("divTotalCost").innerHTML = "$0.00"; document.getElementById("divTotalCost2").innerHTML = "$0.00"};
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}





// ##########################################
// PAYMENT INFO

function SameAsCompanyAddress() {
	document.CheckOut.BillingAddress1.value = sStreet1;
	document.CheckOut.BillingAddress2.value = sStreet2;
	document.CheckOut.BillingCity.value = sCity;
	document.CheckOut.BillingState.value = sState;
	document.CheckOut.BillingZip.value = sZipCode;

}

function checkFields() {
	var co = window.document.CheckOut
	missinginfo = '';
	if(co.CCardType.value == '') {
	missinginfo += "\n     -  Credit Card Type";
	}
	if(co.CCNumber.value == '') {
	missinginfo += "\n     -  Credit Card Number";
	}
	if(co.ExpirationMonth.selectedIndex == '') {
	missinginfo += "\n     -  Expiration Date";
	}
	if(co.ExpirationYear.selectedIndex == '') {
	missinginfo += "\n     -  Expiration Date";
	}
	
	if (missinginfo != '') {
		missinginfo ="_____________________________\n" +
		"You complete the following required fields:\n" +
		missinginfo + "\n_____________________________" +
		"\nPlease correct and submit again.";
		alert(missinginfo);
		return false;
	} else {

		if (isValidCreditCard(co.CCardType.value, co.CCNumber.value)) {
			return CheckForm();
			//return true;
		} else {
			alert('This does not appear to be a valid credit card number. \n Please check the number and submit the form again.')	
			return false;
		}
	}
}

function isValidCreditCard(type, ccnum) {
   	if (type == "VS") {
      	var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   	} else if (type == "MC") {
      	var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   	} else if (type == "DV") {
      	var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   	} else if (type == "AX") {
    	var re = /^3[4,7]\d{13}$/;
	}
   if (!re.test(ccnum)) return false;
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   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 CheckForm() {
	var co = window.document.CheckOut
	co.CCNumber.value = RemoveBad(co.CCNumber.value);
return true;
}
function RemoveBad(strTemp) {
    strTemp = strTemp.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,"");
    return strTemp;
}
