// Copyright (C) 2000-2005 Shopping.com

function writeBanner(banner){
var abc=Math.random()+"";
var random=abc.substring(2,abc.length);
document.writeln("<SCRIPT type=\"text/javascript\" LANGUAGE=\"JavaScript1.1\" SRC=\"http://ad.doubleclick.net/adj/"+banner+";dcopt=ist;tile=1;sz=468x60;ord="+random+"?\">\</SCRIPT>");
}

function transit(k,uk,pid){
var dest;
if(k=='dtuk'){dest='http://www.dealtime.co.uk/';}
else if(k=='dt'){dest='http://www1.dealtime.com/';}
else if(k=='joinmerch'){dest='https://merchants.shopping.com/'+uk+'welcome.html';}
else if(k=='loginmerch'){
 dest='https://merchants.shopping.com/'+uk+'MerchantTool/Home.html';
 if(pid!='') {dest += '?PartnerId='+pid;}
}else if(k=='epinions'){ dest='http://www.epinions.com/';}
else if(k=='joinmerchdtuk'){dest='https://www.dealtime.net/uk/welcome.html';}
else if(k=='loginmerchdtuk'){
 dest='https://www.dealtime.net/uk/MerchantTool/Home.html';
 if(pid!='') {dest += '?PartnerId='+pid;}
}
document.location.href=dest;
}

var img="http://img.shopping.com";
// never EVER change reload(), as this will break cash back
function reload(){window.location.reload()}
function reloadRebate(url){window.location = url}
function ws(s){window.status=s?s:'';return true}
function pops(url,w,h){window.open(url,'popup','screenX=0,screenY=0,resizable=yes,scrollbars=yes,height='+h+',width='+w)}
function popsl(url,w,h,x,y){window.open(url,'popup','screenX='+x+',screenY='+y+',top='+y+',left='+x+',resizable=yes,scrollbars=yes,height='+h+',width='+w)}
function pop(url){pops(url,520,300)}
function dc(url,ct){document.write('<a href='+url+'&CT='+ct+'>')}
function feat(){pops('/xPopups/featuredStore',520,330)}
function feat_prod(){pops('/xPopups/featuredProduct',550,380)}
function trust(){pops('/xPopups/trustedStore',520,470)}
function smart(){pops('/xPopups/smartBuy',520,450)}
function why(){pops('/xPopups/whyStoresListed',520,500)}
function rebate(){pop(img+'/cctool/Rebates/21667966.html')}
function shoppy(){pop(img+'/cctool/files/intro_win.html')}
function na(type){pops(img+'/sc/ds/na' + type + '.html',520,300)}

function userStatusPopup(status){
if(status=='lead'){pop('http://www.shopping.com/xProductReviews/memberLead.html',500,300)
}else if(status=='advisor'){pop('http://www.shopping.com/xProductReviews/memberAdv.html',500,300)
}else{pop('http://www.shopping.com/xProductReviews/memberTopRev.html',500,300)}
}

function shoppyPopUpWin(){
var textlink=img+'/cctool/files/intro_win.html';
var ht=540;var wd=720;var wPos=0;var hPos=0;
if(screen) {wPos=(screen.availWidth-wd)/2;hPos=(screen.availHeight-wd)/2;}
var newwindow=window.open(textlink,'popup','height='+ht+',width='+wd+',left='+wPos+',top='+hPos+', scrollbars=no,toolbar=no,copyhistory=no,resizable=no,directories=no,menubar=no,status=no,location=no');
newwindow.focus();
}

function sortReviews(prd,mrId,z){
var theForm=document.frmSort;
var i=theForm.sortby.selectedIndex;
var sort=theForm.sortby.options[i].value;
var n;
if(prd){
 n='/xPR-'+prd+'~S-'+sort;
 if(z==1){n=n+'~ZD-'+z;}
}else{n='/xMR-~MRD-'+mrId+'~S-'+sort;}
document.location.href=n;
}

linkName2Index=new Object();

function getLinkNamed(name){
var d=document;
if(linkName2Index[name]>=0){return d.links[linkName2Index[name]];}
for(i=d.links.length-1;i>=0;i--){
if(typeof d.links[i].name!="undefined"){if(d.links[i].name==name){linkName2Index[d.links[i].name]=i;return d.links[i];}}
}return null;
}

function cpl(from,to,ct) {
var flnk=getLinkNamed(from);
var tlnk=getLinkNamed(to);
if(flnk!=null&&tlnk!=null){
 var ltxt=tlnk.innerHTML; // IE needs this
 ctidx=flnk.href.lastIndexOf('&CT=');
 if(ctidx!=-1){tlnk.href=flnk.href.substring(0,ctidx+4)+ct;}
 else{tlnk.href=flnk.href;}
 tlnk.innerHTML=ltxt;tlnk.target=flnk.target;tlnk.className="";tlnk.onclick=flnk.onclick;
}
}



// ebates
var merchWinName = null;
var popWin;

function cb(anch, url){
 if(anch && anch.target) merchWinName = anch.target;
 if (window.showModelessDialog) setTimeout("showRebate('"+url+"','popup')",50);
 else showRebate(url, 'popup');
}

function showRebate(url, wName){
 var wSpecs = 'width=290,height=535,screenX=100,screenY=270,top=270,left=100,scrollbars=yes,toolbar=no,menu=no';
 if (window.showModelessDialog) {
  window.showModelessDialog("javascript:function noerror(){return true;} window.onerror = noerror; function doit(){window.open('','"+wName+"', '"+wSpecs+"', true);self.close();} doit();","","dialogTop=12355; dialogLeft=12355; dialogHeight:0px; dialogWidth:0px; status:no; help:no");
  popWin = null;
 } else {
  popWin = window.open(url, wName, wSpecs);
 }
 setTimeout("focusInOrder('"+url+"','"+wName+"','"+wSpecs+"')",1000);
}

function focusInOrder(url, wname, wspecs){
 var mWin = null;
 if (document.hasFocus) {
  if (document.hasFocus() == true) {
   if (merchWinName && merchWinName != "_blank") mWin = window.open("", merchWinName, "");
  }
 } else {
    if(merchWinName && merchWinName != "_blank") mWin = window.open("", merchWinName, "");
 }
 if (mWin) mWin.focus();
 if (!popWin) popWin = window.open(url, wname, wspecs);
 if (popWin) popWin.focus();
}


// end ebates

function handlePrdLnk(pageLink,pageNumber,imageServer) {
pageLink = getPageLink(pageLink);
if (pageNumber > 0) pageLink += "~PG-" + pageNumber;
else pageLink = checkBeforeSbs(pageLink);
if (pageLink == -1) window.open(imageServer + '/sc/SBS/OOPS.html','xxx','width=580,height=500');
else document.location.href=pageLink;
}

function checkBeforeSbs(pageLink) {
var newLink=pageLink;
if ( pageLink.indexOf('xSBS') != -1 ) {
    if ( pageLink.indexOf('PRDLT-') == -1 ) {
        newLink = -1;
    } else {
        var prdLst = pageLink.substring(pageLink.indexOf('PRDLT-'));
        var prdArray = prdLst.split("-");
        if ( prdArray.length == 2 ) newLink = 'index.php/xPF-~PD-' + prdArray[1] ;
    }
}
return newLink;
}

function getPageLink(pageLink) {
var theElements = document.compareprd.elements;
var urlProductsArray;
var prdList="~PRDLT";
var pos=pageLink.indexOf("PRDLT");
if (  pos != -1 ) {
    urlProductsArray = getProductsFromUrl(pageLink);
    prdList="";
}
var i=0;
var checkedProducts=0;
var removedProducts=0;
for ( i=0;i<theElements.length;i++ ) {
    if ( theElements[i].checked && !existsInArray(theElements[i].value,urlProductsArray) ) {
        prdList+="-" + theElements[i].value;
        checkedProducts=1;
    } else if ( !theElements[i].checked && existsInArray(theElements[i].value,urlProductsArray) ) {
        pageLink = removePrdFromUrl(pageLink,theElements[i].value);
        removedProducts++;
    }
}
if ( checkedProducts ) {
    pageLink += prdList;
} else if ( urlProductsArray && removedProducts == (urlProductsArray.length-1) ) {
    pageLink = pageLink.replace("~PRDLT","");
}
return pageLink;
}

function getProductsFromUrl(pageLink) {
var pageLinkArray = pageLink.split("~");
var urlPrdArray;
var i;
for(i=0;i<pageLinkArray.length;i++) {
    if ( pageLinkArray[i].indexOf("PRDLT") != -1 ) {
        urlPrdArray = pageLinkArray[i].split("-");
        break;
    }
}
return urlPrdArray;
}

function existsInArray(val,theArray) {
var retVal=0;
if ( theArray ) {
    var i=0;
    for(i=0;i<theArray.length;i++) {
        if ( val == theArray[i] ) {
            retVal=1;
            break;
        }
    }
}
return retVal;
}

function removePrdFromUrl(pageLink,val) {
return pageLink.replace("-" + val,"");
}

function sortProducts() {
var theForm = document.frmSort;
document.location.href="/xPP-" + theForm.seoUrl.value + "~S-" + theForm.sortDropDown.options[theForm.sortDropDown.selectedIndex].value;
}

function chgl(pageLnk,linkIdString,pgNum,topInd) {
var linkIdArray = linkIdString.split('|');
var j;
for (j=0;j<linkIdArray.length;j++){changeLink(pageLnk,"PL" + topInd + linkIdArray[j],linkIdArray[j]);}
changeLink(pageLnk,"PLP" + topInd,pgNum-1);
changeLink(pageLnk,"PLN" + topInd,parseInt(pgNum)+1);
}

function changeLink(pageLnk,lnkName,pgNum) {
var tlnk=getLinkNamed(lnkName);
if ( tlnk != null ) {
 var newHref="javascript:handlePrdLnk('" + escape(pageLnk) + "','" + pgNum + "')";
 tlnk.href=newHref;
 }
}

function changePrefDomain(server, linkinID, domain) {
 var myDate = new Date();
 myDate.setFullYear(myDate.getFullYear() + 1);
 document.cookie = "prefServer=" +escape(server) + ";expires=" + myDate.toGMTString() + ";path=/" + ";domain=" + domain;
 _redirect("http://" + server + "/?ncrd=1&pref=1&linkin_id=" + linkinID);
}

function _redirect(url) {
 if (url) {opener.location.href=url;}
 window.close();
}

function selectPrefDomain(form, domain) {
 var buttons = document.forms[form].elements["pref"];
 for (i = 0; i < buttons.length; i++ ) {
  if (buttons[i].checked) {
   changePrefDomain(buttons[i].value, '', domain);
  }
 }
}

function Set_Cookie(name,value,expires,path,domain,secure) {
 document.cookie = name + "=" +escape(value) +
 ( (expires) ? ";expires=" + expires.toGMTString() : "") +
 ( (path) ? ";path=" + path : "") +
 ( (domain) ? ";domain=" + domain : "") +
 ( (secure) ? ";secure" : "");
}

function Set_Long_Cookie(name,value) {
  var myDate = new Date();
  myDate.setFullYear(myDate.getFullYear() + 1);
  Set_Cookie(name,value,myDate,'/');
}

//TODO - refactor the cookie handling

// cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*86400000));
		var expires = "; expires=" + date.toGMTString();
	} else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
	//alert("decoded cookie : "+value);
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
// leading zeros
function lz(x) {
    var t = String(x);
    return t.length == 1 ? "0" + t : t;
}
//saved-list object - initialize it asap
var savedList = new Object();
savedList.init = function () {
   this.items = new Object();
   var packed=readCookie("list")
   if(packed && packed != "empty"){    
      var splitItems = packed.split("^")
      for (i in splitItems) {
         var parts = splitItems[i].split("=");
         this.items[unescape(parts[0])] = unescape(parts[1]);
      }
   }
}
savedList.init();
savedList.edit = function(add, id) {
   if (readCookie('list') == null) {
        pops("/xPopups/savedList",470,420);
   }
   this.init();
   if (add) {
      var d = new Date();
      this.items[id] = '' + d.getFullYear() + lz(d.getMonth()+1) + lz(d.getDate()) + lz(d.getHours()) + lz(d.getMinutes()) + lz(d.getSeconds());
   } else {
      delete this.items[id];
   }
   createCookie("list", this.toString(), 730);

   if (document.getElementById("savedListCount")) {
      var count = this.count();
      document.getElementById("savedListCount").childNodes[0].nodeValue=count;
      document.getElementById("savedListStatus").className=(count>0?"saveBoxOn":"saveBoxOff");
   }

   var img=new Image(1,1);
   img.src="/otf?type=sl&act="+(add?1:0)+"&id="+id;;
}
savedList.contains = function(id) {
   return typeof(this.items[id]) != 'undefined';
}
savedList.toString = function () {
   var out="";
   for (id in this.items) {
      if (out!="") out += "^";
      out += escape(id) + "=" + escape(this.items[id]);
   }
   if (out=="") out="empty";
   return out;
}
savedList.count = function () {
   var s = readCookie("list");
   if (s==null || s.length==0 || s=="empty") return 0;
   var parts = s.split("^");
   if (parts==null) return 0; 
   return parts.length;
}
savedList.saved='';
savedList.saveIt='';

function writeSaveBox(id) {
    document.write('<span class="'+(savedList.contains(id)?"save on":"save off")+'" id="'+id+'" \
onmouseover="if(this.className==\'save off\')this.className=\'save hover\'" \
onmouseout="if(this.className==\'save hover\')this.className=\'save off\'" \
onclick="var x=(this.className==\'save hover\');savedList.edit(x, this.id);this.className=(x?\'save on\':\'save off\');this.childNodes[1].childNodes[0].nodeValue=(x?savedList.saved:savedList.saveIt);">\
<img width="17" height="13" src="http://img.shopping.com/sc/glb/spacer.gif"><span class="msg">'+(savedList.contains(id)?savedList.saved:savedList.saveIt)+'</span></span>');
}
