var baseAddUrl = "/webapp/wcs/stores/servlet/IrwWSInterestItemAdd?";     // The first part of the WS call to add a product to the shopping list
var baseGetAllListsUrl = "/webapp/wcs/stores/servlet/IrwWSGetAllInterestLists?";    // The WS call to get all saved lists. 
var baseCreateListUrl = "/webapp/wcs/stores/servlet/IrwWSCreateInterestList?";      // The WS call to create a new list. 
var baseDeleteListUrl = "/webapp/wcs/stores/servlet/IrwDeleteShoppingList?";        // The WS call to delete an existing list. 
var baseRenameListUrl = "/webapp/wcs/stores/servlet/IrwWSRenameInterestList?";      // The WS call to rename an existing list. 
var baseDisplayUrl = "/webapp/wcs/stores/servlet/InterestItemDisplay?";             // The default display url for a shopping list
var baseAddToCartUrl = "/webapp/wcs/stores/servlet/IrwWSOrderItemAdd";              // The default display url for a shopping list
var addUrlSuffix = "&quantity=1";                                                   // Product quantity defaults to 1

var addToShopListPopup = IkeaPopup();

/**
 * Entry point method for Shopping list popups.
 * NOTE! some params (starting with js_fn_*) are global js params added to the calling jsp-page and coming from ShoppingListText_xx_XX.properties 
 * 
 * @param action    		A string to determine what is to be done and what layout to create in the popup
 * @param targetElement		A DOM object that fires the popup, e.g. the button clicked. Needed to position the popup.
 * @param storeId   		The store id
 * @param langId    		The language id
 * @return					Nothing
 */
function activateShopListPopup(action,targetElement,storeId,langId) {
    var newLayout = "";
    switch (action)
    {
    case "save":
        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,25,35);
        newLayout = generateLayoutForShopListPopup(js_fn_POPUP_LOGIN_HEADER,null,js_fn_POPUP_LOGIN_TEXT,null,js_fn_POPUP_CANCEL_BTN,"");
        addToShopListPopup.setGenericContent(newLayout);
        break;
    case "create":
        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,20,-120);
        if(isLoggedIn(storeId)){
            var noOfLists = $('shoppingList').select('.leftNavigation .navItem').size();
            if(noOfLists == js_fn_MAX_NO_OF_LISTS){
                newLayout = generateLayoutForShopListPopup(js_fn_POPUP_CREATE_HEADER,null,js_fn_POPUP_ERROR_MAX_NO_OF_LISTS,null,js_fn_POPUP_CANCEL_BTN,"error");
                addToShopListPopup.setGenericContent(newLayout);
            }else{
                newLayout = generateLayoutForShopListPopup(js_fn_POPUP_CREATE_HEADER,null,null,js_fn_POPUP_CREATE_BTN,js_fn_POPUP_CANCEL_BTN,"callCreateShoppingList('"+storeId+"','"+langId+"')");
                addToShopListPopup.setGenericContent(newLayout);
                enableListName();
            }
        }else{
            newLayout = generateLayoutForShopListPopup(js_fn_POPUP_LOGIN_HEADER,null,js_fn_POPUP_LOGIN_TEXT,null,js_fn_POPUP_CANCEL_BTN,"");
            addToShopListPopup.setGenericContent(newLayout);
        }
        break;
    case "rename":
        var curListObj = {name: js_fn_CURRENT_LISTNAME};
        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,-220,30);
        newLayout = generateLayoutForShopListPopup(js_fn_POPUP_RENAME_HEADER,curListObj,js_fn_POPUP_LOGIN_TEXT,js_fn_POPUP_RENAME_BTN,js_fn_POPUP_CANCEL_BTN,"callRenameShoppingList('"+storeId+"','"+langId+"','"+js_fn_CURRENT_LISTID+"')");
        addToShopListPopup.setGenericContent(newLayout);
        enableListName();
        break;
    case "delete":
        var curListObj = {name: js_fn_CURRENT_LISTNAME};
        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,-220,30);
        newLayout = generateLayoutForShopListPopup(js_fn_POPUP_DELETE_HEADER,curListObj,js_fn_POPUP_DELETE_TEXT,js_fn_POPUP_DELETE_BTN,js_fn_POPUP_CANCEL_BTN,"callDeleteShoppingList('"+storeId+"','"+langId+"','"+js_fn_CURRENT_LISTID+"')");
        addToShopListPopup.setGenericContent(newLayout);
        break;
    case "print":
        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,25,35);
        newLayout = generatePrintLayoutForShopListPopup(storeId,langId,js_fn_POPUP_PRINT_HEADER,js_fn_POPUP_PRINT_BTN,js_fn_POPUP_CANCEL_BTN,"irwStatShoppingList('printShoppingList'); getObject('formPrintShoppingList').submit();closePopup()",js_fn_LOCAL_STORES);
        addToShopListPopup.setGenericContent(newLayout);
        preSelectLocalStorePrint(irwstats_locale);  //Get locale from global stats variable
        preSelectPrintSorting($('formPrintShoppingList'));
        toggleSelStore($('formPrintShoppingList'),$('localStoreNumPrint'));
        break;
    case "add":
        try {
            irwStatShoppingList("POPpopupOpened");
        } catch(e) {}
        
        var prodId = targetElement.attributes.id.value;
        prodId = prodId.replace("popupShoppingList","");
        prodId = prodId.replace("slideshowSaveToList","");

        addToShopListPopup.createGenericPopup(260,"","slPopup","slPopup",targetElement,-40,-160);
        if(isLoggedIn(storeId)){
            getSavedLists(storeId,langId,prodId); // Get all lists
        }else{
            var listObj = {name:"", defaultName: js_fn_DEFAULT_LISTNAME};
            newLayout = generateLayoutForShopListPopup(js_fn_POPUP_SELECT_HEADER,listObj,js_fn_POPUP_LOGIN_TEXT,js_fn_POPUP_SAVE_BTN,js_fn_POPUP_CANCEL_BTN,"respondToSaveToShopList('"+storeId+"','"+langId+"','"+prodId+"')");
            addToShopListPopup.setGenericContent(newLayout);
        }
        break;
    case "email":
        addToShopListPopup.createGenericPopup(402,"","slPopup","slPopup",targetElement,25,35);
        newLayout = generateEmailLayoutForShopListPopup("/webapp/wcs/stores/servlet/IrwEmailShoppingList?storeId="+storeId+"&langId="+langId+"&listId="+js_fn_CURRENT_LISTID);
        addToShopListPopup.setGenericContent(newLayout);
        break;
    case "addToCart":   // Add to shopping cart (NOT shopping list)
        var prodId = targetElement.attributes.id.value;
        prodId = prodId.replace("popupAddToCart","");
        prodId = prodId.replace("slideshowAddToCart","");
		// Cookie is missing for certain criteria. Below section will regenerate cookie, if it doesn't exist
        var cookieExist = getCookie('JSESSIONID');
        if(null==cookieExist ){
        isLoggedIn(storeId);
        }
		try {
			// Changed by FW11 - part2 - IrwWSOrderItemAdd has been changed to accept partNumber
			irwStatShoppingList("buyOnline", prodId);
		} catch(e) {}

        addToShopListPopup.createGenericPopup(200,"","slPopup","slPopup",targetElement,0,-100);
        addItemToCart(prodId, name,storeId);
        break;
    default:
        alert('something went wrong...');
    }
}


/**
 * Function generateLayoutForShopListPopup is a general function that generates a string with complete 
 * HTML layout to be inserted into an IkeaPopup.
 * @param header    		The header text
 * @param listObj     		The current list object if present with attributes id and name. Should be set to null if not used.
 * @param body      		The body text
 * @param btn         		The text for the "submit" button of the popup that fires the event
 * @param link      		The text for the cancel link to just close the popup
 * @param action      		The name of the event to add to the "btn" when clicked (Ex: respondToDelete)
 * @return					The HTML string to be inserted in the popup
*/
function generateLayoutForShopListPopup(header,listObj,body,btn,link,action){
    var retString = ""+
    "<div class=\"content\">"+
    createHeaderLayout(header,listObj,action)+
    "<form name=\"formShoppingListPopup\" method=\"\" action=\"\" id=\"formShoppingListPopup\" onsubmit=\""+action+";return false;\">"+
    createBodyLayout(body,listObj,action)+
    createFooterLayout(btn,link,action)+
    "</form>"+
    "</div>";
    
    return retString;
} 

/**
 * Function generatePrintLayoutForShopListPopup is a specific function that generates a string with complete 
 * HTML layout with printout information to be inserted into an IkeaPopup.
 * NOTE! some params (starting with js_fn_*) are global js params added to the calling jsp-page and coming from ShoppingListText_xx_XX.properties 
 * @param storeId    		The current store id
 * @param langId       		The current language id
 * @param header    		The header text
 * @param btn         		The text for the "submit" button of the popup that fires the event
 * @param link      		The text for the cancel link to just close the popup
 * @param action      		The name of the event to add to the "btn" when clicked (Ex: respondToDelete)
 * @param stores      		An object with the local stores. Contains attributes: value, name
 * @return					The HTML string to be inserted in the popup
*/
function generatePrintLayoutForShopListPopup(storeId,langId,header,btn,link,action,stores){
    var storesCount = stores.length;
    var optionString = "";
    for(var i=0;i<storesCount;i++) {
        optionString += "<option id=\"localStore_"+stores[i].value+"\" value=\""+stores[i].value+"\">"+stores[i].name+"</option>";
    }

    var retString = ""+
    "<div class=\"content\">"+
    createHeaderLayout(header)+
    "<form name=\"formPrintShoppingList\" method=\"get\" action=\"/webapp/wcs/stores/servlet/IrwPrintShoppingList\" id=\"formPrintShoppingList\" target=\"_new\">"+
    "<input type=\"hidden\" name=\"slId\" value="+js_fn_CURRENT_LISTID+">"+
    "<input type=\"hidden\" name=\"storeId\" value=\""+storeId+"\"/>"+
    "<input type=\"hidden\" name=\"langId\" value=\""+langId+"\"/>"+
    "<div class=\"headlineSelect text\">"+js_fn_POPUP_SELECT_STORE+"</div>"+
    "<select name=\"localStoreNum\" id=\"localStoreNumPrint\" onchange=\"toggleSelStore($('formPrintShoppingList'),this)\">"+
    "<option value=\"0\">"+js_fn_POPUP_SELECT_NONE+"</option>"+
    optionString+
    "</select>"+
    "<div class=\"headlineSort text\">"+js_fn_POPUP_PRINT_SORT_BY+"</div>"+
    "<div class=\"listRow\"><input type=\"radio\" id=\"time\" name=\"chkSort\" value=\"time\"/><label for=\"time\">"+js_fn_POPUP_PRINT_TIME_ADDED+"</label></div>"+
    "<div class=\"listRow\"><input type=\"radio\" id=\"weight\" name=\"chkSort\" value=\"weight\"/><label for=\"weight\">"+js_fn_POPUP_PRINT_WEIGHT+"</label></div>"+
    "<div class=\"listRow\"><input type=\"radio\" id=\"location\" name=\"chkSort\" value=\"location\"/><label for=\"location\">"+js_fn_POPUP_PRINT_LOCATION+"</label></div>"+
    "<div class=\"chkBoxRow\"><input type=\"checkbox\" id=\"chkPrintOffers\" name=\"chkPrintOffers\"/><label for=\"chkPrintOffers\">"+js_fn_POPUP_PRINT_STORE_OFFERS+"</label></div>"+
    createFooterLayout(btn,link,action)+
    "</form>"+
    "</div>";
    
    return retString;
}


/**
 * generateSavedListsLayoutForShopListPopup generates inner html layout for the user to select which list to save the product in
 * To be inserted into an IkeaPopup.
 */
function generateSavedListsLayoutForShopListPopup(savedLists,active,header,btn,link,action)
{
	var listString = "";
    var style = "";
    var checked = "";
    var listCount = savedLists.length;
    if(listCount>4){style = "scroll";}
    for(var i=0;i<listCount;i++) {
        if(active == null && i==0){checked = ' checked="checked"';} // if no active list returned from ws set first one
        if(savedLists[i].id==active){checked = ' checked="checked"';}
        listString += "<div class=\"listRow\"><input type=\"radio\" id=\"chkList"+i+"\" name=\"chkList\" value=\""+savedLists[i].id+"\" onclick=\"disableListName()\""+checked+"><label for=\"chkList"+i+"\">"+savedLists[i].name+"</label></div>";
        checked = "";
    }
    
    var retString = ""+
    "<div class=\"content\">"+
    createHeaderLayout(header,null,action)+
    "<form name=\"formShoppingListPopup\" method=\"post\" action=\"\" id=\"formShoppingListPopup\" onsubmit=\""+action+";return false;\">"+
    "<div id=\"listContainer\" class=\""+style+"\">"+listString+"</div>"+
    "<div class=\"listRow\"><input type=\"radio\" id=\"chkListName\" name=\"chkList\" value=\"0\" onclick=\"enableListName()\"/>&nbsp;<input type=\"text\" id=\"listName\" name=\"listName\" value=\""+js_fn_DEFAULT_LISTNAME+"\" disabled=\"true\"/></div>"+
    createFooterLayout(btn,link,action)+
    "</form>"+
    "</div>";
    return retString;
}

/**
 * Function populates an IkeaPopup with an iframe and resizes it based on the loaded document.
*/
function generateEmailLayoutForShopListPopup(page)
{
    var loader = addToShopListPopup.generateLoadingLayout();
    var retString = ""+
    "<div id=\"emailIframeLoader\" style=\"display:;\">" + loader + "</div>"+
    "<div id=\"emailIframeContainer\" style=\"visibility:hidden;\">"+
    "<a href=\"#\" onclick=\"closePopup();return false;\" id=\"emailCloseBtn\" rel=\"nofollow\"></a>"+
    "<iframe src=\""+page+"\" id=\"emailIframe\" height=\"0\" width=\"0\" scrolling=\"no\" frameborder=\"0\" onload=\"resizeMe($('emailIframe')); \"></iframe>"+
    "</div>"
    
    return retString;
}


/**
 * Helper functions to generate layout in popup */
function createHeaderLayout(header, listObj, action) {
    var list = "";
    
    if((listObj != null) && (typeof listObj != 'undefined') && (listObj != "")){
        // If prod added from PIP, display no name in header (action set in onAddToShoppingListComplete()) 
        if(action != "addFromPip"){
            list = "&nbsp;" + listObj.name;
        }
    }
    var retString = ""+
    "<div class=\"headline\" id=\"slPopupH1\">"+header+list+"</div>";
    
    return retString;
}

function createBodyLayout(body, listObj, action) {
    var retString = "<p>"+body+"</p>";
    
    if(action.indexOf("callCreate") != -1){
        retString = "<input type=\"text\" id=\"listName\" name=\"listName\" value=\"\"/>";
    }else if(action.indexOf("callRename") != -1){
        retString = "<input type=\"text\" id=\"listName\" name=\"listName\" value=\""+listObj.name+"\"/>";
    }else if(action.indexOf("respondToSaveToShopList") != -1){
        retString = "<div id=\"listContainer\">"+
        "<div class=\"listRow\"><input type=\"radio\" id=\"chkList1\" name=\"chkList\" value=\".\" checked=\"checked\"><label for=\"chkList1\">"+listObj.defaultName+"</label></div>"+
        "</div>"+
        "<p>"+body+"</p>";
    }else if(action.indexOf("error") != -1){
        retString = "<p style=\"color:#FF5050\">"+body+"</p>";
    }
    
    return retString;
}

function createFooterLayout(btn, link, action) {
    var btnLayout = "";
    // If btn added create the button
    if(btn != null){
        btnLayout = createButtonLayout(""+btn+"","jsButton_shopListPopup","button",""+action+"") + "&nbsp;";
    }
    var retString = ""+
    "<div class=\"buttonRow\">"+
    btnLayout+
    "<a onclick=\"closePopup();addProductEvts();return false;\" href=\"#\" class=\"link\" rel=\"nofollow\">"+link+"</a>"+
    "</div>";
    
    return retString;
}
/** Helper functions to generate layout in popup */


/**
 * Function adds an item to the Shopping Cart
 */
function addItemToCart(prodId,name,storeId) {
    loadingPopup();
	// Changed by FW11 - part2 - IrwWSOrderItemAdd has been changed to accept partNumber
    new Ajax.Request(baseAddToCartUrl, {
        method:'post',
        parameters: {partNumber: prodId, quantity: 1, type: 'json'}, 
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON();
            var code = json.code;
            
            if (code == 0) {
				updateNoOfCartItems(storeId);
                var body = js_fn_POPUP_DONE_TEXT + " <a href=\""+js_fn_POPUP_VIEWCART_URL+"\" class=\"link\" rel=\"nofollow\">" + js_fn_SHOPPING_CART + "</a>";
                var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_DONE_HEADER,null,body,null,js_fn_POPUP_CLOSE_BTN,"");
            } else {
                var body = js_fn_ARTICLE + " " + js_fn_COULDNOTBEADDEDTOSC;
                var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_ERROR_HEADER,null,body,null,js_fn_POPUP_CANCEL_BTN,"");
            }
            addToShopListPopup.setGenericContent(newLayout);
			
        }
    }); 
} 


function getSavedLists(storeId,langId,prodId) {
    // Show the user that we are waiting for data
    loadingPopup();
	var completeURL = baseGetAllListsUrl + "storeId=" + storeId + "&langId=" + langId;
	
    // Call the completed IOWS URL
	new Ajax.Request(completeURL, {
		method: 'get',
		contentType: 'application/xml',
		onSuccess: function(response) {
		    onSavedListsRecieved(response.responseXML,storeId,langId,prodId);
		}
	});		
}


function onSavedListsRecieved(doc,storeId,langId,prodId) {
    // Parse the returned data
    try{
        var activeList = doc.getElementsByTagName("activeList")[0].firstChild.nodeValue;
        if(activeList == ""){activeList = null};
    }catch(e){
        var activeList = null;
    }
    var items = doc.getElementsByTagName("shoppingList");
    var noOfLists = items.length;
    var shoppingLists = new Array();
    
    if(noOfLists > 0) {
        for(var i=0;i<noOfLists;i++) {
            var listItem = parseXmlItemToListInfo(items[i]);
            shoppingLists[i] = listItem; 
        }
    }else{
        var defaultList = {id:'.',name:js_fn_DEFAULT_LISTNAME};
        shoppingLists[0] = defaultList; 
        activeList = null;
    }

    var newLayout = generateSavedListsLayoutForShopListPopup(shoppingLists,activeList,js_fn_POPUP_SELECT_HEADER,js_fn_POPUP_SAVE_BTN,js_fn_POPUP_CANCEL_BTN,"respondToSaveToShopList('"+storeId+"','"+langId+"','"+prodId+"')");
    addToShopListPopup.setGenericContent(newLayout);
}


/*
 * respondToSaveToShopList saves the product to the selected list
 */
function respondToSaveToShopList(storeId,langId,prodId)
{
    // Find selected list item
    var chkBtns = $('formShoppingListPopup').getInputs('radio');
    var listId = chkBtns.find(function(radio) { return radio.checked; }).value;
    
    if(listId == 0){    // If item added to a new list
        listName = $F('listName');
        // Add default name if not entered
        if(listName.strip()==""){
            listName = js_fn_DEFAULT_LISTNAME;  // listName should come from commerce and properties key
        }
    }else{  // Get the listname from the label
        var chkActive = chkBtns.find(function(radio) { return radio.checked; }).id;
        listName = $(chkActive).next().innerHTML;
    }

    //Get hidden input field value if product is GPR
    var partNumberInForm = $("thePartnumberInForm");
    if (""+partNumberInForm != "null") {
        prodId = partNumberInForm.value;
    } 
    
    var listObj = {id:listId, name:listName};
    callAddItemToShoppingList(prodId,storeId,langId,listObj);
}


/**
 * Makes an asynchronous call to the webservice for adding a product to the shopping list.
 * The data call is made asynchronously, when the result is returned
 * the method onAddToShoppingListComplete is called. 

 * @param productNumber		The product number that data is required for. (Example "40103685" = Goliat). 
 * @param storeId		    The store id
 * @param langId		    The language id
 * @param listObj			A list object with needed attributes to save. Contains attributes: id, name
 * @return					Always false, in order to stop link execution
 */
function callAddItemToShoppingList(productNumber,storeId,langId,listObj) {
    // Show the user that we are waiting for data
    loadingPopup();
    
    if(listObj.id==0){  //Product added to a new list
        var completeURL = baseCreateListUrl + "partNumber=" + productNumber + "&langId=" + langId + "&storeId=" + storeId + "&slName=" + encodeURI(listObj.name);
    } else {    //Product added to existing list
        var completeURL = baseAddUrl + "partNumber=" + productNumber + "&langId=" + langId + "&storeId=" + storeId + "&listId=" + listObj.id + addUrlSuffix;
    }

	new Ajax.Request(completeURL, {
		method: 'get',
		contentType: 'application/xml',
		onSuccess: function(response) {
            onAddToShoppingListComplete(response.responseXML,langId,storeId,listObj);
		}
	});
    
	return false;
}


/**
 * Handles the data returned from the callAddItemToShoppingList asynchronous call.
 * The data is parsed to an operation code that should normally be 0.
 * Depending on success, the user is either shown a message that things went well, or an error message.
 * @param doc				The returned WS XML data
 * @return					Nothing
 */
function onAddToShoppingListComplete(doc,langId,storeId,listObj) {
	var responseTag = doc.getElementsByTagName("actionResponse")[0];
	var codeTag = responseTag.getElementsByTagName("code")[0];
	var operationCode = parseInt(codeTag.firstChild.nodeValue);
	var operationSuccess = (operationCode == 0);
    
	if(operationSuccess) {
		try	{
			irwStatShoppingList("addFromPIPorSC");
		} catch (e) {
		}
        //Product was added to a new list so get the listObj from returned xml
        if(listObj.id==0){  
            var list = doc.getElementsByTagName("shoppingList")[0];
            listObj = parseXmlItemToListInfo(list);
        }
        var strBody = "<p>" + js_fn_POPUP_DONE_TEXT + " <a href=\""+baseDisplayUrl+"storeId="+storeId+"&langId="+langId+"&listId="+listObj.id+"\" class=\"link\" rel=\"nofollow\">"+listObj.name+"</a></p>";
		if(! isLoggedIn(storeId)){
			strBody += "<p>" + js_fn_POPUP_LOGIN_TEXT + "</p>";
		}
        var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_DONE_HEADER,listObj,strBody,null,js_fn_POPUP_CLOSE_BTN,"addFromPip");
        addToShopListPopup.setGenericContent(newLayout);
	} else {
        if(listObj.id==0 && operationCode == 6){ // If try to add to new list and max no of lists reached
            var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_ERROR_HEADER,null,js_fn_POPUP_ERROR_MAX_NO_OF_LISTS,null,js_fn_POPUP_CLOSE_BTN,"error");
        }else if(operationCode == 9){// Maximum number of shopping list item reached(maximum quantity for a product is 99).
            var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_ERROR_HEADER,null,js_fn_ERROR_SHOPPING_LIST_MAX_ITEM_QUANTITY_LIMIT_EXCEEDED,null,js_fn_POPUP_CLOSE_BTN,"error");
        }else if(operationCode == 10){// Maximum number of products in the list has been exceeded(maximum products in a list is 101).
            var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_ERROR_HEADER,null,js_fn_ERROR_SHOPPING_LIST_MAX_LIMIT_EXCEEDED,null,js_fn_POPUP_CLOSE_BTN,"error");
        }else{
            var newLayout = generateLayoutForShopListPopup(js_fn_POPUP_ERROR_HEADER,null,js_fn_POPUP_ERROR_TEXT,null,js_fn_POPUP_CLOSE_BTN,"");
        }
        addToShopListPopup.setGenericContent(newLayout);
	}
}


function callCreateShoppingList(storeId,langId){
    // Get list name from the form
    var listName = $F('listName');

    if (validateListName(listName)){
        $('errMsg').hide();
    
        // Show the user that we are waiting for data
        loadingPopup();
        var completeURL = baseCreateListUrl + "langId=" + langId + "&storeId=" + storeId + "&slName=" + encodeURI(listName);

        new Ajax.Request(completeURL, {
            method: 'get',
            contentType: 'application/xml',
            onSuccess: function(response) {
                onCreateShoppingListComplete(response.responseXML,storeId,langId);
            }
        });
    }else{
        $('errMsg').show();
        $('errMsg.error').update(js_fn_ERROR_CREATE_LIST);
    };
    
	return false;
}


function onCreateShoppingListComplete(doc,storeId,langId) {
	var codeTag = doc.getElementsByTagName("code")[0];
	var operationCode = parseInt(codeTag.firstChild.nodeValue);
	var operationSuccess = (parseInt(codeTag.firstChild.nodeValue) == 0);
    
	if(operationSuccess) {
		try	{
			irwStatShoppingList("createNewList");
		} catch (e) {
		}
        // Redirect to display page with current list...
		location.href = baseDisplayUrl+ "langId=" + langId + "&storeId=" + storeId;
	} else {
        closePopup();
        $('errMsg').show();
        $('errMsg.error').update('Error: ' + operationCode);
	}
}

function callDeleteShoppingList(storeId,langId,listId){
    loadingPopup();
    location.href = baseDeleteListUrl + "langId=" + langId + "&storeId=" + storeId + "&slId=" + listId;
}

function onDeleteShoppingListComplete(doc,storeId,langId) {
	var codeTag = doc.getElementsByTagName("code")[0];
	var operationCode = parseInt(codeTag.firstChild.nodeValue);
	var operationSuccess = (parseInt(codeTag.firstChild.nodeValue) == 0);
    
	if(operationSuccess) {
        // Redirect to display page with current list...
		location.href = baseDisplayUrl+ "langId=" + langId + "&storeId=" + storeId;
	} else {
        closePopup();
        $('errMsg').show();
        $('errMsg.error').update('Error: ' + operationCode);
	}
}

function callRenameShoppingList(storeId,langId,listId){
    // Get list name from the form
    var listName = $F('listName');

    if (validateListName(listName)){
        $('errMsg').hide();
    
        // Show the user that we are waiting for data
        loadingPopup();
        var completeURL = baseRenameListUrl + "langId=" + langId + "&storeId=" + storeId + "&slId=" + listId + "&slName=" + encodeURI(listName);

        new Ajax.Request(completeURL, {
            method: 'get',
            contentType: 'application/xml',
            onSuccess: function(response) {
                onRenameShoppingListComplete(response.responseXML,listId,listName);
            }
        });
    }else{
        $('errMsg').show();
        $('errMsg.error').update(js_fn_ERROR_RENAME_LIST);
    };
    
	return false;
}

function onRenameShoppingListComplete(doc,listId,listName) {
	var codeTag = doc.getElementsByTagName("code")[0];
	var operationCode = parseInt(codeTag.firstChild.nodeValue);
	var operationSuccess = (parseInt(codeTag.firstChild.nodeValue) == 0);
    
	if(operationSuccess) {
        closePopup();
        // Update menu item in left nav
        var menuItem = "listId" + listId;
        $(menuItem).update(listName);
        $('errMsg').show();
        $('errMsg.error').update();
        $('errMsg.confirm').update(js_fn_LIST_RENAMED);
		js_fn_CURRENT_LISTNAME = listName; //Added for PR # IKEA00674147

	} else {
        closePopup();
        $('errMsg').show();
        $('errMsg.error').update('Error: ' + operationCode);
	}
}


function isLoggedIn(storeId){
    var status;
    var completeURL = "/webapp/wcs/stores/servlet/GetUserInfo?storeId=" + storeId;

	new Ajax.Request(completeURL, {
		method: 'post',
		contentType: 'application/xml',
        asynchronous: false,    // Needed to return status when response done!
		onSuccess: function(response) {
            var responseXML = response.responseXML;
            var loggedIn = responseXML.getElementsByTagName('loggedIn')[0].firstChild.data;
            if (loggedIn == 'Y' || loggedIn == 'P') {
                status = true;
            }else{
                status = false;
            }
		}
	});
    return status;
}


function parseXmlItemToListInfo(item) {
    var listId = item.getAttribute("id");
    var listName = item.getAttribute("name");
    var returnObject = {id:listId, name:listName};
    return returnObject;
}

/**
 * Closes the popup
 * @return					false to stop link exection
 */
function closePopup() {
    addToShopListPopup.hide();
    return false;
}


/**
 * Makes the popup show the layout that informs the user that a remote call is loading.
 * Requires that a method called generateLoadingLayout that returns valid HTML layout is defined.
 * @return					false to stop link exection
 */
function loadingPopup() {
	addToShopListPopup.loadingPopup();
	return false;
}


/**
 * Functions for enable/disable the input "listName" where the user enters a name for a new list to create.
 * The input should only be enabled when the selectbox in front is selected. And when enabled the text in it should be selected.
 */
function enableListName() {
    $('listName').disabled = false;
    $('listName').select();
}

function disableListName() {
    $('listName').disabled = true;
}

/**
 * Function for enable/disable the "Sort by" radiobuttons and "Include local store offes" checkbox in the print popup.
 * Triggered onchange of select option and also on popup load.
 */
function toggleSelStore(formObj,selObj){
    var selVal = $F(selObj);
    var chkBtns = formObj.getInputs('radio');
    var chkBox = formObj.getInputs('checkbox');
    if(selVal=="0"){
        chkBtns.each(function(obj){
            obj.disabled = true;
        })
        chkBox.each(function(obj){
            obj.disabled = true;
        })
    }else{
        chkBtns.each(function(obj){
            obj.disabled = false;
        })
        chkBox.each(function(obj){
            obj.disabled = false;
        })
    }
}

/**
 * Helper function for generateEmailLayoutForShopListPopup() to resize the iframe after load since it does not support dynamic height
*/
function resizeMe(obj){
    var h = 0;
    
    var h = Try.these(             
        function() {return obj.contentDocument.body.getHeight();},       //FF & Safari
        function() {return obj.contentWindow.document.body.getHeight();},   //IE
        function() {return 710;}
    );
    
    obj.height = h;
    $('emailIframeLoader').hide(); 
    $('emailIframeContainer').style.visibility = 'visible';
}

/**
 * Input validation on shopping list name
*/
function validateListName(name) {
    // Add default name if not entered
    if(name.strip()==""){
        name = js_fn_DEFAULT_LISTNAME;  // Get name from global js variable
    }
    if (name == null || name.length <= 0 || name.length > 254) {
        return false;
    }    
    var vBlackList = ["/",";","<","=",">","?","[","]","{","}","%"]; 
    for (var i = 0; i < vBlackList.length; i++) {
        if (name.indexOf(vBlackList[i]) > -1) {
            return false;
        }
    };
    return true;
}
