//Writen by S Boylen - Copyright Re-Scan Ltd 2008
html_tmp = '<center><div class="popupClosebox large_text"><span class="link_background">&nbsp; <a href="javaScript:;" onClick="hideBox();" class="divHeaderSmallLink bold">Close <img src="images/icons/cross.gif" alt="close" border="0" /></a> &nbsp;</span> </div><div class="css_popup"><div id="popupArea"></div></div></center>';

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//Shows hidden div area
function showBox(aEancode){
	if (aEancode.lendth == 0) 
	{
	    return false;	
	}
    try
    {
	    //Get the Div Element
	    if(document.getElementById) {
		    var divObj = document.getElementById("displayArea");
	    } else if (document.all){
		    var divObj = document.all["displayArea"];
	    }
	      
       divObj.className = 'css_showme';
       divObj.innerHTML =  html_tmp;
       divPostioning("displayArea");

       ajaxRequest('productpopup.php?ean=' + aEancode,'popupArea','PRODUCT');
   }catch(e){}
   
   return false;
}

// Hides hidden div area
function hideBox(){
	try
    {
	    //Get the Div Element
	    if(document.getElementById) {
		    var divObj = document.getElementById("displayArea");
	    } else if (document.all){
		    var divObj = document.all["displayArea"];
	    }
	     
       divObj.className = 'css_hideme';
       divObj.innerHTML =  '';

   }catch(e){}
}

//Tests that the div id is on the current page and if not uses the defult one at the bottom of the footer
function testDivArea(l_testArea,l_backUpArea){
     try
     {
	     if(document.getElementById) {
		     var divObj = document.getElementById(l_testArea);
	     } else if (document.all){
		     var divObj = document.all[l_testArea];
	     }
	     // If the object is null then it is not on the current page, so skip the update to stop errors
		 if (divObj != null) { 
			 return  l_testArea;
		 }else{
		     return  l_backUpArea;	 
		 }  
     }catch(e){
	     return  l_testArea;    
     }	
}

//Make a call the the webserver, and output the result to the elementID
function ajaxRequest(XMLpage,elementID,aType){ 
	var req = null; 
	var dots = '.'
    try
    {
		
		if(document.getElementById) {
	        var divObj = document.getElementById(elementID);
        } else if (document.all){
	        var divObj = document.all[elementID];
        }
       // If the object is null then it is not on the current page, so skip the update to stop errors
		if (divObj != null) { 
			divObj.innerHTML="Please wait..";
		}

		//Get the Domms for the users Browser
		if(window.XMLHttpRequest){
			req = new XMLHttpRequest(); // for firefox
		}
		else if (window.ActiveXObject){
			try
			{
			    req  = new ActiveXObject(Microsoft.XMLHTTP); // for ie
		    }catch(e){
			    req  = new ActiveXObject('Msxml2.XMLHTTP');
		    }				
		}else{
			hideBox();
			disableAjax();
			alert('Sorry: your browser may not support this function, please reload the page. \n');
			return;	
		}
		
		// wait for response from server
		req.onreadystatechange = function()
		{ 
			if (divObj != null) { 
			     divObj.innerHTML="Please wait." + dots;
			    dots += '.'; //Add dots to the wait msg  
		    }
			if(req.readyState == 4)
			{
				if(req.status == 200)//200 = request ok
				{
				// do ajax calls	
									
					var doc = req.responseText;   // assign the file to a var

					// show the output to the screen
					if (divObj != null) { 
					     divObj.innerHTML =  doc;
				     }else{
					     alert('Unable to display results');   
				     }
					if (aType == 'ORDER') 
					{
						showResult(elementID,aType);
					}
				}		
			} 
		} 
		
		var d = new Date() ;// date to make url unique
		var time = d.getTime();
		var URLconnector = "?";
			if(XMLpage.toLowerCase().indexOf("?")!=-1){
				URLconnector ="&";
			}
			
		
		req.open("GET", XMLpage + URLconnector + "time=" + time, true); 
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		req.send(null); 
	}catch(e){
		//hideBox();
		alert('Warning: your browser may not support ajax. \n');	
	}
} 
	
	
//Find the correct place for the popup divPostioning("displayArea");
function divPostioning(aElementId){
    var winW = 630, winH = 460;
    var winY = 0;
    var yPadding = 70;
    
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape") {
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft")!=-1) {
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
         }
     }	
    if(document.getElementById) {
	    var divObj = document.getElementById(aElementId);
    } else if (document.all){
	    var divObj = document.all[aElementId];
    }
    
    //Get the width of the div (or use defult if its null)
    var divW = divObj.style.width;
    if ((divW=='') || (isNaN(divW)) || (divW==0)) {  divW= 500;  }
    winW2 = ((winW-divW)/2)-20;
    
    //get the scroll postion
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        winY = document.body.scrollTop;
    }else{
	    winY = window.pageYOffset;
	}
    if (winH>600) { yPadding=100; }
	
	//try and do what we came here for
    try
    {
        divObj.style.left = winW2;
        divObj.style.top  = (winY+yPadding);
    }catch(e){}   
}
	
	
//Add an item to the order
function addToOrder(aFrom){
    var qtyOK = isNumeric(aFrom.qty);	
    if (!qtyOK) {
	    return false;   
    }
    else
    {
	    var l_qty = aFrom.qty.value;
	    var l_ean = aFrom.ean.value;	
	    var l_pcode	= aFrom.pcode.value;	    
	    try
	    {
		        l_divArea = testDivArea('popupArea','errorDiv');
		        ajaxRequest('order_additem_popup.php?ean=' + l_ean + '&qty=' + l_qty + '&pcode=' + escape(l_pcode),l_divArea,'ORDER');
		        
		        try
		        {
		        	var l_id  = parseInt(aFrom.id.value);
		        	addedItem(l_id,l_qty);
	        	}catch(e){}
		        
		        return false;
	    }catch(e){ return false; }
    }	    
}
	
	
//This to do when an item is added to the div
function addedItem(formID,orderQty){
	var aElementId = 'saleitem' + formID;
	
	if(document.getElementById) {
	    var divObj = document.getElementById(aElementId);
    } else if (document.all){
	    var divObj = document.all[aElementId];
    }
    
    aElementId = 'onorderdiv' + formID;
	
	if(document.getElementById) {
	    var divOrderObj = document.getElementById(aElementId);
    } else if (document.all){
	    var divOrderObj = document.all[aElementId];
    }
    
    if (divObj != null)
    {		    
	    if (orderQty > 0)
	    {
		    divObj.className = "resultsItem  onorder";
	    }
	    else
	    {
			 divObj.className = "resultsItem";    
	    }   
    }
    
    if (divOrderObj != null)
    {		    
	    if (orderQty > 0)
	    {
		    divOrderObj.innerHTML = "My Order";
	    }
	    else
	    {
			 divOrderObj.innerHTML = "";    
	    }   
    }  
}
	
//Add an item to the order
function updateBasket()
{
	    try
	    {
		        ajaxRequest('order_basket_popup.php','basketHolder','BASKET');
		        return false;
	    }catch(e){ return false; }    
}
	
//Show result from add item
function showResult(aElement,aType){
	if(document.getElementById) {
	    var divObj = document.getElementById(aElement);
    } else if (document.all){
	   var divObj = document.all[aElement];
    }
    var l_pdesc = '';
    if (divObj != null)
    {
	     var l_return = parseInt(divObj.innerHTML.trim().substr(0,1)); 
	     l_pdesc = divObj.innerHTML.trim().substr(1,divObj.innerHTML.trim().length);
    }else{
	     var l_return = 9;   //Unknown result
    }
    
    if (aType.toUpperCase() == 'ORDER')
    {      
        var l_showResults = '';
        switch(l_return)
		{
		case 0:
		    l_showResults = 'Please login to add items to your order';
		    break;    
		case 1:
		    l_showResults = ''; //null as we will close this box
		    break;
		case 2:
		    l_showResults = 'Sorry, Unable to add item to your order';
		    break;
		default:
		    l_showResults = 'Unknown result "' + divObj.innerHTML.trim() + '"';
		}
        
		if (l_return != 1){
			if (divObj != null)
			{
				divObj.innerHTML = '<div class="popupMsg">' + l_showResults + '</div>';
			}
		}else{
		   hideBox();
		   updateBasket();	
		}
    }
}
	
//Turn ajax off, but if they dont have cookeies then it wont work!!
function disableAjax(){
	var date = new Date();
	date.setTime(date.getTime()+(365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
    document.cookie = 'cAjax=OFF'+expires+"; path=/";
    alert('Pop-ups disabled');	
}
	
function enableAjax(){
	var date = new Date();
	date.setTime(date.getTime()+(365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
    document.cookie = 'cAjax=ON'+expires+"; path=/";
    alert('Pop-ups enableled');
}

//Gets the product description from he db
function getProduct(aSuprefField,aElement,aForm){
    if(document.getElementById) {
	    var divObj = document.getElementById(aElement);
    } else if (document.all){
	   var divObj = document.all[aElement];
    }	
    if (divObj != null){
	    if (aSuprefField.value.length != 0){
    	    ajaxRequest('product_getdesc.php?pcode=' + aSuprefField.value,aElement,'QUICK');
	    }else{
    	   divObj.innerHTML = '&nbsp;<br />&nbsp;'; 
	    }
	}	    		    
}
	
//Calculates the total line
function calcTotal(aForm){
	var lines = 10;
	var l_total = 0;
	
	for (i=1;i<=10;i++)
	{
		aPcode =   aForm['p_code' + i];
		aQty   =   aForm['p_qty' + i].value;
		aElement = aPcode.value; //I will be amazed if this works!!
		
		//Look to see if there is an element with the pcode as the id
		var divObj = null;  
	    if(document.getElementById){
		   divObj = document.getElementById(aElement);
	    } else if (document.all){
		   divObj = document.all[aElement];
	    }
	    
	    if (divObj != null){
		    var l_cost = parseFloat(divObj.innerHTML);	
		    if ((!isNaN(aQty)) && (aQty>0) && (l_cost>0)){
			    l_total = l_total + (l_cost*aQty);    
		    }		    
	    }
    }
    
    var divObj = null;  
	if(document.getElementById) {
		   divObj = document.getElementById('totalLine');
    } else if (document.all){
	       divObj = document.all['totalLine'];
	}
	if (divObj != null)
	{    
		 l_total = (Math.round(l_total*100)/100);
         divObj.innerHTML = '<b>Total ex-VAT: ' + (l_total) + ' (est)</b>';
    }
}