$(document).ready(function () {

    // Clear the QTY values (we have this as a function as we may need to call this from another event)
    clearCalc();

    //  **************************************************************************************
    //  MAIN ENTRY POINT - WE NEED TO FIRST CHECK IF THE SALES CALC HAS BEEN LOADED
    //  FROM THE HIRE PAGE.. i.e. if the customer is moving outside of a metro area.
    //  **************************************************************************************

    //  Try to retrieve any cached qty's from the hire calc.. if so, populate the sales calc,
    //  if not, the calc is fresh from a sales enquiry only
    $.ajax({
        type: 'GET',
        url: 'AJAXget/getHireQtyCache.ashx',
        async: false,
        dataType: 'xml',
        timeout: 10000,
        success: salesCalcCacheSuccess,
        error: Error
    });

    //  ----------------------------------------------------------------------
    //  Check the results of the cache retrieve
    //  ----------------------------------------------------------------------
    function salesCalcCacheSuccess(xml) {

        $(this).ajaxLoader('hide');
        //  Check if we couldn't return the cached values.. 
        //  If no cached values, we clear the calc and reset the divs to show/hide
        var processFlag = true;
        $(xml).find('error').each(function () {
            clearCalc();

            //  Now show/hide the necessary divs
            $('#divCheckPostcode').show();
            $('#msgNoPostcode').hide();
            $('#divOrderOptions').hide();
            $('#divPhoneOrder').hide();
            processFlag = false;
            return;
        });

        //  Ok, we have the cached values from the hire calc, so populate and recalc
        if (processFlag == true) {
            populateStaticPageData(xml);
            recalc();

            //  Now we need to auto show the order div, as we have come from the hire page where the
            //  postcode has been checked already
            $('#divCheckPostcode').hide();
            $('#msgNoPostcode').hide();
            $('#divOrderOptions').show();
            $('#divPhoneOrder').hide();
        }
    }

    //  ----------------------------------------------------------------------
    //  Standard AJAX error catch
    //  ----------------------------------------------------------------------
    function Error(xml) {
        alert('Sorry, and error occured retrieving your previous details. Please re-enter your requirements.');
        return;
    }

    // **************************************************************************************
    // CHECK POSTCODE
    // Check the postcode entered to see if we can deliver the boxes
    // **************************************************************************************
    $('#btnCheckPostcode').click(function (element) {

        $(this).ajaxLoader('show');

        $('#msgNoPostcode').hide();
        $('#divCheckPostcode').hide();
        $('#divOrderOptions').hide();
        $('#divPhoneOrder').hide();
        var postcode = $('#postcode').val();
        if (postcode == '') {
            $().ajaxLoader('hide');
            alert('Please enter a valid postcode');
            return;
        }

        //  Check if the postcode is somewhere we can delivery to
        $.ajax({
            type: 'GET',
            url: 'AJAXget/getPostcodeCheck.ashx',
            data: 'postcode=' + postcode,
            async: false,
            timeout: 10000,
            success: postcodeCallback,
            error: Error
        });
        return;
    });
    //  ---------------------------------------------------------------------------------------------------------------------
    //  CHECK POSTCODE RETURN RESULTS
    //  If msg is true, then we can service that postcode, continue through the order process
    //  if msg is false, then we cannot provide service - postcode isn't in a franchisee area
    //  if msg is anything else, then we have a server/database error which we can display details about
    //  ---------------------------------------------------------------------------------------------------------------------
    function postcodeCallback(msg) {
        $().ajaxLoader('hide');

        //  Check return results (msg) show the appropriate message if postcode
        //  exists or not
        switch (msg) {
            case 'false':
                $('#msgNoPostcode').show();
                break;
            case 'true':
                $('#divOrderOptions').show();
                $('#msgNoPostcode').hide();
                $('#divCheckPostcode').hide();
                break;
            default:
                alert('Sorry, and error has occured contacting the postcode check service: ' + msg);
        } // end switch msg
    } // end postcode callback

    // **************************************************************************************
    // PHONE ORDER
    // **************************************************************************************
    $('#btnPhoneOrder').click(function () {
        $('#divCheckPostcode').hide();
        $('#msgNoPostcode').hide();
        $('#divOrderOptions').hide();
        $('#divPhoneOrder').show();
    });

    // **************************************************************************************
    // PLACE ORDER
    // We now proceed to push the order details into cache, then move to the
    // order confirmation page.
    // **************************************************************************************
    $('#btnOnlineOrder').click(function () {

        //  Check we actually have some quantities entered
        var bQtyVals = 0;
        $('input[id^="qty"]').each(function (e) {
            if ($(this).val() != '') {
                bQtyVals++;
            }
            if ($(this).val() != '0') {
                bQtyVals++;
            }
        });
        if (bQtyVals < 1) {
            alert('To proceed to the order page, you must select some items');
            return;
        }

        //  Ok, we have items selected, so post the sales order to the order-details
        $(this).ajaxLoader('show');
        $.ajax({
            type: 'POST',
            url: 'AJAXput/putOrderPackageCache.ashx',
            data: $("form").serialize(),
            async: false,
            //dataType: 'xml',
            timeout: 10000,
            success: putOrderCallback,
            error: Error
        });
    });
    //  Once the place order (to cache) is complete, we can re-direct to the order-details.html page
    function putOrderCallback(msg) {
        $().ajaxLoader('hide');
        window.location = 'order-details.html';
    }

    //  **************************************************************************************
    //  MAIN CALCULATOR START
    //  We calculate the box ordering details by checking the input quantities of 
    //  sale products (plus calculating delivery and grand totals)
    // **************************************************************************************

    // We need to trap all QTY field keystrokes in order to re-calculate the form
    // (we are binding on the ID of a field so NAME is not required)
    $('input[id^="qty"]').keyup(function (e) {
        recalc();
    });

    //  --------------------------------------------------------------------------------------
    //  CALCULATOR RECALC: Calculate the QTY inputs for HIRE/SALE etc
    //  --------------------------------------------------------------------------------------			
    function recalc() {
        // Validate the QTY entries to ensure we show blank in QTY if none entered, but keep
        // zero in the variable for the actual calculation process				
        var qtylb = parseInt($('#qtylb').val());
        var qtysb = parseInt($('#qtysb').val());
        var qtypr = parseInt($('#qtypr').val());
        var qtytd = parseInt($('#qtytd').val());
        if (qtylb == '' || isNaN(qtylb)) { qtylb = 0; }
        if (qtysb == '' || isNaN(qtysb)) { qtysb = 0; }
        if (qtypr == '' || isNaN(qtypr)) { qtypr = 0; }
        if (qtytd == '' || isNaN(qtytd)) { qtytd = 0; }
        var qtytr = parseInt($('#qtytr').val());
        var qtyp4 = parseInt($('#qtyp4').val());
        var qtyp2 = parseInt($('#qtyp2').val());
        var qtybw = parseInt($('#qtybw').val());
        var qtymp = parseInt($('#qtymp').val());
        if (qtytr == '' || isNaN(qtytr)) { qtytr = 0; }
        if (qtyp4 == '' || isNaN(qtyp4)) { qtyp4 = 0; }
        if (qtyp2 == '' || isNaN(qtyp2)) { qtyp2 = 0; }
        if (qtybw == '' || isNaN(qtybw)) { qtybw = 0; }
        if (qtymp == '' || isNaN(qtymp)) { qtymp = 0; }

        // =============================================================================								
        // Calculate Sale Section
        // =============================================================================

        // Get the sale cost values (these are within the TD tages at present, but will
        // be coming from the DB at some future time)
        var pricelb = parseFloat($('#pricelb').val());
        var pricesb = parseFloat($('#pricesb').val());
        var pricepr = parseFloat($('#pricepr').val());
        var pricetd = parseFloat($('#pricetd').val());
        var pricetr = parseFloat($('#pricetr').val());
        var pricep4 = parseFloat($('#pricep4').val());
        var pricep2 = parseFloat($('#pricep2').val());
        var pricebw = parseFloat($('#pricebw').val());
        var priceMP = parseFloat($('#pricemp').val());

        // Update sale totals
        $('#totallb').val(parseFloat(pricelb * qtylb).toFixed(2));
        $('#totalsb').val(parseFloat(pricesb * qtysb).toFixed(2));
        $('#totalpr').val(parseFloat(pricepr * qtypr).toFixed(2));
        $('#totaltd').val(parseFloat(pricetd * qtytd).toFixed(2));

        $('#totaltr').val(parseFloat(pricetr * qtytr).toFixed(2));
        $('#totalp4').val(parseFloat(pricep4 * qtyp4).toFixed(2));
        $('#totalp2').val(parseFloat(pricep2 * qtyp2).toFixed(2));
        $('#totalbw').val(parseFloat(pricebw * qtybw).toFixed(2));
        $('#totalmp').val(parseFloat(priceMP * qtymp).toFixed(2));

        // Update sale grand total
        var totlb = parseFloat($('#totallb').val());
        var totsb = parseFloat($('#totalsb').val());
        var totpr = parseFloat($('#totalpr').val());
        var tottd = parseFloat($('#totaltd').val());

        var tottr = parseFloat($('#totaltr').val());
        var totp4 = parseFloat($('#totalp4').val());
        var totp2 = parseFloat($('#totalp2').val());
        var totbw = parseFloat($('#totalbw').val());
        var totmp = parseFloat($('#totalmp').val());

        var totalSaleRunning = totlb + totsb + totpr + tottd + tottr + totp4 + totp2 + totbw + totmp;
        var grandTotalSale = parseFloat(totlb + totsb + totpr + tottd + tottr + totp4 + totp2 + totbw + totmp).toFixed(2);
        $('#ordertotalsale').val(grandTotalSale);

        // =============================================================================								
        // Calculate DELIVERY 
        // the delivery is also worked out as a proportion of the sale.. i.e. if 
        // the normal delivery is 110.00, and the user has 55.00 in SALE items, then
        // the delivery will be 55.00  If the SALE value is greater than 110,
        // then the delivery is FREE
        // =============================================================================

        // Set the current delivery charge
        var deliveryCharge = parseFloat('110.00');

        // Check if the total SALE items are greater or less than the delivery (if less
        // we reduce the delivery cost by the sale amount)
        if (grandTotalSale > 110.00) {
            deliveryCharge = 0
        }
        else {
            // reduce the delivery cost by the sale cost to get our delivery value
            deliveryCharge = deliveryCharge - grandTotalSale;
        }

        // =============================================================================								
        // Update the sale + delivery total
        // =============================================================================								
        var htSaleDeliveryTotal = totalSaleRunning + deliveryCharge;
        $('#saleanddelivery').val((htSaleDeliveryTotal).toFixed(2));
        $('#ordertotaldelivery').val((deliveryCharge).toFixed(2));

        // =============================================================================								
        // Calculate PAY ON DELIVERY (Total Sale Items + Delivery)
        // =============================================================================												

        //var payOnDelivery = grandTotalSale + deliveryCharge;
        $('#ordertotalpayondelivery').val(htSaleDeliveryTotal.toFixed(2));

    }

});                         // end of JQuery OnReady

//	------------------------------------------------------------------
//  FUNCTION TO RETRIEVE QUERYSTRING VALS
//	------------------------------------------------------------------
function getQryVal(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        return "";
    }
    else {
        return results[1];
    }
}

//	------------------------------------------------------------------
//	CALCULATOR CLEAR FUNCTION
//	Resets all quantities to 0
//	------------------------------------------------------------------
function clearCalc() {
    // Set the SALE items to blank
    $('#qtylb').val('');
    $('#qtysb').val('');
    $('#qtypr').val('');
    $('#qtytd').val('');
    $('#qtytr').val('');
    $('#qtyp4').val('');
    $('#qtyp2').val('');
    $('#qtybw').val('');
    $('#qtymp').val('');
}
