// 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
};

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

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

(function($) {

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



    $(document).ready(function() {

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

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

        // Find Purchase License Panel
        jLicensePanel = jPurchaseForm.children("#license_content");

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

        // Find Upgrade Protection Panel
        jUpgradeProtectionPanel = jPurchaseForm.children("#maintenance_content");

	     // Find Upgrade License Panel
        jUpgradeLicensePanel = jPurchaseForm.children("#upgrade_content");

	     // Find Package Change Panel
        jPackageChangePanel = jPurchaseForm.children("#change_content");

        initFormTabs();
        initLicensePanel();
        //initAddMoreUsersPanel();
        initUpgradeProtectionPanel();
	     initUpgradeLicensePanel();
	     initPackageChangePanel();

    });


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

        //Purchase Form Behaviour

       jQuery('.purchaseform .tabs li').click(function() {
            var thisElement = jQuery(this);
            var tabID = "#" + thisElement.attr('id') + "_content";

            jQuery('.purchaseform .pfcontent').removeAttr('opened').attr('closed','').slideUp('fast');
            jQuery('.purchaseform li').removeClass('current');

            thisElement.addClass('current');
            jQuery('.purchaseform').removeClass('closed');
            jQuery(tabID).slideDown('fast').removeAttr('closed').attr('opened','');
        });
    }

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

        var jFirstStepPanel = jStepsPanels.eq("0");
        var jPackageTypeSelect = jFirstStepPanel.find("select");
        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;
            } else {
                enableSecondPanelFn();
            }
            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#purchaseLicense > div.orderinfo").hide().remove();
            jBuyButtonPanel.hide();
            jLicensePanel.find("form#purchaseLicense > 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;
            }
            validateNumberUsersFn();
        })
        .change(); // Trigger the event to perform this function on init

        // 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#purchaseLicense > 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 initUpgradeLicensePanel()
    {
        var jStepsPanels = jUpgradeLicensePanel.find("form#purchaseUpgradeLicense > div.step");
        var jProceedButtonPanel = jUpgradeLicensePanel.find("form#purchaseUpgradeLicense > div.proceedbutton");
        var jBuyButtonPanel = jUpgradeLicensePanel.find("form#purchaseUpgradeLicense > div.buybutton");
        var jLoadingPanel = jUpgradeLicensePanel.find("form#purchaseUpgradeLicense > div.loadingDiv");
        var jClearButtons =  jUpgradeLicensePanel.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 = jUpgradeLicensePanel.find("form#purchaseUpgradeLicense > 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();
        });

        UpgradeLicenseCallbacks.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;
        }
        UpgradeLicenseCallbacks.before = function()
        {
            jClearButtons.unbind();
            jFirstStepPanel.unbind();
            jUpgradeProtectionPanel.unbind();
        }

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

	 function initUpgradeProtectionPanel()
    {
        var jStepsPanels = jUpgradeProtectionPanel.find("form#purchaseUpgradeProtection > div.step");
        var jProceedButtonPanel = jUpgradeProtectionPanel.find("form#purchaseUpgradeProtection > div.proceedbutton");
        var jBuyButtonPanel = jUpgradeProtectionPanel.find("form#purchaseUpgradeProtection > div.buybutton");
        var jLoadingPanel = jUpgradeProtectionPanel.find("form#purchaseUpgradeProtection > 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#purchaseUpgradeProtection > 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 initPackageChangePanel()
    {
        var jStepsPanels = jPackageChangePanel.find("form#packageChange > div.step");
        var jProceedButtonPanel = jPackageChangePanel.find("form#packageChange > div.proceedbutton");
        var jBuyButtonPanel = jPackageChangePanel.find("form#packageChange > div.buybutton");
        var jLoadingPanel = jPackageChangePanel.find("form#packageChange > div.loadingDiv");
        var jClearButtons =  jPackageChangePanel.find("input.clearbutton");

        var jFirstStepPanel = jStepsPanels.eq("0");
        var jPackageTypeSelect = jFirstStepPanel.find("select");
        var unlimitedPackageValue = -1;

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

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

			*/
        PackageChangeCallbacks.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;
        }
        PackageChangeCallbacks.before = function()
        {
            jClearButtons.unbind();
            jFirstStepPanel.unbind();
            jUpgradeProtectionPanel.unbind();
        }

        PackageChangeCallbacks.complete = function()
        {
            initPackageChangePanel();
        }
    }



    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);
}

