 /*
 * Returns an new XMLHttpRequest object, or false if the browser
 * doesn't support it
 */
function newXMLHttpRequest() {

	var xmlreq = false;

	// Create XMLHttpRequest object in non-Microsoft browsers
	if(window.XMLHttpRequest){
		xmlreq = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		try {
			// Try to create XMLHttpRequest in later versions
			// of Internet Explorer
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e1){
			// Failed to create required ActiveXObject
			try {
				// Try version supported by older versions
				// of Internet Explorer
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				// Unable to create an XMLHttpRequest by any means
				xmlreq = false;
			}
		}
	}
	
	return xmlreq;
}

 /*
	* Returns a function that waits for the specified XMLHttpRequest
	* to complete, then passes it XML response to the given handler function.
  * req - The XMLHttpRequest whose state is changing
  * responseXmlHandler - Function to pass the XML response to
  */
 function getReadyStateHandler(req, responseXmlHandler, postcode) {

   // Return an anonymous function that listens to the XMLHttpRequest instance
   return function () {

     // If the request's status is "complete"
     if (req.readyState == 4) {
       
       // Check that we received a successful response from the server
      if (req.status == 200) {

         // Pass the XML payload of the response to the handler function.
         responseXmlHandler(req.responseText, postcode);

       } else {

         // An HTTP problem has occurred
        //alert("HTTP error "+req.status+": "+req.statusText);
      }
     }
   }
 }


var deliveryDateLinkText = "<a href=\"#\" onclick=\"javascript: getDeliveryDates(); return false;\">Check</a>";
var deliveryDateLinkTextBusy = "<img src=\"/siteimages/ajax-loader.gif\" height=\"16\" width=\"16\" alt=\"Loading\" />"; 

// In Stock version

function getDeliveryDates(itemno){
	
	if(document.getElementById('postcode').value.length > 0){
		document.getElementById('getDeliveryDates').innerHTML = deliveryDateLinkTextBusy;
		
		var postcode = document.getElementById('postcode').value;

		var req = newXMLHttpRequest();
		req.open("GET", "/services/picklist/postcode/postcode/" + postcode + "/item/" + itemno);
		req.onreadystatechange = getReadyStateHandler(req, updateSlot, postcode);
		req.send(null);
	}else{
		alert('Please enter a postcode to get a list of possible delivery dates.');
	}
	
}

function updateSlot(input, postcode) {

	var output = "";
	
	// convert the string to an XML object
	//var xmlobject = (new DOMParser()).parseFromString(input, "text/xml");
	
	try{ //Internet Explorer
		xmlobject=new ActiveXObject("Microsoft.XMLDOM");
		xmlobject.async="false";
		xmlobject.loadXML(input);
	}catch(e){
		try{ //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlobject=parser.parseFromString(input,"text/xml");
		}catch(e){
			alert(e.message)
		}
	}

	try{
		var status = xmlobject.getElementsByTagName('Status')[0];
		var root = xmlobject.getElementsByTagName('Runs')[0];
		
		if(root.hasChildNodes()) {
			
			var numFound = 0;
			for(var i=0; i<root.childNodes.length; i++){
	        	var run = root.childNodes[i];
	        	if(run.hasChildNodes()){
	        		var date = run.childNodes[1].firstChild.nodeValue;
					
					output += "<li>" + date + "</li>";
					numFound++;
					if(numFound >= 3){
						break;
					}
	        	}
			}
			
		}
	
	}catch(exception){
	
		document.getElementById('delivery-date-question').innerHTML = "";
		document.getElementById('delivery-date-question').style.display = "none";
		document.getElementById('postcodeResult').innerHTML = "This feature is temporarily unavailable.";
		return;
	}
	
	
	if(output.length > 0){
	
		document.getElementById('delivery-date-question').innerHTML = "";
		document.getElementById('delivery-date-question').style.display = "none";
		
		
		document.getElementById('postcodeResult').innerHTML = "The next three available delivery dates for <strong>" + postcode.toUpperCase() + "</strong> are:"; 
		document.getElementById('postcodeResult').innerHTML += "<ul>" + output + "</ul>";
		document.getElementById('delivery-date-info').style.display = "inline";
		
	}else{
	
		//status null means
		//status 0 means not in database
		//status 1 means in database so we must not deliver there 
		
		if(typeof status != 'undefined'){
			status = status.firstChild.nodeValue;
		}else{
			status = null;
		}

		if(status == null || status == 0){
			document.getElementById('postcodeResult').innerHTML = "<p>The postcode you entered appears to be invalid.</p>";
		}else{
			document.getElementById('postcodeResult').innerHTML = "<p>We don't deliver to this postcode.</p>";
		}
		
		document.getElementById('getDeliveryDates').innerHTML = deliveryDateLinkText;
	}

}

// No Stock version

function getDeliveryDatesNoStock(itemno){
	
	if(document.getElementById('postcode').value.length > 0){
		document.getElementById('getDeliveryDates').innerHTML = deliveryDateLinkTextBusy;
		
		var postcode = document.getElementById('postcode').value;

		var req = newXMLHttpRequest();
		req.open("GET", "/services/picklist/postcode/postcode/" + postcode + "/item/" + itemno);
		req.onreadystatechange = getReadyStateHandler(req, updateSlotNoStock, postcode);
		req.send(null);
	}else{
		alert('Please enter a postcode to get a list of possible delivery dates.');
	}
	
}


function updateSlotNoStock(input, postcode) {

	var output = "";
	
	// convert the string to an XML object
	//var xmlobject = (new DOMParser()).parseFromString(input, "text/xml");
	
	try{ //Internet Explorer
		xmlobject=new ActiveXObject("Microsoft.XMLDOM");
		xmlobject.async="false";
		xmlobject.loadXML(input);
	}catch(e){
		try{ //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlobject=parser.parseFromString(input,"text/xml");
		}catch(e){
			alert(e.message)
		}
	}

	try{
		var status = xmlobject.getElementsByTagName('Status')[0];
		var root = xmlobject.getElementsByTagName('Runs')[0];
		
		if(root.hasChildNodes()) {
			
			var numFound = 0;
			for(var i=0; i<root.childNodes.length; i++){
	        	var run = root.childNodes[i];
	        	if(run.hasChildNodes()){
					numFound++;
					if(numFound >= 3){
						break;
					}
	        	}
			}
		}
	} catch(exception) {
		document.getElementById('delivery-date-question').innerHTML = "";
		document.getElementById('delivery-date-question').style.display = "none";
		document.getElementById('postcodeResult').innerHTML = "This feature is temporarily unavailable.";
		return;
	}
	
	if(numFound > 0){
	
		document.getElementById('delivery-date-question').innerHTML = "";
		document.getElementById('delivery-date-question').style.display = "none";
		
		document.getElementById('postcodeResult').innerHTML = "The delivery estimate for this item is <strong>10-14 working days</strong> for <strong>" + postcode.toUpperCase() + "</strong>."; 
		document.getElementById('delivery-date-info').style.display = "inline";
		
	}else{
	
		//status null means
		//status 0 means not in database
		//status 1 means in database so we must not deliver there 
		
		if(typeof status != 'undefined'){
			status = status.firstChild.nodeValue;
		}else{
			status = null;
		}

		if(status == null || status == 0){
			document.getElementById('postcodeResult').innerHTML = "<p>The postcode you entered appears to be invalid.</p>";
		}else{
			document.getElementById('postcodeResult').innerHTML = "<p>We don't deliver to this postcode.</p>";
		}
		
		document.getElementById('getDeliveryDates').innerHTML = deliveryDateLinkText;
	}

}



function showDeliveryDateEstimator(){
	if(document.getElementById('delivery-date-question')){
		document.getElementById('delivery-date-question').style.display = "block";
	}
}

addLoadEvent(showDeliveryDateEstimator);



/**********************************************************************************************************************/
/* TABS */

var tabIds = Array;

tabIds[0] = 'warranties';
tabIds[1] = 'finance';

function toggleTabs(tabId){
	for(var tab in tabIds){
		if(tabIds[tab] == tabId){
			document.getElementById(tabIds[tab]).className = (tabIds[tab] + "-show");
			document.getElementById(tabIds[tab]+"-tab").className="extras-tab-"+((tab==0)?"left":"other")+"-active"; 
		}else{
			document.getElementById(tabIds[tab]).className = (tabIds[tab] + "-hide");
			document.getElementById(tabIds[tab]+"-tab").className="extras-tab-"+((tab==0)?"left":"other"); 
		}
	}
}
