﻿$(function(){

    makeCalculator();

})
//end of document ready 

function makeCalculator()
{
    var ddStates  = $("#ddStates"), 
        txtWeight = $("#txtWeight"),
        btnCalculate = $("#btnCalculate"),
		txtQuantity = $("#txtQuantity");
		
    
    var lblCalculated = $("#lblCalculated");
                
    btnCalculate.click(function(e){
        //simple validation
        if(txtWeight.val() != ""){
            lblCalculated.html("Calculating...");
            $.ajax({
                type : "GET",
                url  : "calculateshipping.php?"+new Date(),
                data : {stateId:ddStates.val(), weight: txtWeight.val(), quantity: txtQuantity.val()},
                dataType: "json",
                success : function(reply){
                    process_from_server(reply, lblCalculated);
                },
				error: function(reply){
					alert("Error occured while communicating server:\n " + reply.responseText);
				}
                //end function success
            });
            //end of ajax
        }
		else{
			lblCalculated.html("Please provide weight");
		}
        //end if
        e.preventDefault();
    });
    //end of btnCalculate_click
}
//end function

function process_from_server(reply, lblCalculated){
    if(reply.price){
        var html = "Estimated Shipping Price: &nbsp; <strong>" + reply.price + "</strong><br /><div>For exact shipping costs for a multiple product order, you can \"add\" the products to your cart and use the shipping calculator that is below the \"Keep Shopping\" button on the shopping cart.</div>";
        lblCalculated.html(html);
    }
    else if(reply.error){
        lblCalculated.html(reply.error);
    }
    else{
        alert("Could not decode the reply from server:\n"+reply);
    }
    //end if    
}
