$(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
    });
    */
    
    setPrevQtys();
    recalc();
    showHidePostcodeCheck();
    
    $('#switchOrderTypeLink').click(switchOrderType);
    
    if($('#postcode_checked').val() == "Yes"){
	    //  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();
	    //$('#postcode').val($('#top_up_postcode').val()); //ok it's not a top-up but we're piggy-backing
    }else{
    	//clearCalc();
        //  Now show/hide the necessary divs
        $('#divCheckPostcode').show();
        $('#msgNoPostcode').hide();
        $('#divOrderOptions').hide();
        $('#divPhoneOrder').hide();
    }
    
    var is_topup;
    if (!document.getElementById('is_top_up')){
    	is_topup = false;
    }else{
    	is_topup = true;
    }
    if(is_topup){
    	alert("top up");
    	$('#divCheckPostcode').show();
    	$('#msgNoBuy').hide();
        $('#divBuy').hide();
        $('#checkHire').hide();
        $('#divOrderOptions').hide();
        $('#postcode').val($('#top_up_postcode').val());
    }
    
    
    /*
    //  ----------------------------------------------------------------------
    //  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, an error occured storing your order quantities. 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();
        var postcode1 = '';
         if (isNaN(postcode) || 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.php',
           data: 'postcode=' + postcode + '&postcode1=' + postcode1,
            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,false':
            case 'false,true':
                $('#msgNoPostcode').show();
                break;
            case 'true,false':
            case 'true,true':
                $('#divOrderOptions').show();
                $('#msgNoPostcode').hide();
                //$('#divCheckPostcode').hide();
                break;
            default:
                alert('Sorry, an 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/putOrderQuantities.php',
            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();
    });
    

});                           // 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];
    }
}
*/


