$(function(){
    var geocoder, location1, location2;
    var dest ;
    var count=0*1;
    var width;
    var PriceIncVat, UnitPrice,TotalCost;
    var LengthRequired;
    var isLengthUsed;
	var isWidth4= true;
	var previousLength;
	var postcode_error;
    function initialize() {
        geocoder = new GClientGeocoder();
       
     
    }
 

		function ChooseWidth()
		{
		var myWidth=document.getElementById("cboWidth");
		//var mylist=document.getElementById("cboMeasureUnit");
		if (myWidth.options[myWidth.selectedIndex].text=="4 meter(13.1 feet)")
				{
					//depending on what unit was selected for length that unit must be returned for correct
					//area calculation
					
								//if (mylist.options[mylist.selectedIndex].text=="Meter")
										width=4*1;
								//else
											//width=4*3.28;
								
						return width;
				}
				else
				{
						
								width=5*1;
								return width;
							
				}
		
		}

		
		//how many times was button clicked for same set of variables ??
		//use counter and reset if new set variables detected
       function CalcPrice() {
       //var mylist=document.getElementById("cboMeasureUnit");
       var myWidth=document.getElementById("cboWidth");
      try {
      //which width combo selection was made say 4m as deafault
      if (count==0)
			{
					LengthRequired =$("#txtLength").attr("value")*1;
					
						var	RollWidth;
						RollWidth= ChooseWidth(); //$("#txtWidth").attr("value")*1;
						var	Area= LengthRequired*RollWidth;
						UnitPrice=4.99;
						PriceIncVat=Area*UnitPrice*1.15;
						$("#priceOut").text(" price incl vat :£ " + PriceIncVat.toFixed(2));
			}
						
		
			
		
	 }
        catch (error) {
	        alert(error);
        }
    }
   
    function showLocation() {
      //ModeratePostcode();
      //get the two locations
      //moderate postcode and set that then as textboxes value attribute
      var   destination = ModeratePostcode($("#address2").attr("value"));
		//$("#address2").attr("value")==destination;
        geocoder.getLocations("Southport, UK", function (response) {
	        if (!response || response.Status.code != 200) {
		        alert("Sorry, we were unable to find the address");
	        } else {
		        location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
		       
		        geocoder.getLocations(destination , function (response) {
			        if (!response || response.Status.code != 200) {
				        $("#results").text("Sorry, we were unable to find the address.").hide().fadeIn("slow");
			        } else {
			
				        location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
				        calculateDistanceAndPostage();
			        }
		        });
	        }
        });
    }
    
    function ModeratePostcode(destination1)
    {  //if destination is a postcode test is the lenght is 5 or 6 digits ignoring spaces
     //
     var spacePos;
     var Code1;
     var Code2;
     spacePos=  destination1.search(" ")*1;
    
     //remove the space by spliting postcode into two strings and then concat again
     
    Code1= destination1.substr(0,spacePos);
    spacePos= spacePos+1
	Code2=destination1.substr(spacePos,3)
		destination=Code1.concat(Code2);	
		//now count the chars
		var len;
		len=destination.length;
		
		if(len >7)
		{
		alert("Postcode is in wrong format.. enter again");
		var postcode_error=1;
		}
		if(len==7)
		{
		// split after 4 then space and 1 more
			var first;
			var second;
			first= destination.substr(0,4);
			second=destination.substr(4,1);
			second=" " + second;
			dest=first.concat(second);
			return dest;
		}
		if (len == 6)
		
		{
		// split after 3 then space and 1 more
			var first;
			var second;
			first= destination.substr(0,3);
			second=destination.substr(3,1);
			second=" " + second;
			dest=first.concat(second);
			return dest;
			
		}
		
		else if (len ==5)
		{
		//split after 2 then 1 more
		var first;
			var second;
			first= destination.substr(0,2);
			second=destination.substr(2,1);
			second=" " + second;
			dest=first.concat(second);
			return dest;
			
		}
		else
		{
		alert("Postcode is in wrong format.. enter again");
		var postcode_error=1;
		}
    }
    function freeDeliveryCondition()
		{
			if (TotalCost > 499.00)
			{
				TotalCost= PriceIncVat;
			$("#DeliveryCost").text("delivery cost is £0.00 because you spent more than £ 499");
			}
		}
    function calculateDistanceAndPostage()
     {
        try {
        
	       
	        // var   destination = ModeratePostcode($("#address2").attr("value"));
	        var glatlng1 = new GLatLng(location1.lat, location1.lon);
	          //the delivery address coordinates to be determined
	        var glatlng2 = new GLatLng(location2.lat, location2.lon);
	        
	           var   destination = $("#address2").attr("value");
	        var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(0)*1;
	    var destination=$("#address2").attr("value");
	        var deliveryCost=0;



            if ((miledistance <= 10)&&(postcode_error!=1)) {
            deliveryCost = 0.00*1;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
	                $("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                $("#C572_P_7_ABB").parent().fadeIn("fast");
	                
	        } 
	        else if((miledistance <=20) && (miledistance >10))
	        {
					//deliveryCost = 10.00*1;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" .").hide().fadeIn("slow");
					//$("#results").html(PriceIncVat + deliveryCost + " will be  the total cost".<br/>&hellip;").hide().fadeIn("slow");
					$("#C573_P_8_ABB").parent().fadeIn("fast");
	        }
	        
	         else if((miledistance <=30) && (miledistance >20))
	        {
					//deliveryCost = 15.00*1;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C574_P_9_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=40) && (miledistance >30))
	        {
					//deliveryCost = 20.00*1;
					//miledistance =miledistance + 5;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	               //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C575_P_10_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=50) && (miledistance >40))
	        {
					//deliveryCost = 25.00*1;
					//miledistance =miledistance + 5;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C576_P_11_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=75) && (miledistance >50))
	        {
					//deliveryCost = 37.50*1;
					//miledistance =miledistance + 8;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					//$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C577_P_12_ABB").parent().fadeIn("fast");
	        }
	        
	         else if((miledistance <=100) && (miledistance >75))
	        {
					//deliveryCost = 50.00*1;
					//miledistance =miledistance + 10;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C578_P_13_ABB").parent().fadeIn("fast");
	        }
	        
	         else if((miledistance <=150) && (miledistance >100))
	        {
					//deliveryCost = 75.00*1;
					//miledistance =miledistance + 15;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					//$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C579_P_14_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=200) && (miledistance >150))
	        {
					//deliveryCost = 100.00*1;
					//miledistance =miledistance + 20;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles  from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C580_P_15_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=300) && (miledistance >200))
	        {
					//deliveryCost = 150.00*1;
					//miledistance =miledistance + 30;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("C581_P_16_ABB").parent().fadeIn("fast");
	        }
	         else if((miledistance <=400) && (miledistance >300))
	        {
					//deliveryCost = 200.00*1;
					//miledistance =miledistance + 40;
					//$("#DeliveryCost").text("delivery cost is :£ " + deliveryCost);
					//TotalCost=deliveryCost + PriceIncVat;
					//freeDeliveryCondition();
					//$("#TotalCost").text("Total cost :£ " + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport").hide().fadeIn("slow");
	                //$("#results").html(destination+" is "+miledistance+" miles from our store at Southport:  "+deliveryCost+" will be the delivery cost and product cost "+PriceIncVat.toFixed(2)+" ..").hide().fadeIn("slow");
	                $("#C582_P_17_ABB").parent().fadeIn("fast");
	        }
	        /*else {
	            $("#results").html(destination+" is "+miledistance+" miles from our store at Southport.<br/><br/>Delivery cost will have to be calculated for you..&hellip;").hide().fadeIn("slow");
	        }
	        $("#address2").attr("value","Enter a postcode ie. L1 2TE/L18 1JP/CH43 8SW");*/
        } catch (error) {
	        alert(error);
        }
    }

    
    initialize();
    $("#calculate").click(function(){ showLocation(); return false; });
    $("#calculateArea").click(function(){  CalcPrice(); return false; });
    //$("#txtLength").keyup(function(){ if ($(this).val()!=txtLength) { $("#calculateArea").removeAttr("disabled"); } });
    // $("#cboMeasureUnit").click(function(){ ChooseUnit(); return false; });
    $("#address2").focus(function()
    {//L1 1  for liverpool central
    // convert postcodes into the format SK9 6 , L25 7 , TW1 3 : XXX X
			 $(this).attr("value","").blur(function()
				{ if ($(this).attr("value")=="")
						{ 
							$(this).attr("value","Enter a postcode");
						} 
	});
	
	});
});
