//Public -- 03-12-2008 fix for XSS log
var suggestionsSearch;
var DIC_NAME;
var NUM_OF_ITEMS;
var IsSearchSubmit = true;
var URL;

function seoRewriteUrl(rawUrl) 
{
	//just looking for the home page
	if (rawUrl == null || rawUrl == "" || rawUrl == "/") {
		return "";
	}

	//only replace periods in the extenstion since they are used in the prices
	rawUrl = rawUrl.replace('.aspx', '/shp/');
	rawUrl = rawUrl.replace(/&/g, ','); //For Bug20702 - v-gaucha - Modified to replace all instances of '&' with ','
	return rawUrl;
}

function truncate(s, at, postfix)
{
	if (s.length > at)
	{
		var cutOffIdx = at - 1;
		var spaceIdx = s.lastIndexOf(' ', cutOffIdx);
		if (spaceIdx > -1)
			cutOffIdx = spaceIdx;
		s = s.substr(0, cutOffIdx) + postfix;
	}
	
	return s;
}

function show_ads(target, attempt, header)
{
	if (typeof zSr != 'undefined')
	{
		var i = 6;
		var itemHtml = '';
		if (i < zSr.length)
		{
			if (typeof header != 'undefined')
				itemHtml = unescape(header);

			while (i < zSr.length)
			{
				var descr	= truncate(zSr[i++], 90, "...");
				var unused	= zSr[i++];
				var clickURL= zSr[i++];
				var title	= truncate(zSr[i++], 40, "...");
				var sitehost= zSr[i++];
				var bid		= zSr[i++];
				itemHtml += '<div class="adItem"><a href="' + clickURL + '">' + title + '</a><br>' + descr + '<br><a class="truncated" href="' + clickURL + '">' + sitehost + '</a></div>';
				if (i < zSr.length)
					itemHtml += '<div class=\"HR\"></div>';
			}
			document.getElementById(target).innerHTML  += itemHtml;
		}
	}
	else
	{
		if (attempt <= 20)
			window.setTimeout("show_ads('" + target + "', " + ++attempt + ", '" + header + "')", 500);
	}
}
var s_maxCount = 0;
var s_maxReachedMsg = '';

function setMaxVariables(maxCount, maxReachedMsg) {
	s_maxCount = maxCount;
	s_maxReachedMsg = maxReachedMsg;
}

function addToProdComp(prodId, checked)
{
	var cnt = setCookieValue("prodcomp", prodId, (checked?prodId:null), s_maxCount, s_maxReachedMsg);
	if (cnt < 0)
		return false;
	var prodcountT = document.getElementById("prodCompCountT");
	var prodcountB = document.getElementById("prodCompCountB");
	
	if (cnt > 0)
	{
		if (prodcountT)
			prodcountT.innerHTML = "&nbsp;" + cnt + "&nbsp;";
		if (prodcountB)
			prodcountB.innerHTML = "&nbsp;" + cnt + "&nbsp;";
	}		
	else
	{
		if (prodcountT)
			prodcountT.innerHTML = "&nbsp;";
		if (prodcountB)
			prodcountB.innerHTML = "&nbsp;";
	}
	return true;
}

function setCookieValue(name, currVal, newVal, maxCount, maxReachedMsg) 
{
	var valcount = 0;
	var val = getCookieValue(name);
	if (val && val.length > 0)
	{
		var values = val.split("|");
		var found = -1;
		if (currVal)
			for(var valIdx = 0; valIdx < values.length; valIdx++)
			{
				if (values[valIdx] == currVal)
					found = valIdx;
			}
		if (!newVal && found > -1)
		{
			var newvalues = new Array();
			if (found > 0)
			{
				newvalues = newvalues.concat(values.slice(0, found));
			}
			if (found < values.length - 1)
			{
				newvalues = newvalues.concat(values.slice(found + 1, values.length));
			}
			values = newvalues;
		}
		if (newVal && found == -1)
			if (values.length < maxCount)
				values[values.length] = newVal;
			else
			{
				alert(maxReachedMsg);
				return -1;
			}
		newVal = values.join("|");
		if (newVal.length > 0)
			document.cookie = name + "=" + escape(newVal) + ";path=/";
		else
			document.cookie = name + "=;path=/";
			
		valcount = values.length;
	}
	else
	{
		if (newVal)
		{
			document.cookie = name + "=" + escape(newVal) + ";path=/";
			valcount = 1;
		}
	}
	return valcount;
}

function getCookieValue(name) 
{
	var dc = document.cookie;
	var search = name + "=";
	var pos = dc.indexOf("; " + search);
	if (pos == -1) 
	{
		pos = dc.indexOf(search);
		if (pos == -1) return null;
	} 
	else
	{
		pos += 2;
	}
	var pos2 = dc.indexOf(";", pos);
	if (pos2 == -1)
		pos2 = dc.length;
	var val = dc.substring(pos + search.length, pos2);
	return unescape(val);
}

function submitProdComp(name, msg)
{
	var val = getCookieValue(name);
	if (!val || val.length == 0 || val.split("|").length < 2)
	{
		alert(unescape(msg));
		return false;
	}
	return true;
}

function adjustScreenElementsWidth(width)
{
	try
	{
		var availWidth;
		if (document.body.clientWidth)
			availWidth = document.body.clientWidth;
		else 
			availWidth = window.innerWidth;
		if (width > availWidth)
		{
			document.getElementById("header").style.width = width;
			document.getElementById("dark2whiteBar").style.width = width;
			document.getElementById("shopFooter").style.width = width;
		}
	}
	catch(e)	
	{ }
}

function restoreProdCompCookie(max, redirUrl)
{
	setMaxVariables(max, '');
	var matches = window.location.search.match(/itemId=[0-9]+/gi);
	for(i = 0; i < matches.length; i++)
	{
		addToProdComp(matches[i].substring(7, matches[i].length), true);
	}
	if (redirUrl.length > 0)
		window.location = redirUrl;
	else
		history.back();
}

function Redirect(strURL) 
{
	window.location=strURL;
	return false;
}

function Refresh(strURL) 
{
	window.location=strURL;
	return false;
}

function switchDesc(id) {
	var button = document.getElementById("switch_"+id);

	if(button==null)
		return true;

	var more = document.getElementById("more_"+id);
	var part2 = document.getElementById("fullDesc_"+id);
		
	if(button.className=='plusDesc') { //expand
		button.className='minusDesc';
		if(part2!=null) part2.style.display='inline';
		if(more!=null) more.style.display='none';
	} else if(button.className=='minusDesc') { // contract
		button.className='plusDesc';
		if(part2!=null) part2.style.display='none';
		if(more!=null)more.style.display='inline';
	}
	if( navigator != null && navigator.userAgent != null && navigator.userAgent.indexOf("Firefox") != -1 )
		document.body.innerHTML = document.body.innerHTML; // force firefox to re-compute the layout
	return false;
}

function DoSearch(searchText, msg, baseURL) {
    if(!IsSearchSubmit)
        return false;

	if(!searchText || searchText.length<1 || Trim(searchText).length<1) {
		alert(msg);
		return false;
	}
	
	if(baseURL && baseURL!='') {
		window.location=baseURL+seoRewriteUrl('/results.aspx?text='+encodeURIComponent(searchText));
		return false;
	}
	return true;
}
//a-leula's change: To highlight the text value of search textBox to indicate that it generated by the system.
function highlight()
{ 
	var searchText = document.getElementById('searchText');
    //searchText.select();
    //searchText.focus();
    var btnSearch = document.getElementById('btnSearch');
    btnSearch.focus();
}
function ClearSearchBox(searchText)
{
    var allShopping = document.getElementsByName('searchtype')[0];
	//var withinThis = document.getElementsByName('searchtype')[1];
	var searchText = document.getElementById('searchText');
    if((allShopping!=null && allShopping.checked) &&(searchText.className=="searchBox graysearchbox"))
    {
        searchText.value="";
    }
    if(allShopping==null)
    {
      searchText.value="";
    }    
    searchText.className = "normalsearchbox searchBox";
    
}
function SearchBoxNormal()
{
    var searchText = document.getElementById('searchText');
    searchText.className = "normalsearchbox searchBox";
}
function ComScoreDisabled()
{
    var searchText = document.getElementById('searchText');
    //searchText.className = "searchBox";
}
//end of a-leula's change
/* Bug20702 - v-gaucha - 10/01/2006 - New Search Functionality */
function DoSearchNew(searchText, msg, baseURL, Button, queryString)
{	
    if(!IsSearchSubmit)
        return false;
      
	var allShopping = document.getElementsByName('searchtype')[0];
	var withinThis = document.getElementsByName('searchtype')[1];
    
	// Perform shopping search
	if(Button == 'searchButton')
	{
        //Edited by v-chinka on 22 May 2008:Checking for empty string and alert for nonempty string.              		
                if(!searchText || searchText.length<1 || Trim(searchText).length<1)
                {	
			alert(msg);
			return false;
		}
		else if(baseURL && baseURL!='')
			{
			// Search based on the radio button selected
			// 'All Shopping' option
			if(allShopping != null && allShopping.checked)
			{  
				window.location=baseURL+seoRewriteUrl('/results.aspx?text='+encodeURIComponent(searchText)+'&pagelink=sa');		
				return false;
			} 
			// 'In these results/category' option
			else if(withinThis != null && withinThis.checked)
			{
				// Results pages
				if(withinThis.value == 'results')
				{	
					//Strip 'userText' and 'all=1'
					queryString = removeParams(queryString);
					
					//Prepend current 'text' value with new searchText
					//Or add 'text=' param if it does not exist
					if(queryString.match('text='))
						queryString = queryString.replace('text=','text='+encodeURIComponent(searchText+' '));
					else
						queryString = 'text='+encodeURIComponent(searchText)+'&'+queryString;
					
					//Add a 'wText' param for the new search text
					queryString = queryString+'&wText='+encodeURIComponent(searchText);
					
					window.location=baseURL+seoRewriteUrl('/results.aspx?'+queryString+'&pagelink=sr');		
					return false;
				}
				// Category pages
				else if(withinThis.value == 'category')
				{	
					queryString = removeParams(queryString);
					window.location=baseURL+seoRewriteUrl('/results.aspx?text='+encodeURIComponent(searchText)+'&'+queryString+'&pagelink=si');
					return false;
				}
			}
			// Perform default search if none of the above conditions match
			else
			{
				window.location=baseURL+seoRewriteUrl('/results.aspx?text='+encodeURIComponent(searchText));
				return false;
			}
		}
	}
	// Redirect search to web search
	else if(Button == 'webButton')
	{
        //Edited by v-chinka on 22 May 2008: Checking for Empty string and redirecting to                         //Live.com
		if(!searchText || searchText.length<1 || Trim(searchText).length<1)
                {	
		window.location.href='http://search.live.com';
		return false;
		}
                else { window.location.href='http://search.msn.com/results.aspx?q='+encodeURIComponent(searchText)+'&submit=Search&FORM=SHOP&cp=65001';
		return false;
		}
	}
	return true;
}

/* Bug20702 - v-gaucha - 10/01/2006 - Strips 'userText' and 'all=1' querystring params */
function removeParams(queryString)
{
	// Split the querystring params
	var qsParams = new Array();
	qsParams = queryString.split('&');
	
	// Removes the existence of 'userText', 'wText' and 'all' params
	// Also remove the 'searchtype' parameter
	queryString = '';
	for (i=0; i<qsParams.length; i++)
	{
		if (qsParams[i].match('userText=') || qsParams[i].match('all=1') || qsParams[i].match('searchtype=') || qsParams[i].match('wText=') || qsParams[i].match('page=') || Trim(qsParams[i]).length<1)
			continue;
		else
		{
			queryString = queryString + (0 == queryString.length ? '' : '&') +  qsParams[i];
		}
	}

	return queryString;
}

function Trim(source) {
  source = source.replace( /^\s+/g, "" );
  return source.replace( /\s+$/g, "" );
}

function clearChks()
{	
	if( navigator != null && navigator.userAgent != null && navigator.userAgent.indexOf("Firefox") != -1 )
	{
		var inputs = document.body.getElementsByTagName("input");				
		var cookieValue = getCookie("prodcomp");
		var j=-1;
		var prodId;
		var checkId;
		var values;
		
		if(cookieValue !=null)
		{
			values = cookieValue.split("|");
			for(var i=0;i<inputs.length;i++)
			{
				j = inputs[i].id.indexOf("prodcomp_");
				if(j >=0)
				{
					checkId = inputs[i].id;	
					prodId = checkId.substring(9,checkId.length);
					if(cookieValue.length == 0 || !isProdExists(values,prodId))
					{
						inputs[i].checked=false;
					}
				}					
			}
			
			var prodcountT = document.getElementById("prodCompCountT");
			var prodcountB = document.getElementById("prodCompCountB");
			
			if(values !=null && values.length > 0 && values[0].length !=0)
			{
				if (prodcountT)
					prodcountT.innerHTML = "&nbsp;" + values.length + "&nbsp;";
				if (prodcountB)
					prodcountB.innerHTML = "&nbsp;" + values.length + "&nbsp;";
				
			}else
			{
				if (prodcountT)
					prodcountT.innerHTML = "&nbsp;";
				if (prodcountB)
					prodcountB.innerHTML = "&nbsp;";			
			}
							
		}
	}
		return false;
}

function isProdExists(values, prodId)
{
	if (values !=null)
	{
		for(var i=0;i<values.length;i++)
		{
			if(prodId == values[i])
				return true;
		}
	}		
	return false;
}
function getCookie(name)
{
    var cookie = document.cookie;
    var prefix = name + "=";
    var begin = cookie.indexOf("; " + prefix);    
    //if its the only cookie
    if (begin == -1)
    {
        begin = cookie.indexOf(prefix);        
        if (begin != 0) return null;
    }
    else
    {
		//go two characters one for ";" and one for space " "
        begin += 2;
    }
    //find the length of the cookie
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = cookie.length;
    }
    //return the value
    return unescape(cookie.substring(begin + prefix.length, end));
}

function doPopup(){
	var deltaX = document.all?360:356;
	var deltaY = document.all?260:264;
	var popup = document.getElementById('popup');
	var popupContent = document.getElementById('popupContent');
	var firstPrice = document.getElementById('firstPrice');
	var lastPrice = document.getElementById('lastPrice');
	var posx = findPosX(firstPrice)-deltaX;
	var posy = findPosY(firstPrice);
	var bottomY = posy;
	if(lastPrice)
		bottomY = findPosY(lastPrice)-deltaY;
	if(!document.all)
		bottomY = bottomY+10;
	
	popup.style.left = posx;
	popup.style.top = posy;
	popupContent.style.left = posx;
	popupContent.style.top = posy;
	setStyle('popup', 'display', 'block');
	setStyle('popupContent', 'display', 'block');
	
	// follow scroll & resize
	
	var pos = parseInt(popup.style.top);
	window.rePos=function()
	{
		var firstPrice = document.getElementById('firstPrice');
		var posx = findPosX(firstPrice)-deltaX;
		
		if(document.body.scrollTop > popup.y-20)
			popup.y += Math.ceil((document.body.scrollTop - popup.y+20)/5);
		if(popup.y - document.body.scrollTop+330>document.body.clientHeight)
			popup.y -= Math.ceil((popup.y - document.body.scrollTop +330 - document.body.clientHeight)/5);
		
		if(popup.y > popup.bottomY)
			popup.y = popup.bottomY;
		if(popup.y < popup.topY)
			popup.y = popup.topY;
		popup.rePos(posx, popup.y);
		popupContent.rePos(posx, popup.y);
		//if(hideControlPanel!=1)
			setTimeout("rePos()", 10);
	}
	popup.rePos =  function(x,y){this.style.top=y;this.style.left=x;};
	popupContent.rePos = function(x,y){this.style.top=y;this.style.left=x;};
	popup.y = pos;
	popup.bottomY = bottomY;
	popup.topY = posy;
	rePos();
}
function ReportPrice() 
{
	var selects = document.getElementsByTagName('select');
	for (var i=0; i < selects.length; i++) {
		selects[i].style.visibility = 'hidden';
	}
	doPopup();
	return false;
}
function ReportOn(vendor, price, reportID) {
	   document.getElementById('Merchant').value = vendor;
	   document.getElementById('Price').value = price;
	   document.getElementById('reportID').value = reportID;
}
function CSSUpdate(cssClass,cssName,cssValue) {
	var cssRules;
	if (document.all) cssRules = 'rules';
	else if (document.getElementById) cssRules = 'cssRules';

	for (var S = 0; S < document.styleSheets.length; S++){
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++){
			if (document.styleSheets[S][cssRules][R].selectorText == cssClass) {
				document.styleSheets[S][cssRules][R].style[cssName] = cssValue;
				return;
				}
		}
	}
}
function setStyle(objId, style, value){
   document.getElementById(objId).style[style]= value;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function launchImageViewer(newUrl, vwrHeight, vwrWidth)
{ 
    var heightParam = vwrHeight;
    var widthParam = vwrWidth;
    var scrollbarsParam = 'no';
    var nonDefaultParams = '';    
    if (600>=screen.availHeight)
    {
		heightParam = Math.floor(screen.availHeight * .9);
		widthParam += 20;
		scrollbarsParam = 'yes';
		nonDefaultParams += ',top=0';		
		if (isIe7())
		{
			heightParam -= 25;
			widthParam += 4;
			var centeredLeft = Math.floor((screen.availWidth - widthParam)/2);
			nonDefaultParams += ',left=' + centeredLeft;
		}
    }    
    var w=window.open(newUrl, '_blank', 'height=' + heightParam + ',width=' + widthParam + ',status=yes,toolbar=no,location=no,menubar=no,directories=no,history=no,resizable=no,scrollbars=' + scrollbarsParam + nonDefaultParams); 
}

function isIe7()
{
	var ie7 = false;
	var nua = navigator.userAgent;
	var op = (nua.indexOf('Opera') != -1);
	if ((nua.indexOf('MSIE') != -1) && !op)
	{	
		var str_pos = nua.indexOf('MSIE');
		var nu = nua.substr(str_pos+5, 3);		
		ie7 = (nu.substring(0,1)==7);
	}	
	return ie7;
}


/* Function to form the Mail To link on the page */
function GetMailToLink(linkId, subject, greeting, defaultMsg, conclusion, url)
{
    var mailToString = "";
    
    /* 
        Removing white spaces from the url if any
    */    
    if(!url)
    {
        url = location.href;
    }
    else
    {
        while (url.substring(0,1) == ' ')
        {
            url = url.substring(1, url.length);
        }
        
        while (url.substring(url.length-1, url.length) == ' ')
        {
            url = url.substring(0,url.length-1);
        }
        
        if(url == '')
        {
            url = location.href;
        }
    }
    
    var targetURL = url;
      
    /* Forming the mail to string*/                 
    mailToString = escape("mailto:?subject=" + subject + "&body=" + greeting);
    mailToString = mailToString + escape("%0A%0A" + defaultMsg);
    mailToString = mailToString + escape("%0A%0A" + targetURL);
    mailToString = mailToString + escape("%0A%0A" + conclusion);       

    linkId.href = unescape(mailToString);    
}	

// variables for all slideshows 
var xsSlides = new Array(new Array(),new Array(),new Array());	// *** multi-dimensional array to store image src, alt, and captions
var xsSlideIndex;			// *** tracks current slide index number 
var xsSlideHasCap;			// *** true to display Captions *** PASS values in page-embedded script

var xsSlideURL = new Array();		// *** slideshow images 
var xsSlideCAP = new Array();		// *** slideshow captions
var xsSlideALT = new Array();		// *** slideshow alt text
var xsSlideStart;			// *** starting slide index number, -1 for random start *** PASS values in page-embedded script
var xsInterval = 4000;

// initializes user-navigable slideshow 
function xsStartSlideshow(bCap, iStart, bAuto)								
{	
	xsSlideHasCap = bCap;
	if (iStart > -1) 
		xsSlideIndex = iStart;
	else
		xsSlideIndex = xsGetRandomIndex(xsSlides.length);
	if (document.images.xsSlideImage) {
		document.xsSlideImage.src = xsSlides[xsSlideIndex][0];
		document.xsSlideImage.alt = xsSlides[xsSlideIndex][1];
		xsSwapLink();
		if(xsSlideHasCap) xsDisplayCaption();
		xsLoadAllSlides();
	}
	if (bAuto)
		self.setInterval("xsNextSlide()", xsInterval);
	return false;
}

// swaps the href of the slide link
function xsSwapLink()
{	
	var link;
	if (document.all)
		link = document.all.xsSlideLink;
	else if (document.getElementById)
		link = document.getElementById("xsSlideLink");
	if (link != undefined)
		link.href = xsSlides[xsSlideIndex][3];
}

// loads all slides in the array
function xsLoadAllSlides()
{	
	for (i=0;i<xsSlides.length;i++) {
		eval("img" + i + " = new Image()");
		eval("img" + i + ".src = '" + xsSlides[i][0] + "'");
	}
	return false;
}

// displays captions for any slideshow *** DO NOT EDIT 
function xsDisplayCaption()
{
	var cap = "&nbsp;";
	if(typeof(xsSlides[xsSlideIndex][2]) != "undefined") cap = xsSlides[xsSlideIndex][2];
	if(document.all)
		document.all.xsSlideCaption.innerHTML = cap;
	else if(document.getElementById)
		document.getElementById("xsSlideCaption").innerHTML = cap;
	return false;
}

// moves to next index in user-navigable slideshow 
function xsNextSlide()									
{
	xsSlideIndex = (xsSlideIndex < (xsSlides.length-1))? ++xsSlideIndex : xsSlideIndex = 0;
	document.xsSlideImage.src = xsSlides[xsSlideIndex][0];
	document.xsSlideImage.alt = xsSlides[xsSlideIndex][1];
	xsSwapLink();
	if(xsSlideHasCap) xsDisplayCaption();
	return false;
}

// moves to previous index in user-navigable slideshow 
function xsBackSlide(arrayname)								
{
	xsSlideIndex = (xsSlideIndex >= 1)? --xsSlideIndex : xsSlides.length-1
	document.xsSlideImage.src = xsSlides[xsSlideIndex][0];
	document.xsSlideImage.alt = xsSlides[xsSlideIndex][1];
	xsSwapLink();
	if(xsSlideHasCap) xsDisplayCaption();
	return false;
}

// gets a random number 
function xsGetRandomIndex(iMax) {
	var randomNum = Math.random();
	randomNum = randomNum * iMax;
	randomNum = parseInt(randomNum);
	if(isNaN(randomNum)) randomNum = 0; // for Netscape
	return randomNum;
}

// functions for homepage slideshow (fade transitioning, automated, user-navigable)
var xsHomeInterval = 7500;
var xsTimeout;
var filterobj, filtersupp, blenddelay;

function xsStartHomeSlides() {
	filterobj= document.getElementById("xsHomeSlides");
	filtersupp = filterobj.filters;
	blenddelay=(filtersupp)? filterobj.filters[0].duration*1000 : 0;
	xsSlideIndex = xsGetRandomIndex(xsHomeSlides.length);
	xsShowHomeSlide();
}
function xsShowHomeSlide() {
	if (filtersupp)
		filterobj.filters[0].apply()
	for(i=0;i<xsHomeSlides.length;i++) {
		document.getElementById(xsHomeSlides[i]).style.display = (i==xsSlideIndex)?"block":"none";
	}
	if (filtersupp)
		filterobj.filters[0].play();
	xsTimeout = window.setTimeout('xsNextHomeSlide()', xsHomeInterval+blenddelay);
}
function xsBackHomeSlide() {
	clearTimeout(xsTimeout);
	xsSlideIndex = (xsSlideIndex >= 1)? --xsSlideIndex : xsHomeSlides.length-1;
	xsShowHomeSlide();
}
function xsNextHomeSlide() {
	clearTimeout(xsTimeout);
	xsSlideIndex = (xsSlideIndex < (xsHomeSlides.length-1))? ++xsSlideIndex : 0;
	xsShowHomeSlide();
}


// BUG ID: 19999 Start
	var RSxmlhttp = null;
	var RSxmlDoc = null;
	var RSxmlres = null;

	function createRequest()
	{     
		var reqObj = null;      

		try 
		{           
			reqObj = new ActiveXObject("Msxml2.XMLHTTP");   
		}
		catch (err)      
		{           
			try 
			{                 
				reqObj = new ActiveXObject("Microsoft.XMLHTTP");            
			}
			catch (err2) 
			{                 
				try 
				{                       
					try 
					{                           
						netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");                        
					}
					catch (e) 
					{                           
						/* alert("Permission UniversalBrowserRead denied."); */
					}                       
					reqObj = new XMLHttpRequest();
				}
				catch (err3) 
				{                       
					reqObj = null;                
				}           
			}     
		}     

		return reqObj;

	}


	function showRelatedKeywords(val)
	{
		return;
		if ( val.length == 0 )
		{
			var divRelSearch = document.getElementById("relSearch");
			divRelSearch.style.display = "none";
			return true;
		}
			
		var splitKeywords  =  val.split("|");
		var shopHandlerURL = splitKeywords[0];
		var RelatedKeyUrl = splitKeywords[1];
		var Support = splitKeywords[2].replace('&gt;', '>');
		var Score = splitKeywords[3].replace('&gt;', '>');;
		var NoOfKeywords = splitKeywords[4];
		var searchText = document.getElementById('searchText');

		if(searchText)
		{
			var KWDSWSUrl = shopHandlerURL + "?url=" + RelatedKeyUrl + "?" + "term=" + searchText.value  + "|maxTermsPerTerm=" + NoOfKeywords + "|includeStatistics=false|filter=" + Support + " " +Score;
			getRelatedSearchURL(KWDSWSUrl,RSCallback,true);
		}
	}

 

	function LoadXMLDE()
	{

		loadRSXML();
		var root = null;
		root = RSxmlDoc.documentElement;

		var x = root.getElementsByTagName('Term');
		
		for (i=0;i<x.length;i++)
		{
			if(i == 0)
			{
				searchTerm = x[i].childNodes[0].nodeValue;
			}
			else
			{
				searchTerm += "|" + x[i].childNodes[0].nodeValue;
			}
		}
					
			
		/*pageNodes = root.selectNodes("SearchTermSuggestion/Term");
		var searchTerm = null;

		for(var i = 0; i < pageNodes.length;i++)
		{
			if(i == 0)
			{
				searchTerm = pageNodes[i].text;
			}
			else
			{
				searchTerm += "|" + pageNodes[i].text;
			}
		}*/

		BuildRelatedSearchHTML(searchTerm);

	}

	function BuildRelatedSearchHTML(searchTerm)
	{

		var searchTerm = searchTerm.split("|");
		var Host = "http://" + window.location.hostname + ((window.location.port != "") ? ":" + window.location.port : "") + "/";
		var host1 = Host + "results/shp/?text=";
		var div = document.getElementById("relSearch");
		var rS = document.createTextNode("Related searches: ");

		div.appendChild(rS);
		
		for(var idx = 0; idx < searchTerm.length ; idx++ )
		{
			var keywordAnchor = document.createElement("a");
			var linkText = document.createTextNode(searchTerm[idx]);
			
			keywordAnchor.setAttribute("href",host1 + searchTerm[idx] + "&pagelink=rl");
			keywordAnchor.appendChild(linkText);
			
			div.appendChild(keywordAnchor);
			
			if ( idx != searchTerm.length - 1 )
			{
				var gap = document.createTextNode(", ");
				div.appendChild(gap);
			}
		}

		//div.className = "headerDiv leftAndCenterPane";
		div.style.display = "block";

	}

	function getRelatedSearchURL(url, callback, isAsync)
	{     

		if (RSxmlhttp != null) 
		{           
			if (RSxmlhttp.readyState != 4 && RSxmlhttp.readyState != 0)
			RSxmlhttp.abort();      
		}     

		RSxmlhttp = createRequest();  

		if (RSxmlhttp != null) 
		{           
			RSxmlhttp.open("GET", url,true);
			RSxmlhttp.onreadystatechange=RSCallback;        
			RSxmlhttp.send(null);
		}

	}

	function RSCallback()
	{     
		if (RSxmlhttp.readyState == 4) 
		{
			if(RSxmlhttp.status == 200)
			{
				RSxmlres = RSxmlhttp.responseText;
				
				if ( RSxmlres.indexOf("<SearchTermSuggestion>") != -1 )
				{
					LoadXMLDE();
				}else
				{
					var divRelSearch = document.getElementById("relSearch");
					divRelSearch.style.display = "none";
				}
			}           
		}
	}

      

	function loadRSXML()
	{
		if (window.ActiveXObject)
		{
			RSxmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			RSxmlDoc.async="false";
			RSxmlDoc.loadXML(RSxmlres);
		}
		// code for Mozilla, Firefox, Opera, etc.
		else
		{
			var parser=new DOMParser();
			RSxmlDoc = parser.parseFromString(RSxmlres,"text/xml");
		}
	}

// BUG ID: 19999 End

// BUG ID 20695 List and Guides


// List and Guides Started

function slideIn(div) {
	var min = 18;
    var max=100;
	var height = (div.style.height == '') ? parseInt(div.offsetHeight) : parseInt(div.style.height);
	// Hack - Firefox hasn't rendered the refinements pain when the shrinker is wired up.  Therefore, the max value is bogus.
	if (height > max) {max = height;}
//	var he = height - min;
	div.style.height = min + "px";
	div.style.overflow = "hidden";
}

function SlideOut(div,copyhe){
	var min = 18;
	var intervalID = null;
	var height = (div.style.height == '') ? parseInt(div.scrollHeight?div.scrollHeight:div.offsetHeight) : parseInt(div.style.height);
	if( copyhe  < 22 )  
	{div.style.height =  div.scrollHeight + "px";	
	}else{div.style.height =  copyhe + "px";}
	div.style.overflow = 'visible';
	div.style.height = 'auto';
}

function getposOffset(overlay, offsettype){
	var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
	var parentEl=overlay.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

// For xmlhtttp post method

var subobj = null;
var itemId = null;
var itemName = null;
var itemIdTemp = null;
var itemNameTemp = null;
var IsOverlay = null;
// For xmlhtttp post method
function setlistsOverLay(globVar)
{
var globParms = globVar.split("|");
defListNmGL = globParms[0];
linkDetGL = globParms[1];
linkMoreDetGL = globParms[2];
linkUrlGL = globParms[3];
shopUrlGL = globParms[4];
IsOverlay = globParms[5];
}
function overlay(curobj, e, subobjstr, opt_position,itemId,itemName,globVar){
setlistsOverLay(globVar);
	if (document.getElementById){
		subobj=document.getElementById(subobjstr);
			subobj.style.display=(subobj.style.display!="block")? "block" : "none"
			var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0) 
			var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0)
			subobj.style.left=xpos+"px";
			subobj.style.top=ypos+"px";
		//Code added for hiding the AddToList pop-up
		e = (e) ? e : window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) 
			e.stopPropagation();

}
itemIdTemp = itemId ;
itemNameTemp = itemName; // need tuning
// Hack - Firefox rendered one extra div.  Therefore, the max value is bogus.

	if(IscookAuthGL == 1)
		{showPostListName();}
	else
		{showListNamecookie();}
}
function showPostListName()
{
subobj.innerHTML = '';
var check = allListNames();
	for(var idx = 0; idx < check.length ; idx ++)
	{var link = "<div align=left class=listItem1><a href='#' onclick='addItemToList(this);overlayclose();' style=\"outline:none;\">" + check[idx] + "</a></div>";
	subobj.innerHTML = subobj.innerHTML + link;
	} 
}
function showListNamecookie()

{

subobj.innerHTML = '';

var link = "<div align=left class=listItem1><a href='#' onclick='addItemToCokkieList(this);overlayclose();' style=\"outline:none\">" + defListNmGL + "</a></div>";

subobj.innerHTML = subobj.innerHTML + link; 

}
// For xmlhtttp post method

function overlayclose(){
	document.getElementById('listNames').style.display="none";	
}

//itemId = Product ID
//ItemName = Product Name
function addItemToList(link){	
	var listName = link.innerHTML;	
	addShoppingListItem('',listName,'',itemIdTemp,itemNameTemp,'','','',0,false,false,'','');
}

function addItemToCokkieList(link){	//For cookie List
	var listName = link.innerHTML;	
	if(!IscookieDup(itemIdTemp))
	{
	 saveItemCookie(itemIdTemp,defaultListName);
	//Add Item in Default Lists.
	//removeparagraph
		RemoveParagraph(defaultListName);
		itemNameTemp = unescape(itemNameTemp);
		itemNameTemp = NewReplaceAll(itemNameTemp,"@@@","'");	
		itemNameTemp = NewReplaceAll(itemNameTemp,"+"," ");	
		setDivListItems(itemIdTemp,itemNameTemp,defaultListName);
		// remove addexpandcollapse	
		RemoveexpandCollapse(defaultListName);
		AddexpandCollapse(defaultListName);
	} 
}

function NewReplaceAll(argvalue, x, y) 
{
	
  if ((x == y) || (parseInt(y.indexOf(x)) > -1)) 
  {
    errmessage = "replace function error: \n";
    errmessage += "Second argument and third argument could be the same ";
    errmessage += "or third argument contains second argument.\n";
    errmessage += "This will create an infinite loop as it's replaced globally.";
    alert(errmessage);
    return false;
  }
    
  while (argvalue.indexOf(x) != -1) 
  {
    var leading = argvalue.substring(0, argvalue.indexOf(x));
    var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, 
	argvalue.length);
    argvalue = leading + y + trailing;
  }

  return argvalue;
}

function AddexpandCollapse(myList)
{
var img = myList + "_col";
var ddimg = document.getElementById(img);
var div1 = document.getElementById(myList);
var copyhe = parseInt(div1.offsetHeight);
ddimg.onclick = function(){exapndCollapse(div1,ddimg,copyhe);};

}
function RemoveexpandCollapse(myList)
{
var img = myList + "_col";
var ddimg = document.getElementById(img);
ddimg.removeAttribute("onclick");

}
function RemoveParagraph(myList)
{
	var noItmsid = myList + "_noItems";
	var divNoItms = document.getElementById(noItmsid);
	var div = document.getElementById(myList);
	if(divNoItms)
	{
	div.removeChild(divNoItms);
	}
	var detId = myList + "_Details";
	var detDiv = document.getElementById(detId);
	if(detDiv)
	{
	div.removeChild(detDiv);
	}
}
function AddDivList(myList,myListId){ 

        var divContainer = document.getElementById('shp_List_Container');        

	    var div1 = document.createElement("div");
	    div1.id  = myList;
	    div1.style.height = "";
    	
    	var divTitle = document.createElement("div");
    	divTitle.className = "b_list_Title";
    	
		var divt = document.createElement("div");
		divt.className = "list_title_1";
		divt.style.styleFloat = "left";
		divt.style.cssFloat = "left";		
		divt.innerHTML = truncate(myList, 22, "...");
    	divTitle.appendChild(divt);
		
		if(myListId != 0)
		{
			var ddList = document.createElement("div");
			var lId = myList + "_Id";
			ddList.id = lId;
			ddList.innerHTML = myListId;
			ddList.style.display = "none";
			divTitle.appendChild(ddList);
		}
		var ddimg = document.createElement("img");
		ddimg.className = "list_title_1";
		var img = myList + "_col";
		ddimg.id = img;
		ddimg.src = "/img/collapse.gif";
		ddimg.style.cursor = "pointer";
		ddimg.style.styleFloat = "right";
		ddimg.style.cssFloat = "right";
		divTitle.appendChild(ddimg);
		
		var div2 = document.createElement("div");
		div2.style.clear = "right";
	    divTitle.appendChild(div2);
		div1.appendChild(divTitle);
		
		var divDivider = document.createElement("div");
		divDivider.className = "divider";
		div1.appendChild(divDivider);
		
		//Haroon
		 var div = document.createElement("div");
        div.id = myList + "_noItems";           
        div.className = "b_list_div";
    	var p2 = document.createElement("p");
		p2.className = "b_list_p";
		p2.innerHTML = noItmsDivMsGL;
		div.appendChild(p2);
	 	div1.appendChild(div);	
	 	
	 	var divp = document.createElement("div");
		divp.className = "b_list_div";
        var iddiv= myList + '_Details';
		divp.id = iddiv;
		var p3 = document.createElement("p");
		p3.className = "b_list_p";
		var a = document.createElement("a");
		a.className = "context_link";
		a.innerHTML = linkDetGL;
		a.style.cursor = "hand";
		if(myListId != 0)
		{
		    a.href = shopUrlGL + '/ListManager/shp/?ListId='+ myListId;	
		}
		else
		{
		    a.href = shopUrlGL + '/ListManager/shp/?ListId='+ myList;	
		}
		p3.appendChild(a);
		divp.appendChild(p3);
		div1.appendChild(divp);
		
		var divguid = document.getElementById('YourGuid'); 
		if(divContainer !=null)
		{
        if(divguid != null){
				divContainer.insertBefore(div1,divguid);}
				else{
		divContainer.appendChild(div1);}
		}
}

function exapndCollapse(div,img,copyhe){
	if(div.style.overflow == 'hidden'){
		img.src = '/img/collapse.gif';		
		SlideOut(div,copyhe);	
	}
	else{
		img.src = '/img/expand.gif'; 
		slideIn(div);
	}
}

function setDivListItems(itemid,itemName,listName){
	var div1 = document.getElementById(listName);
	
     if(div1.childNodes.length == 5)
		return;
	
	var divLength = div1.childNodes.length
	var itemIDD = itemid;	
	var listDivName = 'divList' + listName ;
	var listDiv = document.getElementById(listDivName);
	
	var listDivId = listName + '_Id' ;
	var listIDEl = document.getElementById(listDivId);
	var listID = null;
	if(listIDEl)
	{
	  listID = listIDEl.innerHTML;
	}
	else
	{
	  listID = listName; // For Cookie
	}
	
	if(listDiv == null){
		listDiv = document.createElement("div");
		listDiv.id = listDivName;
		div1.appendChild(listDiv);		
	}
	
	var listlen = listDiv.childNodes.length;
	if(listlen == 5){
		var divLink = document.createElement("div");
		divLink.className = "b_list_div";
		divLink.id = 'mailLink';
		var p4 = document.createElement("p");
		p4.className = "b_list_p";
		var a3 = document.createElement("a");
		a3.id = 'SeeAllItems';
		a3.className = "context_link";			
		a3.innerHTML = linkMoreDetGL;
		a3.style.cursor = "hand";		
		a3.href = shopUrlGL + '/ListManager/shp/?ListId='+ listID;
		p4.appendChild(a3);
		divLink.appendChild(p4);
		var clearDiv = document.createElement("div");
		clearDiv.style.clear = "right";
		divLink.appendChild(clearDiv);
		listDiv.appendChild(divLink);
		//return ;
    }
	
	
	if(listlen < 5 && itemName)
	{
	var ItemNameList1 = itemName;	
	var div2 = document.createElement("div");
	div2.className = "b_list_div2";
	div2.id = itemIDD;
    var div3 = document.createElement("div");
	div3.className = "b_list_div3";			
	var dumurl =  shopUrlGL + '/Prices/shp/?itemId=' + itemIDD;
	var link = document.createElement('a');
	link.setAttribute('href',dumurl);
	link.innerHTML = truncate(ItemNameList1, 25, "...");
	div3.appendChild(link);
	div2.appendChild(div3);	    
	var div5 = document.createElement("div");
	div5.className = "b_list_div5";
	div2.appendChild(div5);
	
		if(listDiv.childNodes[0] != null)
			listDiv.insertBefore(div2,listDiv.childNodes[0]);
		else
			listDiv.appendChild(div2);
	}
	else if((listlen == 5 || listlen > 5) && itemName)
	{
	var ItemNameList1 = itemName;	
	var div2 = document.createElement("div");
	div2.className = "b_list_div2";
	div2.id = itemIDD;
    var div3 = document.createElement("div");
	div3.className = "b_list_div3";			
	var dumurl = shopUrlGL +  '/Prices/shp/?itemId=' + itemIDD;
	var link = document.createElement('a');
	link.setAttribute('href',dumurl);
	link.innerHTML = truncate(ItemNameList1, 25, "...");
	div3.appendChild(link);
	div2.appendChild(div3);	    
	var div5 = document.createElement("div");
	div5.className = "b_list_div5";
	div2.appendChild(div5);
	
		if(listDiv.childNodes[4] != null && listDiv.childNodes[0])
		{	listDiv.removeChild(listDiv.childNodes[4]);
			listDiv.insertBefore(div2,listDiv.childNodes[0]);
	    }
	}
	
	
	var detName = listName + "_Details";	
	var listDiv = document.getElementById(detName); //haroon
	
	if(divLength == 2 || !listDiv){
		var div = document.createElement("div");
		div.className = "b_list_div";
		var iddiv= listName + '_Details';
		div.id = iddiv;
		var p3 = document.createElement("p");
		p3.className = "b_list_p";
		var a = document.createElement("a");
		a.className = "context_link";
		a.innerHTML = linkDetGL;
		a.style.cursor = "hand";
		a.href = shopUrlGL + '/ListManager/shp/?ListId='+ listID;	
		p3.appendChild(a);
		div.appendChild(p3);
		
		div1.appendChild(div);
		
	}
}


function RemoveDivItem(itemId,obj){
	var mainParentNode = null;
	var parentDivNode = obj.parentNode.parentNode.parentNode;
	var childDivNode = 	obj.parentNode.parentNode;
	
	parentDivNode.removeChild(childDivNode);	
	
	if(parentDivNode.children.length == 0){
		mainParentNode =  parentDivNode.parentNode;		
		
		if(mainParentNode.children[5] != null) // When More Link Exists
			mainParentNode.removeChild(mainParentNode.children[5]);	
			
		mainParentNode.removeChild(mainParentNode.children[4]);	
		mainParentNode.removeChild(mainParentNode.children[3]);	
		mainParentNode.removeChild(mainParentNode.children[2]);	
	}
}

function RemoveAllDivItem(obj){
	var parentDivNode = obj.parentNode.parentNode.parentNode;
	if(parentDivNode.childNodes[5] != null) // When More Link Exists
			parentDivNode.removeChild(parentDivNode.childNodes[5]);
	i = 4;
	do{
		childDivNode = 	parentDivNode.childNodes[i];
		parentDivNode.removeChild(childDivNode);	
		i --;	
	
	}while(i >= 2);
}

// For xmlhtttp post method
var obj = null;
// For xmlhtttp post method
function setlistsopenWin(globVar)
{
var globParms = globVar.split("|");
noItmsDivMsGL = globParms[0];
linkDetGL = globParms[1];
linkMoreDetGL = globParms[2];
linkUrlGL = globParms[3];
shopUrlGL = globParms[4];
}

function openwin(obj,globVar){
    if(globVar != null)
    {
      setlistsopenWin(globVar);
    }
    obj = obj; 
    openPostWin();  
}
// For xmlhtttp post method
function openPostWin()
{
	if(IscookAuthGL == 0){
			var href= document.getElementById('signinUrl').innerText;
			document.location.href = href;
		}else{
			var obj=document.getElementById('Win');	
			var txt = document.getElementById('txtListName');
			obj.style.display=(obj.style.display!="block")? "block" : "none";
			obj.style.left= ((screen.availWidth/2)-150) + "px";
			obj.style.top=((screen.availHeight/2) - 95) + "px";
			txt.focus();
			txt.value = '';
			//divErrorobj.innerHTML = '';
		}
	
	return false;
}
var addStatus = 0;
// For xmlhtttp post method
function setDefaultListParams(listName,listType,mes){
	var listId='';	
	var listType=listType;
	var listDescription='';
	var listSharingLevel = 'Private';
	var listAddToMsnSpace=false;
	var listDisplayOrder=9;
	var ListIsDefaultList=false;
	var listCollapsed=false;
	
	addShoppingList(listId,listName,listType,listDescription,listSharingLevel,
	listAddToMsnSpace,listDisplayOrder,ListIsDefaultList,listCollapsed);
		
}
var Winobj = null;
var divErrorobj=null;
function setCloseGV(globVar)
{
var globParms = globVar.split("|");
noItmsDivMsGL = globParms[0];
linkDetGL = globParms[1];
linkMoreDetGL = globParms[2];
linkUrlGL = globParms[3];
shopUrlGL = globParms[4];
NoListNmGL = globParms[5];
dupListGL = globParms[6];
unAuthGL = globParms[7];
errMsGL = globParms[8];
}

function closePopup(isCancel,glbParm){
	setCloseGV(glbParm);
	Winobj=document.getElementById('Win');
	//divin=document.getElementById('Win');
	var listName='';
	divErrorobj = document.getElementById('DivErrorMsg');
	if(isCancel == 'false'){
	listName = Trim(document.getElementById('txtListName').value);
	
	if(listName == '')
		alert(NoListNmGL);
	else
		setDefaultListParams(listName,'User',0);
		//Winobj.style.display=(Winobj.style.display!="block")? "block" : "none";
		}
	else{
		if(divErrorobj.innerHTML != '')
		{
			divErrorobj.innerHTML = '';
			divErrorobj.style.display=(divErrorobj.style.display!="block")? "block" : "none";
		}
	
		Winobj.style.display=(Winobj.style.display!="block")? "block" : "none";
	}
}

/*      Code added for Multilist.js*/


/*      Code added for XMLParser.js*/

var xmlDoc=null;
var xmlhttp=null;

function loadXMLString(xmlString){
// code for IE
	if (window.ActiveXObject){
	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async="false";
	if(xmlString)
	{
	xmlDoc.loadXML(xmlString);
	return true;
	}
	else
	{
	xmlDoc = null;
	return false;
	}
	
	}
	// code for Mozilla, Firefox, Opera, etc.
	else{
		var parser=new DOMParser();
		xmlDoc=parser.parseFromString(xmlString,"text/xml");
	    return true;			
	}
}

function getListCount(){
	return xmlDoc.childNodes[0].childNodes.length;
}

function getListName(index){
	var arrListNode = new Array();
	if(index >= 0){
		arrListNode[0] = xmlDoc.childNodes[0].childNodes[index].childNodes[0].childNodes[0].nodeValue; //ID
		arrListNode[1] = xmlDoc.childNodes[0].childNodes[index].childNodes[1].childNodes[0].nodeValue; // Name	
	}
	return arrListNode;
	
}

function getListItemCount(listIndex){
	return xmlDoc.childNodes[0].childNodes[listIndex].childNodes[9].childNodes.length;
}

function getListItemNode(listIndex,listItemIndex){
	return xmlDoc.childNodes[0].childNodes[listIndex].childNodes[9].childNodes[listItemIndex].childNodes;
}

function findRecentAddList(listName){
	var i=0;		
	var listCount = xmlDoc.childNodes[0].childNodes.length;
	var nodeVal=null;
	for(i=0 ; i < listCount ; i++){
		try{
		nodeVal = xmlDoc.childNodes[0].childNodes[i].childNodes[1].childNodes[0].nodeValue;
		}catch(e){
			nodeVal = null;
		}
		if(nodeVal != null){
			if(nodeVal.toLowerCase() == listName.toLowerCase())
				return i;
		}		
	}	
	return i-1;
}

function isDuplicate(listName){
	var arrList = getListName(findRecentAddList(listName));
	if(arrList.length > 0 ){
		if(arrList[1].toLowerCase() == listName.toLowerCase())
			return true; // Duplicate List Found in Returing XML.
		else
			return false;  // Duplicate List Not Found.
	}
	else
		return false;  // Duplicate List Not Found.
}
var idxx = 0;
var ItemIDList1 =null;
var cooklen = null;
var ItemNameList1 = null;
var cookiItems = null;
var defaultListName = null;
// for Global
var IscookAuthGL = null;
var defListNmGL = null;
var noItmsDivMsGL = null;
var linkDetGL = null;
var linkMoreDetGL = null;
var linkUrlGL = null;
var shopUrlGL = null;
var NoListNmGL = null;
var dupListGL = null;
var unAuthGL = null;
var ueErrGL = null;
var showList = null;
var dupErrItm = null;
// for End Global
function setlistsResultsVar(globVar)
{
var globParms = globVar.split("|");
IscookAuthGL = globParms[0];
defListNmGL = globParms[1];
defaultListName = defListNmGL;
noItmsDivMsGL = globParms[2];
linkDetGL = globParms[3];
linkMoreDetGL = globParms[4];
linkUrlGL = globParms[5];
shopUrlGL = globParms[6];
showList = globParms[7];
ueErrGL = globParms[8];
dupErrItm = globParms[9];
}
function showlistsResults(globVar)
{
setlistsResultsVar(globVar);
		if (showList == 1)
		{
if(IscookAuthGL == 0)
{
  // create default List	when user is not authenticated.
  AddDivList(defaultListName,0);
  //show cookie Item.
  showCookieListItem(); // Calling remove Paragraph from this function
  AddexpandCollapse(defaultListName); //Haroon

}
else
{
  // Add Default List
  setDefListPrmsResults(defaultListName,'Shopping');
				}
		}
		else
		{
		var divCreateLnk = document.getElementById('create_List_Container');
			if(divCreateLnk)
			{
			divCreateLnk.style.display = "none";
			}
		}
}
function setDefListPrmsResults(listName,listType){
	var listId='';	
	var listType=listType;
	var listDescription='';
	var listSharingLevel = 'Private';
	var listAddToMsnSpace=false;
	var listDisplayOrder=0;
	var ListIsDefaultList=false;
	var listCollapsed=false;

	callListService((getParameters('ADDLIST',listId,listName,listType,listDescription,listSharingLevel,listAddToMsnSpace,listDisplayOrder,ListIsDefaultList,listCollapsed)),addShoppingDefaultList);	
}
function addShoppingDefaultList()
{
 if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       AddCookieItems();}
   }
}
function AddCookieItems()
{
var val = getCookie('prodIDList');
if (val && val.length > 0)
{
getItemsResults(val);
}	
else
{
// CAll Showlists
showLists();
}
}
function getItemsResults(val)
{
	ItemIDList1 = val.split("|");
	cooklen = ItemIDList1.length;
    var url = shopUrlGL + '/ListManager.aspx?getCookie=' + 'KA'; // List Manager Page
    getURL(url,cookiecallback, true);
}

function cookiecallback()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
      cookiItems = xmlhttp.responseText;
      xmlhttp = null;
      dumbCookieItems();}
   }
}

function dumbCookieItems()
{

	if (idxx == 0)
	{
	 	ItemNameList1 = cookiItems.split("|");
    }

 if(idxx < ItemIDList1.length)
 {
 itemNamecook = ItemNameList1[idxx];
 itemIdcook = ItemIDList1[idxx];
 callListService((getParameters('ADDLISTITEM','',defaultListName,'','','Private',false,0,false,false,itemNamecook,'','','',1,false,false,'','',itemIdcook)),dumbCookieItemsPost);
 }
 else
 {
  // Delete Cookie Items
  deleteCookie('prodIDList');
  showLists();
 }
}
function dumbCookieItemsPost()
{

if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
           idxx  = idxx + 1;
           xmlhttp = null;
           dumbCookieItems();}
   }
   else
   {
   }
}
function deleteCookie(name)
{
     var expires = GetExpireDate();
    if (getCookie(name))
    {
        document.cookie = name + "=" + ";expires=" + expires + ";path=/";
    }
}

function showLists(){
	callListService((getParameters('GETALLLISTS',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),showListcallback);
}

function showListCalBack()
{
 if(loadXMLString(xmlhttp.responseText))
	{ 
	 if(isStatus())
	 {
	   	  	var listCount = getListCount();
			if(listCount > 0){
				var i = 0;
				var arrListNode = new Array();
				for (var i=0; i < listCount ; i++){
					arrListNode = getListName(i);			
					AddDivList(arrListNode[1],arrListNode[0]); // 1250
					showListItem(i,arrListNode[0],arrListNode[1]);
					AddexpandCollapse(arrListNode[1]); //Haroon	
				}
			} // List Count
	
			var isOpenListWin = queryString('type');
			if(isOpenListWin == 'listsettings'){
				openwin(null,null); // for opening the list window after authentication.
			}
		
    }// Is Status
  }
}


function showCookieListItem(){
var val = getCookie('prodIDList');
if (val && val.length > 0)
{
getItemsName(val);
}	
}
var ItemIDList =null;
var len = null;
var idx = null;
function getItemsName(val)
{
	var values = val.split("|");
	len = values.length;
	idx =  ( len > 5 ) ? 5 : len ;
	if (val && val.length > 0)
	{
		for(var valIdx = 0; valIdx < idx; valIdx ++)
			{
				if( valIdx == 0)
				{
				ItemIDList = values[valIdx];
				}
				else
				{
				ItemIDList = ItemIDList + "|" +  values[valIdx];
				}
			}
	      var url = shopUrlGL +'/ListManager.aspx?itemIDList=' + ItemIDList;
          getURL(url,addCookieItmsCallBack, true);

        
 }
}

function cookieList()
{

        var valuesName = xmlres.split("|");
        var valuesIds = ItemIDList.split("|");
		listName = defaultListName;
		if(len>0) //Remove Haroon
  	    {
	    RemoveParagraph(listName);
	    }
		for(var Idx1 = 0; Idx1 < idx + 1; Idx1++)
		{
		    itemID = valuesIds[Idx1]; // Ins Item Id
			itemName = valuesName[Idx1]; // Item Name		
			setDivListItems(itemID,itemName,listName);
		}
}
function getCookie(name)
{
    var cookie = document.cookie;
    var prefix = name + "=";
    var begin = cookie.indexOf("; " + prefix);    
    //if its the only cookie
    if (begin == -1)
    {
        begin = cookie.indexOf(prefix);        
        if (begin != 0) return null;
    }
    else
    {
		//go two characters one for ";" and one for space " "
        begin += 2;
    }
    //find the length of the cookie
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = cookie.length;
    }
    //return the value
    return unescape(cookie.substring(begin + prefix.length, end));
}
function IscookieDup(itemIdTemp)
{
var val = getCookie('prodIDList');
if (val && val.length > 0)
		{
			var found = -1;
			var values = val.split("|");
			for(var valIdx = 0; valIdx < values.length; valIdx++)
				{
					if(values[valIdx] == itemIdTemp)
					{
					alert(dupErrItm);
					return true;
					}	
				}
		}
else
{
  return false;
}
}
function saveItemCookie(itemIdTemp,defaultListName)
{

var val = getCookie('prodIDList');
setCookieValues('prodIDList',itemIdTemp,val);

}
		

function setCookieValues(name,prodID,val) 	
{
     var expires = GetExpireDate();
     if (val && val.length > 0)
		{
    		var newvalue = val + "|" +prodID ; 
			document.cookie = name + "=" + escape(newvalue) + ";expires=" + expires + ";path=/";
  		}
	else
	{
		if (prodID)
		{
		  document.cookie = name + "=" + escape(prodID) + ";expires=" + expires + ";path=/" ;
         
        }
	}
	
}	
GetExpireDate = function ()
{
    var expireDate = new Date();
    expireDate.setMonth(expireDate.getMonth() + 1);
    return expireDate.toString();
};
function showListItem(listIndex,listId, listName){	
	var arrItem = new Array();	
	var itemNode =null;
	var itemIndex=0;
	listItemCount = getListItemCount(listIndex);
	if(listItemCount>0) //Haroon
	{
	RemoveParagraph(listName);
	}
	for (itemIndex=0; itemIndex < listItemCount ; itemIndex++){
		itemNode = getListItemNode(listIndex,itemIndex);
		if(itemNode != null){
			arrItem[0] = itemNode[6].childNodes[0].nodeValue; // Ins Item Id
			arrItem[1] = itemNode[1].childNodes[0].nodeValue; // Item Name		
			setDivListItems(arrItem[0],arrItem[1],listName);
		}
	}
}

function getParameters(actionName,listId,listName,listType,listDescription,listSharingLevel,
				listAddToMsnSpace,listDisplayOrder,ListIsDefaultList,listCollapsed,itemName,
				itemDescription,itemUri,itemImageUri,itemDisplayOrder,itemCollapsed,insItemCollapsed,
				insItemData,itemAnnotation,itemId){
				
	var parameters = 'ACTION=' + actionName;
	var insItemId=itemId;
	
	switch(actionName){
		case 'ADDLIST':			
			parameters += '&hidListId='				+ listId;
			parameters += '&hidListName='			+ listName;
			parameters += '&hidListType='			+ listType;
			parameters += '&hidListDescription='	+ listDescription;
			parameters += '&hidListSharingLevel='	+ listSharingLevel;
			parameters += '&hidListAddToMsnSpace='	+ listAddToMsnSpace;
			parameters += '&hidListDisplayOrder='	+ listDisplayOrder;
			parameters += '&hidListIsDefaultList='	+ ListIsDefaultList;
			parameters += '&hidListCollapsed='		+ listCollapsed;
			break;
		case 'DELETEALLITEMS':
			parameters += '&hidListId=' + listId; //Added on 29-09-2006
			parameters += '&hidListName=' + listName;
			break;
		case 'DELETELISTITEM':
			parameters += '&hidListName=' + listName + '&hidListItemId=' + itemId + '&hidinsItemId=' + insItemId;
			break;
		case 'GETALLLISTS':
			parameters = parameters;
			break;
		case 'ADDLISTITEM':
			parameters += '&hidListName='			+ listName;
			parameters += '&hidListDescription='	+ listDescription;
			parameters += '&hidItemName='			+ itemName;
			parameters += '&hidItemDescription='	+ itemDescription;
			parameters += '&hidItemUri='			+ itemUri;
			parameters += '&hidItemImageUri='		+ itemImageUri;
			parameters += '&hidListItemDisplayOrder='	+ itemDisplayOrder;
			parameters += '&hidListCollapsed='		+ itemCollapsed;
			parameters += '&hidinsItemId='			+ insItemId;
			parameters += '&hidinsItemData='		+ insItemData;
			parameters += '&hidItemAnnotation='		+ itemAnnotation;
			break;
		case 'DELETELIST':
			parameters += '&hidListId='				+ listId;
			parameters += '&hidListName='			+ listName;
			break;
			
		case 'GETLIST':
			parameters += '&hidListName='			+ listName;
			break;
	}
	return parameters;
}

var isAuth =false;
function isAuthenticated(){	
	var IsAuth = '<IsAuth>0</IsAuth>';
	if(IsAuth == xmlhttp.responseText){
		return false;
	}
	else if(xmlhttp.responseText == ""){
		return false;
	}
	else{
		isAuth = true;
		return true;
	}		
}

function isStatus(){
	var iStat = '<status>0</status>';
	if(iStat == xmlhttp.responseText){
	   	if(xmlDoc.childNodes[0].childNodes[0].nodeValue == '0')
		   {
			return false;}
		else
		   {
			return true;}
	}else
	  { 
		return true;}		
}
// For xmlhtttp post method
var shopListItemName = null;
var shopListName = null;
var shopItemID = null;
// For xmlhtttp post method

function addShoppingListItem(listId,listName,listDescription,itemId,itemName,itemDescription,itemUri,
				itemImageUri,itemDisplayOrder,itemCollapsed,insItemCollapsed,insItemData,itemAnnotation){
	
	itemName = unescape(itemName);
	itemName = NewReplaceAll(itemName,"@@@","'");	
	itemName = NewReplaceAll(itemName,"+"," ");	
	shopListItemName = itemName;
	shopListName = listName;
	shopItemID = itemId;
	callListService((getParameters('ADDLISTITEM','',listName,'',listDescription,'Private',false,0,false,false,itemName,itemDescription,itemUri,itemImageUri,itemDisplayOrder,itemCollapsed,insItemCollapsed,insItemData,itemAnnotation,itemId)),addShoppingCallBack);
	
}

// For xmlhtttp post method
function addShoppingPostListItem()
{
		if(loadXMLString(xmlhttp.responseText))
		{ // load XML.
		if(isAuthenticated()){
			if(!isDuplicateItem(shopListName,shopListItemName,shopItemID)){
				RemoveParagraph(shopListName); //Haroon 
		   		setDivListItems(shopItemID,shopListItemName,shopListName);
				RemoveexpandCollapse(shopListName);  //Haroon
				AddexpandCollapse(shopListName);  //Haroon	
			}	
			else
			{
				alert(dupErrItm);
			}
		}else{
			alert('UnAuthenticated User');
		}
		}
		
}

// For xmlhtttp post method
function setDelItemGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
}
function removeShoppingListItem(listName,itemId,globVar){
setDelItemGLVar(globVar);	
	callListService((getParameters('DELETELISTITEM',null,listName,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,itemId)),removeShopListCallBack);
	
}
// For xmlhtttp post method
function removeShoppingListPost()
{
		if(loadXMLString(xmlhttp.responseText))
		{ // load XML.
		if(isAuthenticated()){
					if(isStatus()){ // Check for Valid XML for List
						var href = document.location.toString();
		                href = stripHash(href);
						document.location.href = href;				
					}else{
						alert(ueErrGL);
					}
		}else{
			alert(unAuthGL);
		}
		}
	
}
// For xmlhtttp post method
function setDelAllGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
}
function removeShoppingListAllItems(listId,listName,globVar){
setDelAllGLVar(globVar);	
	callListService((getParameters('DELETEALLITEMS',listId,listName,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),remShopListAllCallback);	
}

// For xmlhtttp post method
function remShopListAllItemPost()
{
	if(loadXMLString(xmlhttp.responseText))
	{ // load XML.
	if(isAuthenticated()){
			if(isStatus()){ // Check for Valid XML for List	
		    	     var href = document.location.toString();
		            href = stripHash(href);   	
					document.location.href = href;
				}else{
					alert(ueErrGL);
				}
	}else{
		alert(unAuthGL);
	}
}
}
// For xmlhtttp post method
var delconfmMes = null;
function setDelGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
delconfmMes  = globParms[2];
}
function deleteList(listName,listId,globVar){	
    setDelGLVar(globVar);
    
   var answer = confirm (delconfmMes);
	if (!answer)
		return;
	else
		callListService((getParameters('DELETELIST',listId,listName,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),deleteListCallBack);
	
}
function deleteListPost()
{
	if(loadXMLString(xmlhttp.responseText))
	{ // load XML.
	if(isAuthenticated()){
			if(isStatus()){ // Check for Valid XML for List			       
					var href = document.location.toString();
					href = stripHash(href);
					href = href + "&DL=1";
					document.location.href = href;
				}else{
					alert(ueErrGL);
				}
			//}
	}else{
		alert('UnAuthenticated User');
	}
}	
}

// For xml Post
var addListName = null;
var addlistDisplayOrder = null;
var addlistId=null;	
var addlistType=null;
var addlistDescription=null;
var addlistSharingLevel = null;
var addlistAddToMsnSpace=null;
var addlistDisplayOrder=null;
var addListIsDefaultList=null;
var addlistCollapsed=null;
function addShoppingList(listId,listName,listType,listDescription,listSharingLevel,
				listAddToMsnSpace,listDisplayOrder,ListIsDefaultList,listCollapsed){

	//Call Service & Check Duplicate List.
	// Needs Tuning
	addListName = listName;
     addlistId=listId;	
    addlistType=listType;
    addlistDescription=listDescription;
    addlistSharingLevel = listSharingLevel;
   addlistAddToMsnSpace=listAddToMsnSpace;
   addlistDisplayOrder=listDisplayOrder;
   addListIsDefaultList=ListIsDefaultList;
    addlistCollapsed=listCollapsed;
	callListService((getParameters('GETALLLISTS')),addShoppingListCallBack);
	}
function addShoppingListPost()
{
	if(loadXMLString(xmlhttp.responseText)){ // load XML.
		if(isAuthenticated()){
			if(!isDuplicate(addListName)){
				if(listMaxCount()){
					alert('Maximum number of Lists already exists');
				}
				else{
				listDisplayOrder  = parseFloat(getListCount());
				addlistDisplayOrder = listDisplayOrder;
				addShoppingActualListPost();
				}
				//Winobj.style.display=(Winobj.style.display!="block")? "block" : "none";
				}
				else{	
					if(divErrorobj.innerHTML != dupListGL){
						divErrorobj.style.display=(divErrorobj.style.display!="block")? "block" : "none";
					}	
						divErrorobj.innerHTML = dupListGL;
				}
			}
		}
		else{
			alert(unAuthGL);
		} 
				
	
}
function addShoppingActualListPost()
{
callListService((getParameters('ADDLIST',addlistId,addListName,addlistType,addlistDescription,addlistSharingLevel,addlistAddToMsnSpace,addlistDisplayOrder,addListIsDefaultList,addlistCollapsed)),addShoppingActualCallBackup);

}
function addShoppingActualPost()
{
loadXMLString(xmlhttp.responseText);
			if(isStatus()){ // Check for Valid XML for List
						var arrList = getListName(0);
						addStatus = 1;
					}else{	
						addStatus = -1;
					}
					
// Add List

		switch(addStatus)	{
			case 1:
				var listId = getListName(0); // Error Prone
				AddDivList(addListName,listId[0]);
				AddexpandCollapse(addListName);						
				break;
			case 3:
				divErrorobj.innerHTML = unAuthGL;
				divErrorobj.style.display=(divErrorobj.style.display!="block")? "block" : "none";
				break;
			default:
				divErrorobj.innerHTML = errMsGL;
				divErrorobj.style.display=(divErrorobj.style.display!="block")? "block" : "none";
				break;
		}
		Winobj.style.display=(Winobj.style.display!="block")? "block" : "none";	

}
function callListService(parameters,callback){
	var ListDomain = linkUrlGL;
	var url = shopUrlGL + "/Shopping.ashx?url=" + ListDomain;
	xmlhttp=null;
	// code for Mozilla, etc.
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest()
	}
	// code for IE
	else if (window.ActiveXObject){
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	if (xmlhttp!=null){		
		xmlhttp.onreadystatechange=callback;	
		xmlhttp.open("POST",url,true);		
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");		
		xmlhttp.send(parameters);
	}
	else{
		alert("Your browser does not support XMLHTTP.")
	}
}

function showListcallback()
{
  if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
          showListCalBack();}
   }
}

function addShoppingCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       addShoppingPostListItem();}
   }

}
function removeShopListCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       removeShoppingListPost();}
   }
}
function remShopListAllCallback()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       remShopListAllItemPost();}
   }
}
function deleteListCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       deleteListPost();}
   }
}
function addShoppingListCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       addShoppingListPost();}
   }
}
function addShoppingActualCallBackup()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       addShoppingActualPost();}
   }
}



/*   Code added for User Guides */
var xmlGudhttp = null;
var xmlGudres = null;
var xmlDocGud = null;
var authorName = new Array();
var shortName = new Array();
var title = new Array();
var showGuide = 0;
var getGuidefoo = 'bar';
var Hosts = null;
var gdSerUrl = null;
var gdYrGUd = null;
var gdErr =null;
var gdCreate = null;
var gdShpUrl = null;
var gdHosts = null;
function setGuideGL(glVar)
{
	var guideGL = glVar.split("|");
	showGuide = guideGL[0];
	gdHosts = guideGL[1];
	gdSerUrl = guideGL[2];
	gdYrGUd = guideGL[3];
	gdErr = guideGL[4];
	gdCreate = guideGL[5];
	gdShpUrl = guideGL[6];
}
function showUserGuides(glVar){
setGuideGL(glVar);
var gudUrlUser = gdHosts + "/Shopping.ashx?url=" + gdSerUrl + "GetMyGuides?format=xml";
if(showGuide == 1) // Check If Guide Call is Switch off
{
callGuideService(gudUrlUser,callbackGuides);

}
}
function showGuides()
{
BuildUserGuidesXml();
ParseUserGuidesXMl();
BuildUserGuideHTMl();

}
 
	
function BuildUserGuidesXml()
{
// code for IE
	if (window.ActiveXObject){
		xmlDocGud=new ActiveXObject("Microsoft.XMLDOM");
		xmlDocGud.async="false";
		if(xmlGudres)
		{
		xmlDocGud.loadXML(xmlGudres);
		}
		else
		{
		xmlDocGud = null;
		}
	}
	// code for Mozilla, Firefox, Opera, etc.
	else{
		var parser=new DOMParser();
		xmlDocGud=parser.parseFromString(xmlGudres,"text/xml");
	}
	
}
function ParseUserGuidesXMl()
{
var guideDown = '<guide>0</guide>';
	if(guideDown == xmlGudres){
		return;
	}
	
	if(xmlDocGud!=null)
	{
			if(xmlDocGud.childNodes.length > 0)
			{
    					var root = null;
						root = xmlDocGud.documentElement;
						pageNodes = root.getElementsByTagName('Page');
						if ( pageNodes.length > 0 ) {
								for(var i = 0; i < pageNodes.length;i++)
								{
									var pageIdx = i;
									if(i < 5 ) {ParseUserGuideXMlNode(pageNodes[i],pageIdx);}
								} 
							}
			}
	}
}
// main function
// BuildUserGuideHTMl

function BuildUserGuideHTMl()
{
        var guideDiv = document.createElement("div");
        guideDiv.id = "YourGuid";
        
        var divTitle = document.createElement("div");
    	divTitle.className = "b_Guide_Title";
    	
    	if(showList == 0)
    	{
    		
		var divDivider = document.createElement("div");
		divDivider.className = "divider";
		divTitle.appendChild(divDivider);
    	}
		var divt = document.createElement("div");
		divt.className = "list_title_1";
		divt.style.styleFloat = "left";
		divt.style.cssFloat = "left";		
		divt.innerHTML = gdYrGUd;
		divTitle.appendChild(divt);
		
	
		var ddimg = document.createElement("img");
		ddimg.className = "list_title_1";
		ddimg.src = "/img/collapse.gif";
		ddimg.style.cursor = "pointer";
		ddimg.style.styleFloat = "right";
		ddimg.style.cssFloat = "right";
		divTitle.appendChild(ddimg);
		
		var div2 = document.createElement("div");
		div2.style.clear = "right";
	    divTitle.appendChild(div2);
	    
	    guideDiv.appendChild(divTitle);
		
		var guideDiv1 = document.createElement("div");
		guideDiv1.id  = "YourGuides";
		guideDiv1.style.height = "";
		var guideDown = "<guide>0</guide>";
		if(guideDown == xmlGudres){
	        var diverr = document.createElement("div");
	        diverr.className = "b_list_div2";
			diverr.innerHTML = gdErr;
			guideDiv1.appendChild(diverr);
	   }
		else
		{
		for(var idx = 0 ; idx < authorName.length ; idx ++)
		{
		    var div2 = document.createElement("div");
			div2.className = "b_list_div2";
     	    var div3 = document.createElement("div");
	        div3.className = "b_list_div3";
				    
		    var dumurl = gdShpUrl + authorName[idx] + "/" + shortName[idx];
	
			var link = document.createElement('a');
			link.setAttribute('href',dumurl);
			link.innerHTML = title[idx];
			div3.appendChild(link);
	        div2.appendChild(div3);
	       	   
	      
		   
		    var div4 = document.createElement("div");
		    div4.className = "b_list_div5";
		    div2.appendChild(div4);
			        
	        guideDiv1.appendChild(div2);
       
     	}
     	} 
     	
     	 guideDiv.appendChild(guideDiv1);
     	 
     	 
     	 var guideDown = "<guide>0</guide>";
     	 if(xmlGudres != guideDown){
     		var div6 = document.createElement("div");
			div6.className = "b_list_div2";
			var div7 = document.createElement("div");
			div7.className = "b_list_div3";			
			var dumurl = gdShpUrl + 'createguide';
			var link = document.createElement('a');
			link.setAttribute('href',dumurl);
			link.innerHTML = gdCreate;
			div7.appendChild(link);
			div6.appendChild(div7);	    
				
			var div8 = document.createElement("div");
			div8.className = "b_list_div5";
			div6.appendChild(div8); 
			    
			guideDiv.appendChild(div6);
         }
         var divContainer = document.getElementById('shp_List_Container');
     	 divContainer.appendChild(guideDiv);
     	 var copyhe = parseInt(guideDiv.offsetHeight);
         ddimg.onclick = function(){exapndCollapse(guideDiv,ddimg,copyhe);};
 
}


// BuildUserGuideHTMl
function ParseUserGuideXMlNode(root,pageIdx)
{
	var i;
	var FLD_SHORT_TITLE = 0 ;
		for(i = 0; root.childNodes && i < root.childNodes.length; i++)
		{
		   switch(root.childNodes[i].nodeName)
		   {
						 case "Author": {
								authorName[pageIdx] = root.childNodes[i].childNodes[0].nodeValue;
								break;
						   }
						 case "Fields": {
						 var node = root.childNodes[i]; //Fields
				
	    			    for (var j = 0; j < node.childNodes.length; j++) {
							  
						 var n  = node.childNodes[j]; // field
					
						 for(var idx = 0 ;idx< n.childNodes.length ; idx ++)
						 {
						    switch (n.childNodes[idx].nodeName) {
						    //Just Added
						    case "CodeName" : {
						    if( n.childNodes[idx].childNodes[0].nodeValue == "FLD_SHORT_TITLE" )
						    {
						    FLD_SHORT_TITLE = 1; }
						    else {
						    FLD_SHORT_TITLE = 0; }
						    break; }
						    case "HTML": {
							    if( FLD_SHORT_TITLE == 1)
							    { 
							    shortName[pageIdx]= n.childNodes[idx].childNodes[0].nodeValue;}
								else
								{
								title[pageIdx] =  n.childNodes[idx].childNodes[0].nodeValue;}
								break;
							} //case Html
						 } // for ij
	       			 } //for j
						  
				  } //case fields
			} // case mane switch
	  } // for i
		   
		} //if main
	} // function



// main function
	//var xmlhttp = null;
	
	// for cookie list
	function getURL(url, callback, isAsync)
	{	
	    xmlhttp = null;
	    xmlhttp = createRequest();	
		if (xmlhttp != null) 
		{		
			if (xmlhttp.readyState != 4 && xmlhttp.readyState != 0)			
			xmlhttp.abort();	
		}	
		
		if (xmlhttp != null) 
		{		
			xmlhttp.open("GET", url,isAsync);
			//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlhttp.onreadystatechange=callback;		
			xmlhttp.send(null);
		}
	}

	function callGuideService(url,callback){
     
		if (xmlGudhttp != null) 
		{		
			if (xmlGudhttp.readyState != 4 && xmlGudhttp.readyState != 0)			
			xmlGudhttp.abort();	
		}	
		xmlGudhttp = createRequest();	
		if (xmlGudhttp != null) 
		{		
			xmlGudhttp.open("POST", url, true);
			xmlGudhttp.onreadystatechange=callback;		
			xmlGudhttp.send('foo=' + getGuidefoo);	
		}
		
	}
	
	function addCookieItmsCallBack()
	{	
		if (xmlhttp.readyState == 4) 
		{	if(xmlhttp.status == 200){
		 	xmlres = xmlhttp.responseText;
		 	cookieList();
		 	}		
		    else{
		    xmlres = "ErrorOccured";}
		   
		}
	}
	function callbackGuides()
	{	
	
	 if (xmlGudhttp.readyState == 4) 
		{	if(xmlGudhttp.status == 200){
		 	xmlGudres = xmlGudhttp.responseText;
		 	showGuides();
		 	}		
		    else{
		    xmlGudres = "<guide>0</guide>";}
		   
		}
	}

	
// Guide Service
	
function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }	
}


function queryString(key)
{
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}


/*Code added on 06-10-2006*/
var openGuideobj = null;
var openguidelistName = null;
var gudNickNameUrl = shopUrlGL + "/Shopping.ashx?url=" + gdSerUrl + "GetMyNickname?format|xml";
var xmlGudhttp1 = null;
var nickName = null;
var guideErrorsVarb = null;
var xmlNickNamehttp =null;
var getNickNamefoo = 'bar';
var gdConvGL = null;
var enterNicknm =null;
var EntrNickNm = null;
var PrListDesc =null;
var PleasePrNm = null;
var DupGudFound = null;
var ListCon1Itms = null;
function guideGLVar(GlVarGud)
{
var VarGUd = GlVarGud.split("|");
guideErrorsVarb = VarGUd[0];
enterNicknm = VarGUd[1];
EntrNickNm = VarGUd[2];
PrListDesc = VarGUd[3];
PleasePrNm = VarGUd[4];
DupGudFound = VarGUd[5];
ListCon1Itms = VarGUd[6];
gdConvGL = VarGUd[7];
}
function openGuide(obj,listName,guidGLVar){
	//guideErrorsVarb = guideErrorVar;
	guideGLVar(guidGLVar);
	openGuideobj = obj;
	openguidelistName = listName;
	callListService((getParameters('GETALLLISTS',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),openGuideCallBack);
}

function CallNickName()
{
callConvertGuide(gudNickNameUrl,NickNameCallBack); //CallNickName
}
function NickNameCallBack()
{
if (xmlNickNamehttp.readyState == 4) 
		{	if(xmlNickNamehttp.status == 200){
		 	nickName = xmlNickNamehttp.responseText;
		 	openGuidesCall();
		 	}		
		    else{
		    nickName = "";}
		   
		}
}

function openGuideCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       CallNickName();}
   }
}
function OnYesClickGuide()
{
if (xmlGudhttp1.readyState == 4) 
		{	if(xmlGudhttp1.status == 200){
		 	Redirect(gdConvGL + nickName1 + "/" + guideName + "?edit=1");
		 	}		
		    else{
		    alert(guideErrorVar);}
		   
		}
}
function OnNoClickGuide()
{
  if (xmlGudhttp1.readyState == 4) 
   {
     if(xmlGudhttp1.status == 200){
    
       }
     else{
		alert(guideErrorVar);}
   }
}
function ConvertNotoGuidePost()
{
// Handle No request
}

function callConvertGuide(url,callback){
     
		if (xmlNickNamehttp != null) 
		{		
			if (xmlNickNamehttp.readyState != 4 && xmlNickNamehttp.readyState != 0)			
			xmlNickNamehttp.abort();	
		}	
		xmlNickNamehttp = createRequest();	
		if (xmlNickNamehttp != null) 
		{		
			xmlNickNamehttp.open("POST", url, true);
			xmlNickNamehttp.onreadystatechange=callback;		
            xmlNickNamehttp.send('foo=' + getNickNamefoo);
		}
		
	}
	function ParseNickName()
	{
      nickName = xmlDoc.childNodes[1].childNodes[1].childNodes[0].nodeValue;
	   
	}
function openGuidesCall(){	
		if(IscookAuthGL == 0){
			var href= document.getElementById('signinUrl').innerText;
			document.location.href = href;
		}else{
		    if(loadXMLString(nickName))
		    {
		    ParseNickName();
		    }	
		    
			var obj=document.getElementById('Guidepopup');
			var guideobj=document.getElementById('ItemGuides');	
			var prevName=document.getElementById('previousName');
			var txt = document.getElementById('txtGuideDesc');
			var desc = document.getElementById('txtGuideName');
			obj.style.display=(obj.style.display!="block")? "block" : "none";
			obj.style.left= ((screen.availWidth/2) - 150) + "px";
			obj.style.top=((screen.availHeight/2) - 95) + "px";
			if(nickName != "")
			{
			  var div = desc.parentNode ;
			  div.style.display= "none";
			  var div1 = document.getElementById('nickNameDesc'); 
			  div1.style.display= "none";
			  
			}
			else
			{
			 desc.value = "Enter Your Nickname";
 			}
			
			txt.focus();
			txt.value = openguidelistName;
			//desc.value = openguidelistName;
			prevName.innerHTML = openguidelistName;
			addListItemsName(guideobj,openguidelistName);
			
		}
	return false;
}
var guideName = null;
var nickName1 = null;
function closeGuidePopup(isCancel){
	var obj=document.getElementById('Guidepopup');
	var prevName=document.getElementById('previousName');	
	//var guideName="";
	var guideDescription="";
	var divMsgobj=document.getElementById('DivMsg');
	divMsgobj.innerHTML = '';
	divMsgobj.style.display="none";
	if(isCancel == -1){//When "cancel" is clicked
		obj.style.display=(obj.style.display!="block")? "block" : "none";
		}
	else{//When "cancel" is clicked
		guideName = Trim(document.getElementById('txtGuideName').value);
		guideDescription = Trim(document.getElementById('txtGuideDesc').value);
		var nicNameDiv = document.getElementById('txtGuideName');
		
		if(nickName != "")
		{
		  nickName1 = nickName;
		}
		else
		{
		   nickName1 = guideName;
		}
		if((guideName == "") && (nickName == ""))
		{
			divMsgobj.innerHTML = '<b><font color="red">'+ '&nbsp;&nbsp;' + 'Please provide Your NickName' + '</font></b>';
			divMsgobj.style.display=(divMsgobj.style.display!="block")? "block" : "none";
			return ;
		}
		
		// Haroon Added
		if(guideDescription == "")
		{
			divMsgobj.innerHTML = '<b><font color="red">' + '&nbsp;&nbsp;' + 'Please provide List description' + '</font></b>';
			divMsgobj.style.display=(divMsgobj.style.display!="block")? "block" : "none";
			return ;
		}
		
		if(((guideName == "") && (nickName == "")) || (guideDescription == ""))
		{
			divMsgobj.innerHTML = '<b><font color="red">' + '&nbsp;&nbsp;' + 'Please provide Name or description' + '</font></b>';
			divMsgobj.style.display=(divMsgobj.style.display!="block")? "block" : "none";
			return ;
		}
		
		if(isDuplicateGuide(guideDescription))
		{
			divMsgobj.innerHTML = '<b><font color="red">' + '&nbsp;&nbsp;' + 'Duplicate Guide found'  + '</font></b>';
			divMsgobj.style.display=(divMsgobj.style.display!="block")? "block" : "none";
			return ;
		}
			if(productListIds != "")
			{	
			if(isCancel == 1){//when "Yes" is clicked
				obj.style.display=(obj.style.display!="block")? "block" : "none";
				callConverttoGuide(getGuideParameters(guideDescription,productListIds,nickName1),OnYesClickGuide);
				//TODO: redirection to Guides page
			}
			else if(isCancel == 0){//When "No" is clicked
				obj.style.display=(obj.style.display!="block")? "block" : "none";
				callConverttoGuide(getGuideParameters(guideDescription,productListIds,nickName1),OnNoClickGuide);
			}
			
			}
			
			else
			{
				divMsgobj.innerHTML = '<b><font color="red">' + '&nbsp;&nbsp;' + 'Your list should contain atleast 1 item' + '</font></b>';
				divMsgobj.style.display=(divMsgobj.style.display!="block")? "block" : "none";
				return ;
			}
			
			
	}
	
}


var addListguideobj = null;
var productListIds = null;
function addListItemsName(guideobj,listName)
{	
	addListguideobj = guideobj;
	productListIds = '';
	callListService((getParameters('GETLIST',null,listName,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),addlistNamescallback);
}

function addlistNamescallback()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       addlistNamescall();}
   }
}

function addlistNamescall(){
	 if(loadXMLString(xmlhttp.responseText)){ // load XML.
		if(isAuthenticated())
		{
			var itemCount = getItemCount();
			var j = 0;
			var arrListNode = new Array();
			
				if(itemCount>0)
				{
					arrListNode = getItemName(0);
					productListIds = arrListNode[0];
					for (var j=1; j < itemCount ; j++)
					{
						arrListNode = getItemName(j);
						productListIds = productListIds + ',' + arrListNode[0];
					}
				}
				
			addListguideobj.innerHTML = "&nbsp;&nbsp;Your " + itemCount + " item guide inculdes:";
				for (var j=0; j < itemCount ; j++)
				{
					arrListNode = getItemName(j);
					var link = "<div align=left class=listItem>&nbsp;&nbsp;&nbsp;" + arrListNode[1] + "</div>";
					addListguideobj.innerHTML = addListguideobj.innerHTML + link;
				}
			
		 }
	}
	return productListIds;
}

function getItemCount(){
	return xmlDoc.childNodes[0].childNodes[0].childNodes[9].childNodes.length;
}

function getItemName(index){
	var arrListNode = new Array();
	if(index >= 0){
		arrListNode[0] = xmlDoc.childNodes[0].childNodes[0].childNodes[9].childNodes[index].childNodes[6].childNodes[0].nodeValue;//InsItemID
		arrListNode[1] = xmlDoc.childNodes[0].childNodes[0].childNodes[9].childNodes[index].childNodes[1].childNodes[0].nodeValue;//Name
	}
	return arrListNode;	
}



var renamelistName = null;
var renameDisplayOrder = null;
var renamelistId = null;
function setRenameGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
}
function openRename(obj,listName,listId,displayOrder,globVar){
    setRenameGLVar(globVar);
	renamelistName = listName;
	renameDisplayOrder  = displayOrder;
	renamelistId = listId;
	renameListcall();
	}


function renameListcall(){	
		if(IscookAuthGL == 0){
			var href= document.getElementById('signinUrl').innerText;
			document.location.href = href;
		}else{	
			var obj=document.getElementById('newName');	
			var prevName=document.getElementById('lastName');
			var prevlistId=document.getElementById('DivListId');
			var orderList = document.getElementById('DivdispOrder');
			var txt1 = document.getElementById('newTextName');
			obj.style.display=(obj.style.display!="block")? "block" : "none";
			obj.style.left= ((screen.availWidth/2) - 150) + "px";
			obj.style.top=((screen.availHeight/2) - 95) + "px";
			prevName.innerHTML = renamelistName;
			prevlistId.innerHTML = renamelistId;
			orderList.innerHTML = renameDisplayOrder;
			txt1.value = renamelistName;
			txt1.focus();			
		}
	return false;
}

var closeobj = null;
var closediverrorobj = null;
function setClRenGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
errMsGL = globParms[2];
}

function closeRenamePopup(isCancel,globVar){
    setClRenGLVar(globVar);
	var obj=document.getElementById('newName');
	closeobj = obj;
	var listName='';		
	if(isCancel == 'false'){
		listName = Trim(document.getElementById('newTextName').value);
		var listsId = document.getElementById('DivListId').innerHTML;
		var dispOrder = document.getElementById('DivdispOrder').innerHTML;
		var divErrorobj=document.getElementById('errorMsg');
		closediverrorobj = divErrorobj;
		callListService((getParameters('ADDLIST',listsId,listName,'User','','Private',false,dispOrder,false,false)),closeRenameCallBack);
		}
	else{
		obj.style.display=(obj.style.display!="block")? "block" : "none";
	}
		}


function closeRenameCallBack()
{
if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       closeRenameCall();}
   }
}

function closeRenameCall(){
				loadXMLString(xmlhttp.responseText);
					if(isStatus()){ // Check for Valid XML for List
					    //window.location.href = window.location;
					    var href = document.location.toString();
		                href = stripHash(href);
						//document.location.href = "javascript:history.go(0)";	
						document.location.href = href;					    
						closeobj.style.display=(closeobj.style.display!="block")? "block" : "none";
					}else{	
						closediverrorobj.innerHTML = errMsGL;
				        closediverrorobj.style.display=(closediverrorobj.style.display!="block")? "block" : "none";
				        return;
					}
	}

/*Code added on 06-10-2006*/



/* Code added for testing purpose in List Service */
function createRequest()
{	
	var reqObj = null;	
	try 
	{		
		reqObj = new ActiveXObject("Msxml2.XMLHTTP");	
	}catch (err)	
	{		
		try 
		{			
			reqObj = new ActiveXObject("Microsoft.XMLHTTP");		
		}catch (err2) 
		{			
			try 
			{				
				try 
				{				    
					netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");				   
				} catch (e) 
				{				    
					/* alert("Permission UniversalBrowserRead denied."); */   				
				}				
					reqObj = new XMLHttpRequest();			
			}catch (err3) 
			{				
				reqObj = null;			
			}		
			}	
		}	
		
		return reqObj;
	}
	
	/* */



var mailevtobj = null;
var link = null;
function setMailGLVar(globVar)
{
var globParms = globVar.split("|");
linkUrlGL = globParms[0];
shopUrlGL = globParms[1];
}
function MailToString(evt,listname,globVar)
{
    setMailGLVar(globVar);
	mailevtobj = evt;
	callListService((getParameters('GETLIST',null,listname,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null)),mailcallback);
}


function mailcallback()
{
  if (xmlhttp.readyState == 4) 
   {
     if(xmlhttp.status == 200){
       mailpostCallBack();}
   }
}

function mailpostCallBack(){
	if(loadXMLString(xmlhttp.responseText)){
		if(isAuthenticated())
		{
			var itemCount = getItemCount();
			var j = 0;
			var arrListNode = new Array();

                var mailstring = "mailto:?subject=Shopping List&body=";   
				if(itemCount>0)
				{
					for (var j=0; j < itemCount ; j++)
					{
						arrListNode = getItemName(j);
						mailstring += escape("\n");		
						mailstring += escape(arrListNode[1] + "\n" + shopUrlGL + "/Prices/shp/?itemId=" + arrListNode[0]);
					}
				}
				
			}
		window.location.href = mailstring;
		}
}

function isDuplicateItem(listName,itemName,itemId){
	var divItemContainer = document.getElementById(listName);
	
	if(divItemContainer.childNodes[2].childNodes[0].childNodes.length>0)
		{
			var itemCount = divItemContainer.childNodes[2].childNodes.length;
			for(var i=0;i<itemCount;i++)
			{
				if(divItemContainer.childNodes[2].childNodes[i].id == itemId)
				{
					return true;  //Duplicate Item found
				}
			}
		}
	//}
	else
	{
		return false;  // Duplicate Item Not Found.
	}
}

/*****************************/


/*********************************/

var ItemListIDCookie = null;
var evtcookie = null;

function MailToStringcookie(evt)
{		
		evtcookie = evt;
		var val = getCookie('prodIDList');
	    var values = val.split("|");
	    
	    var len = values.length;
	    var idx;
	    if (val && val.length > 0)
	    {
		for(var valIdx = len - 1; valIdx >= 0; valIdx --)
			{
				if( valIdx == len - 1)
				{
				ItemListIDCookie = values[valIdx];
				}
				else
				{
				ItemListIDCookie = ItemListIDCookie + "|" +  values[valIdx];
				}
			}
	    }
		var url = shopUrlGL + '/ListManager.aspx?itemIDList=' + ItemListIDCookie;
		getURL(url, callbackmailcookie, true);
				
}

function getCookie(name)
{
    var cookie = document.cookie;
    var prefix = name + "=";
    var begin = cookie.indexOf("; " + prefix);    
    //if its the only cookie
    if (begin == -1)
    {
        begin = cookie.indexOf(prefix);        
        if (begin != 0) return null;
    }
    else
    {
		//go two characters one for ";" and one for space " "
        begin += 2;
    }
    //find the length of the cookie
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = cookie.length;
    }
    //return the value
    return unescape(cookie.substring(begin + prefix.length, end));
}

function callbackmailcookie()
{	
	if (xmlhttp.readyState == 4) 
	{	
		if(xmlhttp.status == 200){
        mailcookieCallBack();}
		
	}
}

function mailcookieCallBack()
{
	if(loadXMLString(xmlhttp.responseText)){
		var ItemNameList = new Array();
		ItemNameList = xmlhttp.ResponseText;
		var valuesName = ItemNameList.split("|");
		var valuesIds = ItemListIDCookie.split("|");
		var len = valuesIds.length;
	    var mailToStringcookies = "mailto:?subject=Shopping List&body=";
		for(var valIdx = 0; valIdx < len; valIdx++)
		{
		mailToStringcookies += escape("\n");
		
		mailToStringcookies += escape(valuesName[valIdx] + "\n" + shopUrlGL + "/Prices/shp/?itemId=" + valuesIds[valIdx]);
		}
	    window.location.href = mailToStringcookies; 
	}
}

function RemoveAllListItemcookie()
{
		deleteCookie('prodIDList');	
		//document.location.href = "javascript:history.go(0)";	
		var href = document.location.toString();
		
		href = stripHash(href);
			    
	    document.location.href = href;
}
function stripHash(href)
{
     if(href.charAt(href.length-1) == "#")
	    {
	    href = href.substring(0,href.length - 1);
	    }
	  return href;
}

// For deleting cookie item
function removeShopCookieItem(listName,itemId)
{
ResetCookieIDValues(itemId);
var href = document.location.toString();
href = stripHash(href);
document.location.href = href;
}

function ResetCookieIDValues(prodID)
{
	var val = getCookie('prodIDList');
	var values = val.split("|");
    
    var pos = val.indexOf(prodID);
	var fir = val.substring(0,pos);
	var pos1 = pos + prodID.length;
	var sec = val.substring(pos1+1);
	var newcok = fir + sec;
	if( newcok.charAt(newcok.length-1) == "|")
	{
	newcok = newcok.substring(0,newcok.length - 1);
	}

	ResetCookieValues('prodIDList', newcok);

}

function ResetCookieValues(name, newvalue) 	
{
 var expires = GetExpireDate();
 document.cookie = name + "=" + escape(newvalue) + ";expires=" + expires + ";path=/";
}	
   
   function allListNames()
{
	var divItemContainer = document.getElementById('shp_List_Container');
	var listNames = divItemContainer.childNodes.length;
	var listNamesArray = new Array();
	var j = 0;
	var idx = 0;
	var dropIdx = 0;
	idx = (showGuide!=0)? listNames - 1:listNames; 
		if(listNames>0)
		{
		        if (window.ActiveXObject){ dropIdx = 2;} else {dropIdx = 3;}   
				for(var i = dropIdx;i<idx;i++)
				{
    			    listNamesArray[j] = divItemContainer.childNodes[i].childNodes[0].childNodes[0].innerHTML;
				    j++;
				}
				
				return listNamesArray;
		}
		else
		{
			return null; // No list is present
		}
}


function listMaxCount()
{
	var divItemContainer = document.getElementById('shp_List_Container');
	//Hack - Firefox rendered one extra div.  Therefore, the max value is bogus.
	if (window.ActiveXObject){
		if(divItemContainer.childNodes.length == 13){ //First two child Nodes are for "Your Stuff" & "Create a list" and third for "YourGuides"
			return true; // Maximum number of Lists already there.
		}
		else{
			return false; // List can be added.
		}
	}
	else
	{
		if(divItemContainer.childNodes.length == 14){ //First two child Nodes are for "Your Stuff" & "Create a list" and third for "YourGuides"
			return true; // Maximum number of Lists already there.
		}
		else{
			return false; // List can be added.
		}
	}
}

function getGuideParameters(guidesDescription,productLists,nickName){
				
	var guideparameters = 'format=' + 'xml';
	guideparameters += '&title=' + guidesDescription;
	guideparameters += '&productIds='		+ productLists;
	guideparameters += '&nickName='			+ nickName;
	
	return guideparameters;
}


function callConverttoGuide(guideparameters,callback){
		var url = gdHosts + "/Shopping.ashx?url=" + gdSerUrl + "AddGuide";
		if (xmlGudhttp1 != null) 
		{		
			if (xmlGudhttp1.readyState != 4 && xmlGudhttp1.readyState != 0)			
				xmlGudhttp1.abort();	
		}	
		xmlGudhttp1 = createRequest();	
		if (xmlGudhttp1 != null) 
		{		
			xmlGudhttp1.open("POST", url, true);
			xmlGudhttp1.onreadystatechange=callback;
			xmlGudhttp1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlGudhttp1.send(guideparameters);
		}
		
	}
	
	
function isDuplicateGuide(guideName){
var divItemContainer = document.getElementById('YourGuides');
	if(divItemContainer.childNodes.length>0)
	{
		var itemCount = divItemContainer.childNodes.length;
		for(var i=0;i<itemCount;i++)
		{
			if(divItemContainer.childNodes[i].childNodes[0].childNodes[0].innerHTML.toLowerCase() == guideName.toLowerCase())
				return true; //Duplicate Guide found
		}
	}
	else
	{
		return false; // Duplicate Guide Not Found.
	}
}


/*SuggestionList stuff */
function SetSuggestionService()
{

     suggestionsSearch = new SuggestionBox("suggestionsSearch",URL,"divSuggestions","suggestion","shopsearch", "searchText","btnSearch","");

	if( suggestionsSearch )
	{
		// attach events
		var searchField = document.getElementById("searchText");            
		if( searchField ) 
		{
			searchField.autocomplete = "off";     
			AttachKeyUpEvent(searchField, suggestionsSearch.searchFieldKeyPressHandler);
		}    
     
		if(window.attachEvent) window.attachEvent("onresize",suggestionsSearch.Redraw);
	}
}

// SuggestionBox constructor
function SuggestionBox( newInstanceName, newUrl, newMenuId, newMenuItemId, newFormId, newSearchId, newSearchButton, newErrorMessage )
{
	// all methods are closed on this variable
	// so that even when they are called from
	// event handlers they have access to the
	// 'self' var which then lets them access
	// the contents of the object.
	//
	// WARNING: the self property must be set to
	// empty when this object is disposed of
	// other wise it may cause a circular reference
	// and a memory leak, call the release method	
	var self = this;
	var ErrorState;			
	
	SuggestionBox.prototype.release = function()
	{
		self = null;
	}
	
	// setup some instance variables
	var INSTANCE_NAME = newInstanceName;
	var URL = newUrl;
	var MENU_ID = newMenuId;	
	var MENU_ITEM_ID = newMenuItemId;
	var FORM_ID = newFormId;	
	var SEARCH_ID = newSearchId;
	var SEARCH_BUTTON = newSearchButton;
	var ERROR_MESSAGE = newErrorMessage;	
	
	
	// this is the model data for the menu
	var suggestedItems = new Array();
	var selectedItem = -1;
	
	// define object protoype methods
	SuggestionBox.prototype.searchFieldKeyPressHandler = function( e )
	{
        if (!e) var e = window.event;

		if (document.getElementById( SEARCH_ID ).value.length < 4)
		{
			self.removeMenu();
			return;
		}
	
		
			if( e.keyCode == 13 && self.suggestedItems && self.suggestedItems.length > 0 && self.selectedItem >= 0 && self.selectedItem < self.suggestedItems.length )
			{ // select the first item when return is pressed
				self.removeMenu();						
				document.getElementById( SEARCH_ID ).value = self.suggestedItems[self.selectedItem];
				PerformSearch(SEARCH_BUTTON);
				
			}
			else if( e.keyCode == 13 )
			{
				var searchField = document.getElementById( SEARCH_ID );
				if( searchField && searchField.value.length > 0)
				{
					self.removeMenu();
				}			
			}
			else if( e.keyCode == 40 && self.suggestedItems && self.selectedItem < self.suggestedItems.length - 1)
			{
				self.selectedItem++;
				for(sugItmCt=0;sugItmCt<self.suggestedItems.length;sugItmCt++)
				{
					var popupEntry = document.getElementById('popup_'+sugItmCt);
					if( popupEntry && popupEntry.className)
					{
						popupEntry.className=popupEntry.className.replace(/ selected/,'');
					}
				}
				var popupSelection = document.getElementById('popup_'+self.selectedItem);
				if( popupSelection ) document.getElementById('popup_'+self.selectedItem).className += " selected";
									
			}
			else if( e.keyCode == 38 && self.selectedItem > 0)
			{
				self.selectedItem--;
				for(sugItmCt=0;sugItmCt<self.suggestedItems.length;sugItmCt++)
				{
					var popupEntry = document.getElementById('popup_'+sugItmCt);
					if( popupEntry && popupEntry.className)
					{
						popupEntry.className=popupEntry.className.replace(/ selected/,'');
					}
				}
				var popupSelection = document.getElementById('popup_'+self.selectedItem);
				if( popupSelection ) popupSelection.className += " selected";
				
			}
			else if( e.keyCode == 27 )
			{
				self.removeMenu();
			}
			else
			{
				// cancel the existing timeout
				if( self.timer )
				{
					clearTimeout( self.timer );
				}
				
				// set a timer to call the web service			
				self.timer = setTimeout( INSTANCE_NAME + ".callService();", 250 );			
				if( e.target ) self.targetElement = e.target;
				if( e.srcElement ) self.targetElement = e.srcElement;
				
			}
		
	}

    
	// perform a suggestions web service call
	SuggestionBox.prototype.callService = function()
	{
	    if(!self.ErrorState)
	    {
	        var queryData = serializeForm( document.getElementById( SEARCH_ID ));
	        if(queryData)
		        makeHTTPRequest( URL, queryData, self.extractAndShowMenu, true );
		    else
		        self.removeMenu(); //get rid of the previous menu if no queryData
		}
		
	}

	SuggestionBox.prototype.extractAndShowMenu = function( xmlData )
	{
	    if(xmlData)
	    {
	        self.ErrorState = false;;
		    self.extractItems( xmlData );
		    self.showMenu( xmlData );
		}else
		    self.ErrorState = true;
		    
	}
	
	SuggestionBox.prototype.extractItems = function( xmlData )
	{
		var suggestions = xmlData.getElementsByTagName( "string" );
		self.suggestedItems = new Array();
		self.selectedItem = -1; // unselect the previous item
		for( var i = 0; i < suggestions.length; i++ )
		{
			var content = "";
			
			// search the doms for IE and firefox
			if( suggestions[i].text && suggestions[i].text != "")
			{
				content = suggestions[i].text;
			}
			else if( suggestions[i].textContent && suggestions[i].textContent != "")
			{
				content = suggestions[i].textContent;
			}
			
			// save the results if there were some. Suggestions will always return the number of items asked for, even if they are empty
			if( content )
			{
				self.suggestedItems.push( content );
			}
		}	
		
	}

	SuggestionBox.prototype.showMenu = function()
	{
		// get rid of the previous menu
		self.removeMenu();
	    //if menu is empty don't do anything
	    if(self.suggestedItems.length == 0)
	    {
	        return false;    
	    }
		// build a new menu div
		
		var popupMenuProto = document.getElementById( MENU_ID );
		if( popupMenuProto  )
		{
		    var popupMenu = popupMenuProto.cloneNode( true );
		    var hasContent = false;
		    popupMenu.id = "popupmenu";
		    popupMenu.className = "popupmenu";
			
		    // append each entry in the suggestedItems to the menu div
		    for( var i = 0; i < self.suggestedItems.length; i++ )
		    {
			    popupMenu.appendChild( PopulateTemplate( MENU_ITEM_ID, self.suggestedItems[i] ));
			    popupMenu.lastChild.id = "popup_" + i;
			    popupMenu.lastChild.style.display = "block";
			    if( self.selectedItem == i )
			    {
				    popupMenu.lastChild.className += " selected";				
				    IsSearchSubmit = false;
			    }
		    }	
    		
		    // record the menu for later removal
		    self.popupMenu = popupMenu;
    			
		    // display the menu
		    popupMenu.style.display = "block";
		    popupMenu.style.left = LeftPosition( self.targetElement );
		    popupMenu.style.top = TopPosition( self.targetElement ) + self.targetElement.offsetHeight;
		    document.body.appendChild( popupMenu );
    			
		    // set a click handler for the document which hides the popup menu
		    attachDocumentClick( self.removeMenu );
        }
        
	}
	
	SuggestionBox.prototype.removePopupHandlers = function( element )
	{
		if( element && element.childNodes )
		{
			for( var i = 0; i < element.childNodes.length; i++ )
			{
				element.childNodes[i].onclick = null;
			}
		}			
		
	}
	SuggestionBox.prototype.selectProductName = function( productElement )
	{
	    //var productElement = e.srcElement;
	    var productName = productElement.firstChild.nodeValue;	    	    
		self.removeMenu();
		document.getElementById( SEARCH_ID ).value = productName;		
		PerformSearch(SEARCH_BUTTON);
		
	}

	SuggestionBox.prototype.removeMenu = function()
	{
		if( self.popupMenu )
		{
			self.popupMenu.parentNode.removeChild( self.popupMenu );
			self.popupMenu = null;
		}
		// make sure to detach the menu and its event handlers
		removeDocumentClick( self.removeMenu );
		self.removePopupHandlers();
		
	}	
	
	SuggestionBox.prototype.Redraw = function()
    {
        if(self != null && self.popupMenu != null)
        {
            self.popupMenu.style.left = LeftPosition( self.targetElement );
		    self.popupMenu.style.top = TopPosition( self.targetElement ) + self.targetElement.offsetHeight;
		 }
		 
    }
    
}
/****************************************************************/
/*																*/
/*	These helper functions provide underlying capabilities		*/
/*	that allow the suggestions UI to operate. They will be		*/
/*	replaced with the live.com framework.						*/
/*																*/
/*	TODO: implement using live.com framework					*/
/*																*/
/****************************************************************/
function makeHTTPRequest( url, data, callback, shouldReturnXML )
{
	if( window.XMLHttpRequest )
	{
		var request = new XMLHttpRequest();
	}
	else if( window.ActiveXObject )
	{
		var request = new ActiveXObject("Msxml2.XMLHTTP");	
	}    	
	request.onreadystatechange = requestCallback;	
	request.open( "POST", url, true );	
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	
	request.send( data );		

	function requestCallback()
	{
	    if(request != null)
	    {
	        if( request.readyState == 4 && request.status == 200 )
		    {
		        if( shouldReturnXML )
			    {
				    var data = request.responseXML;
			    }
			    else
			    {
				    var data = request.responseText;
			    }    			
			    callback( data );
		    }
		    else if( request.readyState == 4 && request.status != 200 )
		    {
			    callback();
		    }
		}
	}
}


function serializeForm( inputText )
{
	var formString = null;
	if(inputText)
	{
	    var data =  StringTrim(inputText.value);
	    
	    if(data.length > 0)
	    {
	        if(data.indexOf("*") != 0 && data.length > 3)
	            data = "*" + data;
	        
	        formString = "dictionaryName=" + DIC_NAME + "&query=" + data + "&numberOfResults=" + NUM_OF_ITEMS;
	    }
	}
	return formString;
}

function StringTrim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


function PopulateTemplate( templateId, content )
{
    var template = document.getElementById( templateId );
	
	if( template )
	{
		template = template.cloneNode( true );
		template.appendChild( document.createTextNode( content ));
	}	
	return template;
}



function LeftPosition( element )
{
	if( element.offsetParent )
	{
		return element.offsetLeft + LeftPosition( element.offsetParent );
	}
	else
	{
		return element.offsetLeft;
	}
}
function TopPosition( element )
{
	if( element.offsetParent )
	{
		return element.offsetTop + TopPosition( element.offsetParent );
	}
	else
	{
		return element.offsetTop;
	}
}
function attachDocumentClick( eventHandler )
{
	if (document.layers)
	{
		window.captureEvents(Event.CLICK);
		window.onclick = eventHandler;
	}
	else if (document.all && !document.getElementById)
	{
		document.onclick = eventHandler;
	}
	else if (document.all)
	{
	    document.attachEvent('onclick', eventHandler);
	}
	else if (document.addEventListener)
	{
		document.addEventListener('click', eventHandler, true);
	}
}

function removeDocumentClick( eventHandler )
{
	if (document.layers)
	{
		window.releaseEvents(Event.CLICK);
		window.onclick = null;
	}
	else if (document.all && !document.getElementById)
	{
		document.onclick = null;
	}
	else if (document.all)
	{
		document.detachEvent('onclick', eventHandler);
	}
	else if (document.addEventListener)
	{
		document.removeEventListener('click', eventHandler, true);
	}
}

function redirectEvent( object, method )
{
	object.method( e );
}

function NoSearch()
{
    return false;
}

function PerformSearch(buttonName)
{
    IsSearchSubmit = true;
    var button = document.getElementById(buttonName);    
    button.click();
}

function AttachKeyUpEvent(obj,listner)
{
  if(window.attachEvent) 
  {
      obj.attachEvent("onkeyup",listner);
  }
  else
  {
      obj.onkeyup = listner;  
  }
}
/*SuggestionList stuff*/

//functions for All Shopping Articles feature
function shoppingArticlesSearchHighlight()
{
	var shoppingArticlesSearchText = document.getElementById('shoppingArticlesSearchText');
	var btnShoppingArticlesSearch = document.getElementById('btnShoppingArticlesSearch');
	btnShoppingArticlesSearch.focus();
}

function returnShoppingArticles() 
{
	getEvent=event.keyCode;
	if (getEvent == "13") 
	{
		var btnShoppingArticlesSearch = document.getElementById('btnShoppingArticlesSearch');
		btnShoppingArticlesSearch.focus();
	}
}

function ClearShoppingArticlesSearchBox(shoppingArticlesSearchText)
{
	var shoppingArticlesSearchText = document.getElementById('shoppingArticlesSearchText');
	if(shoppingArticlesSearchText.className=="searchbox grayShoppingArticlesSearchBox")
		shoppingArticlesSearchText.value="";
	shoppingArticlesSearchText.className = "searchBox normalShoppingArticlesSearchBox";
}

function DoSearchAllShoppingArticles(searchText, msg, baseURL, Button, queryString)
{	
	// Redirect search to allShoppingArticles
	if(Button == 'shoppingArticlesSearchButton')
	{
		if(!searchText || searchText.length<1 || Trim(searchText).length<1) 
		{	
			alert(msg);
			return false;
		}
		window.location=baseURL+seoRewriteUrl('/allShoppingArticles.aspx?text='+encodeURIComponent(searchText));
		return false;
	}	
	return true;
}

//end of functions for All Shopping Articles feature

