//global page variables
var calcCars = new Array();
//var calcCarsTypes = new Array('Small', 'Medium (4cyl)','Medium (6cyl)','Large (6cyl)','Large (8cyl)','4WD');
var calcCarsTypeCodes = new Array('SMALL', 'MEDIUM4','MEDIUM6','LARGE6','LARGE8','4WD');
var calcCarsText = new Array('Toyota Corolla or similar','Honda Accord Euro or similar','Subaru Liberty or similar','Holden Commodore SV6 or similar','Holden Commodore SS V or similar','Toyota LandCruiser Prado or similar');

	//collect data from the form
	var carType, annualSalary, carValue, leaseLength, kmsTravelled, state, output;

//submit the form contents
function processQuote(theURL, noScroll, noBlockUI, config, callback){
	
	if(theURL == null || theURL == ""){
		theURL = "Form";
	}
		
	//collect data from the form
	carType = document.getElementById("carType");
	annualSalary = document.getElementById("annualSalary");
	carValue = document.getElementById("carValue");
	leaseLength = document.getElementById("leaseLength");
	kmsTravelled = document.getElementById("kmsTravelled");
	state = document.getElementById("state");
	output = document.getElementById('novatedCalculatorOutput');

	var xml = getXhttp( );
    if (!xml){
		output.innerHTML = "<p class=\"error\">We are unable to provide you with an on-line estimate at this time. Please contact ORIX Australia for assistance!!</p>";
		return false;
	}

	if(carType==null||carType.value.length==0){
		redAlert("<h1>Car Type must be selected</h1>");
		return false;
    }
	
	if(annualSalary==null||annualSalary.value.length==0){
		redAlert("<h1>Annual Salary must be specified</h1>");
		annualSalary.focus();
		return false;
    }

	if(carValue==null||carValue.value.length==0){
		redAlert("<h1>Car Value must be specified</h1>");
		carValue.focus();
		return false;
    }

	if(leaseLength==null||leaseLength.value.length==0){
		redAlert("<h1>Lease Length must be specified</h1>");
		leaseLength.focus();
		return false;
    }
	
	if(kmsTravelled==null||kmsTravelled.value.length==0){
		redAlert("<h1>Travel Distance must be specified</h1>");
		kmsTravelled.focus();
		return false;
    }
	
	if(state==null||state.value.length==0){
		redAlert("<h1>State of Use must be specified</h1>");
		state.focus();
		return false;
    }
	
	if (!noBlockUI) showPleaseWait();
	
	//filter values
	var strParams = 'carType=' + carType.value 
					 + '&annualSalary=' + annualSalary.value 
					 + '&carValue=' + carValue.value 
					 + '&leaseLength=' + leaseLength.value
					 + '&kmsTravelled=' + kmsTravelled.value
					 + '&state=' + state.value;
	if (config instanceof Object) {
		for (var key in config) {
			strParams += "&" + key + "=" + config[key];
		}
	}
	var params = filterStr(strParams);
	var status = "start";
	//prepare the submit string
	xml.open('POST', '/_out/'+theURL+'.html',true);
	//make sure to add following header to dynamically generated page!!
	//<META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="-1">
    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xml.send(params);

	//wait for the response
	xml.onreadystatechange = function() {
        if (xml.readyState == 4){
			if(xml.status == 200){
				//show results
				output.innerHTML = xml.responseText;
				status = "success";
			}else{
				//some error ocurred, display generic error
				output.innerHTML = "<p class=\"error\">We are unable to provide you with an on-line estimate at this time. Please contact ORIX Australia for assistance!!</p>";
				status = "failed";
			}
			//hide Please Wait message and enable page
			if (!noBlockUI) hidePleaseWait();	
		}
		
		//scroll to the results section on the page
		if (!noScroll) new Effect.ScrollTo('novatedCalculatorOutputAnchor');	
		if (typeof(callback) == "function") callback(status);
	}//END onreadystatechange

}

			
//check user inout while he types and make sure he types in digits only!! (no chars or symbols)
function checkForInt(evt){
	var charCode = ( evt.which != null ) ? evt.which : event.keyCode
	return (charCode < 32 || (charCode >= 48 && charCode <= 57))
}

function showPleaseWait() {
	//blocking user input + showing PLEASE WAIT message
	jQuery.blockUI()
}

function hidePleaseWait() {
	//unblocking user input + hiding PLEASE WAIT message
	jQuery.unblockUI();
}

hidePleaseWait = function(){
	//unblocking user input + hiding PLEASE WAIT message
	jQuery.unblockUI();
}

//preload images
function loadCarData(){

	var preload_image_object = new Image();
    
	// set image url
    calcCars = new Array();
    calcCars[0] = "/_images/novated-leasing/calculator/0.jpg";
    calcCars[1] = "/_images/novated-leasing/calculator/1.jpg";
    calcCars[2] = "/_images/novated-leasing/calculator/2.jpg";
    calcCars[3] = "/_images/novated-leasing/calculator/3.jpg";
    calcCars[4] = "/_images/novated-leasing/calculator/4.jpg";
    calcCars[5] = "/_images/novated-leasing/calculator/5.jpg";

	for(i=0; i<6; i++) 
    	preload_image_object.src = calcCars[i];
}

//process selection of different car type
function carTypeChange(arrayIndex){
	var imageHolder = document.getElementById("carTypeImage");
	var textHolder = document.getElementById("carTypeText");
	var valueHolder = document.getElementById("carType");
	var carTypeList = document.getElementById('carTypeList').getElementsByTagName('li');

	for(i = 0; i < carTypeList.length; i++){
		if(i == arrayIndex){
			carTypeList[i].style.fontWeight = "bold";
			carTypeList[i].style.color = "#D00825";
		}else{
			carTypeList[i].style.fontWeight = "";
			carTypeList[i].style.color = "";
		}
	}
	//repopulate the value
	valueHolder.value = calcCarsTypeCodes[arrayIndex];
	
	//replace existing image with selected
	imageHolder.src = calcCars[arrayIndex];
	textHolder.innerText = textHolder.textContent = calcCarsText[arrayIndex];
	//fade out new image
	opacity("carTypeImage",0,100,300);
}

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
	return true;
} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
}


//display dynamically obtained Residual Values Data Table
function displayData(srcTable,displayArea){
	var output = document.getElementById(displayArea);
	var xml = getXhttp( );
    
	if (!xml){
			output.innerHTML = "<p class=\"error\">Could not obtain the latest Residual Value figures. Please contact ORIX via Contact Us page.</p>";
	}else{
		
		//prepare the submit string
		xml.open('POST', '/_out/'+srcTable+'.html',true);
		//make sure to add following header to dynamically generated page!!
	    xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xml.send('');

		//wait for the response
		xml.onreadystatechange = function() {
      		if (xml.readyState == 4){
				if(xml.status == 200){
					//show results
					output.innerHTML = xml.responseText;
				}else{
					//some error ocurred, display returned error text
					output.innerHTML = "<p class=\"error\">Could not obtain the latest Residual Value figures. Please contact ORIX via Contact Us page.</p>";		
				}
			}
		}//END onreadystatechange
	}
}

function proceedWithQuotation(theURL, blankForm) {
	if (!theURL) {
		theURL = "ProcessForm";
	}
	var selector = "#novatedPageOutput";
	showPleaseWait();
	var submitData = null;
	if (!blankForm) {
		submitData = {
			"carType": carType.value,
			"annualSalary": annualSalary.value,
			"carValue": carValue.value,
			"leaseLength": leaseLength.value,
			"kmsTravelled": kmsTravelled.value,
			"state": state.value,
			"withList": "true"
		};
	}
	jQuery.ajax({
		type: "POST",
		url: "/_out/" + theURL + ".html",
		data: submitData,
		dataType: "html",
		success: function(data) {
			jQuery(selector).html(data);

			//setup calendars
			Calendar.setup({ inputField : "regoExpiry", button : "pickRegoExpiry", ifFormat : "%e/%m/%Y", align : "Br", singleClick : true, weekNumbers : false,showOthers : true });
			Calendar.setup({ inputField : "dateOfManufacture", button : "pickManufDate", ifFormat : "%e/%m/%Y", align : "Br", singleClick : true, weekNumbers : false,showOthers : true });	
			hidePleaseWait();	
		},
		error: function() {
			jQuery(selector).html("<p class=\"error\">Could not load Quotation Request Form. Please contact ORIX via Contact Us page.</p>");
			hidePleaseWait();	
		}
  	});
}

//toggle visibility of the selected div
function showMoreFields(selectedValue,targetGroupName){
	var targetGroup = getElementsByClassName(document,"div",targetGroupName);

	if(targetGroup != null && selectedValue != null && selectedValue != ""){
		//traverse through target group and determine which block to expand and which to collapse.
		for(i = 0; i < targetGroup.length; i++){
			if((selectedValue == targetGroup[i].id) && (targetGroup[i].style.display == "none")){
				Effect.SlideDown(targetGroup[i].id, { duration: 0.3 });
			}else if((targetGroup[i].style.display != "none") && (selectedValue != targetGroup[i].id)){
				Effect.SlideUp(targetGroup[i].id, { duration: 0.1 });
			}
		}
	}
}

function populateDD(dropDownURL,sourceArea,targetArea,params){
	document.getElementById(targetArea).disabled = false;
	
	new AjaxJspTag.Select('/_out/'+dropDownURL+'.html', {
						  parameters: params,
						  parser: new ResponseXmlParser(),
						  target: targetArea,
						  executeOnLoad: 'true',
						  preFunction: showPleaseWait, 
						  postFunction: hidePleaseWait, //resetField('make,model,series,option1,option2,option3,option4'),
						  defaultOptions: '',
						  source: sourceArea,
						  eventType: 'onchange',
						  errorFunction: reportError
						  });
}

function populateArea(dropDownURL,sourceArea,targetArea,params){
	document.getElementById(targetArea).disabled = false;

	new AjaxJspTag.HtmlContent('/_out/'+dropDownURL+'.html', {
						  parameters: params,
						  target: targetArea,
						  preFunction: showPleaseWait, 
						  postFunction: hidePleaseWait, //resetField('make,model,series,option1,option2,option3,option4'),
						  source: sourceArea,
						  errorFunction: reportError
						  });
}

var ddBoxes = new Array('reset','leaseType','make','model','series','optionalAccessories');

//when being populated or cleared, we need to reset the dropdowns + other related fields
function resetDD(initiator){
	//define the flag which will be set when clearing of boxes should start
	var startClearing = false;
	
		for(i = 0; i < ddBoxes.length; i++){
			if(initiator.id == ddBoxes[i]){
				//after the current element - initiator - we should clear all elements referenced in the array
				startClearing = true;
			}else if(startClearing == true){
				var curElement = document.getElementById(ddBoxes[i]);
				
				if(curElement != null){
					if(curElement.id == "optionalAccessories"){
						//if its our html area, clear it
						curElement.innerHTML = "&nbsp;";
					}else{
						//its a dropdown, just select default and disable it.
						curElement.selectedIndex = 0;
						curElement.disabled = true;
					}
				}
			}
			
		}
}

function clearDynamicElements(obj){
	//clear drowdowns
	resetDD(obj);
	
	//enable initial dropdown
	document.getElementById(ddBoxes[1]).disabled = false;
	
	//hide additional fields for insurance
	showMoreFields("null","insuranceMore");

	//hide additional fields for insurance
	showMoreFields("null","carCondition");

	return true;
}

function reportError(){
	if ($('model').options.length == 0){
		$('errorMsg').innerHTML = "Dropdown failed to load. Please reload the page.";
	}
	Element.show('errorMsg');
	setTimeout("Effect.DropOut('errorMsg')", 2500);
}

//function that sends quote request data
function submitQuoteRequest(theURL){
	//collect data from the form
	var orixPrevAccount = document.getElementById("orixPrevAccount");
	var fullName = document.getElementById("fullName");
	var streetAddress = document.getElementById("streetAddress");
	var suburb = document.getElementById("suburb");
	var state = document.getElementById("state");
	var postcode = document.getElementById("postcode");

	var workPhone = document.getElementById("workPhone");
	var homePhone = document.getElementById("homePhone");
	var mobile = document.getElementById("mobile");
	var email = document.getElementById("email");

	var employer = document.getElementById("employer");
	var jobTitle = document.getElementById("jobTitle");
	var costCentre = document.getElementById("costCentre");
	var annualSalary = document.getElementById("annualSalary");
	var serviceLengthYears = document.getElementById("serviceLengthYears");
	var serviceLengthMonths = document.getElementById("serviceLengthMonths");
	
	var leaseType = document.getElementById("leaseType");
	var term = document.getElementById("term");
	var annualKms = document.getElementById("annualKms");
	var insuranceOptions = buildValuesArray(getElementsByClassName(document, "input", "insurance"));
	var noClaimBonus = document.getElementById("noClaimBonus");
	var annualPremium = document.getElementById("annualPremium");
	
	var make = document.getElementById("make");
	var model = document.getElementById("model");
	var series = document.getElementById("series");
	var optionalAccessories = getElementsByClassName(document, "input", "optionalAccessories");
	var customAccessories = document.getElementById("customAccessories");
	var stateOfUse = document.getElementById("stateOfUse");
	
	var regoNumber = document.getElementById("regoNumber");
	var regoExpiry = document.getElementById("regoExpiry");
	var currentOdo = document.getElementById("currentOdo");
	var dateOfManufacture = document.getElementById("dateOfManufacture");
	var purchasePrice = document.getElementById("purchasePrice");
	var sellerName = document.getElementById("sellerName");
	var sellerContactPhone = document.getElementById("sellerContactPhone");
	
	var sendtome = document.getElementById("sendtome");
	var isInitPage = document.getElementById("isInitPage");
	var output = document.getElementById('novatedPageOutput');
	var errorMsg = document.getElementById('errorMsg');

	
	var xml = getXhttp( );
    if (!xml){
		output.innerHTML = "<p class=\"error\">We are unable to provide you with an on-line estimate at this time. Please call ORIX Australia for assistance!!</p>";
		return false;
	}

	if(fullName.value.length==0){
		Application.displayFormErrorMessage("Full Name must be specified");
		Application.setElementError(fullName);
		return false;
    } else {
		Application.removeElementError(fullName);
	}
	
	if(workPhone.value.length==0){
		Application.displayFormErrorMessage("Work Phone must be specified");
		Application.setElementError(workPhone);
		return false;
    } else {
		Application.removeElementError(workPhone);
	}
	if(email.value.length==0){
		Application.displayFormErrorMessage("Email must be specified");
		Application.setElementError(email);
		return false;
    } else if (!Application.isValidEmail(email.value)) {
		Application.displayFormErrorMessage("Please provide a valid email address");
		Application.setElementError(email);
		return false;
	} else {
		Application.removeElementError(email);
	}

	if(employer.value.length==0){
		Application.displayFormErrorMessage("Employer must be specified");
		Application.setElementError(employer);
		return false;
    } else {
		Application.removeElementError(employer);
	}

	if(leaseType.value.length==0 || leaseType.selectedIndex==0){
		Application.displayFormErrorMessage("Lease Type must be selected");
		Application.setElementError(leaseType);
		return false;
    } else {
		Application.removeElementError(leaseType);
	}
	
	if(term.value.length==0 || term.selectedIndex==0){
		Application.displayFormErrorMessage("Lease Term must be selected");
		Application.setElementError(term);
		return false;
    } else {
		Application.removeElementError(term);
	}
	
	if(annualKms.value.length==0){
		Application.displayFormErrorMessage("Annual Travel must be specified");
		Application.setElementError(annualKms);
		return false;
    } else {
		Application.removeElementError(annualKms);
	}

	if(make.selectedIndex==0){
		Application.displayFormErrorMessage("Car Make must be selected");
		Application.setElementError(make);
		return false;
    } else {
		Application.removeElementError(make);
	}
	
	if(model.selectedIndex==0){
		Application.displayFormErrorMessage("Car Model must be selected");
		Application.setElementError(model);
		return false;
    } else {
		Application.removeElementError(model);
	}
	
	if(series.selectedIndex==0){
		Application.displayFormErrorMessage("Car Series must be selected");
		Application.setElementError(series);
		return false;
    } else {
		Application.removeElementError(series);
	}

	if(stateOfUse.selectedIndex == 0){
		Application.displayFormErrorMessage("State of Use must be selected");
		Application.setElementError(stateOfUse);
		return false;
	} else {
		Application.removeElementError(stateOfUse);
	}
	
	showPleaseWait();
	
	//filter values
	var params = filterStr('fullName=' + fullName.value
						 +'&streetAddress=' + streetAddress.value
						 +'&suburb=' + suburb.value
						 +'&state=' + state.value
						 +'&postcode=' + postcode.value
						 +'&workPhone=' + workPhone.value
						 +'&homePhone=' + homePhone.value
						 +'&mobile=' + mobile.value
						 +'&email=' + email.value
						 +'&employer=' + employer.value
						 +'&jobTitle=' + jobTitle.value
						 +'&costCentre=' + costCentre.value
						 +'&annualSalary=' + annualSalary.value
						 +'&serviceLengthYears=' + serviceLengthYears.value
						 +'&serviceLengthMonths=' + serviceLengthMonths.value
						 +'&leaseType=' + leaseType.value
						 +'&term=' + term.value
						 +'&annualKms=' + annualKms.value
						 +'&insuranceOptions=' + insuranceOptions
						 +'&noClaimBonus=' + noClaimBonus.value
						 +'&annualPremium=' + annualPremium.value
						 +'&make=' + make[make.selectedIndex].text
						 +'&model=' + model[model.selectedIndex].text
						 +'&series=' + series[series.selectedIndex].text
						 +'&optionalAccessories=' + buildValuesArray(optionalAccessories)
						 +'&customAccessories=' + customAccessories.value
						 +'&stateOfUse=' + stateOfUse.value
						 +'&regoNumber=' + regoNumber.value
						 +'&regoExpiry=' + regoExpiry.value
						 +'&currentOdo=' + currentOdo.value
						 +'&dateOfManufacture=' + dateOfManufacture.value
						 +'&purchasePrice=' + purchasePrice.value
						 +'&sellerName=' + sellerName.value
						 +'&sellerContactPhone=' + sellerContactPhone.value
						 +'&sendtome=' + sendtome.checked
						 +'&isInitPage=' + isInitPage.value
					     +'&orixPrevAccount=' + orixPrevAccount.checked
						 );
	//prepare the submit string
	xml.open('POST', '/_out/'+theURL+'.html',true);
	//make sure to add following header to dynamically generated page!!
	//<META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="-1">
    
	xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xml.send(params);

	//wait for the response
	xml.onreadystatechange = function() {
        if (xml.readyState == 4){
			
			if(xml.status == 200){
				//show results
				var followUpMessage = "";
				if (window.opener) {
					followUpMessage = '<br/>You can either submit another quote or <a href="#" onclick="window.close(); return false;">close this window.</a>';
				} else {
					followUpMessage = '<br/>Please change the form and submit another quote if required.';
				}
				Application.displayFormSuccessMessage(xml.responseText + followUpMessage, "", true);
			}else{
				//some error ocurred, display returned error text
				//populate and unhide error area	
				Application.displayFormErrorMessage(xml.responseText);

	
			}
			//hide Please Wait message and enable page
			hidePleaseWait();	
		}
		//scroll to the results section on the page
		new Effect.ScrollTo('novatedPageOutputAnchor');	
	}//END onreadystatechange
}

//highlight the row when mouse is hovered over it
function rowHover(i){
	var currentRow = document.getElementById("acsRow"+i);
	currentRow.className = "rowHover";
}

//Remove highlight on mouse out (only if corresponding checkbox is not ticked
function rowOut(i){
	var currentRow = document.getElementById("acsRow"+i);
	var currentChkbx = document.getElementById("chkBox"+i);
	
	if(currentChkbx.checked == false){
		currentRow.className = "rowPlain";			
	}else{
		currentRow.className = "rowHighlighted";			
	}
}

//highlight/remove_highlight of the entire row and tick/untick the checkbox when the entire row is clicked
function rowClick(i){
	var currentRow = document.getElementById("acsRow"+i);
	var currentChkbx = document.getElementById("chkBox"+i);

	//check if row is selected (checkbox ticked) already	
	if(currentChkbx.checked == false){
		//not ticked - then tick it
		currentChkbx.checked = true;
		currentRow.className = "rowHighlighted";			
	}else{
		//ticked - remove tick and highlight
		currentChkbx.checked = false;
		currentRow.className = "rowPlain";			
		
	}
}

function printEstimate() {
	Application.openCenteredWindow("print-estimate.html", jQuery("#contentMainArea").width() + 50, 500, null, "calculatorEstimate", function(win) {

	});
}