Array.prototype.contains = function(element){
    for (var i = 0; i < this.length; i++) {
        if (this[i] === element) {
            return true;
        }
    }
    return false;
};

if (!Celigo) 
    var Celigo = {};
Celigo.SNPromotionsManager = (function(){
    //var promotionSuiteletUrl = "https://forms.sandbox.netsuite.com/app/site/hosting/scriptlet.nl?script=34&deploy=1&compid=1034580&h=7462cac2ce4195c17874", 
	var promotionSuiteletUrl = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=34&deploy=1&compid=1034580&h=7462cac2ce4195c17874",
	templateType = null, itemsIds = null, promoRules = null, itemSalesPrice = null, itemDisplayName = null, customerId = null, loginUrl = null, getPromotionRules = function(){
        var url = promotionSuiteletUrl;
		url += "&custpage_celigo_store_id=" + (jQuery(":hidden[name=n]") ? jQuery(":hidden[name=n]").val() : 0);
        url += "&custpage_celigo_item=" + itemsIds.join(",");
        $.getJSON(url + "&callback=?", function(data){
            if (data && data.results) {
                promoRules = data.results;
                if (templateType === 'CATEGORY') {
                    Celigo.CategoryPromotionsManager.showPromotions(promoRules);
                }
                else 
                    if (templateType === 'DRILLDOWN') {
                        celigoPromoMgrItemsInfo = data.itemsInfo;
                        Celigo.DrillDownPromotionsManager.showPromotions(promoRules, itemSalesPrice, itemDisplayName, customerId, loginUrl, itemsIds);
                    }
            }
        });
    }
    
    return {
        init: function(tmplType, arrItemIds){
            templateType = tmplType;
            itemsIds = arrItemIds;
            if (arrItemIds && arrItemIds.length > 0) {
                getPromotionRules();
            }
        },
        ddInit: function(tmplType, arrItemIds, salesPrice, displayName, custId, logUrl){
            templateType = tmplType;
            itemsIds = arrItemIds;
            itemSalesPrice = salesPrice;
            itemDisplayName = displayName;
            customerId = custId;
            loginUrl = logUrl;
            if (arrItemIds && arrItemIds.length > 0) {
                getPromotionRules();
            }
        }
    }
    
})();

Celigo.CategoryPromotionsManager = (function(){
    var promoRuleType = {
        Buy_X_Qty_Of_A_And_Receive_A_Free_Product: "1",
        Buy_XYZ_And_Receive_Percent_Or_Dollar_Off: "8",
        Buy_X_And_Receive_Y_Qty_Of_A_Or_B: "2",
        Spend_$_Amount_And_Receive_A_Free_Product: "9",
        Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off: "10",
        Flat_Discount: "11"
    }, onSale = function(itemId){
        var onSaleElem = '#onSale_item' + itemId;
        jQuery(onSaleElem).html("*On Promo*");
    }, showPromoPrice = function(itemId, promoPrice){
		promoPrice = parseFloat(promoPrice).toFixed(2);
        jQuery("#salesPrice_item" + itemId + " span:first").addClass("crossout");
        jQuery("#salesPrice_item" + itemId + " span:last").after("<span class='promoprice'>$" + promoPrice + "</span>");
    }, onPromotion = function(itemId){
    
    }, getSalePrice = function(itemId){
        var price = jQuery("#hdnSalePrice_item" + itemId).html();
        if (price) {
            price = price.replace(/\$/g, "");
        }
        else {
            price = 0;
        }
        return parseFloat(jQuery.trim(price));
    }
    
    return {
        showPromotions: function(promoRules){
            for (var i = 0; promoRules && i < promoRules.length; i++) {
                if (promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B || promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                    onSale(promoRules[i].item);
                }
                else 
                    if (promoRules[i].custrecord_pr_promo_type === promoRuleType.Flat_Discount) {
                        var salePrice = getSalePrice(promoRules[i].item);
                        var dollarOff = 0;
                        var percentOff = 0;
                        if (promoRules[i].custrecord_pr_dollars_off) {
                            dollarOff = parseFloat(promoRules[i].custrecord_pr_dollars_off);
                            showPromoPrice(promoRules[i].item, salePrice - dollarOff);
                        }
                        else 
                            if (promoRules[i].custrecord_pr_percntage_off) {
                                percentOff = parseFloat(promoRules[i].custrecord_pr_percntage_off);
                                var promoPrice = salePrice - (salePrice * percentOff / 100);
                                promoPrice = Math.round(promoPrice * 100) / 100; //2-decimals
                                showPromoPrice(promoRules[i].item, promoPrice);
                            }
                    }
            }
        }
    }
})();

Celigo.DrillDownPromotionsManager = (function(){

    var promoRuleType = {
        Buy_X_Qty_Of_A_And_Receive_A_Free_Product: "1",
        Buy_XYZ_And_Receive_Percent_Or_Dollar_Off: "8",
        Buy_X_And_Receive_Y_Qty_Of_A_Or_B: "2",
        Spend_$_Amount_And_Receive_A_Free_Product: "9",
        Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off: "10",
        Flat_Discount: "11"
    }, itemSalesPrice = null, itemDisplayName = null, customerId = null, loginUrl = null, currItemId = null, createPromoNameAndPriceTags = function(){
        jQuery('#promoName').html('<div id="proName" class="promoName"></div>');
        jQuery('#promoPrice').html('<div id="newPrice" class="dd-promoprice"></div>');
    }, createPromoDetailsTable = function(){
        var strHtml = '\
			<table cellspacing="0" cellpadding="0" border="0" width="266">\
				<tr>\
					<td height="15"><img src="/site/sn-images-site/sns_itemImageTop.gif" width="266" height="15" /></td>\
				</tr>\
				<tr>\
					<td align="center" style="background-image:url(/site/sn-images-site/sns_itemImage_bg.gif); background-repeat:repeat-y;text-align:left;">\
						<p class="promoDetailName">Promotions:</p>\
						<div class="promoDetailContent"></div>\
					</td>\
				</tr>\
				<tr>\
					<td height="19"><img src="/site/sn-images-site/sns_itemImageBottom.gif" width="266" height="19" /></td>\
				</tr>\
			</table>\
		';
        jQuery('#promoDetail').html(strHtml);
        jQuery('#promoDetail').addClass("promoDetail");
    }, showChoiceItems = function(promoRule){
        var strHtml = '\
			<table cellspacing="0" cellpadding="0" border="0" width="249">\
  				<tbody>\
    				<tr>\
      					<td><img height="10" width="249" src="/site/sn-images-site/sns_addToCart_top.gif"></td>\
    				</tr>\
    				<tr>\
      					<td align="center" style="background-image: url(&quot;/site/sn-images-site/sns_addToCart_bg.gif&quot;); background-repeat: repeat-y;">\
							<table cellspacing="0" cellpadding="0" border="0" width="249" class="cfp-list">\
								<tbody>\
            						<tr>\
              							<td width="10">&nbsp;</td>\
              							<td>\
											<div class="cfp-title">Choose from Products</div>\
                							<table cellspacing="0" cellpadding="0" border="0" width="100%">\
                  								<tbody>\
													';
        if (customerId) {
            for (var i = 0; promoRule.custrecord_pr_choice_item && i < promoRule.custrecord_pr_choice_item.length; i++) {
                strHtml += '\
													<tr>\
                										<td align="left" width="25%" valign="middle"><img width="50" src="' +
                promoRule.custrecord_pr_choice_item[i].img +
                '"></td>\
                										<td align="left" width="41%" valign="middle">' +
                promoRule.custrecord_pr_choice_item[i].text +
                '</td>\
			<td align="left" width="25%" valign="middle"><input type="text" class="input" size="3" id="promoChoice' +
                promoRule.internalid +
                '_' +
                promoRule.custrecord_pr_choice_item[i].id +
                '"></td>\
													</tr>\
													';
                
            }
        }
        else {
            strHtml += '\
															<tr>\
		                										<td align="center" valign="middle"><a href="' + loginUrl + '">Login for details</a></td>\
															</tr>\
															';
        }
        strHtml += '</tbody>\
											</table>\
										</td>\
              							<td width="10">&nbsp;</td>\
            						</tr>\
      							</tbody>\
        					</table>\
						</td>\
    				</tr>\
    				<tr>\
      					<td><img height="9" width="249" src="/site/sn-images-site/sns_addToCart_bottom.gif"></td>\
    				</tr>\
  				</tbody>\
			</table>\
		';
        jQuery('#choiceItems').html(strHtml);
        jQuery('#choiceItems').css({
            "padding-bottom": "10"
        });
        
        
        if (customerId) {
            var url = "/app/site/hosting/scriptlet.nl?script=customscript_celigo_sn_user_promo_option&deploy=customdeploy_celigo_sn_user_promo_optio1";
            jQuery.getJSON(url + "&callback=?", function(promoOptions){
            
                if (promoOptions[promoRule.internalid]) {
                    for (it in promoOptions[promoRule.internalid].items) {
                        if (it !== "clone") {
                            jQuery("#promoChoice" + promoRule.internalid + "_" + it).val(promoOptions[promoRule.internalid].items[it]);
                        }
                    }
                }
                
            });
        }
        
    }, addPromoDetails = function(promoRule){
        jQuery('#proName').append("<strong>" + promoRule.name + "</strong></br>");
        jQuery('.promoDetailContent').append("<p>" + promoRule.custrecord_pr_website_html + "</p>");
    }, showPromoPrice = function(promoPrice){
		promoPrice = parseFloat(promoPrice).toFixed(2);
        jQuery('#oldPrice').addClass("crossout");
        jQuery('#newPrice').html("$" + promoPrice);
    }, addAjaxLoader = function(){
        jQuery("#qty").parent().parent().children()[3].innerHTML = '<img id="celigoSNAjaxLoader" style="vertical-align:middle;" src="/site/promotions/ajax-loader.gif" />';
        jQuery("#celigoSNAjaxLoader").hide();
    }, showAjaxLoader = function(){
        jQuery("#celigoSNAjaxLoader").show();
    }, createPromoItemPopUps = function(){
        jQuery("a.promoitem").each(function(){
            var itemId = jQuery(this).attr("rel");
            
            if (itemId == currItemId) {
                jQuery(this).removeClass("promoitem");
                jQuery(this).addClass("promoitem-disabled");
            }
            
            var str = '<div id="promoItemPopUp' + itemId + '" style="display:none;" class="promoItemPopUp">';
            str += '<a href="#" class="close"><img src="/site/promotions/close.gif"></a>';
            str += '<table cellspacing="0" cellpadding="0" border="0" width="266">';
            str += '<tbody>';
            str += '<tr>';
            str += '<td height="15">';
            str += '<img height="15" width="266" src="/site/promotions/sns-imageTop.gif">';
            str += '</td>';
            str += '</tr>';
            str += '<tr>';
            str += '<td align="center" style="background-image:url(/site/sn-images-site/sns_itemImage_bg.gif); background-repeat:repeat-y;text-align:left;">';
            str += '<table width="90%" border="0" cellspacing="0" cellpadding="0">';
            str += '<tr>';
            str += '<td align="center" valign="top" style="padding-left:5px;padding-right:5px;" rowspan="2">';
            str += '<a href="/s.nl/c.1034580/it.A/id.' + itemId + '/.f"><img class="promoItemPopUp-img" height="86" src="' + celigoPromoMgrItemsInfo[itemId].img + '" /></a>';
            str += '</td>';
            str += '<td class="promoItemPopUp-title" valign="top">';
            str += '<a href="/s.nl/c.1034580/it.A/id.' + itemId + '/.f">' + celigoPromoMgrItemsInfo[itemId].text + '</a>';
            str += '</td>';
            str += '</tr>';
            str += '<tr>';
            str += '<td>';
            str += celigoPromoMgrItemsInfo[itemId].promoDescription || '&nbsp;';
            str += '</td>';
            str += '</tr>';
            str += '</table>';
            str += '</td>';
            str += '</tr>';
            str += '<tr>';
            str += '<td height="19">';
            str += '<img height="19" width="266" src="/site/promotions/sns-imageBottom.gif">';			
            str += '</td>';
            str += '</tr>';
            str += '</tbody>';
            str += '</table>';
            str += '</div>';
            
            jQuery("#promoDetail").after(str);
        });
        
        jQuery("a.promoitem-disabled").click(function(e){
            e.preventDefault();
        });
        jQuery("a.promoitem").hover(function(){
            jQuery.modal.close();
            var itemId = jQuery(this).attr("rel");
            
            setTimeout(function(){
                jQuery("#promoItemPopUp" + itemId).modal({
                    overlayId: 'sn-drilldown-promotions-overlay'
                });
            }, 10);
        });
        
        jQuery("div.promoItemPopUp > a.close").click(function(e){
            e.preventDefault();
            jQuery.modal.close();
        });
    }
    
    return {
        showPromotions: function(promoRules, salesPrice, displayName, custId, logUrl, itemsIds){
            itemSalesPrice = salesPrice;
            itemDisplayName = displayName;
            customerId = custId;
            loginUrl = logUrl;
            currItemId = itemsIds[0];
            
            if (promoRules && promoRules.length > 0) {
                createPromoNameAndPriceTags();
                createPromoDetailsTable();
            }
            for (var i = 0; promoRules && i < promoRules.length; i++) {
                if (promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                    addPromoDetails(promoRules[i]);
                }
                else 
                    if (promoRules[i].custrecord_pr_promo_type === promoRuleType.Flat_Discount) {
                        var salePrice = itemSalesPrice.replace(/\$/g, "");
                        var dollarOff = 0;
                        var percentOff = 0;
                        if (promoRules[i].custrecord_pr_dollars_off) {
                            dollarOff = parseFloat(promoRules[i].custrecord_pr_dollars_off);
                            showPromoPrice(salePrice * 1 - dollarOff);
                        }
                        else 
                            if (promoRules[i].custrecord_pr_percntage_off) {
                                percentOff = parseFloat(promoRules[i].custrecord_pr_percntage_off);
                                var promoPrice = salePrice - (salePrice * percentOff / 100);
                                promoPrice = Math.round(promoPrice * 100) / 100; //2-decimals
                                showPromoPrice(promoPrice);
                            }
                        addPromoDetails(promoRules[i]);
                    }
                    else 
                        if (promoRules[i].custrecord_pr_promo_type === promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
                            showChoiceItems(promoRules[i]);
                            addPromoDetails(promoRules[i]);
                        }
            }
            addAjaxLoader();
            createPromoItemPopUps();
        },
        trackAddToCart: function(itemId){
            var itemForm = jQuery("form#form" + itemId).length > 0 ? jQuery("form#form" + itemId)[0] : null;
            if (itemForm) {
                var orgOnSubmit = itemForm.onsubmit;
                itemForm.onsubmit = function(){
                    if (orgOnSubmit()) {

                        var promoOptions = null;
                        
                        jQuery.each(jQuery("input:text[id^=promoChoice]"), function(){
                            var idParts = this.id.substring("promoChoice".length).split("_");
                            var selQty = 0;
                            if (!isNaN(parseInt(this.value, 10)) && parseInt(this.value, 10) >= 0) {
                                selQty = parseInt(this.value, 10);
                            }
                            
                            
                            if (!promoOptions) {
                                promoOptions = {};
                            }
                            if (!promoOptions[idParts[0]]) {
                                promoOptions[idParts[0]] = {
                                    items: []
                                };
                            }
                            promoOptions[idParts[0]].items.push({
                                id: idParts[1],
                                qty: selQty
                            });
                            
                            
                        });
                        
                        if (promoOptions) {
                            showAjaxLoader();
                            var url = "/app/site/hosting/scriptlet.nl?script=customscript_celigo_sn_user_promo_option&deploy=customdeploy_celigo_sn_user_promo_optio1";
                            url += "&promooptions=" + toJSON(promoOptions);
                            jQuery.getJSON(url + "&callback=?", function(data){
                                itemForm.submit();
                            });
                            return false;
                        }
                        return true;
                        
                    }
                    else {
                        return false;
                    }
                };
            }
        }
    }
})();

Celigo.SNPromotionsWindow = (function(){

    var that = this;
    this.promotionSuiteletUrl = "/app/site/hosting/scriptlet.nl?script=customscript_getpromorules_sl&deploy=customdeploy_getpromorules_sl2";
    this.promoRuleType = {
        Buy_X_Qty_Of_A_And_Receive_A_Free_Product: "1",
        Buy_XYZ_And_Receive_Percent_Or_Dollar_Off: "8",
        Buy_X_And_Receive_Y_Qty_Of_A_Or_B: "2",
        Spend_$_Amount_And_Receive_A_Free_Product: "9",
        Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off: "10",
        Flat_Discount: "11"
    };
    
    
    this.cartData = null;
    this.displayedPromotionIds = [];
    this.autoSelects = [];
    
    
    this.sortPromotions = function(a, b){
        if (a.custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off || a.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
            return 1;
        }
        
        if (b.custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off || b.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
            return -1;
        }
        
        return a.custrecord_pr_promo_type > b.custrecord_pr_promo_type ? 1 : (a.custrecord_pr_promo_type < b.custrecord_pr_promo_type) ? -1 : 0;
    };
    
    
    this.sortPromotions2 = function(a, b){
        // all percent offs should be on last...
        
        
        var promotype1 = 0;
        var promotype2 = 0;
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product) {
            promotype1 = 1;
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product) {
            promotype2 = 1;
        }
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
            promotype1 = 2;
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
            promotype2 = 2;
        }
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Flat_Discount) {
            promotype1 = 3;
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Flat_Discount) {
            promotype2 = 3;
        }
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
            promotype1 = 5;
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
            promotype2 = 5;
        }
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
            if (a.custrecord_pr_dollars_off) {
                promotype1 = 4;
            }
            else {
                promotype1 = 7;
            }
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
            if (b.custrecord_pr_dollars_off) {
                promotype2 = 4;
            }
            else {
                promotype2 = 7;
            }
        }
        
        if (a.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
            if (a.custrecord_pr_percntage_off) {
                promotype1 = 8;
            }
            else {
                promotype1 = 6;
            }
            
        }
        if (b.custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
            if (b.custrecord_pr_percntage_off) {
                promotype2 = 8;
            }
            else {
                promotype2 = 6;
            }
        }
        
        
        
        return promotype1 > promotype2 ? 1 : (promotype1 < promotype2) ? -1 : 0;
    };
    
    this.formatCurrency = function(amount){
        var i = parseFloat(amount);
        if (isNaN(i)) {
            i = 0.00;
        }
        var minus = '';
        if (i < 0) {
            minus = '-';
        }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        s = new String(i);
        if (s.indexOf('.') < 0) {
            s += '.00';
        }
        if (s.indexOf('.') == (s.length - 2)) {
            s += '0';
        }
        s = minus + s;
        return s;
    };
    
    this.getCartTotal = function(amount){
        var total = 0;
        for (var i = 0; i < that.cartData.items.length; i++) {
            total = (total * 1) + (that.cartData.items[i].rate * that.cartData.items[i].qty);
        }
        return total;
    };
    
    
    this.addTableRow = function(type, promotionName, promotionDesc, options, promoId, promoImage){
        var tableID = "tblPromotions";
        var table = document.getElementById(tableID);
        
        var rowCount = table.rows.length - 3;
        var row = table.insertRow(rowCount);
        row.id = "trPromoRow" + promoId;
        
        var chkPromoSelected = document.createElement("input");
        chkPromoSelected.type = "checkbox";
        chkPromoSelected.id = "promo" + promoId;
        chkPromoSelected.checked = "checked";
        chkPromoSelected.disabled = "disabled";
        
        
        var cellPromoDescription = row.insertCell(0);
        cellPromoDescription.className = "lborder";
        cellPromoDescription.innerHTML = promotionDesc;
        
        cellPromoDescription.appendChild(chkPromoSelected);
        
        var cellPromoImage = row.insertCell(1);
        cellPromoImage.className = "promoImage";
        if (promoImage) {
            cellPromoImage.innerHTML = '<img border="0" title="" alt="" src="' + promoImage + '">';
        }
        else {
            cellPromoImage.innerHTML = "N/A";
        }
        
        var cellPromoItemsValue = row.insertCell(2);
        cellPromoItemsValue.innerHTML = options || "&nbsp;";
        
        if (type === that.promoRuleType.Flat_Discount) {
            var itemPrice = 0;
            var discount = 0;
            var itemId = 0;
            for (var i = 0; i < that.cartData.results.length; i++) {
                if (that.cartData.results[i].internalid == promoId) {
                    itemId = that.cartData.results[i].item;
                    itemPrice = that.cartData.itemsInfo[itemId].onlinePrice;
                    if (that.cartData.results[i].custrecord_pr_dollars_off) {
                        discount = that.cartData.results[i].custrecord_pr_dollars_off;
                    }
                    else 
                        if (that.cartData.results[i].custrecord_pr_percntage_off) {
                            discount = parseFloat(that.cartData.results[i].custrecord_pr_percntage_off);
                            discount = (discount * itemPrice) / 100;
                            discount = Math.round(discount * 100) / 100; //2-decimals;
                        }
                    break;
                }
            }
            
            for (i = 0; i < that.cartData.items.length; i++) {
                if (that.cartData.items[i].id == itemId) {
                    discount *= that.cartData.items[i].qty;
                }
            }
            
            cellPromoItemsValue.innerHTML = "$" + that.formatCurrency(discount);
        }
        else 
            if (type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product) {
                var prFor, prItem, prOrderQty, prQty;
                for (var i = 0; i < that.cartData.results.length; i++) {
                    if (that.cartData.results[i].internalid == promoId) {
                        prFor = that.cartData.results[i].item;
                        prItem = that.cartData.results[i].custrecord_pr_item;
                        prOrderQty = that.cartData.results[i].custrecord_pr_quantity_ordered;
                        prQty = that.cartData.results[i].custrecord_pr_promo_quantity;
                        break;
                    }
                }
                
                var appliedQty = 0;
                var discount = 0;
                
                for (i = 0; i < that.cartData.items.length; i++) {
                    if (that.cartData.items[i].id == prFor) {
                        //appliedQty = (that.cartData.items[i].qty * prQty) / prOrderQty;
						appliedQty = Math.floor(that.cartData.items[i].qty/prOrderQty) * prQty;
                        break;
                    }
                }
                discount = appliedQty * (that.cartData.itemsInfo[prItem].onlinePrice);
                cellPromoItemsValue.innerHTML = "$" + that.formatCurrency(discount);
            }
            else 
                if (type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                    cellPromoItemsValue.innerHTML += "<span id='promoVal" + promoId + "'></span>";
                }
                else 
                    if (type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
                        var discount = 0;
                        for (var i = 0; i < that.cartData.results.length; i++) {
                            if (that.cartData.results[i].internalid == promoId) {
                                discount = that.cartData.results[i].custrecord_pr_promo_quantity * that.cartData.itemsInfo[that.cartData.results[i].custrecord_pr_item].onlinePrice;
                                break;
                            }
                        }
                        cellPromoItemsValue.innerHTML = "$" + that.formatCurrency(discount);
                    }
                    else 
                        if (type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
                            var cartTotal = that.getCartTotal();
                            var dollarDiscount = 0;
                            var percentDiscount = 0;
                            var discount = 0;
                            
                            for (var i = 0; i < that.cartData.results.length; i++) {
                                if (that.cartData.results[i].internalid == promoId) {
                                    if (that.cartData.results[i].custrecord_pr_dollars_off) {
                                        dollarDiscount = that.cartData.results[i].custrecord_pr_dollars_off;
                                    }
                                    
                                    if (that.cartData.results[i].custrecord_pr_percntage_off) {
                                        percentDiscount = parseFloat(that.cartData.results[i].custrecord_pr_percntage_off);
                                        percentDiscount = (percentDiscount * cartTotal) / 100;
                                        percentDiscount = Math.round(percentDiscount * 100) / 100; //2-decimals;
                                    }
                                    break;
                                }
                            }
                            
                            discount = Math.max(dollarDiscount, percentDiscount);
                            
                            if (discount === percentDiscount) {
                                that.cartData.results[i].selectedType = "P";
                                that.autoSelects.push("input:radio[name=promo" + promoId + "PrD][value=P]");
                            }
                            else {
                                that.cartData.results[i].selectedType = "D";
                                that.autoSelects.push("input:radio[name=promo" + promoId + "PrD][value=D]");
                            }
                            
                            cellPromoItemsValue.innerHTML = "<span style='display:none;'>" + options + "</span>";
                            //cellPromoItemsValue.innerHTML = options;
                            cellPromoItemsValue.innerHTML += " $" + that.formatCurrency(discount);
                        }
        
        
        
        
        var emptyRow = table.insertRow(rowCount + 1);
        emptyRow.id = "trPromoEmptyRow" + promoId;
        var emptyCell = emptyRow.insertCell(0);
        emptyCell.innerHTML = "";
        emptyCell.colSpan = "3";
        emptyCell.className = "empty";
    };
    this.getPromotions = function(){
        jQuery.getJSON(that.promotionSuiteletUrl + "&custpage_celigo_store_id=" + (jQuery(":hidden[name=n]") ? jQuery(":hidden[name=n]").val() : 0) + "&callback=?", function(data){
            that.cartData = data;
            
            if (that.cartData && that.cartData.results) {
            
            
            
                for (var i = 0; i < that.cartData.results.length - 1; i++) {
                    for (var j = i + 1; j < that.cartData.results.length; j++) {
                        if (that.cartData.results[i].internalid == that.cartData.results[j].internalid) {
                            that.cartData.results.splice(j, 1);
                            j -= 1;
                        }
                    }
                }
                
                that.initializeAvailablePromoQuantities();
                that.setDependentPromotions();
                
                that.cartData.results.sort(that.sortPromotions2);
                
                
                //calculate promo values for each Buy_XYZ_And_Receive_Percent_Or_Dollar_Off
                for (i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                        that.cartData.results[i].promoValue = 0;
                        if (that.cartData.results[i].custrecord_pr_dollars_off) {
                            that.cartData.results[i].promoValue = that.cartData.results[i].custrecord_pr_dollars_off;
                        }
                        else {
                            var listIds = that.cartData.results[i].custrecord_pr_product_and.split(",");
                            var listAmt = 0;
                            for (var li = 0; li < listIds.length; li++) {
                                listAmt = (listAmt * 1) + (that.cartData.itemsInfo[listIds[li]].onlinePrice * 1);
                            }
                            that.cartData.results[i].promoValue = (listAmt * parseFloat(that.cartData.results[i].custrecord_pr_percntage_off)) / 100;
                        }
                    }
                }
                
                for (i = 0; i < that.cartData.results.length; i++) {
                    if (that.displayedPromotionIds.contains(that.cartData.results[i].internalid)) {
                        continue;
                    }
                    that.displayedPromotionIds.push(that.cartData.results[i].internalid);
                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
                        that.addTableRow(that.cartData.results[i].custrecord_pr_promo_type, that.cartData.results[i].name, that.cartData.results[i].custrecord_pr_details, "", that.cartData.results[i].internalid, that.cartData.results[i].custrecord_celigo_pr_image);
                    }
                    else 
                        if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
                            var options = "";
                            if (that.cartData.results[i].custrecord_pr_dollars_off && that.cartData.results[i].custrecord_pr_percntage_off) {
                                options += "<input type='radio' name='promo" + that.cartData.results[i].internalid + "PrD' value='D' />"; //$" + that.cartData.results[i].custrecord_pr_dollars_off;
                                options += "<input type='radio' name='promo" + that.cartData.results[i].internalid + "PrD' value='P' />"; // + that.cartData.results[i].custrecord_pr_percntage_off;
                            }
                            else 
                                if (that.cartData.results[i].custrecord_pr_dollars_off) {
                                    options += "<input type='radio' name='promo" + that.cartData.results[i].internalid + "PrD' value='D' checked />"; //$" + that.cartData.results[i].custrecord_pr_dollars_off;
                                }
                                else 
                                    if (that.cartData.results[i].custrecord_pr_percntage_off) {
                                        options += "<input type='radio' name='promo" + that.cartData.results[i].internalid + "PrD' value='P' checked />"; //$" + that.cartData.results[i].custrecord_pr_percntage_off;
                                    }
                            that.addTableRow(that.cartData.results[i].custrecord_pr_promo_type, that.cartData.results[i].name, that.cartData.results[i].custrecord_pr_details, options, that.cartData.results[i].internalid, that.cartData.results[i].custrecord_celigo_pr_image);
                        }
                        else 
                            if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Flat_Discount) {
                                that.addTableRow(that.cartData.results[i].custrecord_pr_promo_type, that.cartData.results[i].name, that.cartData.results[i].custrecord_pr_details, "", that.cartData.results[i].internalid, that.cartData.results[i].custrecord_celigo_pr_image);
                            }
                            else 
                                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                                    var minQty = that.getMinimumQuantity(that.cartData.results[i].custrecord_pr_product_and);
                                    if (minQty > 0) {
                                        var options = "<select id='selectpromo" + that.cartData.results[i].internalid + "'>";
                                        for (var opt = 0; opt <= minQty; opt++) {
                                            options += "<option value=" + opt + ">" + opt + "</option>";
                                        }
                                        options += "</select>";
                                        that.addTableRow(that.cartData.results[i].custrecord_pr_promo_type, that.cartData.results[i].name, that.cartData.results[i].custrecord_pr_details, options, that.cartData.results[i].internalid, that.cartData.results[i].custrecord_celigo_pr_image);
                                    }
                                }
                                else 
                                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
                                        var options = '<table cellspacing="0" border="1">';
                                        
                                        for (var ci = 0; that.cartData.results[i].custrecord_pr_choice_item && ci < that.cartData.results[i].custrecord_pr_choice_item.length; ci++) {
                                            options += '<tr><td>' + that.cartData.results[i].custrecord_pr_choice_item[ci].text + '</td><td><input type="text" id="promoChoice' + that.cartData.results[i].internalid + '_' + that.cartData.results[i].custrecord_pr_choice_item[ci].id + '" size="3" class="input"></td></tr>';
                                        }
                                        options += '</table>';
                                        
                                        that.addTableRow(that.cartData.results[i].custrecord_pr_promo_type, that.cartData.results[i].name, that.cartData.results[i].custrecord_pr_details, options, that.cartData.results[i].internalid, that.cartData.results[i].custrecord_celigo_pr_image);
                                    }
                }
                that.handlePromoQuantityChange();
                that.setSelected();
                
                jQuery("input:checkbox[id^=promo]").hide();
            }
            
            
        })
        
    };
    
    this.getMaxPromotion = function(promoIds){
        var promoIndx = 0;
        var promoValue = 0;
        
        for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
            if (promoIds.contains(that.cartData.results[i].internalid)) {
                if (that.cartData.results[i].promoValue > promoValue) {
                    if (jQuery("#selectpromo" + that.cartData.results[i].internalid + " > option").length > 1) {
                        promoValue = that.cartData.results[i].promoValue;
                        promoIndx = i;
                    }
                }
            }
        }
        
        return that.cartData.results[promoIndx];
    };
    
    this.setSelected = function(){
        var url = "/app/site/hosting/scriptlet.nl?script=customscript_celigo_sn_user_promo_option&deploy=customdeploy_celigo_sn_user_promo_optio1";
        jQuery.getJSON(url + "&callback=?", function(promoOptions){
        
            selectedPromotions = {};
            if (jQuery('#custbody_celigo_sn_selected_promotions').val()) {
                //selectedPromotions = JSON.parse(jQuery('#custbody_celigo_sn_selected_promotions').val());
                selectedPromotions = eval('(' + jQuery('#custbody_celigo_sn_selected_promotions').val() + ')');
            }
            for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
                if (selectedPromotions[that.cartData.results[i].internalid]) {
                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
                        jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                    }
                    else 
                        if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
                            jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                            jQuery('[name="promo' + that.cartData.results[i].internalid + 'PrD" ][value="' + selectedPromotions[that.cartData.results[i].internalid].V + '"]').attr('checked', true);
                        }
                        else 
                            if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                                jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                                jQuery("#selectpromo" + that.cartData.results[i].internalid).val(selectedPromotions[that.cartData.results[i].internalid].V);
                                jQuery("#selectpromo" + that.cartData.results[i].internalid).change();
                            }
                    
                }
                
                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
                    jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                    if (promoOptions[that.cartData.results[i].internalid]) {
                        for (it in promoOptions[that.cartData.results[i].internalid].items) {
                            if (it !== "clone") {
                                jQuery("#promoChoice" + that.cartData.results[i].internalid + "_" + it).val(promoOptions[that.cartData.results[i].internalid].items[it]);
                            }
                        }
                    }
                }
            }
            
            
            
            for (i = 0; i < that.autoSelects.length; i++) {
                jQuery(that.autoSelects[i]).attr("checked", true);
            }
            
            
            
            
            for (i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
                jQuery("span#promoVal" + that.cartData.results[i].internalid).html("N/A");
                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                    var dependentPromotions = that.cartData.results[i].dependentPromotions;
                    dependentPromotions.push(that.cartData.results[i].internalid);
                    var maxPromotion = that.getMaxPromotion(dependentPromotions);
                    jQuery("#selectpromo" + maxPromotion.internalid).val(jQuery("#selectpromo" + maxPromotion.internalid + " > option").length - 1);
                    jQuery("#selectpromo" + maxPromotion.internalid).change();
                    jQuery("span#promoVal" + maxPromotion.internalid).html("$" + that.formatCurrency(jQuery("#selectpromo" + maxPromotion.internalid).val() * maxPromotion.promoValue));
                }
            }
            
            that.applyDropdownPromos();
            
            jQuery.each(jQuery("select[id^='selectpromo']"), function(){
                var promoId = jQuery(this).attr("id").substring(11);
                jQuery(this).hide();
                if (jQuery(this).val() == 0) {
                    jQuery("#trPromoRow" + jQuery(this).attr("id").substring(11)).hide();
                    jQuery("#trPromoEmptyRow" + jQuery(this).attr("id").substring(11)).hide();
                }
            });
            
            jQuery("input:radio[name^='promo']").hide();
            
            if (!that.getURLParameter('hidepromotions')) {
                that.showPromotionsWin();
            }
            
        });
    };
    
    this.validateDependentPromotions = function(dependentPromotions){
        //remove already applied max promos		
        var filteredDependentPromotions = [];
        
        jQuery.each(dependentPromotions, function(index, value){
            if (jQuery("#selectpromo" + value).val() == 0) {
                filteredDependentPromotions.push(value);
            }
        });
        return filteredDependentPromotions;
    };
    
    this.applyDropdownPromos = function(){
        if (that.areThereApplicablePromos()) {
            for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
                jQuery("span#promoVal" + that.cartData.results[i].internalid).html("N/A");
                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                    if (jQuery("#selectpromo" + that.cartData.results[i].internalid).val() == 0) {
                        if (jQuery("#selectpromo" + that.cartData.results[i].internalid + " > option").length > 1) {
                            var dependentPromotions = that.cartData.results[i].dependentPromotions;
                            dependentPromotions.push(that.cartData.results[i].internalid);
                            dependentPromotions = that.validateDependentPromotions(dependentPromotions);
                            
                            var maxPromotion = that.getMaxPromotion(dependentPromotions);
                            jQuery("#selectpromo" + maxPromotion.internalid).val(jQuery("#selectpromo" + maxPromotion.internalid + " > option").length - 1);
                            jQuery("#selectpromo" + maxPromotion.internalid).change();
                            jQuery("span#promoVal" + maxPromotion.internalid).html("$" + that.formatCurrency(jQuery("#selectpromo" + maxPromotion.internalid).val() * maxPromotion.promoValue));
                        }
                    }
                }
            }
            
            that.applyDropdownPromos();
        }
    };
    
    this.areThereApplicablePromos = function(){
        var flag = false;
        jQuery.each(jQuery("select[id^='selectpromo'][value=0]"), function(){
            if (jQuery("#" + this.id + " > option").length > 1) {
                flag = true;
            }
        });
        return flag;
    };
    
    this.setSelectedOLD = function(){
        selectedPromotions = {};
        if (jQuery('#custbody_celigo_sn_selected_promotions').val()) {
            //selectedPromotions = JSON.parse(jQuery('#custbody_celigo_sn_selected_promotions').val());
            selectedPromotions = eval('(' + jQuery('#custbody_celigo_sn_selected_promotions').val() + ')');
        }
        for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
            if (selectedPromotions[that.cartData.results[i].internalid]) {
                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
                    jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                }
                else 
                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
                        jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                        jQuery('[name="promo' + that.cartData.results[i].internalid + 'PrD" ][value="' + selectedPromotions[that.cartData.results[i].internalid].V + '"]').attr('checked', true);
                    }
                    else 
                        if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                            jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                            jQuery("#selectpromo" + that.cartData.results[i].internalid).val(selectedPromotions[that.cartData.results[i].internalid].V);
                            jQuery("#selectpromo" + that.cartData.results[i].internalid).change();
                        }
                        else 
                            if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
                                jQuery("#promo" + that.cartData.results[i].internalid).attr("checked", true);
                                for (it in selectedPromotions[that.cartData.results[i].internalid].items) {
                                    if (it !== "clone") {
                                        jQuery("#promoChoice" + that.cartData.results[i].internalid + "_" + it).val(selectedPromotions[that.cartData.results[i].internalid].items[it]);
                                    }
                                }
                            }
            }
        }
    };
	
	this.closePromotionsPopup = function(){
		jQuery.modal.close();
		//this.applyPromotions(); //closing popup will trigger applyPromotions
	};
	
    this.applyPromotions = function(){
    
        //jQuery.modal.close();
        //setTimeout(function(){
            jQuery("#divSNApplyingPromotions").modal({
                overlayId: 'sn-applying-promotions-overlay'
            });
        //}, 10);
        
        jQuery("#celigoSNAjaxLoader").show();
        jQuery("#btnApplyPromotions").attr("disabled", true);
        
        var selectedPromotions = {};
        var selectedPromotionIds = [];
        
        for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
        
            if (selectedPromotionIds.contains(that.cartData.results[i].internalid)) {				
                continue;
            }
            selectedPromotionIds.push(that.cartData.results[i].internalid);
            
            if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_Qty_Of_A_And_Receive_A_Free_Product || that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_A_Free_Product) {
                //if (jQuery("#promo" + that.cartData.results[i].internalid).attr("checked")) {
                selectedPromotions[that.cartData.results[i].internalid] = {
                    V: 0
                };
                //}
            }
            else 
                if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Spend_$_Amount_And_Receive_Percent_Or_Dollar_Off) {
                    //if (jQuery("#promo" + that.cartData.results[i].internalid).attr("checked")) {
                    //if (jQuery("input:radio[name=promo" + that.cartData.results[i].internalid + "PrD]:checked").val()) {
                    selectedPromotions[that.cartData.results[i].internalid] = {
                        //V: jQuery("input:radio[name=promo" + that.cartData.results[i].internalid + "PrD]:checked").val()
                        V: that.cartData.results[i].selectedType
                    };
                //}
                //}
                }
                
                else 
                    if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                        //if (jQuery("#promo" + that.cartData.results[i].internalid).attr("checked")) {
                        selectedPromotions[that.cartData.results[i].internalid] = {
                            V: jQuery("#selectpromo" + that.cartData.results[i].internalid).val()
                        };
                    //}
                    }
                    
                    else 
                        if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_X_And_Receive_Y_Qty_Of_A_Or_B) {
                        
                            //if (jQuery("#promo" + that.cartData.results[i].internalid).attr("checked")) {
                            selectedPromotions[that.cartData.results[i].internalid] = {
                                items: {}
                            };
                            
                            for (var ci = 0; that.cartData.results[i].custrecord_pr_choice_item && ci < that.cartData.results[i].custrecord_pr_choice_item.length; ci++) {
                                var qty = jQuery("#promoChoice" + that.cartData.results[i].internalid + "_" + that.cartData.results[i].custrecord_pr_choice_item[ci].id).val();
                                if (!isNaN(parseInt(qty, 10)) && parseInt(qty, 10) >= 0) {
                                    qty = parseInt(qty, 10);
                                }
                                else {
                                    qty = 0;
                                }
                                selectedPromotions[that.cartData.results[i].internalid].items[that.cartData.results[i].custrecord_pr_choice_item[ci].id] = qty;
                                
                            }
                            
                            
                        //}
                        }
            
        }
        
        //alert(toJSON(selectedPromotions));
        
        
        
        
        var promoOptions = null;
        
        jQuery.each(jQuery("input:text[id^=promoChoice]"), function(){
            var idParts = this.id.substring("promoChoice".length).split("_");
            var selQty = 0;
            if (!isNaN(parseInt(this.value, 10)) && parseInt(this.value, 10) >= 0) {
                selQty = parseInt(this.value, 10);
            }
            if (!promoOptions) {
                promoOptions = {};
            }
            if (!promoOptions[idParts[0]]) {
                promoOptions[idParts[0]] = {
                    items: []
                };
            }
            promoOptions[idParts[0]].items.push({
                id: idParts[1],
                qty: selQty
            });
        });
        
        var urlToRedirect = document.location.href;
        if (urlToRedirect.indexOf('?') > -1) {
            urlToRedirect += '&hidepromotions=1';
        }
        else {
            urlToRedirect += '?hidepromotions=1';
        }
        
        //alert(toJSON(selectedPromotions));
		
		for(var sp in selectedPromotions){
			if (sp !== "clone") {
				selectedPromotions[sp].dt = new Date().getTime();
			}
		}
        
        if (promoOptions) {
            var url = "/app/site/hosting/scriptlet.nl?script=customscript_celigo_sn_user_promo_option&deploy=customdeploy_celigo_sn_user_promo_optio1";
            url += "&promooptions=" + toJSON(promoOptions);
            jQuery.getJSON(url + "&callback=?", function(data){
                var url = '/app/site/backend/setcheckoutvalue.nl?sc=4&redirect=' + encode(urlToRedirect) + '&custbody_celigo_sn_selected_promotions=' + toJSON(selectedPromotions);
                document.location.href = url;
            });
        }
        else {
            var url = '/app/site/backend/setcheckoutvalue.nl?sc=4&redirect=' + encode(urlToRedirect) + '&custbody_celigo_sn_selected_promotions=' + toJSON(selectedPromotions);
            document.location.href = url;
        }
        
        //alert(JSON.stringify(selectedPromotions));				
        //applyPromotions(JSON.stringify(selectedPromotions));
    
        //var url = '/app/site/backend/setcheckoutvalue.nl?sc=4&redirect='+encode(document.location.href+'&hidepromotions=1')+'&custbody_celigo_sn_selected_promotions='+toJSON(selectedPromotions);
        //document.location.href = url;
    
    };
    this.getMinimumQuantity = function(csItemIds){
        var arrItems = csItemIds.split(",");
        var qty = 0, minQty = null;
        for (var i = 0; arrItems && i < arrItems.length; i++) {
            qty = that.getCartItemAvailablePromoQty(arrItems[i]);
            if (minQty === null) {
                minQty = qty;
            }
            minQty = Math.min(minQty, qty);
        }
        if (!minQty) {
            minQty = 0;
        }
        return minQty;
    };
    this.getCartItemAvailablePromoQty = function(itemId){
        for (var i = 0; that.cartData.items && i < that.cartData.items.length; i++) {
            if (parseInt(itemId, 10) === parseInt(that.cartData.items[i].id, 10)) {
                return parseInt(that.cartData.items[i].availablePromoQty, 10);
            }
        }
        return 0;
    };
    this.initializeAvailablePromoQuantities = function(){
        for (var i = 0; that.cartData.items && i < that.cartData.items.length; i++) {
            that.cartData.items[i].availablePromoQty = that.cartData.items[i].qty;
        }
    };
    this.setDependentPromotions = function(){
        for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
            that.cartData.results[i].dependentPromotions = [];
            that.cartData.results[i].qty = 0;
        }
        for (i = 0; that.cartData.results && i < that.cartData.results.length - 1; i++) {
            if (that.cartData.results[i].custrecord_pr_promo_type === that.promoRuleType.Buy_XYZ_And_Receive_Percent_Or_Dollar_Off) {
                var areDependent = that.areDependentPromotions(that.cartData.results[i], that.cartData.results[i + 1]);
                if (areDependent) {
                    that.cartData.results[i].dependentPromotions.push(that.cartData.results[i + 1].internalid);
                    that.cartData.results[i + 1].dependentPromotions.push(that.cartData.results[i].internalid);
                }
            }
        }
    };
    this.areDependentPromotions = function(promo1, promo2){
        if (promo1.internalid !== promo2.internalid && promo2.custrecord_pr_product_and) {
            var promo1Items = promo1.custrecord_pr_product_and.split(",");
            var promo2Items = promo2.custrecord_pr_product_and.split(",");
            for (var i = 0; promo2Items && i < promo2Items.length; i++) {
                if (promo1Items.contains(promo2Items[i])) {
                    return true;
                }
            }
        }
        return false;
    };
    this.handlePromoQuantityChange = function(){
        jQuery("select[id^='selectpromo']").change(function(){
            var promotion = that.getPromotionById(jQuery(this).attr("id").substring(11));
            var diff = parseInt(promotion.qty, 10) - parseInt(jQuery(this).val(), 10);
            promotion.qty = jQuery(this).val();
            var promoItems = promotion.custrecord_pr_product_and.split(",");
            for (var item = 0; that.cartData.items && item < that.cartData.items.length; item++) {
                if (promoItems.contains(that.cartData.items[item].id)) {
                    that.cartData.items[item].availablePromoQty = that.cartData.items[item].availablePromoQty * 1 + parseInt(diff, 10);
                }
            }
            that.dependentPromotionsParsed = [];
            that.adjustDependentPromotions(promotion.internalid, promotion.dependentPromotions);
        });
    };
    
    this.changePromoQuantity = function(promoId, qty){
    
        var promotion = that.getPromotionById(promoId);
        var diff = parseInt(promotion.qty, 10) - parseInt(qty, 10);
        promotion.qty = qty;
        var promoItems = promotion.custrecord_pr_product_and.split(",");
        for (var item = 0; that.cartData.items && item < that.cartData.items.length; item++) {
            if (promoItems.contains(that.cartData.items[item].id)) {
                that.cartData.items[item].availablePromoQty = that.cartData.items[item].availablePromoQty * 1 + parseInt(diff, 10);
            }
        }
        that.dependentPromotionsParsed = [];
        that.adjustDependentPromotions(promotion.internalid, promotion.dependentPromotions);
        
    };
    
    this.getPromotionById = function(promoId){
        for (var i = 0; that.cartData.results && i < that.cartData.results.length; i++) {
            if (that.cartData.results[i].internalid == promoId) {
                return that.cartData.results[i];
            }
        }
    };
    this.adjustDependentPromotions = function(promoId, dependentPromotions){
        that.dependentPromotionsParsed.push(promoId);
        for (var dp = 0; dependentPromotions && dp < dependentPromotions.length; dp++) {
            if (!that.dependentPromotionsParsed.contains(dependentPromotions[dp])) {
                var dependentPromotion = that.getPromotionById(dependentPromotions[dp]);
                var minQty = that.getMinimumQuantity(dependentPromotion.custrecord_pr_product_and);
                var qtySelect = jQuery("select:[id=selectpromo" + dependentPromotion.internalid + "]");
                var qtySelected = qtySelect.val();
                jQuery('option', qtySelect).remove();
                
                minQty = (minQty * 1) + (qtySelected * 1);
                
                for (var opt = 0; opt <= minQty; opt++) {
                    qtySelect.append('<option value="' + opt + '" selected="selected">' + opt + '</option>');
                }
                qtySelect.val(qtySelected);
                that.adjustDependentPromotions(dependentPromotion.internalid, dependentPromotion.dependentPromotions);
            }
        }
    };
    this.getURLParameter = function(name){ //String
        var url = document.location.href;
        var regexS;
        var regex;
        var results;
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        regexS = "[\\?&]" + name + "=([^&#]*)";
        regex = new RegExp(regexS);
        results = regex.exec(url);
        return results ? results[1] : "";
    };
    this.showPromotionsWin = function(){
    
        if (that.cartData.results.length > 0) {
            jQuery("#divSNPromotions").modal({
                closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
                position: ["15%", ],
                overlayId: 'sn-promotions-overlay',
                containerId: 'sn-promotions-container',
                onClose: function(dialog){
					dialog.data.hide();
					jQuery("a.simplemodal-close").hide();						
                    celigoSNPromotionsWindowMgr.applyPromotions();
                }
            });            
            jQuery("#celigoSNAjaxLoader").hide();
            jQuery("#btnApplyPromotions").attr("disabled", false);
            
            if (jQuery.browser.msie && jQuery("#divSNPromotions")[0].scrollHeight > 550) {
                jQuery("#divSNPromotions").height(500);
            }
        }
        
    };
    this.init = function(){        
        jQuery("#additionalfieldstable").after('<div id="divSNPromotions" style="display:none;"><table id="tblPromotions" cellspacing="0" border="1"><tr><th colspan="3" class="tborder lborder" align="left">You are eligible for the following promotional offers. Discounts like dollars off or percentage off are reflected in the subtotal of your order and can be reviewed and changed before you checkout.</th></tr><tr><td colspan="4" class="empty"></td></tr><tr><th class="lborder">Promotion/Sale Description</th><th>Free Items</th><th>Promotion Items Value</th></tr><tr><td colspan="3" class="empty"></td></tr><tr><th colspan="3" class="lborder" align="left">Multiples of free promotional items associated with your order will be reflected in checkout. All discounts are applied at checkout.</th></tr><tr><td colspan="3" class="empty"></td></tr><tr><td class="lborder promoImage" colspan="3" align="center"><img id="celigoSNAjaxLoader" style="vertical-align:middle;display:none;" src="/site/promotions/ajax-loader.gif" /> <input id="btnApplyPromotions" type="button" value="Return to Checkout" onclick="celigoSNPromotionsWindowMgr.closePromotionsPopup();"/></td></tr></table></div>');
        jQuery("#additionalfieldstable").after('<div id="divSNApplyingPromotions" style="display:none;"><table ><tr><td><img src="/site/promotions/ajax-loader2.gif"/></td></tr><tr><td>Applying Promotions</td></tr></table></div>');
        that.getPromotions();
        jQuery("a#aShowPromotionsWin").click(function(e){
            e.preventDefault();
            celigoSNPromotionsWindowMgr.showPromotionsWin();
        });
    }
});
