// Perform on load action

var PurchaseFormCallbacks =
{
    condition: null,
    before: null,
    complete: null
};

var AddMoreUsersCallbacks =
{
    condition: null,
    before: null,
    complete: null
};

var UpgradeProtectionCallbacks =
{
    condition: null,
    before: null,
    complete: null
};

(function($) {

    // Fields
    var jPurchaseForm;
    var jContentPanel;
    var jLicensePanel;
    var jAddMoreUsersPanel;
    var jUpgradeProtectionPanel;


    $(document).ready(function() {

        // Find purchase form
        jPurchaseForm = $(".purchaseform");

        // Find content form
        jContentPanel = jPurchaseForm.children(".content");

        // Find Purchase License Panel
        jLicensePanel = jContentPanel.children(".license");

        // Find Add more users panel
        jAddMoreUsersPanel = jContentPanel.children(".addMoreUser");

        // Find Upgrade Protection Panel
        jUpgradeProtectionPanel = jContentPanel.children(".upgradeProtection");

        initFormTabs();

        var tab = $.query.get('tab');
        if (tab == 'upgradeProtection'){
             $(".purchaseform .tabs .first")
                .removeClass("tabactive")
                .next()
                .removeClass()
                .addClass("tab-uu");

             $(".purchaseform .tabs .second")
                .next()
                .removeClass()
                .addClass("tab-ua");

             $(".purchaseform .tabs .third")
                .addClass("tabactive")
                .next()
                .removeClass()
                .addClass("tab-a");
        }
        
        initLicensePanel();
        initAddMoreUsersPanel();
        initUpgradeProtectionPanel();

    });


    function initFormTabs()
    {
        var jTabs = jPurchaseForm.children(".tabs");

        // Init first tab
        jTabs.children(".first")
            .after('<div class="tab-au"></div>')
            .click(function() {
                if ($(this).attr("class").indexOf("tabactive")==-1) {
                    $(".purchaseform .tabs .second")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-uu");
                    $(".purchaseform .tabs .third")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-u");
                }
                $(this)
                    .addClass("tabactive")
                    .next()
                    .removeClass()
                    .addClass("tab-au");

                // Show the Purchase License panel and hide all others
                if (jLicensePanel.is(":hidden")) {
                    // Hide all content divs
                    jContentPanel.children("div").hide();

                    // Show the license panel
                    jLicensePanel.show();
                }

            });

        // Init second tab
        jTabs.children(".second")
            .after('<div class="tab-uu"></div>')
            .click(function() {
                if ($(this).attr("class").indexOf("tabactive")==-1) {
                    $(".purchaseform .tabs .first")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-ua");
                    $(".purchaseform .tabs .third")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-u");
                }
                $(this)
                    .addClass("tabactive")
                    .next()
                    .removeClass()
                    .addClass("tab-au");

                // Show the Add More Users panel and hide others
                if (jAddMoreUsersPanel.is(":hidden")) {

                    jContentPanel.children("div").hide();
                    jAddMoreUsersPanel.show();
                }

            });

        // Init third tab
        jTabs.children(".third")
            .after('<div class="tab-u"></div>')
            .click(function() {
                if ($(this).attr("class").indexOf("tabactive")==-1) {
                    $(".purchaseform .tabs .first")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-uu");
                    $(".purchaseform .tabs .second")
                        .removeClass("tabactive")
                        .next()
                        .removeClass()
                        .addClass("tab-ua");
                }
                $(this)
                    .addClass("tabactive")
                    .next()
                    .removeClass()
                    .addClass("tab-a");

                // Show the Upgrade Protection panel and hide others.
                if (jUpgradeProtectionPanel.is(":hidden")) {

                    jContentPanel.children("div").hide();
                    jUpgradeProtectionPanel.show();

                }
            });
    }

    function initLicensePanel()
    {
        var jStepsPanels = jLicensePanel.find("form > div.step");
        var jProceedButtonPanel = jLicensePanel.find("form > div.proceedbutton");
        var jBuyButtonPanel = jLicensePanel.find("form > div.buybutton");

        var jFirstStepPanel = jStepsPanels.eq("0");
        var jPackageTypeSelect = jFirstStepPanel.find("select");
        var jUserNumberDl = jFirstStepPanel.find("dl.userNumber");
        var jUserNumberTextBox = jUserNumberDl.find("dd  input:text");
        var jUserNumberSpan = jUserNumberDl.find("dd span.userNumber");
        var jUserNumberErrorSpan = jUserNumberDl.find("dd span.error");
        var rangeSeparator = ":";
        var unlimitedPackageValue = -1;
        
        var jSecondStepPanel = jStepsPanels.eq("1");

        // Common for all items
        jLicensePanel.keypress(function(eventObj){
            if (eventObj.keyCode == 13)
            {
                if (jProceedButtonPanel.is(":visible"))
                {
                    jProceedButtonPanel.children("input#proceed").click();
                }
                if (jBuyButtonPanel.is(":visible"))
                {
                    return;
                }
                eventObj.preventDefault();
            }
        });
        jStepsPanels.find("input").add(jStepsPanels.find("a"))
            .focus(function(){
                activateStep($(this).parents("div.step").get(0));
            });


        var disableSecondPanelFn = function()
        {
            disableStep(jSecondStepPanel.get(0));
            jProceedButtonPanel.hide();
        }
        var enableSecondPanelFn = function()
        {
            enableStep(jSecondStepPanel.get(0));
            if (jSecondStepPanel.find("input:radio").is(":checked") &&
                !jBuyButtonPanel.is(":visible"))
            {
                jProceedButtonPanel.show();
            }
        }
        var validateNumberUsersFn = function() {
            jUserNumberErrorSpan.hide();
            var packageTypeValue = jPackageTypeSelect.val();
            if (packageTypeValue == 0)
            {
                disableSecondPanelFn();
                return false;
            }
            var userNumberRange = packageTypeValue.split(rangeSeparator);
            if (userNumberRange.length == 1)
            {
                enableSecondPanelFn();
            }
            else
            {
                var userNumber = jUserNumberTextBox.val();
                if (!isInteger(userNumber) || !isPositiveInteger(userNumber))
                {
                    jUserNumberErrorSpan.text("Please enter a valid number.").show();
                    disableSecondPanelFn();
                    return false;
                }
                userNumber = parseInt(userNumber);
                if (userNumber >= userNumberRange[0] &&
                    userNumber <= userNumberRange[1])
                {
                    enableSecondPanelFn();
                }
                else
                {
                    jUserNumberErrorSpan.text("Please enter a number within the specified range.").show();
                    disableSecondPanelFn();
                    return false;
                }
            }
            return true;
        };
        var resetToStepPanelFn = function()
        {
            jFirstStepPanel
                .removeClass("disabledwithpointer")
                .attr("title", "")
                .find("input").add(jFirstStepPanel.find("select"))
                    .attr("disabled", false);
            jSecondStepPanel
                .removeClass("disabledwithpointer")
                .attr("title", "")
                .find("input:radio")
                    .attr("disabled", false);
            jLicensePanel.find("form > div.orderinfo").hide().remove();
            jBuyButtonPanel.hide();
            jLicensePanel.find("form > div.proceedbutton").show();
        }

        // Step 1
        jFirstStepPanel.click(function() {
            if (jFirstStepPanel.is(".disabledwithpointer"))
            {
                resetToStepPanelFn();
            }
            activateStep(this);
        })

        jPackageTypeSelect.change(function(){
            var jThis = $(this);
            var selectValue = jThis.val();
            if (selectValue == 0)
            {
                jUserNumberDl.hide();
                validateNumberUsersFn();
                return;
            }
            var range = selectValue.split(rangeSeparator);
            jUserNumberDl.show();
            if (range.length == 1)
            {
                jUserNumberTextBox.hide();
                jUserNumberErrorSpan.hide();

                var spanText;
                if (selectValue == unlimitedPackageValue)
                {
                    spanText = "unlimited";
                }
                else
                {
                    spanText = "up to " + selectValue;
                }
                jUserNumberSpan.show().text(spanText);
                validateNumberUsersFn();
            }
            else
            {
                jUserNumberSpan.hide();
                jUserNumberTextBox.show().val(range[0]).focus().select();
                validateNumberUsersFn();
            }
        })
        .change(); // Trigger the event to perform this function on init
        jFirstStepPanel.find("input:text")
            .keyup(validateNumberUsersFn)
            .focus(validateNumberUsersFn);
            

        // Step 2
        jSecondStepPanel.click(function(){
            if (jSecondStepPanel.is(".disabledwithpointer"))
            {
                resetToStepPanelFn();
            }
            activateStep(this);
        });
        jSecondStepPanel.find("input:radio").click(function(){
            jProceedButtonPanel.show();
        });
        jSecondStepPanel.find("a").click(function(eventObj) {
            var jThis = $(this);
            if (jThis.parents("div.stepdisabled").size() > 0 ||
                jThis.parents("div.disabledwithpointer").size() > 0)
            {
                eventObj.preventDefault();
            }
        });

        // Clear button
        jLicensePanel.find("#licensePurchaseClear").click(function(eventObj){
            resetToStepPanelFn();
            disableSecondPanelFn();
            activateStep(jFirstStepPanel.get(0));
            eventObj.preventDefault();
            jPackageTypeSelect.val(0).change();
        });

        PurchaseFormCallbacks.before = function(){            
            
            jLicensePanel.unbind();
            jLicensePanel.find("form > div.step").unbind();
            jLicensePanel.find("input").unbind();
            jSecondStepPanel.find("a").unbind();
        };
        
        PurchaseFormCallbacks.condition = function(){            
            var result = validateNumberUsersFn();
            return result;
        };

        PurchaseFormCallbacks.complete = initLicensePanel;
    }

    function initAddMoreUsersPanel()
    {
        var jStepsPanels = jAddMoreUsersPanel.find("form > div.step");
        var jProceedButtonPanel = jAddMoreUsersPanel.find("form > div.proceedbutton");
        var jBuyButtonPanel = jAddMoreUsersPanel.find("form > div.buybutton");
        var jLoadingPanel = jAddMoreUsersPanel.find("form > div.loadingDiv");
        var jClearButtons =  jAddMoreUsersPanel.find("input.clearbutton");

        var jFirstStepPanel = jStepsPanels.eq("0");
        var jSecondStepPanel = jStepsPanels.eq("1");

        // Common for all items
        jAddMoreUsersPanel.keypress(function(eventObj){
            if (eventObj.keyCode == 13)
            {
                if (jProceedButtonPanel.is(":visible"))
                {
                    jProceedButtonPanel.find("input#proceed").click();
                }
                if (jBuyButtonPanel.is(":visible"))
                {
                    return;
                }
                eventObj.preventDefault();
            }
        });
        jStepsPanels.find("input").add(jStepsPanels.find("a"))
            .focus(function(){
                activateStep($(this).parents("div.step").get(0));
            });

        var resetToFirstStepFn = function()
        {
                jProceedButtonPanel.show();
                jBuyButtonPanel.hide();
                var jFormDivs = jAddMoreUsersPanel.find("form > div");
                jFormDivs.filter(".orderinfo").remove();
                jSecondStepPanel.unbind();
                jSecondStepPanel.find("input").unbind();
                jSecondStepPanel.remove();
                jSecondStepPanel = $([]);
                jFormDivs.filter(".licenseinfo").remove();
                jFormDivs.filter(".licenseerror").remove();
                jFirstStepPanel
                    .removeClass("disabledwithpointer")
                    .attr("title", "")
                    .find("input:text")
                        .attr("disabled", false);
                jClearButtons.hide();

        }
        jFirstStepPanel.click(function() {
            if (jLoadingPanel.is(":visible"))
            {
                return;
            }
            if (jFirstStepPanel.is(".disabledwithpointer"))
            {
                resetToFirstStepFn();
            }
            activateStep(this);
        });

        jSecondStepPanel.click(function(){
            if (jSecondStepPanel.is(".disabledwithpointer"))
            {
                jProceedButtonPanel.show();
                jBuyButtonPanel.hide();
                var jFormDivs = jAddMoreUsersPanel.find("form > div");
                jFormDivs.filter(".orderinfo").remove();
                jSecondStepPanel
                    .removeClass("disabledwithpointer")
                    .attr("title", "")
                    .find("input:text")
                        .attr("disabled", false);

            }
            activateStep(this);
        });

        jClearButtons.click(function(eventObj){
            resetToFirstStepFn();
            jFirstStepPanel.find("input:text").val("");
            activateStep(jFirstStepPanel.get(0));
            eventObj.preventDefault();
        });

        AddMoreUsersCallbacks.condition = function()
        {
            var jLicenseIdTextBox = jFirstStepPanel.find("input:text");
            if (!jLicenseIdTextBox.attr("disabled"))
            {
                var licenseId = jLicenseIdTextBox.val();
                if (isWhitespace(licenseId))
                {
                    alert("Please specify your license ID.");
                    jLicenseIdTextBox.focus();
                    return false;
                }
            }
            var jAddUserNumberTextBox = jSecondStepPanel.find("input:text");
            if (jAddUserNumberTextBox.size() > 0 &&
                !jAddUserNumberTextBox.attr("disabled"))
            {
                var numberOfUsers = jAddUserNumberTextBox.val();
                if (isWhitespace(numberOfUsers))
                {
                    alert("Please specify the number of users.");
                    jAddUserNumberTextBox.focus();
                    return false;
                }
                if (!isInteger(numberOfUsers) || !isPositiveInteger(numberOfUsers))
                {
                    alert("Please specify the valid number of users.");
                    jAddUserNumberTextBox.focus();
                    return false;
                }
                if (numberOfUsers < 10)
                {
                    alert("The minimum number of users that you can add is 10.");
                    jAddUserNumberTextBox.focus();
                    return false;
                }
            }
            return true;
        };
        AddMoreUsersCallbacks.before = function()
        {
            jClearButtons.unbind();
            jStepsPanels.unbind();
            jStepsPanels.find("input").unbind();
            jStepsPanels.find("a").unbind();
            jAddMoreUsersPanel.unbind();
        };
        AddMoreUsersCallbacks.complete = function()
        {
            initAddMoreUsersPanel();
        };
    }

    function initUpgradeProtectionPanel()
    {
        var jStepsPanels = jUpgradeProtectionPanel.find("form > div.step");
        var jProceedButtonPanel = jUpgradeProtectionPanel.find("form > div.proceedbutton");
        var jBuyButtonPanel = jUpgradeProtectionPanel.find("form > div.buybutton");
        var jLoadingPanel = jUpgradeProtectionPanel.find("form > div.loadingDiv");
        var jClearButtons =  jUpgradeProtectionPanel.find("input.clearbutton");

        var jFirstStepPanel = jStepsPanels.eq("0");

        // Common for all items
        jUpgradeProtectionPanel.keypress(function(eventObj){
            if (eventObj.keyCode == 13)
            {
                if (jProceedButtonPanel.is(":visible"))
                {
                    jProceedButtonPanel.find("input#proceed").click();
                }
                if (jBuyButtonPanel.is(":visible"))
                {
                    return;
                }
                eventObj.preventDefault();
            }
        });
        var resetToFirstStepFn = function()
        {
            jProceedButtonPanel.show();
            jBuyButtonPanel.hide();
            var jFormDivs = jUpgradeProtectionPanel.find("form > div");
            jFormDivs.filter(".orderinfo").remove();
            jFormDivs.filter(".licenseinfo").remove();
            jFirstStepPanel
                .removeClass("disabledwithpointer")
                .attr("title", "")
                .find("input:text")
                    .attr("disabled", false);
            jClearButtons.hide();
            
        }

        jFirstStepPanel.click(function() {
            if (jLoadingPanel.is(":visible"))
            {
                return;
            }
            var jThis = $(this);
            if (jThis.is(".disabledwithpointer"))
            {
                resetToFirstStepFn();
            }
            activateStep(this);
        });

        jClearButtons.click(function(eventObj) {
            resetToFirstStepFn();
            jFirstStepPanel.find("input:text").val("");
            activateStep(jFirstStepPanel.get(0));
            eventObj.preventDefault();
        });

        UpgradeProtectionCallbacks.condition = function()
        {
            /*
            if (jQuery('.upgradeProtection #upgradeProtectionPurchaseStep').val() != true){
                var licenseId = jQuery('.upgradeProtection #upgradeProtectionLicenseId');
                if (jQuery.trim(jQuery(licenseId).val()) == "") {
                    alert('Please specify a license ID.');
                    jQuery(licenseId).focus();
                    return false;
                }
            }*/
            return true;
        }
        UpgradeProtectionCallbacks.before = function()
        {
            jClearButtons.unbind();
            jFirstStepPanel.unbind();
            jUpgradeProtectionPanel.unbind();
        }

        UpgradeProtectionCallbacks.complete = function()
        {
            initUpgradeProtectionPanel();
        }
    }

    function activateStep(itemToActivate)
    {
        var jItemToActivate = $(itemToActivate);
        if (jItemToActivate.is(".stepdisabled") ||
            jItemToActivate.is(".currentstep") ||
            jItemToActivate.is(".disabledwithpointer"))
        {
            return;
        }
        // Remove the class currentStep from all items
        jItemToActivate.parent().children('div.currentstep').removeClass("currentstep");
        jItemToActivate.addClass("currentstep");
    }

    function disableStep(itemToDisable)
    {
        var jItemToDisable = $(itemToDisable);
        if (jItemToDisable.is(".stepdisabled"))
        {
            return;
        }
        jItemToDisable.addClass("stepdisabled");
        jItemToDisable.find("input").attr("disabled", true);
        jItemToDisable.find("select").attr("disabled", true);
    }

    function enableStep(itemToEnable)
    {
        var jItemToEnable = $(itemToEnable);
        if (!jItemToEnable.is(".stepdisabled"))
        {
            return;
        }
        jItemToEnable.removeClass("stepdisabled")
        jItemToEnable.find("input").attr("disabled", false);
        jItemToEnable.find("select").attr("disabled", false);
    }


})(jQuery)




function ClearUpgradeProtectionPurchase(){
    ClearPurchaseSteps('.upgradeProtection ');
}


function ShowOrderInfo(baseSelector){
    var purchase = jQuery(baseSelector+' .orderinfo');
    if(purchase.length){
        purchase.show();
        jQuery(baseSelector+' .orderinfo div').show();
        jQuery(baseSelector+' .buybutton').show();
    }else{
        jQuery(baseSelector+' .proceedbutton').show();
    }
}

function NextStepRadioButton(){

    var obj = jQuery(this);
    var objp = jQuery(this).parent();
    var objpp = jQuery(this).parent().parent();

    if (obj.hasClass('withInputField')){
        objp.find('input:text')
        .removeAttr('disabled')
        .bind('keypress' , NextStepRadioButton)
        .focus();
    }else{
        objp.prev().prev().remove();
        objpp.removeClass("currentstep").addClass("step");

        if (objpp.is('ul[last]')) {
            jQuery('.license .proceedbutton').show();
        }else{
            var next = objpp.next();
            if (!next.is(".currentstep")){
                next
                .removeClass("stepdisabled")
                .addClass("currentstep")
                .prepend('<li class="arrow"><img src="img/arrow.png"></li>')
                .find(" *[disabled]:not(:text)")
                .removeAttr('disabled');
                next
                .find('input:radio').bind("change" , NextStepRadioButton);
            }
        }
        // Unbind current radio buttons
        objp.find('input:radio').unbind('change', NextStepRadioButton);
    }
    obj.unbind('keypress' , NextStepRadioButton);
}
