﻿$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};



$(document).ready(function () {
    global.init();
    home.init();

    products.init();
    controls.init();

    validation.init();
    shop.init();
});

/* Global Functions */
var global = {
    init: function () {
        global.initSearchBox();
        global.initNewsletterBox();
        global.initSitefintyForm();
        global.initVerticalScrollingList();
    },
    initSubNav: function () {
        var items = $('#subNav ul > li > a');

        var width = (100 / items.length);
        items.parent().css('width', width + '%');

        var height = 0;
        items.each(function () {
            if ($(this).height() > height) {
                height = $(this).height();
            }
        });
        items.css('height', height + 'px');
    },
    initSearchBox: function () {
        var initialText = "Search Zintel";
        var textBox = $('#search :text');
        global.initWatermark(textBox, initialText, 'watermark');
    },
    initNewsletterBox: function () {
        var initialText = "@ Subscribe to our newsletter";
        var textBox = $('#newsletter :text');
        global.initWatermark(textBox, initialText, 'watermark');
    },
    initWatermark: function (textBox, initialText, watermarkClass) {
        textBox.filter(function () {
            return $(this).val() == "" || $(this).val() == initialText;
        })
        .addClass(watermarkClass).val(initialText);

        textBox.focus(function () {
            $(this).filter(function () {
                return $(this).val() == "" || $(this).val() == initialText;
            }).removeClass(watermarkClass).val("");
        });

        textBox.blur(function () {
            $(this).filter(function () {
                return $(this).val() == "";
            }).addClass(watermarkClass).val(initialText);
        });
    },
    initSitefintyForm: function () {
        // set default button when enter key pressed in a text box
        $('.sfFormsEditor :text').keypress(function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                $(this).parents('.sfFormsEditor:first').find(':submit').click();
                return false;
            }
        });
    },
    initVerticalScrollingList: function () {
        $('.verticalScrollingList').each(function () {
            var height = $(this).height() + 'px';
            $(this).totemticker({
                row_height: height,
                mousestop: true,
                speed: 1000
            });
        });
    },
    showAjaxLoading: function (elem) {
        if (elem.next('.ajaxLoading').length == 0) {
            // applicationRoot is written to client
            elem.after('<img src="' + applicationRoot + 'UserControls/Images/loading.gif" alt=" " class="ajaxLoading" />');
        }
    },
    hideAjaxLoading: function (elem) {
        elem.next('.ajaxLoading').remove();
    }
}

var products = {
    init: function () {
        //$('#accordion').accordion();
        var accordion = $('#accordion');
        if (accordion.length > 0) {
            accordion.find('.toggle').click(function () {
                var panel = products.getPanel($(this));
                var plusMinus = $(this);
                if (!plusMinus.hasClass('plusMinus')) {
                    plusMinus = $(this).parents('.accordionHeader').find('.plusMinus');
                }

                if (panel.is(':visible')) {
                    panel.slideUp();
                    plusMinus.removeClass('minus');
                }
                else {
                    panel.slideDown();
                    plusMinus.addClass('minus');
                }
            });

            $('.accordionBlock').hoverIntent(function () {
                var panel = $(this).find('.panel');
                if (!panel.is(':visible') && !panel.hasClass('expanded')) {
                    $(this).find('.toggle:first').click();
                    panel.addClass('expanded');
                }
            },
            function () { });
        }
    },
    getPanel: function (e) {
        return e.parentsUntil('.accordionBlock').next('.panel');
    },
    getShowHide: function (showHide) {
        if (!showHide.hasClass('showHide')) {
            showHide = showHide.parents('.accordionHeader').find('.showHide');
        }
        return showHide;
    }
}

var validation = {
    validateEmail: function (elem) {
        var re = new RegExp(/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/);
        var valid = re.test(elem.val());
        validation.toggleError(elem, valid, 'Invalid email');
        return valid;
    },
    toggleError: function (elem, isValid, errorMessage) {
        if (!isValid && elem.next('.errorShow').length == 0) {
            elem.after('<span class="errorShow">' + errorMessage + '</span>');
        }
        else if (isValid) {
            elem.next('.errorShow').remove();
        }
    },
    validateRequiredField: function (elem) {
        var valid;
        if (elem.is('select')) {
            var value = parseInt(elem.val());
            valid = value > -1;
        }
        else if (elem.is(':checkbox')) {
            valid = elem.is(':checked');
        }
        else {
            valid = elem.val().length > 0;
        }
        validation.toggleError(elem, valid, '*');
        return valid;
    },
    validateNumberOnly: function (elem, ignoreEmpty) {
        //        if (!elem) {
        //            elem = $("#shopCreditCardSSC");
        //        }
        var value = elem.val();

        var valid = true;
        if (!ignoreEmpty || value.length > 0) {
            var value = value.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(' ','');
            var intRegex = /^\d+$/;
            if (!intRegex.test(value)) {
                valid = false;
                validation.toggleError(elem, valid, 'The field must be numeric.');
               
            }

           
        }
        return valid;
    },
    validate: function (container) {
        var valid = true;
        container.find('.required:visible')
            .each(function () {
                valid = validation.validateRequiredField($(this)) && valid;
            });
        container.find('.email')
        .each(function () {
            valid = validation.validateEmail($(this)) && valid;
        });
        return valid;
    },
    init: function () {
        $('.required').blur(function () {
            validation.validateRequiredField($(this));
        });
        $('.email').blur(function () {
            validation.validateEmail($(this));
        });
        $('.numberonly').blur(function () {
            validation.validateNumberOnly($(this));
        });
    }
}

var shop = {
    validation: {
        validateCreditCard: function (elem, ignoreEmpty) {
            if (!elem) {
                elem = $("#shopCreditCard");
            }
            var value = elem.val();

            var valid = true;
            if (!ignoreEmpty || value.length > 0) {
                //                var re = new RegExp("^((4\d{3})|(5[1-5]\d{2})|(6011)|(34\d{1})|(37\d{1}))-?\d{4}-?\d{4}-?\d{4}|3[4,7][\d\s-]{15}$");
                //valid = re.test(elem.val());
                value = value.replace(/ /g, '');
                valid = value.length >= 13 && value.length <= 16;

                this.toggleError(elem, valid);
            }
            return valid;
        },
        validateCreditCardCVV: function (elem, ignoreEmpty) {
            if (!elem) {
                elem = $("#shopCreditCardSSC");
            }
            var value = elem.val();

            var valid = true;
            if (!ignoreEmpty || value.length > 0) {
                valid = value.length > 2 && value.length < 5;
                this.toggleError(elem, valid);
            }
            return valid;
        },

        toggleError: function (elem, valid) {
            if (!valid) {
                elem.next('.error').show();
            } else {
                elem.next('.error').hide();
            }
        }
    },
    item: {
        service: null,
        answerpoint: null
    },
    cart: {
        products: new Array(),
        cartContainer: function () {
            return $('#cartContents');
        },
        addItem: function (product, price) {
            var container = shop.cart.cartContainer();
            container.find('.temp').remove();
            container.append('<div class="cartRow temp"><div class="cartProduct">' + product + '</div><div class="cartPrice">' + price + '</div></div>');
        }
    },
    getAvailableNumbersBlock: function () {
        return $('#availableNumbers');
    },
    refreshAvailableNumbers: function (force) {
        var availableNumbersBlock = shop.getAvailableNumbersBlock();
        if (force || availableNumbersBlock.children().length == 0) {
            var data = {};
            data.productId = shop.getCurrentProductId();
            data.refresh = force;

            $.ajax({
                cache: false,
                url: "/WebServices/ZintelShop.svc/AvailableNumbers",
                data: JSON.stringify(data),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function () {
                    //alert("An error occurred with your order. Please refresh the page or try again.");
                    shop.showSessionTimeoutDialog();
                },
                success: function (data) {
                    if (!data || !data.d) {
                        shop.showSessionTimeoutDialog();
                    }
                    else {
                        // clear existing
                        availableNumbersBlock.html('');

                        $.each(data.d, function () {
                            var id = 'availableNumber_' + this.Number.replace(/ /g, '');
                            availableNumbersBlock.append('<div class="availableNumberRow"><label for="' + id + '">' + this.DisplayNumber + '</label><input type="radio" id="' + id + '" value="' + this.Number + '" name="selectedNumber" /></div>');
                        });
                    }
                }
            });
        }
    },
    wizard: null,
    ajaxProcessing: false, // whether the page is in the middle of an ajax request
    init: function () {
        // test if on shop page
        if ($('#wizard').length == 1) {
            this.initWizard();
            this.initEvents();

            this.initAccountDetailsForm();

            this.initShopServices();

            $('#answerpoint :text').keypress(function (e) {
                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                    $('#wizard').smartWizard('moveForward');
                    return false;
                }
            });

            $('#accountDetails :text').keypress(function (e) {
                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                    $('#wizard').smartWizard('moveForward');
                    return false;
                }
            });

            $('#' + $('#ProductToSelect').val()).attr('checked', 'checked').click();

            $(document).ajaxStart(function () {
                $('#wizard .actionBar .ajaxLoading').show();
                shop.ajaxProcessing = true;
            });

            $(document).ajaxStop(function () {
                $('#wizard .actionBar .ajaxLoading').hide();
                shop.ajaxProcessing = false;
            });
        }
    },
    initEvents: function () {
        $('#refreshAvailableNumbers').click(function () {
            shop.refreshAvailableNumbers(true);
        });

        $('#wizard .addMoreProducts').click(function () {
            $('#shopServices :checked').removeAttr('checked');
            $('#smartOrExistingWrapper :checked').removeAttr('checked');
            shop.hideSmartOrExistingFields();
            $('#wizard').smartWizard('reset');

            var uploadControl = $find('UploadInvoice');
            if (uploadControl.getUploadedFiles().length > 0) {
                uploadControl.addFileInput();
            }
        });

        $('#wizard .selectedNumberSource').blur(function () {
            $('#wizard .selectedNumber').text($(this).val());
        });

        $('#shopExistingAccountRow :radio').click(function () {
            if ($(this).val() == 'true') {
                $('#shopExistingAccountNumberRow').slideDown();
            }
            else {

                $('#shopExistingAccountNumberRow').slideUp();
            }
        });

        // when the existing service check box is clicked, decheck the smart number check box and toggle existing service fields
        $('#existingService').click(function () {
            $('#smartNumber').removeAttr('checked');

            if ($(this).is(':checked')) {
                $('#smartOrExistingWrapper .error').hide();
                $('#availableNumbersWrapper').hide().find(':checked').removeAttr('checked');
                $('#uploadInvoiceWrapper').show();

                $('#existingNumberFields').show();
                $('#rightsOfUseConfirmationWrapper').hide();
                $('#smartNumberAndRouFields').hide();
            } else {
                shop.hideSmartOrExistingFields();
            }
        });

        // when the smart number check box is clicked, decheck the existing service check box and toggle smart number fields
        $('#smartNumber').click(function () {
            $('#existingService').removeAttr('checked');

            if ($(this).is(':checked')) {
                $('#smartOrExistingWrapper .error').hide();
                $('#uploadInvoiceWrapper').hide();
                $('#availableNumbersWrapper').hide().find(':checked').removeAttr('checked');

                $('#existingNumberFields').hide();
                $('#rightsOfUseConfirmationWrapper').show();
                $('#smartNumberAndRouFields').show();
            } else {
                shop.hideSmartOrExistingFields();
            }
        });

        $('#newConnectionYes').click(function () {
            $('#smartOrExistingWrapper :checked').removeAttr('checked');
            $('#smartOrExistingWrapper .error').hide();
            shop.hideSmartOrExistingFields();
        });

        shop.initAddons();
    },
    hideSmartOrExistingFields: function () {
        $('.smartOrExistingFields').hide().find(':checkbox, :radio, :text').removeAttr('checked').val('');
        $('#availableNumbersWrapper').show();
    },
    fileUploadValidationFailed: function (sender, e) {
        $('#uploadInvoiceWrapper .fileError').show();
        sender.deleteFileInputAt(0);
    },
    fileUploaded: function (sender, e) {
        $('#uploadInvoiceWrapper .fileError').hide();
    },
    initWizard: function () {
        shop.wizard = $('#wizard').smartWizard(
            {
                onForwardStep: shop.validateStep,
                onLeaveStep: shop.leaveStep,
                onShowStep: shop.showStep,
                selected: 0,
                keyNavigation: false
            }
        );

        // configure specific ways of clearing errors
        $('#shopServices :radio').click(function () {

            shop.currentProduct = null;

            // clear all text fields
            $('#wizard :text').val('');

            $('#shopServices .error').fadeOut('fast');

            $('#wizard .selectedService').text(shop.getProductLabelFromRadio($(this)));

            // get product details
            shop.getProductDetails($(this).val(), true);


        });

        $('#step-2 #availableNumbersWrapper').on('click', ':radio', function () {
            $('#step-2 .error').fadeOut('fast');

            var options = { to: "#cart", className: "ui-effects-transfer" };
            $(this).effect('transfer', options, null, null);

            $('#wizard .selectedNumber').text($(this).prev('label').text());
        });
        $('#step-4 :radio').click(function () {
            $('#step-4 .error').fadeOut('fast');
        });
    },
    savePhoneNumber: function () {
        var elem = $('#step-2 #availableNumbersWrapper :checked');
        var data = {};
        data.number = elem.val();

        if (data.number != '') {
            $.ajax({
                cache: false,
                url: "/WebServices/ZintelShop.svc/SetPhoneNumber",
                data: JSON.stringify(data),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function () {
                    //alert("An error occurred with your order. Please refresh the page or try again.");
                    shop.showSessionTimeoutDialog();
                },
                success: function (data) {
                    if (!data) {
                        shop.showSessionTimeoutDialog();
                    }
                    else if (!data.d) {
                        // number stolen by another user so refresh available numbers
                        shop.refreshAvailableNumbers(true);
                        alert('Unfortunately this number has just been reserved, please select a new number.');
                        $('#pickYourNumberStepButton').click();
                    }
                    else {
                        // success!
                        shop.ajaxProcessing = false;
                        elem.addClass('reserved');
                        $('#wizard').smartWizard('moveForward');
                    }
                }
            });
        }
    },
    initAccountDetailsForm: function () {
        $("#shopCreditCard").blur(function () {
            shop.validation.validateCreditCard($(this), true);
        });

        $("#shopCreditCardSSC").blur(function () {
            shop.validation.validateCreditCardCVV($(this), true);
        });
    },
    refreshCurrentProductDetails: function (product) {
        $('#shopPricingTable').html(product.PricingTable);

        shop.addPricingEventHandlers();

        //        if (product.CanPickNumber) {
        //            $('#numberAllocatedForYouDiv').hide().find(':radio').removeAttr('checked');
        //            $('#availableNumbersWrapper').show();
        //        }
        //        else {
        //            $('#availableNumbersWrapper').hide();
        //            $('#numberAllocatedForYouDiv').show().find(':radio').attr('checked', 'checked');
        //        }
    },
    refreshCart: function (cart) {
        // clear review your cart
        var reviewCart = $('#reviewYourCart');
        reviewCart.html('');

        var cartContents = $('#cartContents');
        cartContents.html('');

        $.each(cart.Items, function (index, elem) {
            // add to mini cart
            var html = '';
            if (elem.Addons.length > 0) {
                html = '<div class="cartRow"><div class="cartProduct">'
                    + elem.ProductName + '</div><div class="cartPriceLabel">Setup:</div><div class="cartPrice">$' + elem.SetupFeeExcludingAddons + '</div>'
                    + '<div class="cartPriceLabel">First Month:</div><div class="cartPrice">$' + elem.PricePerMonthExcludingAddons + '</div>'
                    + '<div class="cartPriceLabel"><b>Settings:</b></div>'
                    + '<div class="cartPrice"></div>'
                    + '<div class="cartPriceLabel">' + (elem.Addons[0] == null ? '' : elem.Addons[0].Name) + '</div>'
                    + '<div class="cartPrice"></div>'
                    + '<div class="cartPriceLabel">Setup:</div>'
                    + '<div class="cartPrice">' + (elem.Addons[0] == null ? '' : '$'+elem.Addons[0].SetupFee) + '</div>'
                    + '<div class="cartPriceLabel">First Month:</div>'
                    + '<div class="cartPrice">' + (elem.Addons[0] == null ? '' : '$' + elem.Addons[0].PricePerMonth) + '</div>'
                + '</div>';
            } else {
                html = '<div class="cartRow"><div class="cartProduct">'
                    + elem.ProductName + '</div><div class="cartPriceLabel">Setup:</div><div class="cartPrice">$' + elem.SetupFee + '</div>'
                    + '<div class="cartPriceLabel">First Month:</div><div class="cartPrice">$' + elem.PricePerMonth + '</div>'
            }
            cartContents.append(html);

            //update review your cart
            reviewCart.append('<div class="cartRow"></div>');
            //            reviewCart.find('.cartRow:last')
            //                      .append('<div class="cartProduct">' + elem.ProductName + ' (' + (elem.IsContract ? '12 month plan' : 'No contract') + ')'
            //                        + (elem.PhoneNumber != '' ? '<span class="cartPhoneNumber">(' + elem.PhoneNumber + ')</span>' : '') + ' </div>');
            if ($('#smartNumber').is(':checked')) {

                var smartnumber = $(".selectedNumber").html();
                reviewCart.find('.cartRow:last')
                      .append('<div class="cartProduct">' + elem.ProductName + ' (' + (elem.IsContract ? '12 month plan' : 'No contract') + ')<span class="cartPhoneNumber"> - Smartnumber: ' + smartnumber + ' </span> </div>');

            }
            else {
                reviewCart.find('.cartRow:last')
                      .append('<div class="cartProduct">' + elem.ProductName + ' (' + (elem.IsContract ? '12 month plan' : 'No contract') + ')'
                        + (elem.PhoneNumber != '' ? '<span class="cartPhoneNumber">(' + elem.PhoneNumber + ')</span>' : '') + ' </div>');
            }
            reviewCart.find('.cartRow:last')
                      .append('<div class="cartPrice">$' + elem.SetupFeeExcludingAddons + '</div>')
                      .append('<div class="cartPrice">$' + elem.PricePerMonthExcludingAddons + '</div>')
                      .append('<a href="javascript:void(0);">Remove</a>')
                      .append('<div class="clear"></div>');

            reviewCart.find('.cartRow:last a')
                      .click(function () {
                          shop.removeItem(elem.LineNumber);
                      });

            reviewCart.append('<div class="addonLabel">Settings:</div>');

            $.each(elem.Addons, function (addonIndex, elem) {
                reviewCart.append('<div class="cartAddonRow' + ((addonIndex % 2 == 1) ? " alternatingRow" : "") + '"></div>');
                reviewCart.find('.cartAddonRow:last')
                          .append('<div class="cartProduct">' + elem.Name + '</div>')
                          .append('<div class="cartPrice">$' + elem.SetupFee + '</div>')
                          .append('<div class="cartPrice">$' + elem.PricePerMonth + '</div>')
                          .append('<a href="javascript:void(0);">Remove</a>')
                          .append('<div class="clear"></div>')
                          .append(elem.AnswerPointHtml);


                reviewCart.find('.cartAddonRow:last a')
                          .click(function () {
                              shop.removeAddon(elem);
                          });
            });
        });

        // mini cart sub total
        $('#cartTotal .cartPrice').text('$' + cart.SubTotal);

        if (cart.Total == 0) {
            $('#WhatIsTheNextStepForZero').show();
            $('#WhatIsTheNextStep').hide();
        }
        else {
            $('#WhatIsTheNextStepForZero').hide();
            $('#WhatIsTheNextStep').show();
        }

        $('#totalCharge').text('$' + cart.Total);
        $('#gst').text('$' + cart.GST);
        $('#subtotal').text('$' + cart.SubTotal);
    },
    removeItem: function (lineNumber) {
        var data = {};
        data.lineNumber = lineNumber;

        $.ajax({
            cache: false,
            url: "/WebServices/ZintelShop.svc/RemoveCartItem",
            data: JSON.stringify(data),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () {
                //alert("An error occurred with your order. Please refresh the page or try again.");
                shop.showSessionTimeoutDialog();
            },
            success: function (data) {
                shop.refreshCart(data.d);

                if ($('#reviewYourCart .cartRow').length == 0) {
                    // no items in cart so refresh page
                    window.location.reload(true);
                }
            }
        });
    },
    removeAddon: function (elem) {
        var data = {};
        data.addonId = elem.Id;

        $.ajax({
            cache: false,
            url: "/WebServices/ZintelShop.svc/RemoveAddOn",
            data: JSON.stringify(data),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () {
                //alert("An error occurred with your order. Please refresh the page or try again.");
                shop.showSessionTimeoutDialog();
            },
            success: function (data) {
                shop.refreshCart(data.d);
            }
        });
    },
    initAddons: function () {
        $('#addonsWrapper').on('click', '.addonsRow a', function () {
            // create the id of the div holding the extra fields required for this addon
            var id = $(this).attr('class') + '_fields';

            // hide the status until user has confirmed the addon
            $('#AddOnStatus').hide();

            // hide the extra fields for all other addons except the one the user has just selected
            $('#addonsDynamic .addonFieldContent').not('#' + id).hide();


            var dynamicField = $('#' + id).fadeIn();

            if (dynamicField.length == 0) {
                // no fields to add so just add straight to cart
                var url = "/WebServices/ZintelShop.svc/Add" + $(this).attr('class') + '/Addon';
                shop.submitAddon(url, submitButton);
            }
            else {
                // update description of current addon selected
                $('#currentAddon').text($(this).parent().find('.addonsDesc').text())
                    .fadeIn();
            }
        });

        // when the user presses return in a text box in a dynamic field, submit the addon
        $('#addonsDynamic .addonFieldContent :text').keypress(function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                $(this).parents('.addonFieldContent:first').find('.addonsSubmit').click();
                e.preventDefault();
                return false;
            }
        });

        $('#timeRoutingTable .time').timepicker({});

        // addon confirm button clicked so send to server if valid
        $('.addonsSubmit').click(function () {
            var addonContainer = $(this).parents('.addonFieldContent:first');
            var a = shop.currentProduct;
            if (validation.validate(addonContainer)) {
                var submitButton = $(this);
                global.showAjaxLoading($(this));
                shop.showTransferToCart($(this));

                // find the url to submit the addon - .url hidden field in Shop.ascx
                var url = "/WebServices/ZintelShop.svc/" + $(this).parent().find('.url').val();
                shop.submitAddon(url, submitButton);
            }
        });
    },
    submitAddon: function (url, submitButton) {
        // do transfer and add to session
        var data = submitButton.parent().find(':input').serializeObject();

        if (url == '/WebServices/ZintelShop.svc/AddTimeRoutingAddOn') {
            // special case for this one...

            data.RoutingDays = new Array();
            // go thru each routing row and add a time entry to the array
            $('#timeRoutingTable .timeRoutingRow').each(function (index) {
                var timeEntry = {};
                timeEntry.DayOfWeek = index + 1;
                timeEntry.StartTime = $(this).find('.time:first').val();
                timeEntry.EndTime = $(this).find('.time:last').val();
                timeEntry.PhoneNumber = $(this).find('.phoneNumber').val();

                data.RoutingDays.push(timeEntry);
            });
        }

        var wcfData = {};
        wcfData.addon = data;

        $.ajax({
            cache: false,
            url: url,
            data: JSON.stringify(wcfData),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () {
                //alert("An error occurred with your order. Please refresh the page or try again.");
                shop.showSessionTimeoutDialog();
                if (submitButton) {
                    global.hideAjaxLoading(submitButton);
                }
            },
            success: function (data) {
                if (!data) {
                    shop.showSessionTimeoutDialog();
                }
                else {
                    //if only one Addon per product
                    if (data.d.OrderItemOnlyOneAddon) {
                        if (submitButton) {
                            global.hideAjaxLoading(submitButton);
                        }

                        $('#addonsDynamic .addonFieldContent').fadeOut(function () {
                            $('#AddOnStatus')
                        .html('Saved')
                        .show()
                        .fadeOut(2000);
                        });
                        shop.refreshCart(data.d);

                        $('#currentAddon').hide();
                    }
                    // if not only one addon then show error message
                    else {
                        if (submitButton) {
                            global.hideAjaxLoading(submitButton);
                        }
                        alert('You can Only choose ONE Setting per service.');


                    }
                }
            }
        });
    },
    showTransferToCart: function (elem) {
        var options = { to: "#cart", className: "ui-effects-transfer" };
        elem.effect('transfer', options, null, null);
    },
    // when the user selects a pricing plan, submit to server and move to next tab
    addPricingEventHandlers: function () {
        $('#shopPricing .addToCart').click(function () {

            var data = {};
            data.priceId = $(this).parents('.pricingHeader:first').find('.pricingId').val();
            data.isContract = $(this).hasClass('isContract');

            $.ajax({
                cache: false,
                url: "/WebServices/ZintelShop.svc/SetPricePackage",
                data: JSON.stringify(data),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function () {
                    //alert("An error occurred with your order. Please refresh the page or try again.");
                    shop.showSessionTimeoutDialog();
                },
                success: function (data) {
                    if (!data || !data.d) {
                        shop.showSessionTimeoutDialog();
                    }
                    else {
                        shop.refreshCart(data.d.Cart);
                        $('#addonsWrapper').html(data.d.AddonsTable);
                   
                        shop.ajaxProcessing = false;
                        $('#wizard').smartWizard('moveForward');
                    }
                }
            });

            var options = { to: "#cart", className: "ui-effects-transfer" };
            $(this).effect('transfer', options, null, function () {
                //shop.cart.addItem(shop.getProductLabelFromRadio($(this)), '$-');
            });
        });
    },
    getProductLabelFromRadio: function (obj) {
        return obj.prev('span.productName').text();
    },
    currentProduct: null,
    getCurrentProduct: function () {
        return shop.currentProduct;
    },
    getCurrentProductId: function () {
        return $('#shopServices :checked').val();
    },
    getProductDetails: function (productId, refreshUI) {
        $.ajax({
            cache: false,
            url: "/WebServices/ZintelShop.svc/Product",
            data: '{"id":"' + productId + '"}',
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () {
                alert("An error occurred with your order. Please refresh the page or try again.");
            },
            success: function (data) {
                shop.currentProduct = data.d;

                if (refreshUI) {
                    shop.refreshCurrentProductDetails(data.d);
                }
                shop.refreshAvailableNumbers(true);
            }
        });
    },
    initShopServices: function () {
        $('#shopServices :radio').click(function () {
            var options = { to: "#cart", className: "ui-effects-transfer" };
            $(this).effect('transfer', options, null, function () {
                shop.cart.addItem(shop.getProductLabelFromRadio($(this)), '$-');
            });
        });
    },
    initSelectAllSubProducts: function () {
        $('.addAllSubProducts').click(function () {

            $(this).parents('.shopExtrasRow').find('.shopExtrasSubProducts :checkbox').attr('checked', true);
        });
    },
    showSessionTimeoutDialog: function () {
        $('#sessionExpiredErrorDialog').dialog({
            dialogClass: "errorDialog",
            modal: true,
            title: "Session Expired",
            buttons: { "Ok": function () { $(this).dialog("close"); window.location.reload(true); } }
        });
    },
    isPaymentProcessing: false,
    processPayment: function () {
        // prevent double clicking
        if (!shop.isPaymentProcessing) {
            shop.isPaymentProcessing = true;

            // assumed to be valid by now...

            // display dialog to prevent user from clicking another button
            var dialogOptions = { modal: true, title: "Processing Payment", buttons: {}, closeOnEscape: false };
            var dialog = $('#paymentProcessingDialog').dialog(dialogOptions);

            var data = {};
            data["CreditCardNumber"] = $('#shopCreditCard').val().replace(/ /g, '');
            data["CreditCardExpiryMonth"] = $('#shopCreditCardExpiryMonth').val();
            data["CreditCardExpiryYear"] = $('#shopCreditCardExpiryYear').val();
            data["CreditCardCVV"] = $('#shopCreditCardSSC').val();

            var customer = {};
            customer["ContactName"] = $('#shopCustomerName').val();
            customer["ContactPosition"] = $('#shopCustomerPosition').val();
            customer["BusinessName"] = $('#shopBusinessName').val();
            customer["ABN"] = $('#shopAbn').val();
            customer["PhoneNumber"] = $('#shopContactNumber').val();
            customer["Email"] = $('#shopEmail').val();
            customer["PhoneNumber"] = $('#shopContactNumber').val();
            customer["AccountNumber"] = $('#shopExistingAccountNumber').val();

            var wcfData = {};
            wcfData.payment = data;
            wcfData.customer = customer;

            $.ajax({
                cache: false,
                url: "/WebServices/ZintelShop.svc/Pay",
                data: JSON.stringify(wcfData),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function () {
                    shop.isPaymentProcessing = false;
                    dialog.dialog('close');
                    alert("An error occurred with your order. Please refresh the page or try again.");
                },
                success: function (data) {
                    // hide dialog and continue to next page with confirmation values set
                    dialog.dialog('close');

                    var successfulPayment = data && data.d && data.d.Id > 0;
                    if (successfulPayment) {
                        shop.populateConfirmationFields(data.d);

                        // clear cart as payment was successful.
                        $('#cartContents').html('');
                        $('#cartTotal .cartPrice').text('');

                        shop.ajaxProcessing = false;
                        $('#wizard').smartWizard('moveForward');

                        // prevent user going back
                        $('#wizard .buttonPrevious').hide();
                        $('#wizard .buttonCart').hide();
                        $('#wizard .stepButton').addClass('disabled');

                        shop.addGoogleConversionScript();
                    }
                    else if (data && data.d && data.d.Status == "Session Timeout") {
                        shop.showSessionTimeoutDialog();
                    }
                    else {
                        $('#paymentErrorDialog').dialog({
                            dialogClass: "errorDialog",
                            modal: true,
                            title: "Payment Error",
                            buttons: { "Ok": function () { $(this).dialog("close"); } }
                        });
                    }

                    shop.isPaymentProcessing = false;
                }
            });
        }
    },
    addGoogleConversionScript: function () {
        if (typeof google_conversion_id != 'undefined') {
            $.getScript('https://www.googleadservices.com/pagead/conversion.js');
        }
        // google analytics code on every page
        _gaq.push(['_trackPageview', '/shop-paid']);
    },
    populateConfirmationFields: function (order) {
        $('#orderId').text(order.Id);
    },
    showStep: function (obj) {
        var stepNum = parseInt(obj.attr('rel'));

        switch (stepNum) {
            case 4:
                $('#currentAddon').hide();
                $('#addonsDynamic .addonFieldContent').hide();
                break;
            default:
                break;
        }
    },
    leaveStep: function (obj) {
        var stepNum = parseInt(obj.attr('rel'));
        var leaveStep = true;
        switch (stepNum) {
            case 4:
                break;
            case 6:
                break;
            default:
                break;
        }
        return leaveStep;
    },
    validateStep: function (obj) {
        if (shop.ajaxProcessing) {
            alert('Your shopping cart is currently being updated, please try again in a few seconds.');
            return false;
        }

        var stepNum = parseInt(obj.attr('rel'));

        var args = {};
        args.valid = true;
        args.showError = true;

        switch (stepNum) {
            case 1:
                shop.validateStep1(args);
                break;
            case 2:
                shop.validateStep2(args);
                break;
            case 3:
                shop.validateStep3(args);
                break;
            case 4:
                break;
            case 6: // Payment info
                args.valid = shop.validation.validateCreditCard(null, false);
                args.valid = shop.validation.validateCreditCardCVV(null, false) && args.valid;
                args.valid = validation.validate($('#accountDetails')) && args.valid;

                var paymentRequired = args.valid && $('#orderId').text().length == 0;
                if (paymentRequired) {
                    shop.processPayment();
                }

                // prevent generic below
                return args.valid && !paymentRequired;
            default:
                break;
        }

        if (!args.valid && args.showError) {
            $('#step-' + stepNum + ' .error').fadeIn('fast');
        }
        else if (args.valid) {
            $('#step-' + stepNum + ' .error').hide();
        }

        return args.valid;
    },
    // validate select service tab
    validateStep1: function (args) {
        args.valid = $('#shopServices :checked').length == 1;
        args.showError = false;

        if (args.valid) {
            if ($('#newConnectionWrapper :checked').val() == 'false' && $('#smartOrExistingWrapper :checked').length == 0) {
                $('#smartOrExistingWrapper .error').show();
                args.valid = false;
                args.showError = false;
            }
            else {
                $('#smartOrExistingWrapper .error').hide();
            }
        }
        else {
            $('#shopServices .error').fadeIn('fast');
        }
    },
    // validate number selection tab
    validateStep2: function (args) {
        args.valid = false;

        var availableNumbersWrapper = $('#availableNumbersWrapper');
        if (availableNumbersWrapper.is(':visible')) {
            var checked = $('#availableNumbersWrapper :checked');
            args.valid = checked.length == 1;
            if (args.valid) {
                if (!checked.hasClass('reserved')) {
                    args.valid = false;
                    args.showError = false;
                    shop.savePhoneNumber();
                }
            }
        } else {
            args.valid = validation.validate($('#step-2'));

            if (args.valid) {
                shop.saveExistingServiceDetails();
            }
        }
    },
    // validate pricing plan step
    validateStep3: function (args) {
        // once you've selected a price plan, there should be no temporary rows in the cart
        args.valid = $('#cartContents .temp').length == 0;
        args.valid = validation.validate($('#shopPricingConditionsWrapper')) && args.valid;
    },
    selectProduct: function (id) {
        //$('#' + id).attr('checked', 'checked');//.click();
    },
    saveExistingServiceDetails: function () {
        var data = $('#answerpoint .smartOrExistingFields :input').serializeObject();

        var wcfData = {};
        wcfData.existingService = data;

        $.ajax({
            cache: false,
            url: '/WebServices/ZintelShop.svc/UpdateExistingServiceFields',
            data: JSON.stringify(wcfData),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () {
                //alert("An error occurred with your order. Please refresh the page or try again.");
                shop.showSessionTimeoutDialog();
            },
            success: function (data) {
                if (!data) {
                    shop.showSessionTimeoutDialog();
                }
            }
        });
    }
}

/* Homepage only functions */
var home = {
    init: function () {
        //this.bounce(0, 3);
        this.fadeIn(0, 3);

        var rotator = $('#ListRotatorPanel');
        if (rotator.length == 1) {
            rotator.bxSlider({
                auto: true,
                autoControls: false,
                speed: 600,
                controls: false,
                autoHover: true
            });
        }
    },
    bounce: function (index, lastIndex) {
        $('.contentBox:eq(' + index + ')').effect('bounce', null, 500, function () {
            if (index < lastIndex) {
                home.bounce(index + 1, lastIndex);
            }
        });
    },
    fadeIn: function (index, lastIndex) {
        $('.contentBox:eq(' + index + ')').fadeIn(700, function () {
            if (index < lastIndex) {
                home.fadeIn(index + 1, lastIndex);
            }
        });
    }
}

var controls = {
    init: function () {
        controls.initExpandableList();
    },
    getHeaderElem: function (obj) {
        return (obj.is('h5') ? obj : obj.next());
    },
    getPlusMinusElem: function (obj) {
        return (obj.is('.plusMinus') ? obj : obj.prev());
    },
    initExpandableList: function () {
        $('.expandableList .toggle').toggle(function () {
            var headerText = controls.getHeaderElem($(this));
            var plusMinus = controls.getPlusMinusElem($(this));

            plusMinus.addClass('minus');
            headerText.addClass('selected')
                    .parent('.header')
                    .nextAll('.listContent:first')
                    .slideDown();

        }, function () {
            var headerText = controls.getHeaderElem($(this));
            var plusMinus = controls.getPlusMinusElem($(this));

            plusMinus.removeClass('minus');
            headerText.removeClass('selected')
                    .parent('.header')
                    .nextAll('.listContent:first')
                    .slideUp();
        });
    },
    initPricing: function () {
        var pricing = $('#pricing');
        var pricingCols = pricing.find('.pricingColumn');

        var width = 0;
        $.each(pricingCols, function () {
            width += $(this).outerWidth();
        });

        pricing.css('width', width);

        pricingCols.not(':first').hover(function () {
            $(this).find('.pricingHeaderBackground').addClass('pricingHeaderHighlight');
        }, function () {
            $(this).find('.pricingHeaderBackground').removeClass('pricingHeaderHighlight');
        });
    }
}

