$(document).ready(function(){
    OZ.init();
});


var OZ = window.OZ || {};
OZ = {
    //Which page of the form are we on?
    currentPage: 0,
    
    selctedOriginState: '',
    selctedDestinationState: '',
    
    selectedQuote: '',
    
    init: function() {
        $('#oz-Content .oz-next').bind("click", function(e){
            OZ.switchPage(1);
        });
        $('#oz-Content .oz-back').bind("click", function(e){
            OZ.switchPage(-1);
        });
        $('#oz-Content .oz-back-to-start').bind("click", function(e){
            OZ.switchPage(0);
        });
        
        //Change thing your sending
        $('#oz-sending').bind("change", function(e){
            var selectedPackagingTypes = OZ.packagingTyperPerDropDown[$(this).val()];
            
            var html = '';
            for(i in selectedPackagingTypes) {
                html += "<option value='"+OZ.packagingTypes[selectedPackagingTypes[i]]+"'>"+OZ.packagingTypes[selectedPackagingTypes[i]]+"</option>";
            }
            
            $('#oz-packaging').html(html);
        });
        
        //Update quanity or weight
        $('#oz-quanity, #oz-weight').bind('blur', function(e){
            var qunaity = $('#oz-quanity').val();
            var weight = $('#oz-weight').val(); 
            
            if(qunaity != '' && weight != '') {
                var totalWeight = parseInt(qunaity) * parseInt(weight);
                $('#oz-total-weight').html(totalWeight);
            }
        });
        
        //Update business or residential
        $('.oz-type-origin').bind('click', function(e){
            if($(e.target).val() == 'Business') {
                $('.oz-company-name-origin').show();
            }
            else {
                $('.oz-company-name-origin').hide();
            }
        });
        //Update business or residential
        $('.oz-type-destination').bind('click', function(e){
            if($(e.target).val() == 'Business') {
                $('.oz-company-name-destination').show();
            }
            else {
                $('.oz-company-name-destination').hide();
            }
        });
        
        //Address lookup
        $('.oz-find-address').bind('click', function(e){
            var target = $(e.target);
            var elmSelected = target.attr('name');
            var postcode = $('#oz-postcode-'+elmSelected).val();
            
            if(postcode == '')
            {
                $('#oz-postcode-error-'+elmSelected).html('Please enter a valid postcode').show();
                return false;
            }
            
            var params = {
                action: 'addressLookup',
                postcode: postcode
            };
            
            target.val('Loading...');
            $.post('ajax_handlers/freight_funcs.php', params, function(data){
                target.val('Find');
                if(data.error) {
                    $('#oz-postcode-error-'+elmSelected).html('Please enter a valid postcode').show();
                }
                else {
                    var html = '';
                    for(i in data) {
                        html += "<option value='"+data[i].suburb+"'>"+data[i].suburb+"</option>";
                        if(elmSelected == 'origin')
                            OZ.selctedOriginState = data[i].state;
                        else
                            OZ.selctedDestinationState = data[i].state;
                    }
                    
                    $('#oz-suburb-'+elmSelected).html(html).removeClass('oz-form-error');
                    $('.oz-suburb-'+elmSelected).css('visibility', 'visible');
                }
            }, 'json');
        });
    },

    
    switchPage: function(direction) {
        //If going forward
        if(direction > 0) {
            if(!OZ.validate()) {
                return false;
            }
        }
        
        if(this.currentPage == 2 && direction == 1) {
            OZ.getQuotes();
        }
        
        if(this.currentPage == 6 && direction == 1) {
            OZ.sendToPayment();
            return false;
        }
        
        
        $('#oz-page-'+this.currentPage).hide();
        if(direction == 0)
            this.currentPage = 0;
        else
            this.currentPage += direction;
            
        //Fill in address details
        if(this.currentPage == 5) {
            $('#oz-suburb-fixed-origin').html($('#oz-suburb-origin').val());
            $('#oz-postcode-fixed-origin').html($('#oz-postcode-origin').val());
        }
        if(this.currentPage == 6) {
            $('#oz-suburb-fixed-destination').html($('#oz-suburb-destination').val());
            $('#oz-postcode-fixed-destination').html($('#oz-postcode-destination').val());
        }
        
        
        $('#oz-page-'+this.currentPage).show();
    },
    
    validate: function() {
        var currentElem = null;
        for(i in OZ.fieldsToValidate[this.currentPage]) {
            currentElem = $('#'+i);
            
            if( (i == 'oz-terms' && !currentElem.attr('checked')) ||
                jQuery.trim(currentElem.val()) == '')
            {
                currentElem.addClass('oz-form-error');
                alert(OZ.fieldsToValidate[this.currentPage][i]);
                return false;
            }
            else
            {
                currentElem.removeClass('oz-form-error');
            }
        }
        
        return true;
    },
    
    getQuotes: function() {
        $('#oz-quote-error').hide();
        
        var params = {
            'action': 'getQuotes',
            'affil-id': $('#oz-affil-id').val(),
            
            'sending': $('#oz-sending').val(),
            'packaging': $('#oz-packaging').val(),
            'quanity': $('#oz-quanity').val(),
            'fragile': $('#oz-fragile').is(':checked') ? 'Y' : 'N',
            
            'length': $('#oz-length').val(),
            'width': $('#oz-width').val(),
            'height': $('#oz-height').val(),
            'weight': $('#oz-weight').val(),
            
            //'street-origin': $('#oz-street-origin').val(),
            'postcode-origin': $('#oz-postcode-origin').val(),
            'suburb-origin': $('#oz-suburb-origin').val(),
            'state-origin': this.selctedOriginState,
            'type-origin': $("input[name='type-origin']:checked").val(),
            
            //'street-destination': $('#oz-street-destination').val(),
            'postcode-destination': $('#oz-postcode-destination').val(),
            'suburb-destination': $('#oz-suburb-destination').val(),
            'state-destination': this.selctedDestinationState,
            'type-destination': $("input[name='type-destination']:checked").val(),
            
            'ready-date': $('#oz-pickup-year').val() + '-' + $('#oz-pickup-month').val() + '-' + $('#oz-pickup-day').val(),
            'ready-time': $("input[name='pickup-time']:checked").val()
        };
        
        $.post('ajax_handlers/freight_funcs.php', params, function(data){
            if(data.error) {
                OZ.switchPage(-1);
                $('#oz-quote-error').html(data.error).show();
            }
            else {
                OZ.drawQuotes(data.data);
                OZ.switchPage(1);
            }
        }, 'json');
    },
    
    drawQuotes: function(quotes) {

        var html = '';
        for(i in quotes) {
            var inDays = (quotes[i].etaFrom == quotes[i].etaTo) ? quotes[i].etaTo : quotes[i].etaFrom + '-' + quotes[i].etaTo;
            
            html += '<tr><td>' + quotes[i].carrier + ' (' + quotes[i].service + ')</td>';
            html += '<td>' + inDays + '</td>';
            html += '<td>$' + quotes[i].price + '</td>';
            html += '<td><a href="" class="oz-buy-link" id="' + quotes[i].ourRef + '">Buy</a></td></tr>';

            //html += '<td><a href="https://secure.4mation.com.au/globalps/payment.php?buyDQuoteId=' + quotes[i].ourRef + '&CompanyID=40" target="_top">Buy</a></td></tr>';
        }
        
        $('#oz-page-4 tr:gt(1)').remove();
        $('#oz-page-4 tr:last').after(html);
        
        $('.oz-buy-link').click(function(e){
            e.preventDefault();
            
            OZ.buyQuote($(e.target).attr('id'));
           
           return false;
        });
    },

    buyQuote: function(quoteRef) {
        OZ.selectedQuote = quoteRef;
        OZ.switchPage(1);
    },
    
    //This needs to save contact details then send to payment page
    sendToPayment: function() {
        var params = {
            'action': 'saveContactInfo',
            'quote-ref': OZ.selectedQuote,
            
            'street-origin': $('#oz-street-origin').val(),
            'postcode-origin': $('#oz-postcode-origin').val(),
            'suburb-origin': $('#oz-suburb-origin').val(),
            'state-origin': this.selctedOriginState,
            
            'name-origin': $('#oz-name-origin').val(),
            'company-name-origin': $('#oz-company-name-origin').val(),
            'phone1-origin': $('#oz-phone1-origin').val(),
            'phone2-origin': $('#oz-phone2-origin').val(),
            'email-origin': $('#oz-email-origin').val(),
            
            'street-destination': $('#oz-street-destination').val(),
            'postcode-destination': $('#oz-postcode-destination').val(),
            'suburb-destination': $('#oz-suburb-destination').val(),
            'state-destination': this.selctedDestinationState,
            
            'name-destination': $('#oz-name-destination').val(),
            'company-name-destination': $('#oz-company-name-destination').val(),
            'phone1-destination': $('#oz-phone1-destination').val(),
            'phone2-destination': $('#oz-phone2-destination').val(),
            'email-destination': $('#oz-email-destination').val()
        };
        
        $.post('ajax_handlers/freight_funcs.php', params, function(data){
            window.open('https://secure.4mation.com.au/globalps/payment.php?buyDQuoteId=' + OZ.selectedQuote + '&CompanyID=40', "_top");
        }, 'json');
    },
    
    fieldsToValidate: {
        0: {
            'oz-quanity': 'Please enter a valid quanity',
            'oz-length': 'Please enter a valid length',
            'oz-width': 'Please enter a valid width',
            'oz-height': 'Please enter a valid height',
            'oz-weight': 'Please enter a valid weight'
        },
        1: {
            'oz-postcode-origin': 'Please enter a valid origin address',
            'oz-suburb-origin': 'Please enter a valid origin address',
            'oz-postcode-destination': 'Please enter a valid destination address',
            'oz-suburb-destination': 'Please enter a valid destination address'
        },
        5: {
            'oz-name-origin': 'Please enter a valid contact name',
            'oz-street-origin': 'Please enter a valid street',
            
            'oz-phone1-origin': 'Please enter a valid phone number',
            'oz-email-origin': 'Please enter a valid email'
        },
        6: {
            'oz-name-destination': 'Please enter a valid contact name',
            'oz-street-destination': 'Please enter a valid street',
            
            'oz-phone1-destination': 'Please enter a valid phone number',
            'oz-email-destination': 'Please enter a valid email',
            
            'oz-terms': 'Please agree to the terms and conditions before continuing'
           }
    },

    
    packagingTypes: {
        1: 'Backpack',
        3: 'Box',
        6: 'Carton',
        7: 'Crate',
        8: 'Cylinder',
        9: 'Document Envelope',
        11: 'Flat Pack',
        12: 'Letter',
        14: 'Pallet',
        15: 'Parcel',
        16: 'Pipe',
        18: 'Satchel/Bag',
        19: 'Skid',
        20: 'Suitcase',
        21: 'Tube',
        22: 'Unpackaged or N/A',
        23: 'Wheel/Tyre'
    },
    
    packagingTyperPerDropDown: {
        'Household Goods': [3,6,7,8,9,11,12,14,15,18,19,22,23],
        'Excess Baggage': [1,3,6,20],
        'Furniture': [3,6,7,11,14,19,22],
        'Other (Etc.)': [3,6,7,8,9,11,12,14,15,16,18,19,21,22,23]
    }
};

