//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Old Browser detected, You should consider updgrading!");
	}
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Starts the AJAX request.
function searchEmail(email) {
	

	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		
		   if (email != ''){
		   document.getElementById('show_form').style.display = 'inline'; 
		 
		 
		   var str = escape(document.getElementById('email').value);
		   searchReq.open("GET", 'ajax/check_email.php?email=' + str, true);
		   searchReq.onreadystatechange = handleUserDetails; 
		   searchReq.send(null);
		   }else{
		   alert('Please enter your email address');
		   }


	}		
}

//Called when the AJAX response is returned.
function handleUserDetails() {
	if (searchReq.readyState == 4) {

			var str = searchReq.responseText;


			//spilt string returned from database query into different variables and then populate form	
			 document.getElementById('contact').value = str.slice(str.indexOf("xcontactx")+9,str.indexOf("ycontacty"));
			 document.getElementById('address').value = str.slice(str.indexOf("xaddressx")+9,str.indexOf("yaddressy"));
			 document.getElementById('suburb').value = str.slice(str.indexOf("xsuburbx")+8,str.indexOf("ysuburby"));
			 document.getElementById('city').value = str.slice(str.indexOf("xcityx")+6,str.indexOf("ycity"));
			 document.getElementById('pcode').value = str.slice(str.indexOf("xpcodex")+7,str.indexOf("ypcodey"));
			 document.getElementById('phone').value = str.slice(str.indexOf("xphonex")+7,str.indexOf("yphoney"));
	         document.getElementById('fax').value = str.slice(str.indexOf("xfaxx")+5,str.indexOf("yfaxy"));
			 document.getElementById('daddress').value = str.slice(str.indexOf("xdaddressx")+10,str.indexOf("ydaddressy"));
			 document.getElementById('dsuburb').value = str.slice(str.indexOf("xdsuburbx")+9,str.indexOf("ydsuburby"));
			 document.getElementById('dcity').value = str.slice(str.indexOf("xdcityx")+7,str.indexOf("ydcity"));
			 document.getElementById('dpcode').value = str.slice(str.indexOf("xdpcodex")+8,str.indexOf("ydpcodey"));
			
						
			//select state & delievery state option below
			var sel=document.place_order.astate;
				for(var i=0;i<sel.options.length;i++){
					if(sel.options[i].value== str.slice(str.indexOf("xstatex")+7,str.indexOf("ystatey"))){
					  sel.selectedIndex=i;
					}
				}

			var sel2=document.place_order.dstate;
				for(var j=0;j<sel2.options.length;j++){
					if(sel2.options[j].value==str.slice(str.indexOf("xdstatex")+8,str.indexOf("ydstatey"))){
					  sel2.selectedIndex=j;
					}
				}
	
	}
}