var submitter = null;
function submitFunction() {
   submitter = 1;
}

var errCSS = {
    'border-color': 'red',
    'border-style': 'solid'
};

var checkout = {
    charset: 'UTF-8',
    pageLinks: {},
    fieldSuccessHTML: '<div style="margin-left:3px;margin-top:1px;float:left;" class="success_icon ui-icon-green ui-icon-circle-check"></div>',
    fieldErrorHTML: '<div style="margin-left:3px;margin-top:1px;float:left;" class="error_icon ui-icon-red ui-icon-circle-close"></div>',
    fieldRequiredHTML: '<div style="margin-left:3px;margin-top:1px;float:left;" class="required_icon ui-icon-red ui-icon-gear"></div>',
    showAjaxLoader: function (){
        $('#ajaxLoader').show();
    },
    hideAjaxLoader: function (){
        $('#ajaxLoader').hide();
    },
    showAjaxMessage: function (message){
        $('#checkoutButtonContainer').hide();
        $('#ajaxMessages').show().html(message);
    },
    hideAjaxMessage: function (){
        $('#checkoutButtonContainer').show();
        $('#ajaxMessages').hide();
    },
    fieldHasError: function ($element, minLength){
        if ($element.is(':visible') && $element.hasClass('required')){
            if ($element.val().length < minLength){
                return true;
            }
        }
      return false;
    },
    fieldErrorCheck: function ($element, forceCheck, hideIcon){
        forceCheck = forceCheck || false;
        hideIcon = hideIcon || false;
        var errMsg = this.checkFieldForErrors($element, forceCheck);
        if (hideIcon == false){
            if (errMsg != false){
                this.addIcon($element, 'error', errMsg);
                return true;
            }else{
                this.addIcon($element, 'success', errMsg);
            }
        }
      return false;
    },
    checkFieldForErrors: function ($element, forceCheck){
        var hasError = false;
        if ($element.is(':visible') && ($element.hasClass('required') || forceCheck == true)){
            var errCheck = getFieldErrorCheck($element);
            if (!errCheck.errMsg){
                return false;
            }
            
            switch($element.attr('type')){
                case 'password':
                    if ($element.attr('name') == 'password'){
                        if ($element.val().length < errCheck.minLength){
                            hasError = true;
                        }
                    }else{
                        if ($element.val() != $(':password[name="password"]').val()){
                            hasError = true;
                        }
                    }
                break;
                case 'radio':
                    if ($(':radio[name="' + $element.attr('name') + '"]:checked').size() <= 0){
                        hasError = true;
                    }
                break;
                case 'checkbox':
                    if ($(':checkbox[name="' + $element.attr('name') + '"]:checked').size() <= 0){
                        hasError = true;
                    }
                break;
                case 'select-one':
                    if ($element.val() == ''){
                        hasError = true;
                    }
                break;
                default:
                    if ($element.val().length < errCheck.minLength){
                        hasError = true;
                    }
                break;
            }
            if (hasError == true){
                return errCheck.errMsg;
            }
        }
      return hasError;
    },
    addIcon: function ($curField, iconType, title){
        title = title || false;
        $('.success_icon, .error_icon, .required_icon', $curField.parent()).hide();
        switch(iconType){
            case 'error':
                if (this.initializing == true){
                    this.addRequiredIcon($curField, 'Required');
                }else{
                    this.addErrorIcon($curField, title);
                }
            break;
            case 'success':
                this.addSuccessIcon($curField, title);
            break;
            case 'required':
                this.addRequiredIcon($curField, 'Required');
            break;
        }
    },
    addSuccessIcon: function ($curField, title){
        if ($('.success_icon', $curField.parent()).size() <= 0){
            $curField.parent().append(this.fieldSuccessHTML);
        }
        $('.success_icon', $curField.parent()).attr('title', title).show();
    },
    addErrorIcon: function ($curField, title){
        if ($('.error_icon', $curField.parent()).size() <= 0){
            $curField.parent().append(this.fieldErrorHTML);
        }
        $('.error_icon', $curField.parent()).attr('title', title).show();
    },
    addRequiredIcon: function ($curField, title){
        if ($curField.hasClass('required')){
            if ($('.required_icon', $curField.parent()).size() <= 0){
                $curField.parent().append(this.fieldRequiredHTML);
            }
            $('.required_icon', $curField.parent()).attr('title', title).show();
        }
    },
    clickButton: function (elementName){
        if ($(':radio[name="' + elementName + '"]').size() <= 0){
            $('input[name="' + elementName + '"]').click();
        }else{
            $(':radio[name="' + elementName + '"]:checked').click();
        }
    },
    addRowMethods: function($row){
        $row.hover(function (){
            if (!$(this).hasClass('moduleRowSelected')){
                $(this).addClass('moduleRowOver');
            }
        }, function (){
            if (!$(this).hasClass('moduleRowSelected')){
                $(this).removeClass('moduleRowOver');
            }
        }).click(function (){
            if (!$(this).hasClass('moduleRowSelected')){
                var selector = ($(this).hasClass('shippingRow') ? '.shippingRow' : '.paymentRow') + '.moduleRowSelected';
                $(selector).removeClass('moduleRowSelected');
                $(this).removeClass('moduleRowOver').addClass('moduleRowSelected');
                if (!$(':radio', $(this)).is(':checked')){
                    $(':radio', $(this)).attr('checked', 'checked').click();
                }
            }
        });
    },
    queueAjaxRequest: function (options){
        var checkoutClass = this;
        var o = {
            url: options.url,
            cache: options.cache || false,
            dataType: options.dataType || 'html',
            type: options.type || 'GET',
            contentType: options.contentType || 'application/x-www-form-urlencoded; charset=' + this.ajaxCharset,
            data: options.data || false,
            beforeSend: function (){
                checkoutClass.showAjaxMessage(options.beforeSendMsg || 'Ajax Operation, Please Wait...');
                checkoutClass.showAjaxLoader();
            },
            complete: function (){
                checkoutClass.hideAjaxMessage();
                if (document.ajaxq.q['orderUpdate'].length <= 0){
                    checkoutClass.hideAjaxLoader();
                }
            },
            success: options.success,
            error: function (){
                alert(options.errorMsg || 'There was an ajax error, please contact IT Web Experts for support.');
            }
        };
        $.ajaxq('orderUpdate', o);
    },
    updateAddressHTML: function (type){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=' + (type == 'shipping' ? 'getShippingAddress' : 'getBillingAddress'),
            type: 'post',
            beforeSendMsg: 'Updating ' + (type == 'shipping' ? 'Shipping' : 'Billing') + ' Address',
            success: function (data){
                $('#' + type + 'Address').html(data);
            },
            errorMsg: 'There was an error loading your ' + type + ' address, please inform IT Web Experts about this error.'
        });
    },
    updateCartView: function (){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=updateCartView',
            type: 'post',
            beforeSendMsg: 'Refreshing Shopping Cart',
            success: function (data){
                if (data == 'none'){
                    document.location = checkoutClass.pageLinks.shoppingCart;
                }else{
                    $('#shoppingCart').html(data);
                
                    $('.removeFromCart').each(function (){
                        checkoutClass.addCartRemoveMethod($(this));
                    });
                }
            },
            errorMsg: 'There was an error refreshing the shopping cart, please inform IT Web Experts about this error.'
        });
    },
    updateFinalProductListing: function (){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=getProductsFinal',
            type: 'post',
            beforeSendMsg: 'Refreshing Final Product Listing',
            success: function (data){
                $('.finalProducts').html(data);
            },
            errorMsg: 'There was an error refreshing the final products listing, please inform IT Web Experts about this error.'
        });
    },
    updateOrderTotals: function (){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            cache: false,
            data: 'action=getOrderTotals',
            type: 'post',
            beforeSendMsg: 'Updating Order Totals',
            success: function (data){
                $('.orderTotals').html(data);
                checkoutClass.hideAjaxLoader();
            },
            errorMsg: 'There was an error refreshing the shopping cart, please inform IT Web Experts about this error.'
        });
    },
    updateModuleMethods: function (action){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=update' + (action == 'shipping' ? 'Shipping' : 'Payment') + 'Methods',
            type: 'post',
            beforeSendMsg: 'Updating ' + (action == 'shipping' ? 'Shipping' : 'Payment') + ' Methods',
            success: function (data){
                $('#no' + (action == 'shipping' ? 'Shipping' : 'Payment') + 'Address').hide();
                $('#' + action + 'Methods').html(data);
                $('#' + action + 'Methods').show();
            
                $('.' + action + 'Row').each(function (){
                    checkoutClass.addRowMethods($(this));
                
                    $('input[name="' + action + '"]', $(this)).each(function (){
                        if (action == 'shipping'){
                            $(this).click(function (){
                                checkoutClass.setShippingMethod($(this).val());
                                checkoutClass.updateOrderTotals();
                            });
                        }else{
                            $(this).click(function (){
                                checkoutClass.setPaymentMethod($(this));
                                checkoutClass.updateOrderTotals();
                            });
                        }
                    });
                });
                
                if (action == 'shipping'){
                    checkoutClass.clickButton('shipping');
                }else{
                    checkoutClass.clickButton('payment');
                }
            },
            errorMsg: 'There was an error updating ' + action + ' methods, please inform IT Web Experts about this error.'
        });
    },
    updateShippingMethods: function (){
        this.updateModuleMethods('shipping');
    },
    updatePaymentMethods: function (){
        this.updateModuleMethods('payment');
    },
    setModuleMethod: function (type, method, successFunction){
        var checkoutClass = this;
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=set' + (type == 'shipping' ? 'Shipping' : 'Payment') + 'Method&method=' + method,
            type: 'post',
            beforeSendMsg: 'Setting ' + (type == 'shipping' ? 'Shipping' : 'Payment') + ' Method',
            dataType: 'json',
            success: successFunction,
            errorMsg: 'There was an error setting ' + type + ' method, please inform IT Web Experts about this error.'
        });
    },
    setShippingMethod: function (method){
        var checkoutClass = this;
        this.setModuleMethod('shipping', method, function (data){
        });
    },
    setPaymentMethod: function ($button){
        var checkoutClass = this;
        this.setModuleMethod('payment', $button.val(), function (data){
            $('.paymentFields').remove();
            if (data.inputFields != ''){
                $(data.inputFields).insertAfter($button.parent().parent());
            }
        });
    },
    loadAddressBook: function ($dialog, type){
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            data: 'action=getAddressBook&addressType=' + type,
            type: 'post',
            beforeSendMsg: 'Loading Address Book',
            success: function (data){
                $dialog.html(data);
            },
            errorMsg: 'There was an error loading your address book, please inform IT Web Experts about this error.'
        });
    },
    addCountryAjax: function ($input, fieldName, stateCol){
        var checkoutClass = this;
        $input.change(function (event, callBack){
            if ($(this).hasClass('required')){
                if ($(this).val() != '' && $(this).val() > 0){
                    checkoutClass.addIcon($(this), 'success');
                }
            }
            var $thisName = $(this).attr('name');
            checkoutClass.queueAjaxRequest({
                url: checkoutClass.pageLinks.checkout,
                data: 'action=countrySelect&fieldName=' + fieldName + '&cID=' + $(this).val(),
                type: 'post',
                beforeSendMsg: 'Getting Country\'s Zones',
                success: function (data){
                    $('#' + stateCol).html(data);
                    var $curField = $('*[name="' + fieldName + '"]', $('#' + stateCol));
                    
                    if ($curField.hasClass('required')){
                        checkoutClass.addIcon($curField, 'required');
                    }
                    
                    if ($curField.attr('type') == 'select-one'){
                        $curField.change(function (){
                            checkoutClass.fieldErrorCheck($(this));
                        });
                    }else{
                        $curField.blur(function (){
                            checkoutClass.fieldErrorCheck($(this));
                        });
                    }
                    
                    if (callBack){
                        callBack.call();
                    }
                },
                errorMsg: 'There was an error getting states, please inform IT Web Experts about this error.'
            });
        });
    },
    addCartRemoveMethod: function ($element){
        var checkoutClass = this;
        $element.click(function (){
            var $productRow = $(this).parent().parent();
            checkoutClass.queueAjaxRequest({
                url: checkoutClass.pageLinks.checkout,
                data: $(this).attr('linkData'),
                type: 'post',
                beforeSendMsg: 'Removing Product From Cart',
                dataType: 'json',
                success: function (data){
                    if (data.products == 0){
                        document.location = checkoutClass.pageLinks.shoppingCart;
                    }else{
                        $productRow.remove();
                        checkoutClass.updateFinalProductListing();
                        checkoutClass.updateShippingMethods();
                        checkoutClass.updateOrderTotals();
                    }
                },
                errorMsg: 'There was an error updating shopping cart, please inform IT Web Experts about this error.'
            });
          return false;
        });    
    },
    processBillingAddress: function (){
        if ($('.required_icon:visible, .error_icon:visible', $('#billingAddress')).size() > 0){
            return;
        }
        this.setBillTo();
        if ($('#diffShipping:checked').size() <= 0){
            this.setSendTo(false);
        }else{
            this.setSendTo(true);
        }
                
        this.updateCartView();
        this.updateFinalProductListing();
        this.updatePaymentMethods();
        this.updateShippingMethods();
        this.updateOrderTotals();
    },
    setCheckoutAddress: function (type, useShipping){
        var selector = '#' + type + 'Address';
        var sendMsg = 'Setting ' + (type == 'shipping' ? 'Shipping' : 'Billing') + ' Address';
        var errMsg = type + ' address';
        if (type == 'shipping' && useShipping == false){
            selector = '#billingAddress';
            sendMsg = 'Setting Billing Address';
            errMsg = 'billing address';
        }
        
        this.queueAjaxRequest({
            url: this.pageLinks.checkout,
            beforeSendMsg: sendMsg,
            dataType: 'json',
            data: 'action=' + (type == 'shipping' ? 'setSendTo' : 'setBillTo') + '&' + $(':select, :radio, :input', $(selector)).serialize(),
            type: 'post',
            success: function (){
            },
            errorMsg: 'There was an error updating your ' + errMsg + ', please inform IT Web Experts about this error.'
        });
    },
    setBillTo: function (){
        this.setCheckoutAddress('billing', false);
    },
    setSendTo: function (useShipping){
        this.setCheckoutAddress('shipping', useShipping);
    },
    initCheckout: function (){
        var checkoutClass = this;
        
        if (this.loggedIn == false){
            $('#shippingAddress').hide();
            $('#shippingMethods').html('');
        }
        
        $('#checkoutNoScript').remove();
        $('#checkoutYesScript').show();
        
        $('.removeFromCart').each(function (){
            checkoutClass.addCartRemoveMethod($(this));
        });
        
        this.updateFinalProductListing();
        this.updateOrderTotals();
        
        $('checkbox[name="billing_newsletter"]').each(function (){
            $(this).unbind('click').click(function (){
                checkoutClass.queueAjaxRequest({
                    url: checkoutClass.pageLinks.checkout,
                    data: 'action=setCustomerNewsletter&status=' + (this.checked ? 'true' : 'false'),
                    type: 'post',
                    beforeSendMsg: 'Setting Newsletter',
                    dataType: 'json',
                    success: function (data){
                    },
                    errorMsg: 'There was an error (un)setting your newsletter subscription, please inform IT Web Experts about this error.'
                });
            });
        });
        
        $('#diffShipping').click(function (){
            if (this.checked){
                $('#shippingAddress').show();
                $('#shippingMethods').html('');
                $('#noShippingAddress').show();
            }else{
                $('#shippingAddress').hide();
                var errCheck = checkBillingAddress(false);
                if (errCheck == ''){
                    $('#noShippingAddress').hide();
                    checkoutClass.updateShippingMethods();
                }else{
                    $('#noShippingAddress').show();
                }
            }
        });
    
        if (this.loggedIn == true){
            $('.shippingRow, .paymentRow').each(function (){
                checkoutClass.addRowMethods($(this));
            });
    
            $('input[name="payment"]').each(function (){
                $(this).click(function (){
                    checkoutClass.setPaymentMethod($(this));
                    checkoutClass.updateOrderTotals();
                });
            });
        
            $('input[name="shipping"]').each(function (){
                $(this).click(function (){
                    checkoutClass.setShippingMethod($(this).val());
                    checkoutClass.updateOrderTotals();
                });
            });
        }
        
        if ($('#paymentMethods').is(':visible')){
            this.clickButton('payment');
        }
        
        if ($('#shippingMethods').is(':visible')){
            this.clickButton('shipping');
        }
    
        $(':select, :radio, :input, :password', $('#billingAddress')).each(function (){
            if ($(this).attr('name') != undefined && $(this).attr('type') != 'checkbox'){
                if ($(this).attr('type') == 'select-one'){
                    $(this).change(function (){
                        if (checkoutClass.fieldErrorCheck($(this)) == false){
                            checkoutClass.processBillingAddress();
                        }
                    });
                }else if ($(this).attr('type') == 'password'){
                    $(this).blur(function (){
                        if (checkoutClass.fieldErrorCheck($(this), true) == false){
                            checkoutClass.processBillingAddress();
                        }
                    });
                    if ($(this).attr('name') == 'password'){
                        $(this).focus(function (){
                            $(':password[name="confirmation"]').val('');
                        });
                        
                        var rObj = getFieldErrorCheck($(this));
                        $(this).pstrength({
                            addTo: '#pstrength_password',
                            minchar: rObj.minLength
                        });
                    }
                }else{
                    $(this).blur(function (){
                        if ($(this).hasClass('required')){
                            if (checkoutClass.fieldErrorCheck($(this)) == false){
                                checkoutClass.processBillingAddress();
                            }
                        }else{
                            checkoutClass.processBillingAddress();
                        }
                    });
                }
                
                if ($(this).hasClass('required')){
                    checkoutClass.addIcon($(this), 'required');
                }
            }
        });
        
         $('input[name="billing_email_address"]').unbind('blur').blur(function (){
            if (checkoutClass.initializing == true){
                checkoutClass.addIcon($(this), 'required');
            }else{
                if (checkoutClass.fieldErrorCheck($(this), true, true) == false){
                    checkoutClass.queueAjaxRequest({
                        url: checkoutClass.pageLinks.checkout,
                        data: 'action=checkEmailAddress&emailAddress=' + $(this).val(),
                        type: 'post',
                        beforeSendMsg: 'Checking Email Address',
                        dataType: 'json',
                        success: function (data){
                            var $curField = $('input[name="billing_email_address"]');
                            $('.success, .error', $curField.parent()).hide();
                            if (data.success == false){
                                checkoutClass.addIcon($curField, 'error', data.errMsg);
                            }else{
                                checkoutClass.addIcon($curField, 'success');
                            }
                        },
                        errorMsg: 'There was an error checking email address, please inform IT Web Experts about this error.'
                    });
                }
            }
        });
    
       
        $(':select, :radio, :input', $('#shippingAddress')).each(function (){
            if ($(this).attr('name') != undefined && $(this).attr('type') != 'checkbox'){
                $(this).blur(function (){
                    if (checkoutClass.fieldErrorCheck($(this)) == false){
                        checkoutClass.setSendTo(true);
                        checkoutClass.updateCartView();
                        checkoutClass.updateFinalProductListing();
                        checkoutClass.updateShippingMethods();
                    }else{
                        $('#noShippingAddress').show();
                        $('#shippingMethods').hide();
                    }
                });
                
                if ($(this).hasClass('required')){
                    checkoutClass.addIcon($(this), 'required');
                }
            }
        });
        
        $('select[name="shipping_country"], select[name="billing_country"]').each(function (){
            var $thisName = $(this).attr('name');
            if ($thisName == 'shipping_country'){
                checkoutClass.addCountryAjax($(this), 'shipping_state', 'stateCol_shipping');
            }else{
                checkoutClass.addCountryAjax($(this), 'billing_state', 'stateCol_billing');
            }
            
            $(this).change();
        });

        $('#updateCartButton').click(function (){
            checkoutClass.showAjaxLoader();
            checkoutClass.queueAjaxRequest({
                url: checkoutClass.pageLinks.checkout,
                data: 'action=updateQuantities&' + $('input', $('#shoppingCart')).serialize(),
                type: 'post',
                beforeSendMsg: 'Updating Product Quantities',
                dataType: 'json',
                success: function (){
                    checkoutClass.updateCartView();
                    checkoutClass.updateFinalProductListing();
                    if ($('#noPaymentAddress:hidden').size() > 0){
                        checkoutClass.updatePaymentMethods();
                        checkoutClass.updateShippingMethods();
                    }
                    checkoutClass.updateOrderTotals();
                },
                errorMsg: 'There was an error updating shopping cart, please inform IT Web Experts about this error.'
            });
          return false;
        });
        
        $('#checkoutButton').click(function (){
            var errMsg = '';
            if ($('.required_icon:visible', $('#billingAddress')).size() > 0){
                errMsg += 'Please fill in all required fields in "Billing Address"' + "\n";
            }
            if ($('.error_icon:visible', $('#billingAddress')).size() > 0){
                errMsg += 'Please correct fields with errors in "Billing Address"' + "\n";
            }
            
            if ($('#diffShipping:checked').size() > 0){
                if ($('.required_icon:visible', $('#shippingAddress')).size() > 0){
                    errMsg += 'Please fill in all required fields in "Shipping Address"' + "\n";
                }
                if ($('.error_icon:visible', $('#shippingAddress')).size() > 0){
                    errMsg += 'Please correct fields with errors in "Shipping Address"' + "\n";
                }
            }
            
            if (errMsg != ''){
                errMsg = '------------------------------------------------' + "\n" + 
                         '                 Address Errors                 ' + "\n" + 
                         '------------------------------------------------' + "\n" +
                         errMsg;
            }
            
            if ($(':radio[name="payment"]:checked').size() <= 0){
                if ($('input[name="payment"]:hidden').size() <= 0){
                    errMsg += '------------------------------------------------' + "\n" + 
                              '           Payment Selection Error              ' + "\n" + 
                              '------------------------------------------------' + "\n" + 
                              'You must select a payment method.' + "\n";
                }
            }
            
            if ($(':radio[name="shipping"]:checked').size() <= 0){
                if ($('input[name="shipping"]:hidden').size() <= 0){
                    errMsg += '------------------------------------------------' + "\n" + 
                              '           Shipping Selection Error             ' + "\n" + 
                              '------------------------------------------------' + "\n" + 
                              'You must select a shipping method.' + "\n";
                }
            }
            
            if (errMsg.length > 0){
                alert(errMsg);
                return false;
            }else{
                return true;
            }
        });
        
        if (this.ccgvInstalled == true){
            $('input[name="gv_redeem_code"]').focus(function (){
                if ($(this).val() == 'redeem code'){
                    $(this).val('');
                }
            });
            
            $('#voucherRedeem').click(function (){
                checkoutClass.queueAjaxRequest({
                    url: checkoutClass.pageLinks.checkout,
                    data: 'action=redeemVoucher&code=' + $('input[name="gv_redeem_code"]').val(),
                    type: 'post',
                    beforeSendMsg: 'Validating Coupon',
                    dataType: 'json',
                    success: function (data){
                        if (data.success == false){
                            alert('Coupon is either invalid or expired.');
                        }
                        checkoutClass.updateOrderTotals();
                    },
                    errorMsg: 'There was an error redeeming coupon, please inform IT Web Experts about this error.'
                });
              return false;
            });
        }
        
        this.initializing = false;
    }
}