/*
	(c)Copyright 2005 Ford Motor Company. All rights reserved.
*/

// ajax.js
// OR3161 - Use AJAX (asynchronous javascript techniques) to improve 
// site response times and user experience.
//
// NOTE: This file requires eSCAPE.js to be included in the HTML page as well.

var req;
var tabClicked = false;
var motorshow_scroll_pos= 0;
var notableFlag=false;
function startRequest(url) {
	
	startLoading();
	req = getXMLRequestObject();

	if (req) {
        req.onreadystatechange = processStateChange;
        req.open("GET", url, true);
	    sendXMLRequest(req);
	    return false;
    } else {
    	return true;
    }
}

function sendXMLRequest(obj) {
	if (window.XMLHttpRequest) { // Non-IE browsers
	  obj.send(null);
	} 
	else if (window.ActiveXObject) { // IE
	    obj.send();
    }
}

function getXMLRequestObject() {
	var obj;

	if (window.XMLHttpRequest) { // Non-IE browsers
	  obj = new XMLHttpRequest();
	  //req.overrideMimeType('text/xml')
	} 
	else if (window.ActiveXObject) { // IE
	  obj = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return obj;
}

function ajaxTab(currentViewID, targetViewID) {
	tabClicked = true;

	// Restore Motorshow scroll position
	try {
		var scrollContentDiv = getElementRef("scrollContent");
		if(!isUndefined(scrollContentDiv)) {
			scrollContentDiv.style.top = 0;
		}
	} catch(msex) {
		// Ignore this exception - we were unable to store the
		// scroll position of the Motorshow scrolling window
	}
	return startRequest("ajaxTab.do?currentViewID="+currentViewID +"&targetViewID="+targetViewID);
}

function ajaxConfig(button) {
	var frm=document.forms['configForm'];
	var currentViewID = frm.currentViewID.value;
	var mode = frm.selectMode;
	var url = "ajaxConfig.do?"+button.name+".x=1&"+button.name+".y=1&currentViewID="+currentViewID;
	if(mode!=null) { 
		url=url+"&selectMode="+mode.value; 
	}
	return startRequest(url);
}

function ajaxNotableReject(configStr) {
	var frm=document.forms['configForm'];
	var currentViewID = frm.currentViewID.value;
	
	return startRequest("ajaxConfig.do?currentViewID=" + currentViewID + "&targetViewID=" + currentViewID + "&rejectNotable=" + configStr);
}

function ajaxFinancePlanChange(plan, dealID) {	
	var url = "ajaxFinance.do?action=changePlan&dealID="+ dealID + "&planID=" + plan;	
	return startRequest(url);
}

function ajaxFinanceTermChange(term, dealID) {	
	var url = "ajaxFinance.do?action=changeTerm&dealID="+ dealID + "&term=" + term;	
	return startRequest(url);
}

function ajaxFinanceDistanceChange(distance, dealID) {
	var url = "ajaxFinance.do?action=changeDistance&dealID="+ dealID + "&distance=" + distance;	
	return startRequest(url);
}

function ajaxFinanceDepositSet(deposit, dealID) {		

	var url = "ajaxFinance.do?action=setDeposit&dealID="+ dealID + "&depositInput=" + deposit;	

	return startRequest(url);
}

function ajaxFinanceDepositSetEvent(deposit, dealID, e) {		
	var url = "ajaxFinance.do?action=setDeposit&dealID="+ dealID + "&depositInput=" + deposit;	

	if (!e) e = window.event;
	characterCode = (e.keyCode) ? e.keyCode : e.which;	
	
	if(characterCode == 13) {
			return startRequest(url);
	}else{
		return true;
	}	
}

function ajaxFinanceDeposit(deposit, dealID) {		

	var frm=document.forms['financeForm'];

	var url = "ajaxFinance.do?action=changeDeposit&dealID="+ dealID + "&depositInput=" + deposit;	

	return startRequest(url);
}

function ajaxFinanceDepositChange(deposit, dealID, e) {		

	var frm=document.forms['financeForm'];

	var url = "ajaxFinance.do?action=changeDeposit&dealID="+ dealID + "&depositInput=" + deposit;	

	if (!e) e = window.event;
	characterCode = (e.keyCode) ? e.keyCode : e.which;	
	
	if(characterCode == 13) {
			return startRequest(url);
	}else{
		return true;
	}	
}

//  check for valid numeric strings	
function IsNumeric(strString)
{
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}



function processStateChange() {
   	if (req.readyState == 4) { // Complete
    	if (req.status == 200) { // OK response

			var dom = req.responseXML;
	
			// If response is non-XML, simply overwrite the current
			// document contents with what was received (html expected).
			// This caters for displaying fatal error pages, for example.
			if(dom==null || !dom.hasChildNodes()) {
				document.write(req.responseText);
			} else {
	
				// ----------------------------
				// Process start JavaScript
				// ----------------------------
				processJavaScript("start", dom);
	
	
				// --------------------------
				// Update graphic
				// --------------------------
				try {
					var graphicElem = dom.getElementsByTagName("graphic")[0];
					var alt = graphicElem.getAttribute("alt");
					var imagePath=graphicElem.firstChild.nodeValue;
					var summaryImage = getElementRef("summaryImage");
					if(summaryImage!=null) {
				        summaryImage.src = imagePath;
			    	    summaryImage.alt = alt;
			        	summaryImage.title = alt;
					}
				}	
				catch(ex) {
					// If there is an exception, continue anyway since there may not
					// be a graphic element in the returned XML. This caters for
					// the AJAX Error page which simply displays an error notable.
				}	
	
				// ----------------------------
				// Update HTML
				// ----------------------------
				var i;
				for(i=0; i<dom.getElementsByTagName("html").length; i++) {
					var htmlElem = dom.getElementsByTagName("html")[i];
	
					
					// Handle empty tags e.g. <html id="x"></html>
					var html = "";
					if(htmlElem.firstChild) {
						html = htmlElem.firstChild.nodeValue;
					}
					
					var id   = htmlElem.getAttribute("id");
					var tag  = getElementRef(id);
					if(!isUndefined(tag)) {
						tag.innerHTML = html;
					}
				}
				
				// ----------------------------
				// Process end JavaScript
				// ----------------------------
				processJavaScript("end", dom);

			}
		} else {
			// If the request status returned was not 200 (OK), display the
			// standard locale-specific error page, since the request 
			// cannot be processed.
			document.location = "error.do";
		}
		
		finishLoading();
	}	
}

function startLoading() {
	try {
		var scrollContentDiv = getElementRef("scrollContent");
		if(!isUndefined(scrollContentDiv)) {
			motorshow_scroll_pos = scrollContentDiv.style.top;
		}
	} catch(msex) {
		// Ignore this exception - we were unable to store the
		// scroll position of the Motorshow scrolling window
	}
	try {
		// Clear the current session timeout timers since the user is active.
		// IMPORTANT NOTE: The variables used here are declared in sessionTimeout.jsp, 
		// so it is important that these are maintained here in current form, 
		// unless appropriate changes are also made to the declarations	
		clearTimeout(warningHandle);
		clearTimeout(timeoutHandle);
		showHourglassLayer();
		hourglassHandle = setTimeout("showLoading()", 2000); // was 750
	} catch(ex) {
		// Do not worry if its not possible to display loading messages etc
		// Some layout.jsp's do not include all the layers.
	}
}
function ajaxNotable(flag){
	if(flag==true){
	notableFlag=true;
	} else {
	notableFlag=false;
	}
}
function finishLoading() {
	// If tab buttons or back and next buttons are clicked the content of the tabs are forced to scroll to top
	if (tabClicked)
	{
		var contentdivId = getElementRef("contentdiv");
		if(!isUndefined(contentdivId))
		{
		    contentdivId.scrollTop = 0;
		}
	    tabClicked = false;
	}

	// Motorshow
	try {
		var toplink = getElementRef("top_link");
		var bottomlink = getElementRef("bottom_link");

		var contentId = getElementRef("scrollContent");
		var viewId = getElementRef("scrollView");

		var contentHeight = contentId.offsetHeight;
		var viewHeight = viewId.offsetHeight;

		if(isUndefined(contentId.style.top) || contentId.style.top.length==0) {
			contentId.style.top="0px";
		}

		// Restore Motorshow scroll position
		contentId.style.top = motorshow_scroll_pos;

		var top=parseInt(contentId.style.top);

		if(contentHeight <= viewHeight) {
			// Up and Down buttons are not required if there is nothing to scroll up and down
			toplink.style.visibility = "hidden";
			bottomlink.style.visibility = "hidden";	
		} else if(top==0) {
			// Up button is not required if there is nothing to scroll up
			toplink.style.visibility = "hidden";
		}
	} catch(msex) {
		// Ignore this exception
	}

	try {
		hideLoading();
		
		var notable = getElementRef("infoLayer");
		var shaderDiv = getElementRef("shaderDiv");
		
		// If a Notable or other Info Box is present, do not hide
		// the Shader Div, to prevent users clicking on the main 
		// page when they should only be able to click on the Info Box
		if (isUndefined(notable)) {
			if (!isUndefined(shaderDiv)) {
		        //shaderDiv.style.zIndex = 5;
		        shaderDiv.style.visibility = "hidden";
	        }
		} else {
		
				if(notableFlag){
					shaderDiv.style.zIndex = 1;
					shaderDiv.style.visibility = "visible";
				} else {
				shaderDiv.style.visibility = "hidden";
				}
			// If on the Finance Tab (financeForm is present), hide
			// the shaderDiv
			/**var financeForm=document.forms['financeForm'];
			if (isUndefined(financeForm)) {
				shaderDiv.style.zIndex = 1;
			} else {	
				shaderDiv.style.visibility = "hidden";
	    	}*/
	    }
	} catch(ex) {
		// Do not worry if loading elements dont exist on the page
		// Some layout.jsp's do not include all the layers.
	}

	try {
		// Restart the session timeout timers.
		// IMPORTANT NOTE: The variables used here are declared in sessionTimeout.jsp, 
		// so it is important that these are maintained here in current form, 
		// unless appropriate changes are also made to the declarations	
		warningHandle = setTimeout("showSessionTimeoutWarningLayer()", warningTime);
		timeoutHandle = setTimeout(timeoutQS, timeoutTime);
	} catch(ex2) {
	}
	showScrollbar();
	document.body.style.cursor = "default";
	notableFlag=false;
}

function processJavaScript(when, dom) {
	var i;
	for(i=0; i<dom.getElementsByTagName("javascript").length; i++) {
		var jsElem = dom.getElementsByTagName("javascript")[i];

		// description used for information purposes only (e.g. debugging)
		var jsWhen = jsElem.getAttribute("when");
		
		if(jsWhen==when) {
			var jsDescription = jsElem.getAttribute("description");
			var js = jsElem.firstChild.nodeValue;
			try {
				eval(js);
			} catch(e) {
				// If the JavaScript fails to evaluate, ignore since this
				// is not a critical error (mainly affects rollover support
				// on the Colour and Trim tabs). Line below can be used for 
				// debugging, if necessary, by uncommenting.
				
				// alert("AJAX Error (" + jsDescription + ") " + e.message);
			}
		}
	}			
}

// This function can be used to include .js files
// It should be used by JSPs in place of the <script src=""/> tag.
function include(scriptpath) {
	var jsReq = getXMLRequestObject();
	jsReq.open('GET', scriptpath, false);
	sendXMLRequest(jsReq);
	eval(jsReq.responseText);
}

function isIE55() {
	//Detect IE5.5
	version=0
	if (navigator.appVersion.indexOf("MSIE")!=-1){
	temp=navigator.appVersion.split("MSIE")
	version=parseFloat(temp[1])
	}
	
	if (version>=5.5 && version <6.0) {
		return true;
	}
	return false;
}