// Copyright 2004 CrossMedia Services, Inc. All rights reserved. Unauthorized use prohibited.
var slg_itemPhrase = "";
var slg_itemPhrasePlural = "";
var slg_itemcaption = "";
var slg_vdr = "937491807893143244757892937594981432447682917694829376829398143244818886787778898893143244818886787778898893809482777892143244818886787778898893767493748588801432448376897887877898143244848674919314324485889678921432448879798276788674971432449278749192143244769592143244967485809178788792143244887979827678777889889314324492937489857892143244828478741432447688868994927414324484888185921432447674877477827487938291781432447674877477827487938291787279911432449388989291949214324486827681747885921432449576791432448674769892143244749279949187829394917814324488928114324492818889848814324489789376881432448678828378911432448885778774959814324475917487779286749193949274143244807487777891868894879374828714324489788975889892143244";

// adds a trim() method to strings
String.prototype.trim = function() {
 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}





//Akamai Return Url from Listing
var dontSetSLHRedirect = false;
try{dontSetSLHRedirect = doNotSetSLHRedirect;}
catch(e){}

//back button and history functionality
try{
    ak_action = cms_getQueryString("action"," ");
    ak_actionFilter = "|browseavailableonline|browsebrand|browsecategoryall|browsecategoryl1|browsecategoryl2|browsepagelarge|browsepagesingle|browsepagespread|browseshoppinglist|browsepageflash|search|entry|";
    if(ak_actionFilter.indexOf(ak_action.toLowerCase())>-1 && dontSetSLHRedirect == false)    
        setSubCookie("Prefs","SLHListingRedirect", escape(document.location.href), null); 
    
    var ak_history = cms_getCookie("Prefs", "History", "");
    var ak_historyArr = ak_history.trim().split("|");
       
    if(ak_historyArr.length==1 && ak_historyArr[0] == "")
        ak_history = ak_action;
    else if(ak_historyArr.length==1)
        ak_history = ak_history + "|" + ak_action;
    else if(ak_historyArr.length==2){
        ak_history = ak_historyArr[1] + "|" + ak_action;
    }

    setSubCookie("Prefs","History", ak_history, null);            

}catch(e){}


	//add to favorites bookmark
	function bookmark(){
		var pgUrl = window.location.href;
		var pgTitle = document.title;

		if (window.sidebar) {

			window.sidebar.addPanel(pgTitle, pgUrl,"");

		} else if( document.all ) {

			window.external.AddFavorite( pgUrl, pgTitle);

		} else if( window.opera && window.print ) {

			var elem = document.createElement('a');

			elem.setAttribute('href',pgUrl);

			elem.setAttribute('title',pgTitle);

			elem.setAttribute('rel','sidebar');

			elem.click();

		}

	}
	
/* cms_submitDropdown
 * 
 * auto-submits a SELECT's form. Use as the SELECT's onchange event handler and pass a 
 * reference to the SELECT object, e.g.
 * <select name="promotioncode" onChange="javascript:cms_submitDropdown(this)">
 */
function cms_submitDropdown(o){
    var cookieViewMode = cms_getCookie ("DisplayMode", "preferred", null);  
    var pageName;

    if (cookieViewMode == "html")
        pageName = "browsepagespread";
    else
        pageName = "browsepageflash";

    o.form.elements["action"].value = pageName;
    
    if (o.options[o.selectedIndex].value!=''){
        o.form.submit();            
    }
}   

/* cms_getQueryString
 * 
 * defaultvalue is optional. If passed, then 
 * if "key" doesn't exist or is "", defaultvalue
 * is returned. Otherwise null is returned on a mismatch.
 *
 */
function cms_getQueryString(key, defaultvalue) 
{   
        if(key != null)
            key = key.toLowerCase();
    
        var retval;
        var defval = null;
        if (defaultvalue) defval = defaultvalue;
        
        var qs = document.location.search;
        if(qs != null)
            qs = qs.toLowerCase();
        
        var index = qs.indexOf(key + "=");
        
        if (index == -1) return defval;
        
        index = qs.indexOf("=", index) + 1;
        
        var endstr = qs.indexOf("&", index);
        
        if (endstr == -1) endstr = qs.length;
        
        retval = _trim(unescape(qs.substring(index, endstr)).replace(/\+/ig,' '));
        
        if (retval=='') return defval;  // empty string, return default
        
        return retval;
}   

function cms_getQueryString2(url, key, defaultvalue) {
    var retval;
    var defval = null;
    if (defaultvalue) defval = defaultvalue;
    
    var qs = url;
    var index = qs.toLowerCase().indexOf(key.toLowerCase() + "=");
    if (index == -1) return defval;
    index = qs.indexOf("=", index) + 1;
    var endstr = qs.indexOf("&", index);
    if (endstr == -1) endstr = qs.length;
    retval = unescape(qs.substring(index, endstr)).replace(/\+/ig,' ').trim();
    if (retval=='') return defval;  // empty string, return default
    
    return retval;
}

function cms_getQueryString3(key, defaultvalue) 
{   
        if(key != null)
            key = key.toLowerCase();
    
        var retval;
        var defval = null;
        if (defaultvalue) defval = defaultvalue;
        
        var qs = document.location.search;
        if(qs != null)
            qs = qs.toLowerCase();
        
        var index = qs.indexOf(key + "=");
                
        if(index > 0){
        	index = qs.indexOf("&" + key + "=");
        	if (index == -1){
        		index = qs.indexOf("?" + key + "=");
        	}
        }
        
        if (index == -1) return defval;
        
        index = qs.indexOf("=", index) + 1;
        
        var endstr = qs.indexOf("&", index);
        
        if (endstr == -1) endstr = qs.length;
        
        retval = _trim(unescape(qs.substring(index, endstr)).replace(/\+/ig,' '));
        
        if (retval=='') return defval;  // empty string, return default
        
        return retval;
} 

function ReplaceQS(url, name, value){
    var token = "?";
    var index1;
    var index2;         
    var fragment;
    
    index1 = url.indexOf("&" + name + "=");
    if(index1 == -1)
        index1 = url.indexOf("?" + name + "=");
    else
        token = "&";
                
    if(index1 == -1){
        //param not found
        token = (url.indexOf("?") == -1) ? "?" : "&";
        url = url + token + name + "=" + value;             
    }
    else{
        //param found                               
        index2 = url.indexOf(token, index1+1);      
        if(index2 > -1)
            fragment = url.substr(index2);
        else
            fragment = "";      
        url = url.substring(0, index1) + token + name + "=" + value + fragment;
    }           
    return url
}

// cms_getCookie
// defaultvalue is optional. If passed, then 
// if "key" doesn't exist or is "", defaultvalue
// is returned. Otherwise null is returned on a mismatch.
function cms_getCookie(key, subkey, defaultvalue, nounescape) {
    var retval;
    var defval = null;
    if (defaultvalue != null && defaultvalue != undefined) defval = defaultvalue;
    var strKey = key;
    var strSubKey = '';
    if(subkey) strSubKey = subkey;

    var cookiestr = " " + document.cookie + ';';
    var rx = new RegExp('[^&]' + strKey + '=([^;]+)', 'i');
    if(rx.test(cookiestr)) {
        rx.exec(cookiestr);
        if(strSubKey == '') {
            // no subkey, return the match
            retval = (nounescape) ? RegExp.$1 : unescape(RegExp.$1);
            retval = retval.replace(/\+/ig,' ').trim();
            if (retval == '')
                return defval;  // empty string, return default
            else
                return retval;
        }
        else {
            // get the subkey
            var val = (nounescape) ? RegExp.$1 + '&' : unescape(RegExp.$1 + '&');
            rx = new RegExp(strSubKey + '=([^&]+)', 'i');
            if(rx.test(val)) {
                // it's in there
                rx.exec(val);
                retval = (nounescape) ? RegExp.$1 : unescape(RegExp.$1);
                retval = retval.replace(/\+/ig,' ').trim();
                if (retval == '')
                    return defval;  // empty string, return default
                else
                    return retval;
            }
            else {
                // not in there
                return defval;
            }
        }
    }
    else {
        // no match on the key
        return defval;
    }    
}

// cms_setCookie
// sets a cookie value. daysexpire is optional. if missing, then
// the cookie expires with the browser session.
function cms_setCookie(key,value,daysexpire,noescape) {
    var value = (noescape) ? value : escape(value);
    if(daysexpire) {
        var today = new Date();
        var expires = new Date();
        expires.setTime(today.getTime() + 3600000*24*daysexpire);
        document.cookie = escape(key)+"="+value+";expires="+expires.toGMTString()+";path=/";
    }
    else {
        document.cookie = escape(key)+"="+value+";path=/";
    }
}

function openWindow(strPage, strName, strFeatures) {
    var x = window.open(strPage, strName, strFeatures);
}
function dopopup(strPage, lngWidth, lngHeight) {
    var x, y;
    var agt=navigator.userAgent.toLowerCase(); 
    var is_aol = (agt.indexOf("aol") != -1)
  
  // initially assume 640x480
    var screenWidth = 640;
    var screenHeight = 480;

  
  if (window.screen.availHeight) {
    screenWidth = window.screen.availWidth; 
    screenHeight = window.screen.availHeight;
  }
  else if (window.screen.height) {
    screenWidth = window.screen.width; 
    screenHeight = window.screen.height - 50;
  }
  else if (document.all) {
    screenWidth = document.body.offsetWidth + window.screenLeft - 15;
    screenHeight = document.body.offsetHeight + window.screenTop - 15;
  } 
  else if (document.layers) {
    screenWidth = window.outerWidth - 20;
    screenHeight = window.outerHeight - 50;
  }
  if(is_aol) {
    if(lngWidth > (screenWidth - 40)) lngWidth = screenWidth - 40;
    if(lngHeight > (screenHeight - 120)) lngHeight = screenHeight - 120;
    x = 0; 
    y = 0;
  }
  else {
    if(lngWidth > screenWidth) lngWidth = screenWidth;
    if(lngHeight > screenHeight) lngHeight = screenHeight;
    x = (screenWidth - lngWidth)/2;
    y = (screenHeight - lngHeight)/2;
    if(x<0) x=0;
    if(y<0) y=0;
  }
  window.open(strPage, 'x', 'height='+lngHeight+',width='+lngWidth+',left='+x+',top='+y+',status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');

}
  
function printFrame(strPage, skipPrint){

    //create Iframe and within page
	var el = document.createElement("iframe");
	
	//set atttibutes of the Iframes
	el.setAttribute('id', '_print');
	el.setAttribute('name', '_print');
	
	//append iframe to page
	document.body.appendChild(el);
	
	//set width and height to 0
	el.style.width = 0 + "px";
	el.style.height = 0 + "px";
	
	//set src of the iframe
	el.setAttribute('src', strPage);
	

	// sc 4.x sites skip this part because the print page executes the print directly via execCommand()
	if(skipPrint==null || skipPrint==undefined){
		el.onload = delayPrint();
	}
 }

function delayPrint(){
	setTimeout(printframe, 1000);
}

function printframe(){	
	window.focus();
	window.print();
}

    var da = (document.all) ? 1 : 0;
    var pr = (window.print) ? 1 : 0;
    var mac = (navigator.userAgent.indexOf("Mac") != -1); 
    var noprint = false;

    if (!pr && (!da || mac)) noprint = true;

function printPage() {
    if (pr) // NS4, IE5
        window.print()
    else if (da && !mac) // IE4 (Windows)
        vbPrintPage()
    return false;
}

if (da && !pr && !mac) {
document.writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
document.writeln('<' + 'SCRIPT LANGUAGE="VBScript">');
document.writeln('Sub window_onunload');
document.writeln('  On Error Resume Next');
document.writeln('  Set WB = nothing');
document.writeln('End Sub');
document.writeln('Sub vbPrintPage');
document.writeln('  OLECMDID_PRINT = 6');
document.writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
document.writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
document.writeln('  On Error Resume Next');
document.writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
document.writeln('End Sub');
document.writeln('<' + '/SCRIPT>');
}

function clearDefault(theobject) {
  if (theobject.defaultValue==theobject.value) theobject.value = ""
} 

function ChangeCookie ( )
{
    document.write("Welcome to my world!!!");
}

function URLDecode(urlString) 
{
  return unescape(urlString); 
}

function GeneratePTQS()
{                   
    var cookievals = document.cookie.split(";");
    var subcookievals = "";
    var qs = document.location.search;
    
    for(var i=0; i<cookievals.length; i++)
    {
        var name = _trim(cookievals[i].split("=")[0]);
        var value = _trim(cookievals[i].split("=")[1]);
        if( name.toLowerCase().indexOf("slhbanner") > -1 || 
            name.toLowerCase().indexOf("slhcookie") > -1 ||
            name.toLowerCase().indexOf("slhregcookie") > -1 ||
            name.toLowerCase().indexOf("slhtrackingsessionid") > -1 ||
            name.toLowerCase().indexOf("prefs") > -1)
        {
            if(cookievals[i].indexOf("&") > -1) 
            {   
                var parentName = name.toLowerCase();
                var values = cookievals[i].split("=");
                var prefsFilter = "|adref|detid|matchtype|dimexpand|keywordsearched|wt.srch|";
                values.shift();
                values = values.join("=").split("&");
                for(var x=0; x<values.length; x++)
                {
                    name = _trim(values[x].split("=")[0]);
                    value = _trim(values[x].split("=")[1]);
                    
                    if((name != "") && (parentName != "prefs" || (parentName == "prefs" && prefsFilter.indexOf("|" + name + "|") > -1)))
                        qs += "&" + name + "=" + value;                                         
                }
            }   
            else
                qs += "&" + name + "=" + escape(cookievals[i].split("=")[1]);
        }
    }
    return qs;          
}   

function GetPageCounter()
{
    return cms_getCookie("SLHPageCounter");
}

function _trim(str) {
    if(str != null)
    {
        var x = str;
        x=x.replace(/^\s*(.*)/, "$1");
        x=x.replace(/(.*?)\s*$/, "$1");
        return x;
    }
    return "";
}

function setSubCookie(uName, name, value, timeexpire)
{
    uValue = cms_getCookie(uName, null, null, true);
    if(uValue) {                    
        uCookies = uValue.split("&");
        var found = -1;
        for( c = 0; c < uCookies.length; c++ ){                       
            t = uCookies[c].split( '=' );
            if(t[0] == name) {
                found = 1;
                t[1] = escape(value);
                uCookies[c] = t.join( '=' );
                break;
            }
        }
        if( found == -1 )
            uCookies[uCookies.length] = name + '=' + value;
                                            
        uValue = uCookies.join( '&' );
    } else
        uValue = name + '=' + value;

    // update real cookie
    if(timeexpire)
        cms_setCookie(uName, uValue, timeexpire, true);
    else
        cms_setCookie(uName, uValue, null, true);
}

function ReturnFromListing()
{
    var url = cms_getQueryString("ref", null);

    if(url == null)
        url = unescape(unescape(cms_getCookie("Prefs","SLHListingRedirect","", true)));
        
    if(url == null || url == "")
    {
        document.location.href = "default.aspx?action=entry";
        return;
    }

	if(url.lastIndexOf("action=browsepageflash") > -1)
	{
		var temp = url.split("pagenumber")[0] + "startpage" + url.split("pagenumber")[1];
		url = temp;
	}
    document.location.href = url;
}

function AddShoppingListUI(storeId, listingId, offerId, addtext, removetext, onclick, style, target, originalLink){
    var result = AddShoppingListListing(storeId, listingId, offerId);
    if(result){
        DrawShoppingListLink(listingId, originalLink, addtext, removetext, onclick, style, target, offerId, "innerhtml")
        DrawShoppingListCount(null, null, "innerhtml");
        if(slg_itemcaption!="")
            DrawListingCaption(listingId, slg_itemcaption, offerId, "innerhtml");
        
        //tracking    
        var finalPrice = cms_getQueryString2(originalLink, 'finalprice', '0.0')
        var url = [];
    
        url[0] = "http://ptsc.shoplocal.com/pt" + document.location.pathname + ReplaceQS(GeneratePTQS(),"action","addshoppinglist") + "&pagecounter=" + GetPageCounter() + "&slhlogon=" + cms_getCookie("SLHUID", "UID") + "&siteid=" + cms_getCookie("Prefs", "SiteID") + "&referrer=" + escape(document.location) + "&random=" + escape(Math.random());       
        DrawTracker(url, "pt", "pixelTrackerContainer", true);
        
        url[0] = "http://it.shoplocal.com/it.ashx?" + uid + "|~|" + cms_getCookie("Prefs", "SiteID") + "|~|8|~||~|" + storeId + "|~|" + listingId + "|~|" + escape(Math.random()).replace(".","");
        DrawTracker(url, "et", "eventTrackerContainer", true);
                     
        dcsMultiTrack('DCS.sl_ffunc','addshoppinglist','DCSext.sl_zip','','DCSext.sl_zipcnt','','DCSext.sl_circ','','DCSext.sl_circ_p','','DCSext.sl_tx_s', finalPrice ,'WT.oss','','WT.oss_r','','WT.tx_u','1','WT.pn_sku', listingId ,'WT.si_n','','WT.si_p','','WT.tx_e','lp');
    }       
}

function RemoveShoppingListUI(storeId, listingId, offerId, addtext, removetext, onclick, style, target, originalLink){
    var result = RemoveShoppingListListing(storeId, listingId, offerId);
    if(result){
        DrawShoppingListLink(listingId, originalLink, addtext, removetext, onclick, style, target, offerId, "innerhtml")
        DrawShoppingListCount(null, null, "innerhtml");
        if(slg_itemcaption!="")
            DrawListingCaption(listingId, slg_itemcaption, offerId, "innerhtml");
        
        //tracking    
        var url = [];
        url[0] = "http://ptsc.shoplocal.com/pt" + document.location.pathname + ReplaceQS(GeneratePTQS(),"action","removeshoppinglist") + "&pagecounter=" + GetPageCounter() + "&slhlogon=" + cms_getCookie("SLHUID", "UID") + "&siteid=" + cms_getCookie("Prefs", "SiteID") + "&referrer=" + escape(document.location) + "&random=" + escape(Math.random());
        DrawTracker(url, "pt", "pixelTrackerContainer", true);
                
        dcsMultiTrack('DCS.sl_ffunc','removeshoppinglist','DCSext.sl_zip','','DCSext.sl_zipcnt','','DCSext.sl_circ','','DCSext.sl_circ_p','','DCSext.sl_tx_s','','WT.oss','','WT.oss_r','','WT.tx_u','1','WT.pn_sku', listingId ,'WT.si_n','','WT.si_p','','WT.tx_e','lp');            
    }       
}

function DrawShoppingListLink(listingId, link, addtext, removetext, onclick, style, target, offerId, mode)
{   
    //backward compatibility
    var vdir = "";
    var action = cms_getQueryString("action"," ").toLowerCase();
    try{vdir = window.location.href.split('/')[3];}catch(e){}
    if(action == "browseshoppinglist" || action == "printshoppinglist" || num_to_str(slg_vdr).indexOf("|" + vdir + "|")==-1){
        DrawShoppingListLink2(listingId, link, addtext, removetext, onclick, style, target, offerId)
        return;
    }
   
    // clean up parameters
    offerId = (offerId==undefined || offerId==null) ? "" : offerId;
    target = (target==undefined || target==null) ? "" : target;    
    style = (style==undefined || style==null) ? "" : style        

    onclick = (onclick==undefined || onclick==null) ? "" : onclick.replace(/`/g,"'");       
    addtext = addtext.replace(/`/g,"'").replace(/\"/g, "'");    
    removetext = removetext.replace(/`/g,"'").replace(/\"/g, "'");    
    
    var onclickparam = onclick.replace(/\'/g,"`")
    var addtextparam = addtext.replace(/\'/g,"`");
    var removetextparam = removetext.replace(/\'/g,"`")
                    
    var storeId = cms_getQueryString("storeid", null, "null");       
    var inList = GetShoppingListListing(storeId, listingId, offerId);
    var spanId = "sl|" + storeId + "|" + listingId + "|" + offerId;
    var renderedLink = "";
              
    if(inList)
        renderedLink = '<a target="' + target + '" onclick="' + onclick + '" style="' + style + '" href="javascript:RemoveShoppingListUI(\'' + storeId + '\',\'' + listingId + '\',\'' + offerId + '\',\'' + addtextparam + '\',\'' + removetextparam + '\',\'' + onclickparam + '\',\'' + style + '\',\'' + target + '\',\'' + link + '\')"><nobr>' + removetext + '</nobr></a>';
    else
        renderedLink = '<a target="' + target + '" onclick="' + onclick + '" style="' + style + '" href="javascript:AddShoppingListUI(\'' + storeId + '\',\'' + listingId + '\',\'' + offerId + '\',\'' + addtextparam + '\',\'' + removetextparam + '\',\'' + onclickparam + '\',\'' + style + '\',\'' + target + '\',\'' + link + '\')"><nobr>' + addtext + '</nobr></a>';

    if(mode == "innerhtml")       
        document.getElementById(spanId).innerHTML = renderedLink;       
    else
        document.write("<span style='' id='" + spanId + "'>" + renderedLink + "</span>");                
}

function DrawShoppingListCount(itemPhrase, itemPhrasePlural, mode)
{
    if(itemPhrase==null)
        itemPhrase = slg_itemPhrase;
    else
        slg_itemPhrase = itemPhrase;
    
    if(itemPhrasePlural==null)
        itemPhrasePlural = slg_itemPhrasePlural;
    else
        slg_itemPhrasePlural = itemPhrasePlural;

    var itemCount = cms_getCookie("ShoppingListCount",null,"0");
    var itemPhrase = (itemCount == "1") ? " " + itemPhrase : " " + itemPhrasePlural;
    if(itemPhrase.trim() == "")
        itemPhrase = "";
    
    if(mode == "innerhtml"){
        if(document.getElementById("spnShoppingListCount")!=null)
            document.getElementById("spnShoppingListCount").innerHTML = itemCount + itemPhrase;
    }
    else
        document.write("<span id='spnShoppingListCount' style=''>" + itemCount + itemPhrase + "</span>");

}

function DrawShoppingListLink2(listingId, link, addtext, removetext, onclick, style, target, offerId)
{
    var storeId = cms_getQueryString("storeid", null, "null");
    var ids = cms_getCookie("shoppinglist", null, "");
    var tempShopLink = link;
    var match;
    var inList;
    var tempLinkbegin;
    var tempLinkend;
    var searchfor;
    style = (style==null || style=="") ? " " : " style=\"" + style + "\" ";
    onclick = (onclick==null || onclick=="") ? " " : " onclick=\"" + onclick + "\" ";
    target = (target==null || onclick=="") ? " " : " target=\"" + target + "\" ";

    //try to find the action in the URL; if found replace action with correct action
    
    //searchfor = "action%3daddshoppinglist%26";
    searchfor = "action=addshoppinglist&";
    match = tempShopLink.indexOf (searchfor);
    if (match != -1){
        tempLinkbegin = tempShopLink.substring (0, match);
        tempLinkend = tempShopLink.substring (match+searchfor.length, tempShopLink.length);
    } else {
        //searchfor = "action%3dremoveshoppinglist%26";
        searchfor = "action=removeshoppinglist&";
        match = tempShopLink.indexOf (searchfor);
        if (match != -1){
            tempLinkbegin = tempShopLink.substring (0, match);
            tempLinkend = tempShopLink.substring (match+searchfor.length, tempShopLink.length);
        } else {
            searchfor = "Default.aspx%3f";
            match = tempShopLink.indexOf (searchfor);
            if (match != -1){
                tempLinkbegin = tempShopLink.substring (0, match+searchfor.length);
                tempLinkend = tempShopLink.substring (match+searchfor.length, tempShopLink.length); 
            }       
        }
    }
        
    //try to get catid from the qs
    var catId = cms_getQueryString("CatId", null, "null");
    catId = (catId != null) ? "|" + catId : "";
    
    //try to get catid from cookie
    if(catId == "")
    {
        catId = cms_getQueryString2(unescape(cms_getCookie("SLHListingRedirect", null, "")), "CatId", "");
        catId = (catId != null) ? "|" + catId : "";
    }
    
    //append offerid
    listingId += (offerId != null) ? ":" + offerId : "";

    //try to find in list without catid         
    inList = (ids.indexOf(listingId + "," + storeId) > -1); 

    //try to find in list with catid            
    if(!inList)
        inList = (ids.indexOf(listingId + catId + "," + storeId) > -1);

    if(inList){
        document.write("<a" + target + style + "href=\"" + tempLinkbegin + "action=removeshoppinglist&" + tempLinkend + "\">" + removetext + '</a>');
    } else {
        document.write("<a" + target + onclick + style + "href=\"" + tempLinkbegin + "action=addshoppinglist&" + tempLinkend + "\">" + addtext + '</a>');
    }
}

function DrawListingCaption (listingId, caption, offerId, mode)
{
    slg_itemcaption = caption;
    
    storeId = cms_getQueryString("storeid", null, "null");
    offerId = (offerId==undefined || offerId==null) ? "" : offerId;

    //try to find in list without catid         
    inList = GetShoppingListListing(storeId, listingId, offerId)    
    
    //try to find in list with catid            
    var captionId = "slci|" + listingId + "|" + offerId + "|";
    if(inList){     
        if(mode == "innerhtml"){
            if(document.getElementById(captionId)!=null)
                document.getElementById(captionId).innerHTML = caption;
        }
        else
            document.write ("<span style='' id='" + captionId + "'>" + caption + "</span>");
    }
    else{
        if(mode == "innerhtml"){
            if(document.getElementById(captionId)!=null)
                document.getElementById(captionId).innerHTML = "";
        }
        else{
            document.write ("<span style='' id='" + captionId + "'></span>");
        }
    }
}

function deleteCookie(name, path, domain) 
{
    if ( cms_getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function DrawViewAllItems(url, itemphrase, circularphrase)
{
    var displayMode = (cms_getCookie("DisplayMode", "preferred", "html"));
    var action = (displayMode == "html") ? "browsepagesingle" : "browsepageflash";
    var ignoreFlashStateParam = "ignore=true&"
    if(action != "browsepageflash"){
	ignoreFlashStateParam = "";
    }
    
    try{
        //TODO: this could be done more efficient with regular expressions - gj
        var qs = url.substring(url.indexOf("?")+1, url.length);
        var qsArray = qs.split("&");
        
        qs = "";    
        for(var i=0; i<qsArray.length; i++){        
            if(qsArray[i].split("=")[0].toLowerCase() == "action")
                qsArray[i] = "action=" + action;
            qs += qsArray[i] + "&";         
        }
        
        url = url.split("?")[0] + "?" + qs; 
    }
    catch(e){}
            
	if(url.lastIndexOf("action=browsepageflash") > -1)
	{
		var temp = url.split("pagenumber")[0] + "startpage" + url.split("pagenumber")[1];
		url = temp;
	}
    document.location.href = url + ignoreFlashStateParam;
}


function WishListListingExists(sid, lid, cid)
{   
    var ids = cms_getCookie("wishlist", null, " ");
        
    //try to find in list without catid         
    var pos = ids.indexOf(lid + "," + sid);
    
    //try to find in list with catid            
    if(pos > -1)
    {
        document.catalog.SetVariable('itemInWishListCookie', "true");
        return;
    }
        
    pos = ids.indexOf(lid + cid + "," + sid);   
    if(pos > -1)
    {
        document.catalog.SetVariable('itemInWishListCookie', "true");
        return;
    }
    else
    {
        document.catalog.SetVariable('itemInWishListCookie', "false");
        return;
    }
}

function GetWishListListing(sid, lid, cid)
{       
    var ids = cms_getCookie("wishlist", null, " ");
        
    //try to find in list without catid         
    var pos = ids.indexOf(lid + "," + sid);
    
    //try to find in list with catid            
    if(pos > -1)
        return ((pos>0) ? "," : "") + lid + "," + sid;
    else
        pos = ids.indexOf(lid + cid + "," + sid);
        
    if(pos > -1)
        return ((pos>0) ? "," : "") + lid + cid + "," + sid;
    else
        return "";          
}

function RemoveWishListListing(sid, lid, cid)
{
    //get wishlist cookie
    var ids = new String(cms_getCookie("wishlist", null, " "));
    if(ids == "")
        return false;
    
    var wishlistvalue = GetWishListListing(sid, lid, cid);
            
    if(wishlistvalue != ""){    
        var regEx = new RegExp (wishlistvalue, 'gi') ;
        ids = ids.replace(regEx, '');
        if(ids.indexOf(',') == 0)
            ids = ids.substring(1, ids.length-1);
            
        cms_setCookie("WishList",ids);
        
        var idcount = 0;    
        try{idcount = parseInt(cms_getCookie("wishlistcount", null, " "));}
        catch(e){}
        
        if(idcount>0)
        {
            SetListCount();
            --idcount;          
            cms_setCookie("WishListCount",idcount);         
        }
        return;
    }
    else{
        return;
    }           
}

function AddWishListListing(sid, lid, cid)
{
    lid = (cid!=null&&cid!="") ? lid + cid : lid;   
    var ids = new String(cms_getCookie("wishlist", null, " ")).trim();  
    var wishlistvalue = GetWishListListing(sid, lid, cid);  
    try{
        idcount = parseInt(cms_getCookie("wishlistcount", null, " "));
        if(idcount == 20)
        {
            SetListCount();
            return;
        }
    }
    catch(e){}
    
    if(wishlistvalue == ""){    
        ids = (ids == "") ? lid+","+sid : ids+","+lid+","+sid;
        cms_setCookie("WishList",ids,360);          
        var idcount = 0;    
        try{idcount = parseInt(cms_getCookie("wishlistcount", null, "0"));}
        catch(e){}
        
        SetListCount();
        idcount++;      
        cms_setCookie("WishListCount", idcount,360);        
        return;
    }
    else{
    
        return;
    }           
}

function SetListCount()
{   
    var idcount = parseInt(cms_getCookie("wishlistcount", null, " "));
    //alert(idcount);
    if(isNaN(idcount))
    {
        idcount = 0;
        fc.setVariable("/flashMoreInfo:wishListCount", idcount);        
    }
    else
    {
        fc.setVariable("/flashMoreInfo:wishListCount", idcount);
    }
}

//Either HTML or Flash link shows
function DrawToggleLink (modePhrase, HTMLmode, Flashmode, strRetailerAdPageID, strPromotionCode, strSID, linkID, toggleStyle)
{    
    var currentStoreID = cms_getQueryString("storeid","-1");
    if(currentStoreID == "-1"){currentStoreID = cms_getCookie ("Prefs","StoreID",null,"0");}    
    else{setSubCookie("Prefs","StoreID",currentStoreID,1000);}
    
    var modePref = cms_getCookie ("DisplayMode", "preferred", null);
    var HTMLLink;
    var FlashLink;

    linkIDvalue = (linkID==null || linkID=="") ? " " : " id=\"" + linkID + "\" ";

    if (strRetailerAdPageID != ""){
        if (modePref == "flash"){
            HTMLLink = "\Default.aspx?action=" + HTMLmode + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID;
            document.write ("<div class=\"modeLink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + HTMLLink + "')\">" + modePhrase + "</a></div>");
        } else {
            FlashLink = "\Default.aspx?action=" + Flashmode + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID;
            document.write ("<div class=\"modeLink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + FlashLink + "')\">" + modePhrase + "</a></div>");
        }
    } else if (strPromotionCode != "") {
        if (modePref=="flash"){
            HTMLLink = "\Default.aspx?action=" + HTMLmode + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode;
            document.write ("<div class=\"modeLink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + HTMLLink + "')\">" + modePhrase + "</a></div>");
        } else {
            FlashLink = "\Default.aspx?action=" + Flashmode + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode;
            document.write ("<div class=\"modeLink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + FlashLink + "')\">" + modePhrase + "</a></div>");
        }
    }
}

//Both HTML/Flash links show
function DrawToggleLink2 (htmlPhrase, flashPhrase, strAction, strRetailerAdPageID, strPromotionCode, strSID, linkID, toggleStyle)
{
    var currentStoreID = cms_getQueryString("storeid","-1");
    if(currentStoreID == "-1"){currentStoreID = cms_getCookie ("Prefs","StoreID",null,"0");}
    else{setSubCookie("Prefs","StoreID",currentStoreID,1000);}
    
    linkIDvalue = (linkID==null || linkID=="") ? " " : " id=\"" + linkID + "\" ";

    if (strRetailerAdPageID != ""){
        HTMLLink = "\Default.aspx?action=" + strAction + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID + "&pagenumber=1";
        FlashLink = "\Default.aspx?action=browsepageflash" + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID + "&pagenumber=1";
        document.write ("<div class=\"HTMLmodelink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + HTMLLink + "')\">" + htmlPhrase + "</a></div>");
        document.write ("<div class=\"Flashmodelink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + FlashLink + "')\">" + flashPhrase + "</a></div>");  
    } else if (strPromotionCode != "") {
        HTMLLink = "\Default.aspx?action=" + strAction + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode + "&pagenumber=1";
        FlashLink = "\Default.aspx?action=browsepageflash" + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode + "&pagenumber=1";
        document.write ("<div class=\"HTMLmodelink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + HTMLLink + "')\">" + htmlPhrase + "</a></div>");
        document.write ("<div class=\"HTMLmodelink\"><a" + linkIDvalue + "href=\"javascript:GoToPromotion('" + FlashLink + "')\">" + flashPhrase + "</a></div>");
    }
}

//HTML/Flash radio buttons
function DrawToggleLink3 (HTMLAction, FlashAction, HTMLmode, Flashmode, strRetailerAdPageID, strPromotionCode, strSID, linkID, toggleStyle)
{
    var currentStoreID = cms_getQueryString("storeid","-1");
    if(currentStoreID == "-1"){currentStoreID = cms_getCookie ("Prefs","StoreID",null,"0");}    
    else{setSubCookie("Prefs","StoreID", currentStoreID,1000);}

    var modePref = cms_getCookie ("DisplayMode", "preferred", null);

    linkIDvalue = (linkID==null || linkID=="") ? " " : " id=\"" + linkID + "\" ";

    var RetailerHTMLLink = "\Default.aspx?action=" + HTMLAction + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID + "&pagenumber=1";
    var RetailerFlashLink = "\Default.aspx?action=" + FlashAction + "&storeid=" + currentStoreID + "&rapid=" + strRetailerAdPageID + "&pagenumber=1";
    var PromoHTMLLink = "\Default.aspx?action=" + HTMLAction + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode + "&pagenumber=1";
    var PromoFlashLink = "\Default.aspx?action=" + FlashAction + "&storeid=" + currentStoreID + "&promotioncode=" + strPromotionCode + "&pagenumber=1";

    if (strPromotionCode != "") {
        if (modePref=="flash"){
            setSubCookie("DisplayMode","preferred","html",1000);
            window.location = PromoHTMLLink;
        } else {
            setSubCookie("DisplayMode","preferred","flash",1000);
            window.location = PromoFlashLink;
        }
    }else if (strRetailerAdPageID != ""){
        if (modePref == "flash"){
            setSubCookie("DisplayMode","preferred","html",1000);        
            window.location = RetailerHTMLLink;     
        } else {
            setSubCookie("DisplayMode","preferred","flash",1000);
            window.location = RetailerFlashLink;
        }
    } 
}

//The toggle link above/below the circular cover image and the link for the circular cover itself
function DrawEntryToggle (CircAction, StoreID, RapID, PromoCode, DefaultView, prefMode, fsid)
{
    var displayMode = (cms_getCookie("DisplayMode","preferred", null));

    if ((prefMode != null && prefMode != "")&& displayMode!= null){
        if (prefMode == "html"){
            setSubCookie("DisplayMode","preferred","html",1000);
            displayMode = "html";
        } else {
            setSubCookie("DisplayMode","preferred","flash",1000);       
            displayMode = "flash";
        }
    }
    
    if (displayMode == null){
        if (prefMode == null || prefMode == "")
            displayMode = (DefaultView=="1" || DefaultView=="2" || DefaultView=="10") ? "html" : "flash";
        else 
            displayMode = prefMode;
        
        setSubCookie("DisplayMode","preferred",displayMode,1000);
    } 

    if (displayMode == "html")
        window.location = "Default.aspx?action=" + CircAction + "&storeid=" + StoreID + "&rapid=" + RapID.trim() + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;  
    else
        window.location = "Default.aspx?action=browsepageflash" + "&storeid=" + StoreID + "&rapid=" + RapID.trim() + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;
}

//Toggle link - current mode text, toggle a link or both are links
function DrawEntryDualToggle (HTMLtxt, Flashtxt, CircAction, StoreID, RapID, PromoCode, DefaultView, LinkStat, LinkPos)
{
    var displayMode = (cms_getCookie("DisplayMode", "preferred", null));
    var ToggleLink;
    var CurrentLink;
    var CurrentPhrase;
    var TogglePhrase;

    if (displayMode == null)
        displayMode = (DefaultView=="1" || DefaultView=="2" || DefaultView=="10") ? "html" : "flash";

    if (displayMode == "html"){
        setSubCookie("DisplayMode","preferred", "html",1000);
        CurrentLink = "Default.aspx?action=" + CircAction + "&storeid=" + StoreID + "&rapid=" + RapID + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;
        CurrentPhrase = HTMLtxt;
        ToggleLink = "Default.aspx?action=browsepageflash" + "&storeid=" + StoreID + "&rapid=" + RapID + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;
        TogglePhrase = Flashtxt;    
    } else {
        setSubCookie("DisplayMode","preferred", "flash",1000);
        CurrentLink = "Default.aspx?action=browsepageflash" + "&storeid=" + StoreID + "&rapid=" + RapID + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;
        CurrentPhrase = Flashtxt;
        ToggleLink = "Default.aspx?action=" + CircAction + "&storeid=" + StoreID + "&rapid=" + RapID + "&pagenumber=1&prvid=" + PromoCode + "&promotioncode=" + PromoCode;
        TogglePhrase = HTMLtxt;
    }
    if ((LinkStat == "bothLinks" || LinkStat == "bothlinks" || LinkStat == "BothLinks" )&& CurrentLink != null && CurrentLink != ""){
        if (LinkPos == "stack" || LinkPos == "Stack"){
            document.write ("<div id=\"toggleleft\"><a href=\"javascript:GoToPromotion('" + CurrentLink + "')\">" + CurrentPhrase + "</a></div>");
            document.write ("<div id=\"toggleright\"><a href=\"javascript:GoToPromotion('" + ToggleLink + "')\">" + TogglePhrase + "</a></div>");
        } else {
            document.write ("<span id=\"toggleleft\"><a href=\"javascript:GoToPromotion('" + CurrentLink + "')\">" + CurrentPhrase + "</a></span>");
            document.write ("<span id=\"toggledivider\">&nbsp;|&nbsp;</span>");
            document.write ("<span id=\"toggleright\"><a href=\"javascript:GoToPromotion('" + ToggleLink + "')\">" + TogglePhrase + "</a></span>");
        }
    } else {
        if (LinkPos == "stack" || LinkPos == "Stack"){
            document.write ("<div id=\"notLink\">" + CurrentPhrase + "</div>");
            document.write ("<div id=\"toggleright\"><a href=\"javascript:GoToPromotion('" + ToggleLink + "')\">" + TogglePhrase + "</a></div>");
        } else {
            document.write ("<span id=\"notLink\">" + CurrentPhrase + "</span>" + "<span id=\"toggledivider\">&nbsp;|&nbsp;</span><span id=\"toggleright\"><a href=\"javascript:GoToPromotion('" + ToggleLink + "')\">" + TogglePhrase + "</a></span>");
        }
    }

}

function GoToPromotion (ToggleURL){
    if (ToggleURL.indexOf ("browsepageflash")>0)
        setSubCookie("DisplayMode","preferred", "flash",1000);
    else 
        setSubCookie("DisplayMode","preferred", "html",1000);
        
    document.location.href = ToggleURL;
}

function DrawDetailViewAllItems (url)
{
    displayMode = (cms_getCookie("DisplayMode", "preferred", "html"));
    var action = (displayMode == "html") ? "browsepagesingle" : "browsepageflash";
    searchfor = "browsepagesingle";
    
    match = url.indexOf (searchfor);
    if (match != -1){
        tempLinkbegin = url.substring (0, match);
        tempLinkend = url.substring (match+searchfor.length, url.length);   
    } else {
        searchfor = "browsepageflash";
        match = url.indexOf (searchfor);
        if (match != -1){
            tempLinkbegin = url.substring (0, match);
            tempLinkend = url.substring (match+searchfor.length, url.length);   
        } else {
            var ViewAllLink = url;
        }
    }
        
    ViewAllLink = tempLinkbegin + action + tempLinkend; 
    window.location = ViewAllLink;  

}

function findShopLink (gridURL){
    searchfor = "addshoppinglist";
    match = gridURL.indexOf (searchfor);
    var gridListingID;
    
    if (match != -1){
        searchfor = "listingid";
        match = gridURL.indexOf (searchfor);
        gridListingID = gridURL.substring(match+10, match+21);
        return (gridListingID);
    } else {
        searchfor = "removeshoppinglist";
        match = gridURL.indexOf (searchfor);
        if (match != -1){
            searchfor = "listingid";
            match = gridURL.indexOf (searchfor);
            gridListingID = gridURL.substring(match+10, match+21);
            return (gridListingID);
        } else {
            return (0);     
        }
    }
}

var MM_PreviousVersion;
var MM_contentVersion = 7;
var MM_FlashCanPlay = false;
var bolHybridMode = false;

var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;    
if ( plugin ) {
        var words = navigator.plugins["Shockwave Flash"].description.split(" ");
        for (var i = 0; i < words.length; ++i){
            if (isNaN(parseInt(words[i])))
            continue;
            var MM_PluginVersion = words[i]; 
        }
        MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
&& (navigator.appVersion.indexOf("Win") != -1)) {
    document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
    document.write('on error resume next \n');
    document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
    document.write('MM_PreviousVersion = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion-1)))\n');
    document.write('</SCR' + 'IPT\> \n');
}

function DrawFlashMovie(id, url, width, height, flashvars)
{       
    if(flashvars==null)
        flashvars = "";

    if(MM_FlashCanPlay){
        document.write('<OBJECT style="border:0px solid Red" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" id="' + id + '" width="' + width + '" height="' + height + '" ALIGN="" VIEWASTEXT>');
        document.write('<param name="FlashVars" VALUE="' + flashvars + '">');   
        document.write('<param name="wmode" value="opaque">');
        document.write('<param name="allowScriptAccess" value="always">');
        document.write('<param name="movie" value="' + url + '" />');
        document.write('<param name="quality" value="high" />');
        document.write('<param name="scale" value="exactfit" />');
        document.write('<param name="bgcolor" value="#ffffff" />');
        document.write('<EMBED src="' + url + '" quality="high" scale="exactfit" bgcolor="#ffffff" width="' + width + '" height="' + height + '" swLiveConnect="true" ID="catalogN" NAME="' + id + '" ALIGN="" wmode="opaque" allowScriptAccess="always" FlashVars="' + flashvars + '" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>');
        document.write('</OBJECT>');
    }
    else{
        document.write('<table border="1" width="' + width + '" height="' + height + '" style="text-align:center;vertical-align:center;"><tr><td><a href="http://www.macromedia.com/go/getflashplayer" target="_new">Flash Required<br>Download Here</a></td></tr></table>');
    }
    
}

function DrawEmailAddress (){
    var emailAddress = cms_getCookie("QuickHoundEmailAlerts", "NotificationAddress242", null, null);
    if (emailAddress != "" && emailAddress != null)
        document.write (emailAddress);
}



//------------------------------------------------------------


function GetShoppingListListing(sid, lid, oid, mode)
{   
    //-2094570364:1965916,2398236 - with offerid
    //-2094570364,2398236 - without offerid
    var ids = cms_getCookie("shoppinglist", null, " ");
    var result = "";
        
    //empty list
    if(ids == " "){
        result = (mode==1) ? "<result></result>" : "";
        return result;
    }

    if(oid==null || oid==""){
        pos = ids.indexOf(lid + "," + sid);                 
        if(pos > -1){        
            // returns either 1965916,2398236 or ,1965916,2398236
            result = ((pos>0) ? "," : "") + lid + "," + sid;
            return ((mode==1) ? "<result>" + result + "<result>" : result);
        }
    }
    else{
        pos = ids.indexOf(lid + ":" + oid + "," + sid);
        if(pos > -1){
            // returns either -2094570364:1965916,2398236 or ,-2094570364:1965916,2398236
            result = ((pos>0) ? "," : "") + lid + ":" + oid + "," + sid;
            return ((mode==1) ? "<result>" + result + "<result>" : result);     
        }        
    }
    
    result = ((mode==1) ? "<result></result>" : "");
    return result;                
}

function RemoveShoppingListListing(sid, lid, oid, mode)
{
    var ids = new String(cms_getCookie("shoppinglist", null, " "));
    if(ids == "" || ids == " ")
        return (mode==1) ? "<result>false</result>" : false;
    
    var shoppinglistvalue = GetShoppingListListing(sid, lid, oid);
            
    if(shoppinglistvalue != ""){    
        var regEx = new RegExp (shoppinglistvalue, 'gi') ;
        ids = ids.replace(regEx, '');
        if(ids.substring(0,1) == ",")
            ids = ids.substring(1,ids.length);
        
        cms_setCookie("ShoppingList",ids, 360);
        
        var idcount = 0;    
        try{idcount = parseInt(cms_getCookie("ShoppingListCount", null, " "));}
        catch(e){}
        
        if(idcount>0){
            --idcount;
            cms_setCookie("ShoppingListCount",idcount, 360);
        }
        return (mode==1) ? "<result>true</result>" : true;
    }
    else{
        return (mode==1) ? "<result>false</result>" : false;
    }           
}

function AddShoppingListListing(sid, lid, oid, mode)
{
    try{
        if(sid==null || sid==undefined || sid.trim()=="" || isNaN(sid))
            return (mode==1) ? "<result>false</result>" : false;
        if(lid==null || lid==undefined || lid.trim()=="" || isNaN(lid))
            return (mode==1) ? "<result>false</result>" : false;
        if(oid!=null && oid.trim()!="" && isNaN(oid)) 
            return (mode==1) ? "<result>false</result>" : false;
            
        var ids = new String(cms_getCookie("shoppinglist", null, " ")).trim();  
        var shoppinglistvalue = GetShoppingListListing(sid, lid, oid);
                    
        if(shoppinglistvalue == ""){
            lid = (oid!=null&&oid.trim()!="") ? lid + ":" + oid : lid;  
            ids = (ids == "") ? lid+","+sid : ids+","+lid+","+sid;
            cms_setCookie("ShoppingList",ids, 360);

            var idcount = 0;    
            try{idcount = parseInt(cms_getCookie("ShoppingListCount", null, "0"));}
            catch(e){}
            
            idcount++;      
            cms_setCookie("ShoppingListCount", idcount, 360);       
            return (mode==1) ? "<result>true</result>" : true;
        }
        else{
            return (mode==1) ? "<result>false</result>" : false;
        }   
    }
    catch(e){
        return (mode==1) ? "<result>false</result>" : false;
    }       
}

function GetShoppingListCount(mode)
{      
    var count = 0;  
    try{count = parseInt(cms_getCookie("ShoppingListCount", null, "0"));}
    catch(e){}
    
    return (mode==1) ? "<result>" + count + "</result>" : count;        
}

function GetShoppingList()
{   
    var count = 0;  
    try{count = parseInt(cms_getCookie("ShoppingListCount", null, "0"));}
    catch(e){}
    
    var list = new String(cms_getCookie("shoppinglist", null, " "));        
    var xml = "<result><list>" + list.trim() + "</list><count>" + count + "</count></result>";
    return list.trim();
}

function GetShoppingListFlash(){
    fc.callFunction("_global.HTMLConduit","cbGetShoppingList", GetShoppingList());
}

function GetShoppingListCountFlash(mode){
    fc.callFunction ("_global.DATA.shoppingListData","updateListingCount", [GetShoppingListCount(mode), GetShoppingList()]);    
}

function AddShoppingListListingFlash(input){
	
    var arrinput = new Array(); 
    arrinput = input.split(','); 
    fc.callFunction ("_global.DATA.shoppingListData","shoppingListUpdated", [AddShoppingListListing(arrinput[0], arrinput[1], arrinput[2], 1), GetShoppingList()]);        
    GetShoppingListFlash();    
}

function RemoveShoppingListListingFlash(input){
	
    var arrinput = new Array(); 
    arrinput = input.split(',');    
    
    fc.callFunction("_global.DATA.shoppingListData","shoppingListUpdated", [RemoveShoppingListListing(arrinput[0], arrinput[1], arrinput[2], 1), GetShoppingList()]);
    GetShoppingListFlash();    
}

function UpdateShoppingListFlex(input){
    var arrinput = new Array(); 
    arrinput = input.split(','); 

    var result;
    if (arrinput[0]==0) { 
      result= RemoveShoppingListListing(arrinput[1], arrinput[2], arrinput[3], 0);
    }else {
      result= AddShoppingListListing(arrinput[1], arrinput[2], arrinput[3], 0);
    }
    return result;
}

function str_to_num(text) {
    
    var num_out = "";        
    var str_in = escape(text);
    
    for(i = 0; i < str_in.length; i++) 
        num_out += str_in.charCodeAt(i) - 23;
            
    return num_out;
}

function num_to_str(text) {
    var num_in;    
    var str_out = "";
    var num_out = text;  
   
    for(i = 0; i < num_out.length; i += 2) {
        num_in = parseInt(num_out.substr(i,[2])) + 23;
        num_in = unescape('%' + num_in.toString(16));
        str_out += num_in;
    }
    return unescape(str_out);
   
}

//------------------------------------------------------------