﻿var Step1ViewHelper = (function() {
    function fnStep1ViewHelperConstructor(oNewView) {
        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*                 Private Variables                */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        var oView;
        var bValidated = false;

        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*            Class Level Private Methods           */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        function getCurrencySign(iCurrency) {
            var sCurrencySign;

            switch (iCurrency) {
                case 2:
                    sCurrencySign = "\u00A3";
                    break;
                case 4:
                    sCurrencySign = "\u20AC";
                    break;
                default:
                    sCurrencySign = "$";
                    break;
            }

            return sCurrencySign;
        }
        
        function getContactAddressByRegion(region)
        {
            switch(region)
            {
                case "North America":
                case "South America":
                    return "ordersus@solarwinds.com";
                default:
                    return "ordersemea@solarwinds.com";
            }
        }
        
        function queryString(parameter) { 
          var loc = location.search.substring(1, location.search.length);
          var param_value = false;

          var params = loc.split("&");
          for (i=0; i<params.length;i++) {
              param_name = params[i].substring(0,params[i].indexOf('='));
              if (param_name.toLowerCase() == parameter.toLowerCase()) {
                  param_value = params[i].substring(params[i].indexOf('=')+1)
              }
          }
          if (param_value) {
              return param_value;
          }
          else {
              return ""; //Here determine return if no parameter is found
          }
        }
        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*          Class Level Priveleged Methods          */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        this.addLicenseItem = function(sProductCategory, oLicenseItem) {
            var iId = oLicenseItem.getId();
            var iQuantity = oLicenseItem.getQuantity();
            if (iId && iId.toString().length > 0 && iQuantity && iQuantity.toString().length > 0) {
                oView.addPopulatedProductLicense(sProductCategory, oLicenseItem.getId().toString(), oLicenseItem.getQuantity());
                oView.showLastListItemAdded(sProductCategory);
            }
            else
                oView.addNewProductLicense(sProductCategory);
            this.showDeleteButtonsByProductCategory(sProductCategory);
        }
        
        this.changecontactlinks = function(region)
        {
            var siteflag = queryString("siteid");
            var contactEmail = getContactAddressByRegion(region);

            if(siteflag && siteflag.toLowerCase() == "kiwi")
            {
                var s1toplnk = $("step1topcontactlnkkiwi");
                if(s1toplnk)
                {
                    s1toplnk.href = "mailto:" + contactEmail;
                    s1toplnk.innerHTML = contactEmail;
                }
                
                var s3botlnk = $("step3kiwibottomcontactlnk");
                if(s3botlnk)
                {
                    s3botlnk.href = "mailto:" + contactEmail;
                    s3botlnk.innerHTML = contactEmail;
                }
            }
        }
        
        this.setTopStoreLnk = function()
        {
            var siteflag = queryString("siteid");
            var solarwindsStoreLnkFormat = "http://shopping.netsuite.com/app/site/backend/intl/setshopperregioninfo.nl?selcurrency={3}&c={1}&n={4}&selsubsidiary={2}&redirect={0}";
            var solarwindsStoreLnkRedirectFormat = "http://shopping.netsuite.com/s.nl?c={0}&n={1}";
            
            if(siteflag && siteflag.toLowerCase() == "kiwi")
            {
                var shopID = 9;
                var siteID = 638609;
                
                var s1topLnk = $("kiwiStoreTopLink");
                
                if(s1topLnk)
                {
                     var redirectUrl = unescape(format(solarwindsStoreLnkRedirectFormat, siteID,shopID));
                     s1topLnk.href = format(solarwindsStoreLnkFormat,redirectUrl,siteID,currentSubsidiary,currentCurrency,shopID);
                }
            }
        }
        
        function format( text )
        {
            if ( arguments.length <= 1 )
            {
                return text;
            }

            var tokenCount = arguments.length - 2;

            for( var token = 0; token <= tokenCount; token++ )

            {
                text = text.replace( new RegExp( "\\{" + token + "\\}","gi" ), arguments[ token + 1 ] );

            }

             return text;
        }

        this.changeLicenseItemDisplays = function(aNetSuiteItems, hPromotions, oRegion) {
            var hProductSpecialOffers = $H();
            var hSpecialOffers = $H();

            var iCurrency = oRegion.getCurrency();
            var sCurrencySign = getCurrencySign(iCurrency);
            var aNetSuiteItemPricePromotions;
            var oNetSuiteItem;
            var sProduct;
            var sProductCategory;
            var iLowestPrice = 1000000;
            var sLowestPriceString;
            var sCurrentCategory;
            var oNetSuiteItemPrice;
            var oPromotion;
            var fAmount;
            var sOptionText;
            for (var iNetSuiteItem = 0; iNetSuiteItem < aNetSuiteItems.length; iNetSuiteItem++) {
                oNetSuiteItem = aNetSuiteItems[iNetSuiteItem];
                sProduct = oNetSuiteItem.getProduct();
                setProductSpecialOffer(sProduct, false);
                sProductCategory = oNetSuiteItem.getProductCategory();
                setProductCategorySpecialOffer(sProductCategory, false);
                oNetSuiteItemPrice = oNetSuiteItem.getPrices().get(iCurrency);
                fAmount = oNetSuiteItemPrice.getAmount();
                sOptionText = oNetSuiteItem.getShortName() + " " + oNetSuiteItem.getLongName();
                
                //Get minimal price for each category. If category changes - update the view
                if (sCurrentCategory != sProductCategory)
                {                    
                    if (sLowestPriceString)
                        oView.setLowestPriceByProductCategory(sCurrentCategory, sLowestPriceString);
                    sCurrentCategory = sProductCategory;
                    sLowestPriceString = "";
                    iLowestPrice = 1000000;
                }
                //if category is not changed - calculate minimal price
                if (fAmount < iLowestPrice)
                {
                    iLowestPrice = fAmount;
                    sLowestPriceString = "Starts at " + sCurrencySign + fAmount;
                    sCurrentCategory = sProductCategory;
                }
                
                aNetSuiteItemPricePromotions = oNetSuiteItemPrice.getPromotions();
                if (aNetSuiteItemPricePromotions.length > 0) {
                    setProductSpecialOffer(sProduct, true);
                    setProductCategorySpecialOffer(sProductCategory, true);
                    for (var iNetSuiteItemPricePromotion = 0; iNetSuiteItemPricePromotion < aNetSuiteItemPricePromotions.length; iNetSuiteItemPricePromotion++) {
                        oPromotion = hPromotions.get(aNetSuiteItemPricePromotions[iNetSuiteItemPricePromotion].getId());
                        if (oPromotion.getIsPercentage())
                            //fAmount *= (100 + oPromotion.getAmount());
			    fAmount = Math.abs(fAmount * (100 + oPromotion.getAmount()) / 100);			
                        else
                            fAmount += oPromotion.getAmount();
                    }
                    //if Promotion - recalculate minimal price
                    if (fAmount < iLowestPrice)
                    {
                        iLowestPrice = fAmount;
                        sLowestPriceString = sCurrencySign + fAmount;
                        sCurrentCategory = sProductCategory;
                    }
                }
                if (iNetSuiteItem == (aNetSuiteItems.length - 1))
                {
                    oView.setLowestPriceByProductCategory(sCurrentCategory, sLowestPriceString);
                }
                oView.setListItemTextByProductCategoryAndValue(sProductCategory, oNetSuiteItem.getId(), sOptionText);
            }

            hSpecialOffers.each(function(oPair) {
                var sProductCategory = oPair.key;
                if (oPair.value) {
                    oView.addListItemTextByProductCategoryAndValue(sProductCategory, "", " - SPECIAL OFFER");
                    oView.showProductCategorySpecialOffer(sProductCategory);
                }
                else {
                    oView.removeListItemTextByProductCategoryAndValue(sProductCategory, "", " - SPECIAL OFFER");
                    oView.hideProductCategorySpecialOffer(sProductCategory);
                }
            });

            hProductSpecialOffers.each(function(oPair) {
                var sProduct = oPair.key;
                if (oPair.value)
                    oView.showProductSpecialOffer(sProduct);
                else
                    oView.hideProductSpecialOffer(sProduct);
            });

            function setProductSpecialOffer(sProduct, bValue) {
                if (bValue || !hProductSpecialOffers.get(sProduct))
                    hProductSpecialOffers.set(sProduct, bValue);
            }

            function setProductCategorySpecialOffer(sProductCategory, bValue) {
                if (bValue || !hSpecialOffers.get(sProductCategory))
                    hSpecialOffers.set(sProductCategory, bValue);
            }
        }

        this.changePhoneNumber = function() {

        }

        this.collapseAllAccordionItems = function() {
            oView.collapseAllAccordionItems();
        }

        this.disableErrorMessages = function() {
            bValidated = false;
        }

        this.enableErrorMessages = function() {
            bValidated = true;
        }

        this.expandAllAccordionItems = function() {
            oView.expandAllAccordionItems();
        }

        this.hideDeleteButtonsByProductCategory = function(sProductCategory) {
            oView.hideDeleteButtonsByProductCategory(sProductCategory);
        }

        this.hideLicenseRequirement = function() {
            oView.hideLicenseRequirement();
        }

        this.hideSpecialOffers = function() {
            oView.hideSpecialOffers();
        }

        this.modifyLicenseItemAt = function(sProductCategory, oLicenseItem, iIndex, bModifyData) {
            var iId = oLicenseItem.getId();
            var iQuantity = oLicenseItem.getQuantity();
            if (bModifyData)
                oView.modifyProductCategoryListItemAt(sProductCategory, iIndex, iId, iQuantity);
            if ((iId && iId.toString().length > 0) && (iQuantity && iQuantity.toString().length > 0 && iQuantity > 0))
                oView.showListItemAdded(sProductCategory, iIndex);
            else
                oView.hideListItemAdded(sProductCategory, iIndex);
        }

        this.removeLicenseItemAt = function(sProductCategory, aLicenseItems, iIndex) {
            oView.removeProductLicenseAt(sProductCategory, iIndex);
            if (aLicenseItems.length == 1)
                this.hideDeleteButtonsByProductCategory(sProductCategory);
        }

        this.setSalesPhoneNumber = function(oSubsidiaries, oRegion) {
            oView.setSalesPhoneNumber(oSubsidiaries.get(oRegion.getSubsidiaryId()).getPhone());
        }

        this.showDeleteButtonsByProductCategory = function(sProductCategory) {
            oView.showDeleteButtonsByProductCategory(sProductCategory);
        }

        this.showErrorMessages = function(hErrorLists) {
            this.enableErrorMessages();
            if (hErrorLists)
                this.updateErrorMessages(hErrorLists);
        }

        this.showLicenseRequirement = function() {
            oView.showLicenseRequirement();
        }
        
        this.selectOrion100License = function() {
            var licensesList = $("orionLicenses");
		    
		    if(licensesList && licensesList.options)
		    {
		        licensesList.options[1].selected = "selected";
		    }
        }
        
        this.focusQuantityForOrion = function()
        {
            var orionQtyTbx = $("orionNpmQty");
            
            if(orionQtyTbx)
            {
                orionQtyTbx.focus();
            }
        }
        
        this.showSpecialOffers = function(aNetSuiteItems, hPromotions, oRegion, sProduct, iMouseX, iMouseY) {
            var iCurrency = oRegion.getCurrency();
            oView.clearSpecialOffers();

            var hUsedPromotions = $H();
            aNetSuiteItems.each(function(oNetSuiteItem, iIndex) {
                var aProductCategoryWords = oNetSuiteItem.getProductCategory().split(" ");
                aProductCategoryWords.each(function(oWord, iIndex) {
                    aProductCategoryWords[iIndex] = oWord.capitalize();
                });
                if (oNetSuiteItem.getProduct() == sProduct) {
                    var aPricePromotions = oNetSuiteItem.getPrices().get(iCurrency).getPromotions();
                    aPricePromotions.each(function(oPricePromotion, iIndex) {
                        var iId = oPricePromotion.getId();
                        var oPromotion = hPromotions.get(iId);
                        if (!hUsedPromotions.get(iId)) {
                            var dEndDate = oPromotion.getEndDate();
                            var iMonth = dEndDate.getMonth() + 1;
                            var sAmount = parseInt(Math.abs(oPromotion.getAmount())).toString();
                            var sAmount = oPromotion.getIsPercentage() ? (sAmount + "%") : (getCurrencySign(iCurrency) + sAmount);
                            oView.addSpecialOffer("Selected " + aProductCategoryWords.join(" ") + " SKUs " + sAmount + " off now through " + (iMonth < 10 ? "0" : "") + iMonth.toString() + "/" + dEndDate.getDate() + "/" + dEndDate.getFullYear() + "!");
                            //oView.addSpecialOffer(oPromotion.getDescription() + " now through " + (iMonth < 10 ? "0" : "") + iMonth.toString() + "/" + dEndDate.getDate() + "/" + dEndDate.getFullYear() + "!");
                            hUsedPromotions.set(iId, true);
                        }
                    });
                }
            });
            oView.showSpecialOffers(iMouseX, iMouseY);
        }

        this.toggleAccordionItemDisplay = function(oElement) {
            var oAccordionItem = oElement.up("li");
            if (oAccordionItem.hasClassName("Collapsed"))
                oView.expandAccordionItem(oAccordionItem);
            else
                oView.collapseAccordionItem(oAccordionItem);
        }

        this.updateErrorMessages = function(hErrorLists) {
            if (bValidated) {
                var aProductCategories = hErrorLists.keys();
                var sProductCategory;
                for (var iProductCategory = 0; iProductCategory < aProductCategories.length; iProductCategory++) {
                    sProductCategory = aProductCategories[iProductCategory];
                    if (hErrorLists.get(sProductCategory).length == 0)
                        oView.hideProductCategoryError(sProductCategory);
                    else
                        oView.showProductCategoryError(sProductCategory);
                }
            }
        }
        
        this.updateCurrentCurrencyAndSubsidiary = function (dataObject)
        {
            currentSubsidiary = dataObject.subsidiary;
            currentCurrency = dataObject.currency;
        }
        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*                 Initialize Class                 */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        oView = oNewView;

    }

    return fnStep1ViewHelperConstructor;
})();