/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    le.inlineShoppingBag.js - inline shopping bag functionality
    This is a singleton object and is instantiated on page load
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
function inlineShoppingBag() {
    var isbWindow                   = document.getElementById("inlineShoppingBag");
    var isbLayout                   = isbWindow.getElementsByTagName("div");
    var isbLineItems                = [];
    var keepShoppingDiv             = document.getElementById("keepShoppingButton");
    var keepShoppingLink            = document.getElementById("keepShoppingButtonLink");
    var checkoutDiv                 = document.getElementById("checkoutButton");
    var isbAccountLoginLink         = document.getElementById("isbAccountLoginLink");
    var isbAccountLogin             = document.getElementById("isbAccountLogin");
    var viewBagDiv             		= document.getElementById("viewBagButton");
    var isbShoppingBagSubTotalText  = document.getElementById("isbShoppingBagSubTotalText");
    var isbItems                    = document.getElementById("isbItems");
    var errorContainer              = document.getElementById("isbError");
    var thisIsb                     = this;
    var cartTotal                   = 0;
    var numItems                    = 0;
    var isLoggedIn                  = 0;
    var isUpdateItem                = false;
    var isNewAddress				= false;
    var inventoryStatus             = "";
    var theBuyGrid;
    var singleSelObj;
    var singleSelNum				= 0; //initialize this for collection pages
    var selObjs;
    var shoppingBagLink;       
    var refer = getReferForLink();

    this.displayBag = function() {
    	isbItems.innerHTML = "";
        isbShoppingBagSubTotalText.innerHTML = toCurrency(cartTotal/100) + "&nbsp;";
        window.cartValue = toCurrency(cartTotal/100);
        var i; 
        if (isLoggedIn == 1) {
            hide(isbAccountLogin);
	    } else {
 	    	isbAccountLoginLink.href = securedNetComEnvURL + "/cgi-bin/ncommerce3/ExecMacro/" +netComMacroPath+ "regentry.d2w/report";
            show(isbAccountLogin);
	   	}
		doDebug("[displayBag] selObjs = " + selObjs);
        if (selObjs != null && selObjs != undefined ) {
        	var total = 0;
        	for (i = 0; i < selObjs.length; i++) {
				if (selObjs[i] != null) {
        			thisIsb.addLineItemToDisplay(selObjs[i], total);
        			total++;
        		}
        	}
        } else if (numItems > 0){
        	doDebug("[displayBag] numItems = " + numItems);
            thisIsb.addLineItemToDisplay(singleSelObj, singleSelNum);
		}
		// we must be in error message mode.
		if (numItems < 1) {
			hide(isbItems)
		}
        isbWindow.style.visibility = "visible";
        // resize the ISB to 300 px if it gets too long
        if(isbWindow.offsetHeight >= 300){
            isbItems.style.height = "300px";
            isbItems.style.overflow = "auto";
        }
       	show(isbWindow);
        movePopupLayer(isbWindow);
        keepShoppingLink.focus();
        doDebug("[displayBag] - complete"); 
	};

	this.parseResponse = function(request) {
        var xmldoc = request.responseXML;
        var inventoryErrors = "";
        var errorNum = xmldoc.getElementsByTagName('ErrorNum')[0].childNodes[0].nodeValue;
        if (errorNum != 0) {
        	errorContainer.innerHTML = "An error occurred.<br> ErrorNum: "+errorNum;
        	/*if (xmldoc.getElementsByTagName('ErrorText')) {
        		errorContainer.innerHTML +="<br>"+xmldoc.getElementsByTagName('ErrorText')[0].childNodes[0].nodeValue;
        	}*/
        	errorContainer.innerHTML = messages.error[33].getMessageText(true);
        	show(errorContainer);
        	thisIsb.displayBag();
        	return;
        }
        doDebug("[parseResponse] responseXML: " + request.responseText);
        theSid = xmldoc.getElementsByTagName('sid')[0].childNodes[0].nodeValue;
        doDebug("[parseResponse]theSid: " + theSid);
        cartTotal = xmldoc.getElementsByTagName('ItemSubTotal')[0].childNodes[0].nodeValue;
        doDebug("[parseResponse] cartTotal: " + cartTotal);
        numItems = xmldoc.getElementsByTagName('ItemCount')[0].childNodes[0].nodeValue;
        doDebug("[parseResponse] numItems: " + numItems);
        isLoggedIn = xmldoc.getElementsByTagName('IsLoggedIn')[0].childNodes[0].nodeValue;
        doDebug("[parseResponse] isLoggedIn: " + isLoggedIn);
        shoppingBagLink = hostname + "/cgi-bin/ShoppingBag.cgi?refer=" + encodeURIComponent(refer);
        // update single item selection
        if (selObjs == null || selObjs == 'undefined') {
        	var shoppingBagPrice;
        	shoppingBagPrice = xmldoc.getElementsByTagName('UnitPrice')[0].childNodes[0].nodeValue;
        	doDebug("[parseResponse] shoppingBagPrice: " + shoppingBagPrice);
        	singleSelObj.shoppingBagPrice = shoppingBagPrice / 100;
        } else {
        	var shoppingBagPrice, i;
        	var total = 0;
        	shoppingBagPrice = xmldoc.getElementsByTagName('UnitPrice')[0].childNodes[0].nodeValue;
        	for (i = 0; i < selObjs.length; i++) {
				if (selObjs[i] != null) {
					singleSelObj = selObjs[i];
        			shoppingBagPrice = xmldoc.getElementsByTagName('UnitPrice')[total].childNodes[0].nodeValue;
        			doDebug("[parseResponse] shoppingBagPrice_" + total + ": " + shoppingBagPrice);
        			selObjs[i].shoppingBagPrice = shoppingBagPrice / 100;
        			total++;
        		}
        	} 	
        }
		// if single item 
		if (selObjs == null || selObjs == 'undefined'){
			inventoryStatus = xmldoc.getElementsByTagName("InventoryCode")[0].childNodes[0].nodeValue;
			doDebug("[parseResponse] inventoryStatus: " + inventoryStatus);
			if (inventoryStatus == "N" || inventoryStatus == "U") {
				inventoryErrors = inventoryErrors + messages.info.productNoInventory(document.getElementById('productName_prd_' + singleSelObj.buyGridNumber).innerHTML, colorAssoc[singleSelObj.colorCode], sizeAssoc[singleSelObj.sizeCode]) + "<br /> <br />";
			}
		}
		// if collections or multi-item
		else{
			var currentSelectionIndex;
			for(currentSelectionIndex = 0;currentSelectionIndex < selObjs.length;currentSelectionIndex++){ 
				inventoryStatus = xmldoc.getElementsByTagName("InventoryCode")[currentSelectionIndex].childNodes[0].nodeValue;
				doDebug("[parseResponse] inventoryStatus: " + inventoryStatus);
				if (inventoryStatus == "N" || inventoryStatus == "U") {
					inventoryErrors = inventoryErrors + messages.info.productNoInventory(document.getElementById('productName_prd_' + selObjs[currentSelectionIndex].buyGridNumber).innerHTML, colorAssoc[selObjs[currentSelectionIndex].colorCode], sizeAssoc[selObjs[currentSelectionIndex].sizeCode]) + "<br /> <br />";
				}
			}
		}
        if (inventoryErrors != null && inventoryErrors.length > 0) {
        	errorContainer.innerHTML = inventoryErrors
        	show(errorContainer);
        }
		if (isUpdateItem == false) {
		    thisIsb.displayBag();
		} else if (isUpdateItem == true && (inventoryStatus != "N" || inventoryStatus != "U")) {
			window.location = shoppingBagLink;
		}
        if (isNewAddress == true) {
			doDebug("[parseResponse] found new address");
			loadBasicCustomerData();
			var buyGridI; 
			// if new address added, then update all the buy grids with the new list
    		for(buyGridI in sA){
				buyGrids[buyGridI].buildShipToList();
			}
		}
		if(theBuyGrid != null){
			theBuyGrid.enableAddToBagButton();
		}
		doDebug("[parseResponse]- complete");
    };
    this.buildAddToBagRequest = function(selectionNum) {
		var url="";
     	var selection = singleSelObj;
     	if (selection.shipTo == "-1") {
     		url += "nickName=" + escape(selection.shipToNickname) + "&";
     	}
  		// Someone Else == "-2"
     	else if (selection.shipTo == "-2") {
     		isNewAddress = true;
     		url += "nickName=" + escape(selection.shipToNickname) + "&";
     	} else if (parseInt(selection.shipTo) > 0) {
     		isNewAddress = false;
     		url += "addr_rn=" + selection.shipTo + "&";
     	}
     	url += this.buildSelectionAddToBagString(selection);
     	url += "&prmenbr="+countryCode;
        doDebug("request=" + url);
		return url;
    };
    this.buildSelectionAddToBagString = function(selection) {
	   	var str ="prnbr=" + lpad(selection.style, 6) + "&size=" + selection.sizeCode + "&colorCode=" + selection.colorCode + "&q=" + selection.quantity;
	   	str +="&mc="+ mediaCodeYear + selection.sku.mediaCode;
	   	
    	if (selection.monogrammed) {
    		str += "&monogram=Y&MGMAREA=" + selection.monogram.location;
    		str +="&monoTypeCode=" + selection.monogram.style;
    		var monoValue;
	        switch (selection.monogram.type) {
	            case "Single Initial":
	            	str += "&MGMIND=1";
	                monoValue = selection.monogram.siText;
	                break;
	            case "Initials":
		            str = str + "&MGMIND=1";
	                monoValue = selection.monogram.multiInitialArr.join("");
	                break; 
	        /*  need to filter out more than one line sql options in sql.  
	        	case "Multi-Line":
	            	str = str + "&MGMIND=2";
	                monoValue = selection.monogram.multiLineArr.join("|");
	                break;
	         */
	            default:
	            	str = str + "&MGMIND=2";
	                monoValue = selection.monogram.wordText;
	                break;
	        }
	        str += "&MGMTXT=" + escape(monoValue);
    	}
    	if (selection.hemmed == true) {
 		   	if(selection.hemming.finished == false) {
    			str += "&hemable=N";
    		} else if(selection.hemming.length != null && selection.hemming.length != "") {
    		    str += "&hemable=Y";
    			str += "&HEMINSEAM=" + selection.hemming.length;
	    		if (selection.hemming.cuffed) {
	    			str += "&HEM_RN="+netCommerceHemmingCuffedId;
	    		} else {
	    			str += "&HEM_RN="+netCommerceHemmingStraightId;
	    		}
    		}
    	} else {
    		str += "&hemable=N";
    	}
    	//str += "&cm_merch=" + getCategoryID();
    	doDebug("selection addtobag string=" + str);
        return str;
    };
    this.addToBag = function(selectionNum,theBuyGridPar) {
        var requestURL = addToBagServerURL + "/cgi-bin/ncommerce3/ProdPageAddToBag?";	
        var requestParams = this.buildAddToBagRequest(selectionNum);
		try {
        	theBuyGridPar.disableAddToBagButton();
            var loader = new contentLoader(requestURL, thisIsb.parseResponse, thisIsb.handleError, "POST", requestParams);
        } catch (err) {
            errorContainer.innerHTML = messages.error[33].getMessageText(true);
            show(errorContainer);
            theBuyGridPar.enableAddToBagButton();
            window.onerror()
        }
    };
    this.addSelectionToBag = function(selectionNum,selectionObj,theBuyGridPar) {
        singleSelObj = selectionObj;
        singleSelNum = selectionNum;
        theBuyGrid = theBuyGridPar;
        doDebug("[addSelectionToBag] singleSelObj: " + singleSelObj);
        doDebug("[addSelectionToBag] sku.mediaCode = " + singleSelObj.sku.mediaCode);
        doDebug("[addSelectionToBag] sku.checkDigit = " + singleSelObj.sku.checkDigit);
        this.sendAddToBagMetric();
        this.addToBag(selectionNum,theBuyGridPar);
    };
     this.sendAddToBagMetric = function(){
		s = s_gi(s_account);
        s.linkTrackVars='products,events';
        s.linkTrackEvents='scAdd,event12';
        s.events='scAdd,event12';
        s.products=';' + singleSelObj.style + ';;;event12=' + singleSelObj.quantity;
        s.tl(true,'o','Add To Bag');
    }
    this.handleError = function(request) {
        errorContainer.innerHTML = messages.error[33].getMessageText(true);
        show(errorContainer);
        thisIsb.displayBag();
       // buyGrids[singleSelNum].enableAddToBagButton();
        doDebug("[addToBag handleError] There was an AJAX error...");
    };
    this.addLineItemToDisplay = function(lineItem, lineItemNum) {
        var isbItemClass = "isbItem_last";
        var prodImage = lineItem.productImageURL;
        doDebug("[addLineItemToDisplay] prodImage: " + prodImage);
        var el = document.createElement("div");  
        isbItems.appendChild(el); 
        var innerHTML = "<div id=\"isbItem_" + lineItemNum + "\" class=\""+ isbItemClass + "\">" +
                	   "<div id=\"isbImage_" + lineItemNum + "\" class=\"isbImage\">" +
                       "<img src=\"" + prodImage + "\" width=\"100\" alt=\"\" />" + "</div>" +
                       "<div id=\"isbInfo_" + lineItemNum + "\" class=\"isbInfo\">" +
                       "<div id=\"isbName_" + lineItemNum + "\" class=\"isbName\">" + lineItem.styleText + "</div>";
        if (lineItem.colorCode != null && lineItem.colorCode != "") {
           innerHTML = innerHTML + "<div id=\"isbColor_" + lineItemNum + "\" class=\"isbColor\">" +
                       "<span class=\"featureText\">" + isbColor + " </span><span class=\"attributeText\">" + colorAssoc[lineItem.colorCode] + "</span>" +
                       "</div>";
        }
        if (lineItem.sizeCode != null && lineItem.sizeCode != "" && lineItem.hemmed == false) {
 		    innerHTML = innerHTML + "<div id=\"isbSize_" + lineItemNum + "\" class=\"isbSize\">" +
        	    "<span class=\"featureText\">" + isbSize + " </span><span class=\"attributeText\">" + sizeAssoc[lineItem.sizeCode] + "</span>" +
                "</div>";
        } else if (lineItem.sizeCode != null && lineItem.sizeCode != "" && lineItem.hemmed == true) {
 			var displaySizeCode = sizeAssoc[lineItem.sizeCode];
        	if (lineItem.hemming.finished == false) {
       			displaySizeCode = displaySizeCode + " x " + unfinished;
       		} else {
       			displaySizeCode = displaySizeCode + " x " + lineItem.hemming.length;
       		}
        	if (lineItem.hemming.cuffed == true) {
        		displaySizeCode = displaySizeCode + " (" + cuffed + ")" 
        	}  
            innerHTML = innerHTML + "<div id=\"isbInseam_" + lineItemNum + "\" class=\"isbSize\">" +
                "<span class=\"featureText\">" + isbSize + "</span><span class=\"attributeText\">" + displaySizeCode + "</span>" +
                "</div>";
        }
        innerHTML = innerHTML + "<div id=\"isbQuantity_" + lineItemNum + "\" class=\"isbQuantity\">" +
                       "<span class=\"featureText\">" +isbQuantity + "</span><span class=\"attributeText\">" + lineItem.quantity + "</span>" +
                       "</div>" +
                       "<div id=\"isbPrice_2\" class=\"isbPrice\">" +
                       "<span class=\"featureText\">"+ isbPrice + "</span><span class=\"attributeText\">" + toCurrency(lineItem.shoppingBagPrice) + "</span>" +
                       "</div>";
        // handle the summary of VAS options           
        if (lineItem.monogrammed == true || 
                lineItem.giftBox == true ) 
            {
            var monoHolder = "";
            var gbHolder = "";
            var suHolder = "";
            if (lineItem.monogrammed == true) {
                monoHolder = isbMonogramming;
            }
            if (lineItem.giftBox == true) {
                gbHolder = isbGiftbox;
            }
            innerHTML = innerHTML + "<div id=\"isbVas_" + lineItemNum + "\" class=\"isbVAS\">" +
                        "<span class=\"attributeText\">" + monoHolder + suHolder + gbHolder + "</span>" +
                        "</div>";
        }
        // the closing div
        innerHTML += "</div>";
		el.innerHTML = innerHTML;
        doDebug("[addLineItemToDisplay] line item html: " + el.innerHTML);
	};
    // close add to bag confirmation
    keepShoppingDiv.onclick = function() {
        hide(isbWindow);
        wipeProductPage();
        return false;
    };
    // go to checkout
    checkoutDiv.onclick = function() {
      //  window.location = hostname + "/cgi-bin/ShoppingBag.cgi?Checkout.x=1&Checkout.y=1&refer=" + encodeURIComponent(refer);
    }; 
    // view bag
    viewBagDiv.onclick = function() {
        window.location = securedNetComEnvURL + "/cgi-bin/ncommerce3/ExecMacro/"+netComMacroPath+"ShoppingBag.d2w/report";
        return false;
    }; 
}
/*===========================================================
    Clear all selections and buy grids on the product page by
    reloading it fresh from the history.
===========================================================*/
function wipeProductPage() {
	// if single item, no fit change, and the sid is the same 
	if(! multiItem && currentBuyGridUrl == null){
		history.go(0);
		return;
	}
	var newURL;
	// if multi-item page construct new url
	if(multiItem){
		newURL = hostname + '/pp/MultiItem.html' + multiItem.reloadPage();
	}
	// if single item product page and there was a fit change
	if(! multiItem && currentBuyGridUrl != null){
		var edit = new RegExp('\\/(\\w*)\\-');
		var productName = window.location.href.match(edit)[1];
		var styleNum = (sA[currentBuyGridUrl].buyGridNum).substr(1);
		if(productName == 'StylePage'){
		newURL = "/pp/StylePage-" + styleNum + "_" + sA[currentBuyGridUrl].styleList["SN-" + styleNum].mediaCode + ".html";  
		} else{
		newURL = currentBuyGridUrl.replace(/ProdPageBG/,productName);
		}
		newURL = hostname + newURL + window.location.search;
	}
	// if single item product page and there was not a fit change
	else if(!multiItem){
		newURL = window.location.href;
	}
	var finalURL = newURL.replace(/#+.*$/, "");
	doDebug("[] finalURL='"+finalURL+"'");
   	window.location.href = finalURL;
}
