/**
* 	David Sheardown
* 	Nov 2008
*
* 	HIREABOX HIRE PROCESS FUNCTIONS AND CALCULATOR
* 	This code is used on the order.html page to handle JQuery DIV hiding/showing
* 	as well as the actual calculator code and order process steps
* 
*  David Sheardown 
* 	May 2010
*  UPDATE - Now contains logic to look up postcode and process the order
*/
//	------------------------------------------------------------------
//	DOCUMENT.ONLOAD
//	This function is triggered as the document/page is loaded
//	------------------------------------------------------------------
$(document).ready(function () {

    //	------------------------------------------------------------------
    //	CALCULATOR CLEAR FUNCTION
    //	Resets all quantities to 0
    //	------------------------------------------------------------------
    function clearCalc() {
        // Set the HIRE items to blank (we check later if blank, and act as zero)
        $('#qtyLB').val('');
        $('#qtySB').val('');
        $('#qtyPR').val('');
        $('#qtyTD').val('');

        // Set the SALE items to blank (we check later if blank, and act as zero)
        $('#qtyTR').val('');
        $('#qtyP4').val('');
        $('#qtyP2').val('');
        $('#qtyBW').val('');
        $('#qtyMP').val('');

        // Set the DEPOSIT items to blank (we check later if blank, and act as zero)
        $('#qtyLB2').html('');
        $('#qtySB2').html('');
        $('#qtyPR2').html('');
        $('#qtyTD2').html('');
    }

    // Clear the QTY values (we have this as a function as we may need to call this from another event)
    clearCalc();

    // -------------------------------------------------------------
    // SETUP EVENTS TO HIDE/SHOW THE DIFFERENT SECTIONS
    // -------------------------------------------------------------

    // Set the HIDE events for sections we don't need to see to start with i.e.
    // these are sections that are shown once we click something etc

    $('#delivery').hide(); 				// Hide CHECK DELIVERY in case it is maximised
    $('#noDelivery').hide(); 		// Hide NO DELIVERY message
    $('#yesDelivery').hide(); 		// Hide YES DELIVERY message
    $('#checkMetro').hide(); 			// Hide YES METRO message
    $('#noBuy').hide(); 				// Hide GOOD BYE message 

    // OnClick YES in delivery area and YES metro area
    $('#chkDelivery').click(function () {
        //$('#checkMetro').show('slow');
    });

    // OnClick OK to YES metro area and show Calculator as next step
    $('#yesCalc').click(function () {
        $('#delivery').hide('slow');
        $('#divOrderStep2').show('slow');
    });

    // OnClick YES in delivery area and NO metro area
    $('#noMetroArea').click(function () {
        $('#yesDelivery').hide('slow');
        $('#noDelivery').show('slow');
    });

    $('#yesBuyBoxes').click(function () {

        window.location = "sales-calculator.html";
    });

    // OnClick NO to BUY BOXES as not delivering to METRO AREA
    $('#noBuyBoxes').click(function () {
        $('#noBuy').show('slow');
        $('#noDelivery').hide('slow');
    });

    // OnClick OK as NOT BUYING BOXES
    $('#bye').click(function () {
        //go to the Home page as cannot service customer
        window.location = "index.html";
    });

    // Onclick for SHOW delivery
    $('#showDelivery').click(function () {
        $('#delivery').show('slow');
        $('#noDelivery').hide(); 		// Hide NO DELIVERY message
        $('#yesDelivery').hide(); 		// Hide YES DELIVERY message
        $('#noBuy').hide(); 			// Hide NO BUY BOXES message

    });

    // Onclick for SHOW delivery - click on header image
    $('#showDelivery2').click(function () {
        $('#delivery').show('slow');
        $('#noDelivery').hide(); 		// Hide NO DELIVERY message
        $('#yesDelivery').hide(); 		// Hide YES DELIVERY message

    });

    // Onclick for HIDE delivery
    $('#hideDelivery').click(function () {
        $('#delivery').hide('slow');
    });

    // Onclick for HIDE delivery inside delivery box
    $('#hideDelivery2').click(function () {
        $('#delivery').hide('slow');
    });

    // Onclick for SHOW CALCULATOR and HIDE DELIVERY
    $('#showCalculator').click(function () {
        $('#delivery').hide('slow'); //Hide Check Delivery Area in case it is maximised
    });

    // Onclick for SHOW CALCULATOR and HIDE DELIVERY
    $('#showCalculator2').click(function () {
        $('#delivery').hide('slow');
    });

    // Onclick for HIDE CALCULATOR
    //$('#hideCalculator').click(function()
    //{
    //$('#divOrderStep2').hide('slow');
    //}
    //);


    // SHOW by default...
    $('#quantityHelp').show();

    // Onclick for SHOW quantity help
    $('#showQuantityHelp').click(function () {
        $('#quantityHelp').show('slow');
    }
			);

    // Onclick for HIDE quantity help
    $('#hideQuantityHelp').click(function () {
        $('#quantityHelp').hide('slow');
    }
			);

    // Hide by default...
    $('#processHelp').hide();

    // Onclick for SHOW quantity help
    $('#showProcessHelp').click(function () {
        $('#processHelp').show('slow');
    }
			);

    // Onclick for HIDE process help
    $('#hideProcessHelp').click(function () {
        $('#processHelp').hide('slow');
    }
			);

    // Hide DEPOSIT DETAILS by default...
    $('#DepositItems').hide();
    $('#DepositTotals').hide();
    $('#plusDeposit').hide();

    // Onclick for SHOW deposit items
    $('#showDepositItems').click(function () {
        $('#DepositItems').show('slow');
        $('#DepositTotals').show('slow');
        $('#plusDeposit').show('slow');
    }
			);

    // Onclick for HIDE deposit items
    $('#hideDepositItems').click(function () {
        $('#DepositItems').hide('slow');
        $('#DepositTotals').hide('slow');
        $('#plusDeposit').hide('slow');
    });

    // Hide ORDER STEP 3 by default...
    //$('#OrderStep3').hide();

    // **************************************************************************************
    // CHECK POSTCODE
    // Check the postcode entered to see if we can deliver the boxes
    // **************************************************************************************
    $('#btnCheckPostcode').click(function (element) {

        $(this).ajaxLoader('show');
        $('#msgNoBuy').hide();
        $('#divBuy').hide();
        $('#msgNoPostcode').hide();
        $('#checkHire').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':
                $('#checkHire').show();
                $('#msgNoPostcode').hide();
                $('#msgNoBuy').hide();
                $('#divBuy').hide();
                break;
            default:
                alert('Sorry, and error has occured contacting the postcode check service: ' + msg);
        } // end switch msg
    } // end postcode callback

    // **************************************************************************************
    //  CHECK IF CAN HIRE i.e. moving within the metro area
    // **************************************************************************************
    $('#btnMetroYes').click(function () {
        $('#msgNoBuy').hide();
        $('#divBuy').hide();
        $('#msgNoPostcode').hide();
        $('#checkHire').hide();
        $('#divOrderOptions').show();
    });
    $('#btnMetroNo').click(function () {
        $('#checkHire').hide();
        $('#divOrderOptions').hide();
        $('#divBuy').show();
    });

    // **************************************************************************************
    //  CHECK IF WISH TO BUY OR NOT (Hire not available)
    // **************************************************************************************
    $('#btnSaleNo').click(function () {
        $('#msgNoPostcode').hide();
        $('#divOrderOptions').hide();
        $('#msgNoBuy').show();
    });

    //  Check the BUY CLICK event
    $('#btnSaleYes').click(function () {

        //  Get the existing Qty fields
        var htQty = 'qtysb=' + $('#qtySB').val() + '&';
        htQty += 'qtylb=' + $('#qtyLB').val() + '&';
        htQty += 'qtypr=' + $('#qtyPR').val() + '&';
        htQty += 'qtytd=' + $('#qtyTD').val() + '&';
        htQty += 'qtytr=' + $('#qtyTR').val() + '&';
        htQty += 'qtyp4=' + $('#qtyP4').val() + '&';
        htQty += 'qtyp2=' + $('#qtyP2').val() + '&';
        htQty += 'qtybw=' + $('#qtyBW').val() + '&';
        htQty += 'qtymp=' + $('#qtyMP').val() + '&';
        htQty += 'postcode=' + $('#postcode').val();

        //  Post qty's / postcode to the cache
        $(this).ajaxLoader('show');
        $.ajax({
            type: 'POST',
            url: 'AJAXput/putHireQtyCacheForSaleCalc.ashx',
            data: htQty,
            async: false,
            //dataType: 'xml',
            timeout: 10000,
            success: salesCalcCacheSuccess,
            error: Error
        });
    });
    function salesCalcCacheSuccess(result) {
        $(this).ajaxLoader('hide');
        if (result == 'cached') {
            //  Cached the qty details, so direct to the sales calc
            window.location = 'sales-calculator.html';
        }
        else {
            //  An issue with caching for the sales-calc
            alert('Sorry, there was an issue with the server, cannot process your request.  Please retry');
        }
    }

    // **************************************************************************************
    // PHONE ORDER
    // **************************************************************************************
    $('#btnPhoneOrder').click(function () {
        $('#msgNoBuy').hide();
        $('#divBuy').hide();
        $('#msgNoPostcode').hide();
        $('#checkHire').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 () {

        $(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');
        if (msg == 'cached') {
            window.location = 'order-details.html';
        }
        else {
            alert('Sorry, there was an issue proceeding with your order, please try again');
        }
    }

    // **************************************************************************************
    //  STANDARD AJAX ERROR 
    //  Traps any ajax errors..
    // **************************************************************************************
    function Error(XMLHttpRequest, textStatus, errorThrown) {
        $().ajaxLoader('hide')
        alert('Sorry, we cannot seem to access the website at the moment, please try again.');
    }

    // **************************************************************************************
    // MAIN CALCULATOR START
    // We calculate the box ordering details by checking the input quantities of hire
    // products and sale products (plus calculating delivery and grand totals)
    // **************************************************************************************

    // --------------------------------------------------------------------------------------
    // PACKAGES: Identify clicks of selected packages, and pre-populate the calculator QTY's
    //			 Sets the QTY values to the desired values, recalcs and hides the packages
    // --------------------------------------------------------------------------------------

    //	PACKAGE: Studio
    $('#package_studio').click(function () {
        $('#qtyLB').val('10');
        $('#qtySB').val('20');
        $('#qtyPR').val('2');
        $('#qtyTD').val('1');
		$('#qtyTR').val('2');
		$('#qtyP2').val('1');
		$('#qtyP4').val('');
        $('#qtyBW').val('1');
        $('#qtyMP').val('1');
        recalc();
        //$('#quantityHelp').hide('slow');
    });

    //	PACKAGE: Small
    $('#package_small').click(function () {
        $('#qtyLB').val('15');
        $('#qtySB').val('25');
        $('#qtyPR').val('3');
        $('#qtyTD').val('1');
		$('#qtyTR').val('3');
		$('#qtyP2').val('1');
		$('#qtyP4').val('');
        $('#qtyBW').val('2');
        $('#qtyMP').val('1');
        recalc();
        //$('#quantityHelp').hide('slow');
    });

    //	PACKAGE: Medium
    $('#package_medium').click(function () {
        $('#qtyLB').val('20');
        $('#qtySB').val('40');
        $('#qtyPR').val('5');
        $('#qtyTD').val('1');
		$('#qtyTR').val('5');
		$('#qtyP2').val('');
		$('#qtyP4').val('1');
        $('#qtyBW').val('3');
        $('#qtyMP').val('1');
        recalc();
        //$('#quantityHelp').hide('slow');
    });

    //	PACKAGE: Large
    $('#package_large').click(function () {
        $('#qtyLB').val('40');
        $('#qtySB').val('80');
        $('#qtyPR').val('7');
        $('#qtyTD').val('2');
		$('#qtyTR').val('8');
		$('#qtyP2').val('1');
		$('#qtyP4').val('1');
        $('#qtyBW').val('4');
        $('#qtyMP').val('2');
        recalc();
        //$('#quantityHelp').hide('slow');
    });

    // --------------------------------------------------------------------------------------
    // CALCULATOR EVENTS: Trap focus, clicks etc of QTY fields to bind the recalc function
    // --------------------------------------------------------------------------------------

    // 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() {
        // Get the actual quantity values HIRE, and check if the qty is blank - default to zero for the calc 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; }

        // Get the actual quantity values SALE, and check if the qty is blank - default to zero for the calc process
        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; }

        // Copy hire qty values to the deposit section, and get the deposit qty vals
        // This is to show the user how the deposit total is shown
        $('#qtyLB2').val(qtyLB);
        $('#qtySB2').val(qtySB);
        $('#qtyPR2').val(qtyPR);
        $('#qtyTD2').val(qtyTD);
        var qtyLB2 = parseInt($('#qtyLB2').val());
        var qtySB2 = parseInt($('#qtySB2').val());
        var qtyPR2 = parseInt($('#qtyPR2').val());
        var qtyTD2 = parseInt($('#qtyTD2').val());

        // =============================================================================								
        // Calculate Hire Section
        // =============================================================================

        // Get the hire 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());

        // Update hire 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));

        // Update hire items total
        var totLB = parseFloat($('#totallb').val());
        var totSB = parseFloat($('#totalsb').val());
        var totPR = parseFloat($('#totalpr').val());
        var totTD = parseFloat($('#totaltd').val());
        var totalHireRunning = totLB + totSB + totPR + totTD;
        var grandTotalHire = parseFloat(totLB + totSB + totPR + totTD).toFixed(2);
        $('#hireTotal').val(grandTotalHire);

        // =============================================================================								
        // Calculate DELIVERY (this only applies to HIRE items NOT SALE ITEMS)
        // the delivery is also worked out as a proportion of the hire.. i.e. if 
        // the normal delivery is 71.50, and the user has 35.00 in HIRE items, then
        // the delivery will be 36.50.  If the HIRE value is greater than 71.50,
        // then the delivery is FREE
        // =============================================================================

        // Set the current delivery charge
        var deliveryCharge = parseFloat('77.00');

        // Check if the total HIRE items are greater or less than the delivery (if less
        // we reduce the delivery cost by the hire amount)
        if (grandTotalHire > 77.00) {
            deliveryCharge = 0
        }
        else {
            // reduce the delivery cost by the hire cost to get our delivery value
            deliveryCharge = deliveryCharge - grandTotalHire;
        }

        // =============================================================================								
        // Update the hire + delivery total
        // =============================================================================								
        var htHireDeliveryTotal = totalHireRunning + deliveryCharge;
        $('#hireTotalANDdelivery').val((htHireDeliveryTotal).toFixed(2));
        $('#deliveryTotal').val((deliveryCharge).toFixed(2));

        // Also update the hidden order hire/delivery values which get posted to the order confirmation page
        $('#ordertotalhire').val(grandTotalHire);
        $('#ordertotaldelivery').val(deliveryCharge);

        // =============================================================================												
        // Calculate SALE items
        // =============================================================================								

        // Get the sale costs
        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
        $('#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 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 saleTotal = parseFloat(totTR + totP2 + totP4 + totBW + totMP);
        $('#saleGrandTotal').val(saleTotal.toFixed(2));

        // Update hidden sale total value which is posted to the order confirmation page
        $('#ordertotalsale').val(saleTotal.toFixed(2));

        // =============================================================================								
        // Calculate Deposit Section
        // =============================================================================

        // Get the hire cost values (these are within the TD tages at present, but will
        // be coming from the DB at some future time)
        var depLB = parseFloat($('#depLB').val());
        var depSB = parseFloat($('#depSB').val());
        var depPR = parseFloat($('#depPR').val());
        var depTD = parseFloat($('#depTD').val());

        // Update deposit totals
        $('#deptotallb').val(parseFloat(depLB * qtyLB2).toFixed(2));
        $('#deptotalsb').val(parseFloat(depSB * qtySB2).toFixed(2));
        $('#deptotalpr').val(parseFloat(depPR * qtyPR2).toFixed(2));
        $('#deptotaltd').val(parseFloat(depTD * qtyTD2).toFixed(2));

        // Update deposit grand total
        var totdepLB = parseFloat($('#deptotallb').val());
        var totdepSB = parseFloat($('#deptotalsb').val());
        var totdepPR = parseFloat($('#deptotalpr').val());
        var totdepTD = parseFloat($('#deptotaltd').val());

        var grandTotalDeposit = parseFloat(totdepLB + totdepSB + totdepPR + totdepTD).toFixed(2);
        $('#depositTotal').val(grandTotalDeposit);

        // Update hidden field to post through to the order confirmation page
        $('#ordertotaldeposit').val(grandTotalDeposit);

        // =============================================================================								
        // Calculate GRAND TOTAL SUMMARY SECTION
        // =============================================================================

        // Show the TOTAL HIRE (Inc Deposit) + SALE ITEMS
        $('#hirePlusSalesTotal').val((saleTotal + htHireDeliveryTotal).toFixed(2));

        // Show the TOTAL HIRE + TOTAL DEPOSIT				
        var summaryTotalHireDeposit = parseFloat(grandTotalDeposit) + parseFloat(grandTotalHire);
        $('#hirePlusDepositTotal').val(summaryTotalHireDeposit.toFixed(2));

        // Show the TOTAL SALE items
        $('#saleSummaryTotal').val(saleTotal.toFixed(2));

        // =============================================================================								
        // Calculate PAY ON DELIVERY (Total Hire+Deposit + Sale Items + Delivery)
        // =============================================================================												

        var payOnDelivery = summaryTotalHireDeposit + saleTotal + deliveryCharge;
        $('#payOnDelivery').val(payOnDelivery.toFixed(2));

        // Also update hidden field for Grand Total Pay on Delivery which is posted to the order confirmation page
        $('#ordertotalpayondelivery').val(payOnDelivery.toFixed(2));

        // =============================================================================								
        // SHOW (Repeat) the DEPOSIT which will be refunded
        // =============================================================================												

        $('#depositsummarytotal').val(grandTotalDeposit);
    }

});   // end of JQuery OnReady
