function OpenVisualsWindow(url)
{
	var w = 800;
	var h = 500;
	
	var center = '';
	if(screen.width != null && screen.height != null)
	{
		var top = (screen.height - h) / 2;
		var left = (screen.width - w) / 2;
		
		center = ',top=' + top + ',left=' + left;
	}
	var win = window.open( url, 'Visualisations','height=' + h + ',width=' + w + ',scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,resizable=yes' + center, true);
	if(win == null)
	{
		alert('You might have a popup blocker installed. Please configure it to allow popups for winesource.com');
	}
}
function OpenPopWindow(url, w, h)
{
	var center = '';
	if(screen.width != null && screen.height != null)
	{
		var top = (screen.height - h) / 2;
		var left = (screen.width - w) / 2;
		
		center = ',top=' + top + ',left=' + left;
	}
	var win = window.open( url, 'Visualisations','height=' + h + ',width=' + w + ',scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,resizable=yes' + center, true);
	if(win == null)
	{
		alert('You might have a popup blocker installed. Please configure it to allow popups for winesource.com');
	}
}

function ChangeDisplay(objId, newDisplay)
{
	if (document.getElementById || document.all)
	{
		var objStyle = GetStyle(objId);
		if (objStyle != null)
		{
			objStyle.display = newDisplay;
		}
	}
}
function ChangeDisplays(objId, newDisplay, objLinkId, newLinkDisplay)
{
	if (document.getElementById || document.all)
	{
		var objStyle = GetStyle(objId);
		if (objStyle != null)
		{
			objStyle.display = newDisplay;
		}
		var objLinkStyle = GetStyle(objLinkId);
		if (objLinkStyle != null)
		{
			objLinkStyle.display = newLinkDisplay;
		}
	}
}
function GetObject(objId)
{
	if (document.getElementById && document.getElementById(objId))
	{
		return document.getElementById(objId);
	}
	else if (document.all && document.all(objId))
	{
		return document.all(objId);
	}
	else
	{
		return null;
	}			
}
function GetStyle(objId)
{
	if (document.getElementById && document.getElementById(objId))
	{
		return document.getElementById(objId).style;
	}
	else if (document.all && document.all(objId))
	{
		return document.all(objId).style;
	}
	else
	{
		return null;
	}
}
//START - Recently Viewed functions
var __rvCookieName = 'RecentlyViewed';

function DisplayRecentlyViewed()
{
	var rv = GetRecentlyViewed();
	
	if(rv != null)
	{
		var table = GetObject('RecentlyViewed');
		var container = GetObject('RecentlyViewedContainer');
		if(table != null && container != null)
		{
			var val = '<ul>';
			var count = 0;
			for(var i = rv.length -1; i >= 0 && count < 5; i--)
			{
				var parts = rv[i].split('=');
				var page = parts[0].indexOf('BG') == 0 ? 'Room.aspx' : 'Item.aspx';
				val += '<li><a href="/' + page + '/item_' + parts[0] + '-desc_' + parts[1] + '" class="ColorLink">' + parts[1].replace(/\+/g, " ") + '</a></li>';
				count++;
			}
			val += '</ul>';
			table.style.display = 'block';
			container.innerHTML = val;
		}
	}
}
function AddToRecentlyViewed(sku, name)
{
	var rv = GetRecentlyViewed();
	var newVal = "";
	var start = 0;
	
	if(rv != null)
	{		
		if(rv.length >= 5)
		{
			start = rv.length - 4;
		}
		
		for(var i = start; i < rv.length ; i++)
		{
			var parts = rv[i].split('=');
			if(parts[0] != sku)
			{
				newVal += '&' + rv[i];
			}
		}
	}
	
	newVal += '&' + sku + '=' + name;
	newVal = newVal.substring(1);

	SetCookie(__rvCookieName, newVal, 10957);
}

function GetRecentlyViewed()
{
	var c = GetCookie(__rvCookieName);
	if(c != null)
	{
		return c.split('&');
	}
	
	return null;
}
//END -- Recenly Viewed functions

//START -- Endeca functions
function GetUrl()
{
	/*
	var _searchPage = "Shop.aspx";
	
	var end = location.href.lastIndexOf('.aspx');
	var url = location.href.substring(0, location.href.lastIndexOf('/', end) +1);
	url += _searchPage;
	
	alert(url);
	return url;
	*/
	
	return "/Results.aspx";
}

function GoToPage(offset)
{
	__exit = false;
	var url = GetUrl();
	
	var addterms = ["No="+offset];
	var removeterms = ["No"];
	var newurl = ConstructURL("CURRENTURL", removeterms, addterms);
	newurl = url + newurl;
	
	location.href = newurl;
}

function Search(newSearch, terms)
{
	
	if(terms.length > 0 && terms != 'YOUR SEARCH' && terms != '-- Keyword --')
	{
		__exit = false;

		var url = GetUrl();	
		terms = encodeURIComponent(terms);
			    
		if (newSearch) 
		{
				//var terms = encodeURIComponent(document.Form1.Header_SearchBox_SearchTextBox.value);
				var removeterms = ["all", "sku", "qty", "clid", "desc", "navBar", "N","Ne","No","Nao","Ntk","Ntt","D","Dn","Nty","Ntx","Dx","in_dym","in_dim_search", "pg", "item", "FFNe","kw", "ATT","CMP","KBID", "LID"];
				var addterms = ["N=0","Ntk=search_all","Ntt="+terms,"Nty=1","D="+terms,"Dn=0","Ntx=mode+matchallany","Dx=mode+matchallany"];
				var newurl = ConstructURL("CURRENTURL", removeterms, addterms);            
				newurl = url + newurl;
				location.href = newurl;
		}
		else
		{
				//var terms = encodeURIComponent(document.Form1.Nav_SearchBox_SearchTextBox.value);
				var removeterms = ["all", "sku", "qty", "clid", "desc", "No","Nao","Ntk","Ntt","D","Dn","Nty","Ntx","Dx","in_dym","in_dim_search", "pg", "item", "kw", "ATT","CMP","KBID", "LID"];
				var addterms = ["Ntk=search_all","Ntt="+terms,"Nty=1","D="+terms,"Ntx=mode+matchallany","Dx=mode+matchallany"];
				var newurl = ConstructURL("CURRENTURL", removeterms, addterms);                
				newurl = url + newurl;            
				location.href = newurl;  
		}
	}
}



function ConstructURL(url,removeterms,addterms) {

	var params = BuildURLArray(url);

	var newurl = "";

	for (var i=0; i<params.length; i++) {

		val = CheckArray(removeterms,params[i][0]);

		if (val == -1)

			newurl = newurl + "&" + params[i][0] + "=" + params[i][1];

	}

	for (var i=0; i<addterms.length; i++) {

		newurl = newurl + "&" + addterms[i];

	}

	if (newurl.length > 0) {

		newurl = newurl.substr(1);

		newurl = "?"+newurl;

	}

	else {

		newurl = "?N=0";

	}

	return newurl;

}

function BuildURLArray(oldurl) {

	var returnArray = new Array();

	var url;

	if (oldurl == "CURRENTURL")
	{
		url = location.pathname.substr(location.pathname.lastIndexOf('.aspx'));
		url = url.substr(5);
	
		if(url.length > 0)
		{
			url = url.replace(/\//g, "?");
			url = url.replace(/_/g, "=");
			url = url.replace(/-/g, "&");
			url = url.replace(/\]\|/g, "_");
			url = url.replace(/%5D%7C/g, "_");
		}
		else
		{
			url = location.search;
		}
	}
	else if (oldurl == "BLANKURL")
	{

	}

	else {

		var tokens = oldurl.split("?");

		url = "?"+tokens[1];

	}		

	if (url) {

		url = url.substr(1);

		var params = url.split("&");

		for (var i=0; i<params.length; i++) {

			var param = params[i].split("=");

			returnArray[i] = param;

		}

	}

	return returnArray;

}

function CheckArray(removeterms,checkterm) {

	for (var i=0; i<removeterms.length; i++) {

		if (removeterms[i] == checkterm)

			return 1;

	}

	return -1;

}

function GetValue(url, term) {

	var params = BuildURLArray(url);

	for (var i=0; i<params.length; i++) {

		if (params[i][0] == term) {

			return params[i][1];

		}

	}

	return -1;

}

//END -- Endeca functions

var __promoTimerId;
var __promoImg;
var __promoImgSrc;
var __promoLnk;
var __promoUrl;

function startPromo()
{
	fo_pause();
	swapImg2(__promoImg, __promoImgSrc);
	swapLnk(__promoLnk, __promoUrl);
}

function stopPromo()
{
	clearTimeout(__promoTimerId);
}
function swapPromo(img, imgSrc, lnk, url)
{
	__promoImg = img;
	__promoImgSrc = imgSrc;
	__promoLnk = lnk;
	__promoUrl = url;	
	
	__promoTimerId = setTimeout(startPromo, 250);
}
function swapLnk(lnk, url)
{
	lnk = document.getElementById(lnk);
	if(lnk != null)
	{
		lnk.href = url;
	}
}
function swapImg3(id, imgSrc)
{
	swapImg2(document.getElementById(id), imgSrc);
}
function swapImg2(img, imgSrc)
{
	if(img != null)
	{
		img.src = imgSrc;
	}
}
function ValidateCreditCardNumber( source, targetArgs )
{
	targetArgs.IsValid = false;
	cardNumber = targetArgs.Value;
	if ( cardNumber.length >= 13 )
	{
		if ( ValidCardPrefixAndLength ( targetArgs.Value ) )
		{
			targetArgs.IsValid = ValidCheckSum( targetArgs.Value );
		}
	}

}

/// <summary>
/// Compares the card number prefix with the card type as the first order check
/// </summary>
/// <returns></returns>
function ValidCardPrefixAndLength( cardNumber )
{
	var result;
			
	cardType = element("PCardTypeDDL");

	switch ( cardType.value )
	{
		
		case "VISA":
			result = ValidVISAPrefixAndLength( cardNumber );
			break;

		case "American Express":
			result = ValidAmexPrefixAndLength(cardNumber);
			break;

		case "MasterCard":
			result = ValidMasterCardPrefixAndLength(cardNumber);
			break;

		case "Discover":
			result = ValidDiscoverPrefixAndLength(cardNumber);
			break;
	
	}
	
	return result;
}

function ValidCheckSum( cardNumber )
{
	result = false;
	
	weight = 2;
	sum = 0;
	digit = 0;
	for( i = cardNumber.length - 2; i > -1; --i )
	{
		digit = weight * (cardNumber.charCodeAt(i) - 0x30 );
		sum = sum + CLikeDiv(digit ,10) + (digit % 10);

		if ( weight == 2 )
			weight = 1;
		else 
			weight = 2;
	}

	 mod = (10 - sum%10) % 10;
	checkDigit = cardNumber.charCodeAt( cardNumber.length -1  ) - 0x30;
	result = (mod == checkDigit);

	return result;

}

function CLikeDiv( value, divisor )
{
	result = value / divisor;
	if ( result < 1 )
		return 0;
	else
		return 1;
}

function ValidVISAPrefixAndLength( cardNumber )
{
	correctPrefix = (cardNumber.charAt(0) == "4");
	return ( correctPrefix && (cardNumber.length == 13 || cardNumber.length == 16))
}

function ValidAmexPrefixAndLength(cardNumber)
{
	prefix = cardNumber.substring( 0, 2);
	correctPrefix =  (prefix == "34" || prefix == "37");
	return ( correctPrefix && cardNumber.length == 15)
}

function ValidMasterCardPrefixAndLength(cardNumber)
{
	prefix = cardNumber.substring( 0, 2);
	correctPrefix = (prefix == "51" || prefix == "52" || prefix == "53" || prefix == "54" || prefix == "55");
	return ( correctPrefix && cardNumber.length == 16)	
}

function ValidDiscoverPrefixAndLength(cardNumber)
{
	prefix = cardNumber.substring( 0, 4);
	correctPrefix =  (prefix == "60110" || prefix == "60112" || prefix == "60113" || prefix == "60114" || prefix == "60119");
	return ( correctPrefix && cardNumber.length == 16)			
}

function element( id )
{
	if ( document.getElementById != null )
	{
		return document.getElementById( id );
	}
	if ( document.all != null )
	{
		return document.all[id];
	}
	if ( document.layers != null )
	{
		return document.layers[id]
	}
}

function ValidateExpirationDate( source, arguments )
{
	arguments.IsValid = false;
	
	selectedYear = arguments.Value;
	selectedMonth = element("PExpMonthDDL").value;
	now = new Date();
	thisYear = now.getFullYear();
	thisMonth = now.getMonth();
	
	if ( thisYear < selectedYear )
	{
		arguments.IsValid = true;
	}
	else if ( thisYear == selectedYear && thisMonth <= selectedMonth )
	{
		arguments.IsValid = true;
	}
	
}


function RevalidateYear( sel )
{
	validator = element("DateCustomValidator");
	if ( validator != null )
		ValidatorValidate( validator );
	
}

function ShowHiRes( name, code, image, appPath )
{
	url = appPath + 'LargeImage.aspx?img=' + image +'&name=' + name + '&code=' + code;	
	url = url.replace(/#/,"%23");
	cw = window.open( url, 'ProductShowHiRes','height=450,width=610,status=no,toolbar=no,menubar=no,location=no,resizable=yes',true);
}

var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;
			
function SuperSizeMe( childWindow, width, height )
{
	if ( isIE )
	{
		childWindow.resizeTo( width,	height);	
	}
	else if ( isNN )
	{
		childWindow.innerWidth=width;
		childWindow.innerHeight=height;
	}
	childWindow.focus();
}


function Continue()
{
	var newloc = "/default.aspx";
	alert( newloc );
	
	for ( i = history.length - 1; i >= 0; ++i )
	{
		alert(i);
		loc = history[i].toUpperCase();	
		alert( loc );
		if ( loc.indexOf("EMAIL") == -1 )
		{
			newloc = loc;
			break;
		}
	}

	window.location = newloc;
}

function RequestMoreInfo( itemId, groupId, cname )
{
	url = '/MoreProductInfo.aspx?itemId=' + itemId + '&groupId=' + groupId + '&cname=' + cname +  '&pUrl=' + escape( window.location );
	window.open( url, 'ProductShowMoreInfo','height=600,width=500,status=no,toolbar=no,menubar=no,location=no,resizable=yes, scrollbars=yes ',true);
}

function GeneralEmail()
{
	window.open( '/GeneralEmail.aspx', 'Email','height=400,width=500,status=no,toolbar=no,menubar=no,location=no,resizable=yes, scrollbars=yes ',true);
}

function ShowAdditionalImages( listitemId )
{
	url = '/AdditionalImages.aspx?id=' + listitemId;
	window.open( url , "AdditionalImages", 'height=600,width=570,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes',true);
}

function showAdditionalLinkPopup( url )
{
	window.open( url, "AdditionalInformation", 'height=600,width=750,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes',true);
}

function PopupLiveChat( queue )
{
	var chat = window.open("http://www.furniturefind.com/Chat.aspx?ChatQueue=" + queue, 'CHAT', 'height=270,width=550,status=no,toolbar=no,menubar=no,location=no,resizable=yes', true);
	if(chat == null)
	{
		alert("You appear to have a pop-up blocker that prevents the chat window from opening. Please enable pop-ups for this site and try again.");
	}
}


function getCookieVal (offset) 
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;

	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) 
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	
	while (i < clen) 
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
		
		i = document.cookie.indexOf(" ", i) + 1;

		if (i == 0) break; 
	}
	
	return null;
}

function WriteCookie (name, value, expires) 
{
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var path = '/';
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	
	var cookie = name + "=" + value +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path == null) ? "" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
	
	document.cookie = cookie;
}

function DeleteCookie (name) 
{
	var exp = new Date();
	exp.setTime (exp.getTime() - 1000000000);  // This cookie is history (changed -1 to make it previous time)
	var cval = GetCookie (name);
	document.cookie =name + "=" + cval + "; expires=" + exp.toGMTString();
}

function SetCookie(name, value, expiredays)
{
	var expdate = new Date(); 
	if(expiredays != null)
	{
		expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * expiredays)); 
	}
	else
	{
		expdate = null;
	}
	
	WriteCookie(name, value, expdate);  
}

function swapImg(argImageName, argImageSrc, argDivArray)
{
  var divArray = "" ;
  //Check to see if the target image is in a div or layer, then switch images.
  if (document.layers && argDivArray)
  {
    for( var i = 0; i < argDivArray.length; i++ ) 
    {
     divArray += 'document.' + argDivArray[i] + '.';
    }
     eval(divArray + 'document.' + argImageName + '.src ="' + argImageSrc + '";');
     return true;
  }
  else
  {
    document[argImageName].src = argImageSrc;
  }
}

function fjsBBB(){
	window.open('http://www.bbbonline.org/cks.asp?id=362100020','bbbonline','width=500,height=420,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no')
}


/* kbid stuff goes here. We should really not do this but time is short */
var scriptLoc = 'http://www.affiliates-furniturefind.com/rep.asp';
var kbId = 0;
var queryString = window.location.search.substring(1);
var imgdata = '';
var subdata = '';

if (queryString.length > 0)
{
	var pairs = queryString.split('&');
							
	for(var i = 0; i < pairs.length; i++)
	{
		var pairs2 = pairs[i].split('=');
		
		switch(pairs2[0].toLowerCase())
		{
			case 'kbid':
				kbId = pairs2[1];
				break;
			case 'clearcookie':
				if (pairs2[1] == 1)
				{
					DeleteCookie("kbid");
				}
				break;
			case 'img':
				imgdata = pairs2[1];
				break;
			case 'sub':
				subdata = pairs2[1];
				break;
		}
	} //end for
}//end if

if (GetCookie("kbid") == null)
{
	if (kbId != 0)
	{
		var img = new Image();
		var url = scriptLoc + '?id=' + kbId;
		if (imgdata != '')
		{
			url += '&img=' + imgdata
		}

		if (subdata != '')
		{
			url += '&sub=' + subdata
		}

		img.src = url;
		
		SetCookie("kbid", kbId, 1);
	}
}//end if
function popupCartOrderHelp(url, width, height){
	window.open(url,'CartOrderHelp','width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes')
}