/*--------------------------------------------------------------
pricing.js
Javascript for CentremapsLive map interface
Code for retrieving and displaying prices and extent areas
Lovell Johns Ltd
Jan 2010
----------------------------------------------------------------*/

//-------------------------------------------------------------------------PRICING SCRIPTS
//****************Function to ensure zeros displayed at end of price	
function formatPrice(passedPrice) {   
	inPrice = String(passedPrice);
	var testLen1 = inPrice.length;
	var sep = inPrice.indexOf(".");
	if(sep == -1){		
		inPrice = inPrice + ".00";
	}else{
		var rest = inPrice.substring(0,(sep+1))  
		var testLen2 = rest.length;
		if(testLen1 == (testLen2 + 1)){
			inPrice = inPrice + "0";
		}
	}
	return(inPrice);
}
//****************Update the price
function updatePrice(theSelectedProductIndex){
	//Reset previously stored pricing info and messages
	document.getElementById("mmpercents"+theSelectedProductIndex).value = "";				
	document.getElementById("orderprice"+theSelectedProductIndex).value = "0";
	document.getElementById("calcprice"+theSelectedProductIndex).value = "0";
	document.getElementById("prodmessage"+theSelectedProductIndex).innerHTML = "";
	//Get the selected product
	var selectedData = document.getElementById("data" + theSelectedProductIndex).value 
	if(selectedData != ""){
		//Get the extent ID attached to selected product and create retrieve price link
		var theExtentID = document.getElementById("extent"+theSelectedProductIndex).value;				
		if(theExtentID != ""){
			//Define if the order is small enough for online order
			var theMaxSize = Number(document.getElementById("maxsize" + theSelectedProductIndex).value); 
			var theExtentID = document.getElementById("extent" + theSelectedProductIndex).value;
			var extentGeom = getExtentGeomByID(theExtentID)
			var extentAreaKM = extentGeom.getArea() / 1000000;
			if((extentAreaKM > theMaxSize) && (theMaxSize != 0)){				//**EXCEEDS MAX SIZE FOR THE DATA
				document.getElementById("prodmessage"+theSelectedProductIndex).innerHTML = "<p class='error'>Please note that the area selected is too big for online order. Contact " + document.varform.thesitename.value + " direct for large data requirements. Or request a quote <a href='javascript:sendQuoteReq(\"" + theSelectedProductIndex + "\");'>here</a></p>";
				document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>&pound; **.**</p>"; 
				document.getElementById("orderprice"+theSelectedProductIndex).value = "offline";			
			}else{																//**SHOW GET PRICE LINK
				if((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "") && (document.varform.data.value.substring(0,4) != "OSMM") && ((document.getElementById("layersPrice"+theSelectedProductIndex).value == "") || (document.getElementById("layersPrice"+theSelectedProductIndex).value == "0"))){
					showDialog('Warning','Please define data supplier before retrieving the price.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>&pound; **.**</p>"; 					
				}else{
					document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>&pound; **.**<br/><a href='javascript:retrievePrice(\"show\",\""+ theSelectedProductIndex + "\",\"" + theExtentID + "\");' style='font-size:10px;'>Get Price</a></p>"; 	
				}
			}				
		}else{															//No extent set price to zero						
			document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>&pound; **.**</p>"; 
		}		
	}
	updateTotalPrice();					//Update the total price to reflect the changes
}
//****************Script to retreive the price from server
function retrievePrice(theAction,theSelectedProductIndex,theExtentID){
	if((geomString == "") || (theExtentID == "")){
		showDialog('Warning','Please ensure an extent is defined for this product.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<img src='images/loader.gif'>"; 	
		//Get data extent geometry,extent width, height,scale,product code and name
		var theProdCode = document.getElementById("data" + theSelectedProductIndex).value 
		theProdCode = theProdCode.replace(/\+/g,"%2B");	
		var theProduct = document.getElementById("datadesc" + theSelectedProductIndex).value 
		theProduct = theProduct.replace(/\+/g,"%2B");		
		var extentGeom = getExtentGeomByID(theExtentID);
		if(theProdCode.toLowerCase().indexOf("osmmbwpack") == 0){
			var extentGeom = null;
			for(p=0; p < extentLayer2.features.length;p++){
				if(theExtentID == extentLayer2.features[p].attributes.id){
					extentGeom = extentLayer2.features[p].geometry;
					break;
				}
			}
		}
		var theExtentArea = extentGeom.getArea() / 1000000;
		var theExtentWidth = extentGeom.getBounds().getWidth();
		var theExtentHeight = extentGeom.getBounds().getHeight();
		var theExtentPerim = extentGeom.getLength(); 	//Get Perimeter in metres		
		var geomString = String(extentGeom).substring(9,(String(extentGeom).length -2));
		//Check if 2 extents have been passed (This will happen for map packs) - get the first (biggest)
		if(geomString.indexOf("),(") != -1){
			//var tempString = geomString.substring((geomString.indexOf("),(") +3), geomString.length); //(geomString.length - (geomString.indexOf("),(") +3)));	
			var tempString = geomString.substring(0, geomString.indexOf("),("));
			geomString = tempString;
		}
		var theScale = document.getElementById("scale" + theSelectedProductIndex).value;
		//Set query string and send request
		var qstring = "xtent=" + geomString + "&data=" + theProdCode + "&prodname=" + theProduct + "&action=" + theAction  + "&region=" + document.varform.region.value + "&selectedindex=" + theSelectedProductIndex + "&extentarea=" + theExtentArea + "&extentperim=" + theExtentPerim + "&scale=" + theScale + "&extentWidth=" + theExtentWidth + "&extentHeight=" + theExtentHeight + "&thesite=" + document.varform.thesite.value + "&cid=" + document.varform.cid.value;			
		var getPriceReq = new ajaxObject('retrievePrice.php', handlePriceResponse);
		getPriceReq.update(qstring,'POST');	
	}
}
//****************Handles the response from getting the price
function handlePriceResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){																//Check data returned	
			if(responseText.indexOf('|' != -1)) {
				var tempArray = new Array();
				tempArray = responseText.split('|');
				passedSplits = tempArray[0];
				passedPrice = tempArray[1];												//Retrieve the price value
				theAction = tempArray[2];												//Retrieve the action -ie what to do next
				theSelectedProductIndex = tempArray[6];									//Retrieve the selected item to change the price for
				theMessageToPrint = tempArray[7];										//Retrieve any messages
				theDiscountModel = tempArray[8];										//Retrieve discount model
				theMinPrice = tempArray[9];												//Retrieve min price to ensure when discounting does not go lower than this
				wasAdjusted = tempArray[10];											//Retrieve if the price was aqdjusted by tariff or white label code					
				//If product has multi suppliers add the suppliers pricing here.
				if(Number(document.getElementById("layersPrice"+theSelectedProductIndex).value) != 0){   
					passedPrice = Number(passedPrice) + Number(document.getElementById("layersPrice"+theSelectedProductIndex).value);			
					passedPrice = formatPrice(Math.round(passedPrice*100)/100);		//Format price correctly
				}					
				if((passedPrice == "0.00") && ((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != ""))){			//**Prompt to choose a data supplier
					showDialog('Warning','Please ensure you choose a data supplier.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					getSupplierInfo(true);
				}else if((passedPrice == "0.00") || (Number(passedPrice) == 0)){																	//**Error retrieving
					showDialog('Error','There has been an error retrieving the price for this data.<br/>Please try again or contact ' + document.varform.thesitename.value + '.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');	
					var theExtentID = document.getElementById("extent"+theSelectedProductIndex).value;				
					if(theExtentID != ""){
						document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>&pound; **.**<br/><a href='javascript:retrievePrice(\"show\",\""+ theSelectedProductIndex + "\",\"" + theExtentID + "\");' style='font-size:10px;'>Get Price</a></p>"; 	
					}
					document.getElementById("mmpercents"+theSelectedProductIndex).value = "";
					document.getElementById("orderprice"+theSelectedProductIndex).value = "0";
					document.getElementById("calcprice"+theSelectedProductIndex).value = "0";
				}else{																																//**Show the price
					if(passedPrice != "Price Available on Request"){	
						document.getElementById("mmpercents"+theSelectedProductIndex).value = passedSplits;						//Store on hidden
						document.getElementById("orderprice"+theSelectedProductIndex).value = passedPrice;					
						//Need to show discounted price to the user
						terminalDisc = getTerminalDiscount("1",theDiscountModel);	
						//Define the area discount value
						if(theDiscountModel == "os"){							//Don't apply area discount to BGS model
							selectedProductIndex = getSelectedProductIndex();	
							var theExtentFeature = getFeatureExtentByID(document.getElementById("extent" + selectedProductIndex).value);
							var extentArea = theExtentFeature.geometry.getArea() / 1000000;
							theExtentProp = extentArea / 234411;			 
							theExtentPercent = theExtentProp * 100;
							areaDiscount = getAreaDiscount(theExtentPercent);
						}else{
							areaDiscount = 0;
						}					
						//Define the actual discount and new price
						if(theDiscountModel == "os"){		
							if(areaDiscount <= terminalDisc){
								theDiscount = areaDiscount;
							}else{
								theDiscount = terminalDisc;
							}
						}else if(theDiscountModel == "bgs"){			
							theDiscount = terminalDisc;
						}else{
							theDiscount = 0;
						}
						if(theDiscount != 0){
							thePriceToShow = (Number(passedPrice) - (Number(passedPrice) * theDiscount));
							thePriceToShow = formatPrice(Math.round(thePriceToShow*100)/100);
						}else{
							thePriceToShow = passedPrice;
						}						
						//Set to previous price if discounting takes below the min price
						if(wasAdjusted == "no"){										//Only relevant for unadjusted prices
							if(Number(thePriceToShow) < theMinPrice){
								thePriceToShow = theMinPrice;
							}
						}
						document.getElementById("calcprice"+theSelectedProductIndex).value = thePriceToShow;	
						thePriceToShow = "&pound; " + thePriceToShow;
						document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p>" + thePriceToShow + "</p>"; 
					}else{	
						document.getElementById("mmpercents"+theSelectedProductIndex).value = "";
						document.getElementById("orderprice"+theSelectedProductIndex).value = "0";
						document.getElementById("calcprice"+theSelectedProductIndex).value = "0";		
						document.getElementById("showdataprice"+theSelectedProductIndex).innerHTML = "<p class='error'>Price Available on Request. Request quote <a href='javascript:sendQuoteReq(\"" + theSelectedProductIndex + "\");'>here</a></p>"; 
					}								
					if(theMessageToPrint == ""){
						document.getElementById("prodmessage"+theSelectedProductIndex).innerHTML = "";
					}else if(theMessageToPrint == "message2"){
						document.getElementById("prodmessage"+theSelectedProductIndex).innerHTML = "<p class='error' align='center'>Note: Order may be tiled due to size.</p>";
					}else if(theMessageToPrint == "message3"){
						document.getElementById("prodmessage"+theSelectedProductIndex).innerHTML = "<p class='error' align='center'>Note: Elongated site pricing.</p>";
					}
				}				
			}	 
		}		
		updateTotalPrice();					//Update the total price to add the new product price			
		//If the process was run to get a missing price see if there are any more to retieve
		if(theAction == "showmissing"){
			getPriceIndex++;
			getMissingPrices();
		}
	}
}
//****************Calculates the total order price and displays
function updateTotalPrice(){
	var totalPrice = 0;
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){				//Loop thru the selected products
		//if(isNaN(document.getElementById("orderprice" + String(i+1)).value) == false){
		//	totalPrice += Number(document.getElementById("orderprice" + String(i+1)).value);	
		//}
		if(isNaN(document.getElementById("calcprice" + String(i+1)).value) == false){
			totalPrice += Number(document.getElementById("calcprice" + String(i+1)).value);	
		}	
	}
	//Update on the page
	if(totalPrice == 0){
		document.getElementById("topPrice").innerHTML = "&pound;**.**";
		document.getElementById("bottomPrice").innerHTML = "&pound;**.**";
	}else{
		document.getElementById("topPrice").innerHTML = "&pound;" + formatPrice(String(Math.round(totalPrice*100)/100));
		document.getElementById("bottomPrice").innerHTML = "&pound;" + formatPrice(String(Math.round(totalPrice*100)/100));
	}
}
//****************Function to calculate discount based on number of terminals
function getTerminalDiscount(noOfTerminals,theDiscountModel){
	terminalDisc = 0;
	if(theDiscountModel == "os"){
		terminalBands = new Array('1','2','3-5','6-10','11-20','21-50','51-100','101-500','500+');
		terminalDiscounts = new Array(0.875,0.8,0.7,0.55,0.4,0.2,0.1,0,0);								
	}else if(theDiscountModel == "bgs"){	
		terminalBands = new Array('1','2','3-5','6-10','11-20','21-50','51-100','101+');
		terminalDiscounts = new Array(0.9,0.85,0.8,0.7,0.6,0.5,0.4,0);	
	}else if(theDiscountModel == "none"){	
		terminalBands = new Array('1+');
		terminalDiscounts = new Array(0);	
	}
	for(t=0;t<terminalBands.length;t++){
		if(noOfTerminals == terminalBands[t]){
			terminalDisc = terminalDiscounts[t];			
		}
	}
	return terminalDisc;
}
//****************Function to calculate area discount based on % of total UK area	
function getAreaDiscount(theExtentPercent) {  
	areaDiscount = 0;
	if(theExtentPercent < 0.1){
		areaDiscount = 0;
	}else if((theExtentPercent >= 0.1) &&  (theExtentPercent < 0.25)){
		areaDiscount = 0.23;
	}else if((theExtentPercent >= 0.25) &&  (theExtentPercent < 0.5)){
		areaDiscount = 0.4;
	}else if((theExtentPercent >= 0.5) &&  (theExtentPercent < 1)){
		areaDiscount = 0.5;
	}else if((theExtentPercent >= 1) &&  (theExtentPercent < 2)){
		areaDiscount = 0.6;
	}else if((theExtentPercent >= 2) &&  (theExtentPercent < 3)){
		areaDiscount = 0.7;
	}else if((theExtentPercent >= 3) &&  (theExtentPercent < 4)){
		areaDiscount = 0.76;
	}else if((theExtentPercent >= 4) &&  (theExtentPercent < 5)){
		areaDiscount = 0.8;
	}else if((theExtentPercent >= 5) &&  (theExtentPercent < 6)){
		areaDiscount = 0.83;
	}else if((theExtentPercent >= 6) &&  (theExtentPercent < 7)){
		areaDiscount = 0.85;
	}else if((theExtentPercent >= 7) &&  (theExtentPercent < 8)){
		areaDiscount = 0.865;
	}else if(theExtentPercent >= 8){
		areaDiscount = 0.875;
	}
	return areaDiscount;
}
//****************Adds prepaid credit to input area when using against an order
function applyPrepaidCredit(creditToUse){
	document.getElementById("credittouse").value = creditToUse;
	document.getElementById("credittousedisp").value = creditToUse;
	var newPrice = Number(document.getElementById("amount").value) - Number(creditToUse);	
	document.getElementById("amountminuscredit").value = formatPrice(Math.round(newPrice*100)/100);
	document.getElementById("totaldiv").innerHTML = "<div id='totaldiv'><strong>" + document.getElementById("amountminuscredit").value + "</strong></div>";
	//Show remove credit link
	document.getElementById("usecredit").style.display = "none";
	document.getElementById("remcredit").style.display = "block";	
}
//****************Removes prepaid credit to input area when using against an order
function remPrepaidCredit(creditToUse){
	document.getElementById("credittouse").value = "0";
	document.getElementById("credittousedisp").value = "0";	
	var newPrice = Number(document.getElementById("amount").value); 	
	document.getElementById("amountminuscredit").value = formatPrice(Math.round(newPrice*100)/100);
	document.getElementById("totaldiv").innerHTML = "<div id='totaldiv'><strong>" + document.getElementById("amountminuscredit").value + "</strong></div>";
	//Show add credit link
	document.getElementById("usecredit").style.display = "block";
	document.getElementById("remcredit").style.display = "none";		
}

//-------------------------------------------------------------------------REQUEST QUOTE SCRIPTS
//****************Emails quote request to site admin
function sendQuoteReq(theSelectedProductIndex){
	if(document.varform.cid.value == ""){
		showDialog('Warning','Please ensure you are logged in before requesting a quote.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');									
	}else{
		//Get the data product, user id and site area to pass
		var theProdCode = document.getElementById("data" + theSelectedProductIndex).value; 
		theProdCode = theProdCode.replace(/\+/g,"%2B");	
		var theExtentID = document.getElementById("extent" + theSelectedProductIndex).value;	
		var extentGeom = getExtentGeomByID(theExtentID);
		var theExtentArea = extentGeom.getArea() / 1000000;
		var geomString = String(extentGeom).substring(9,(String(extentGeom).length -2))
		var qstring = "thedata=" + theProdCode + "&thecid=" + document.varform.cid.value + "&thearea=" + theExtentArea + "&thecoords=" + geomString;
		var quoteReq = new ajaxObject('quote_request.php', handleQuoteReqResponse);
		quoteReq.update(qstring,'POST');
	}
}
//****************Handles the response from getting quote
function handleQuoteReqResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText == "yes"){														
			showDialog('','A request for a quote has been sent to ' + document.varform.thesitename.value + '.<br/>You will be emailed with a response soon.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','success');									
		}else{
			showDialog('Error','"Request could not be sent. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');									
		}		
	}
}
//--------------------------------------------------------End of file.
