/**
*
* 	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
*  
* 	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 () {
	//$(".voucher").colorbox();
    //free delivery and no need to check postcode on top-ups so lets check if the server 
    //provided the magic word for this request
 
    // Clear the QTY values (we have this as a function as we may need to call this from another event)
   // clearCalc();
    
    //set quantities based on posted data and recalc
    setPrevQtys();
    recalc();
    showHidePostcodeCheck();
    
    $('#paperpickup').change(function (e) {
        recalc();
    });
	   var is_topup = Boolean(document.getElementById('is_top_up'));
    if(is_topup){
    	alert("top up");
		$('#pickuppostcode').val($('#postcode').val());
		$('#divOrderOptions').hide();
    }
    
    // -------------------------------------------------------------
    // 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');
    });

    // 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();
        var postcode1 = $('#pickuppostcode').val();        
        if (isNaN(postcode) || isNaN(postcode1) || postcode == '' || postcode1 == '') {
            $().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':
                $('#msgNoPostcode').show();
                $('#postcode_checked').val('No');
                break;
            case 'false,true':
                $('#msgNoPostcode').show();
                $('#postcode_checked').val('No');
                break;                
            case 'true,false':
                $('#checkHire').hide();
                $('#divOrderOptions').hide();
                $('#divBuy').show();
                break;
            case 'true,true':
                $('#msgNoBuy').hide();
                $('#divBuy').hide();
                $('#msgNoPostcode').hide();
                $('#checkHire').hide();
                $('#divOrderOptions').show();
                break;                
            default:
                alert('Sorry, an error has occured contacting the postcode check service: ' + msg);
            	$('#postcode_checked').val('No');
        } // 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(switchOrderType);
    $('#switchOrderTypeLink').click(switchOrderType);
    
    /*
    function salesCalcCacheSuccess(result) {
        //$(this).ajaxLoader('hide');
        
        if (result == 'cached') {
	        //  Cached the qty details, so direct to the sales calc
	    	
	        //alert('gone');
	        toSalesForm=document.createElement("form");
	    	var fldName = "is_top_up";
	    	var salesField = document.createElement('input');
	    	salesField.setAttribute("name",fldName);
			salesField.setAttribute("id",fldName);
			salesField.setAttribute('type','text');
			salesField.setAttribute("value",$('#'+fldName).val());
			toSalesForm.appendChild(salesField);
			toSalesForm.setAttribute('method','post');
	    	toSalesForm.action='sales-calculator.html';
	    	toSalesForm.submit();
    		//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/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');
        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
   
    // --------------------------------------------------------------------------------------
    // 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();
    });

});      // end of JQuery OnReady

