$(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;
    function initialize() {
        geocoder = new GClientGeocoder();
        UnitPrice=$("#carpet_price span").text();
        //alert("unit price " + UnitPrice);
     
    }
 

		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;

						PriceIncVat=Area*UnitPrice*1.15;
						$("#priceOut").text("Includes VAT : \u00a3" + 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");
		return "Southport,UK";
		}
		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");
		return "Southport,UK";
		}
    }
    function freeDeliveryCondition()
		{
			if (TotalCost > 499.00)
			{
				TotalCost= PriceIncVat;
			$("#DeliveryCost").text("delivery cost is \u00a30.00 because you spent more than \u00a3499");
			}
		}
    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) {
            deliveryCost = 0.00*1;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
	             $("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        } 
	        else if((miledistance <=20) && (miledistance >10))
	        {
					deliveryCost = 10.00*1;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" .<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
					//$("#results").html(PriceIncVat + deliveryCost + " will be  the total cost".<br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=30) && (miledistance >20))
	        {
					deliveryCost = 15.00*1;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=40) && (miledistance >30))
	        {
					deliveryCost = 20.00*1;
					miledistance =miledistance + 5;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=50) && (miledistance >40))
	        {
					deliveryCost = 25.00*1;
					miledistance =miledistance + 5;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=75) && (miledistance >50))
	        {
					deliveryCost = 37.50*1;
					miledistance =miledistance + 8;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	        
	         else if((miledistance <=100) && (miledistance >75))
	        {
					deliveryCost = 50.00*1;
					miledistance =miledistance + 10;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	        
	         else if((miledistance <=150) && (miledistance >100))
	        {
					deliveryCost = 75.00*1;
					miledistance =miledistance + 15;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=200) && (miledistance >150))
	        {
					deliveryCost = 100.00*1;
					miledistance =miledistance + 20;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles  from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=300) && (miledistance >200))
	        {
					deliveryCost = 150.00*1;
					miledistance =miledistance + 30;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	         else if((miledistance <=400) && (miledistance >300))
	        {
					deliveryCost = 200.00*1;
					miledistance =miledistance + 40;
					$("#DeliveryCost").text("Delivery Cost: \u00a3" + deliveryCost);
					TotalCost=deliveryCost + PriceIncVat;
					freeDeliveryCondition();
					$("#TotalCost").text("Total Cost: \u00a3" + TotalCost.toFixed(2));
					$("#results").html(destination+" is "+miledistance+" miles from our store at Southport<br/><br/><br/><br/>&hellip;").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)+" ..<br/><br/><br/><br/>&hellip;").hide().fadeIn("slow");
	        }
	        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");
						} 
	});
	
	 });
});