// Shopping JavaScript


ua = navigator.userAgent;
isMacIE5 = ((ua.indexOf("Mac") != -1) && (ua.indexOf("MSIE") != -1));
isSafari = (ua.indexOf("Safari") != -1);



// Misc Functionality


function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;



// Leader


var li = 1; //index of leader (to be replaced by javascript autocounting elements in future)
var l = 5; //length of leader
var intSeconds = 30; //seconds controlling automatic rotation
var t = ''; // timeout

function loadLeaderController() {

	if($('leader_previous')) {
		$('leader_previous').onclick = function() { rotatePrevious(); }
	}

	if($('leader_next')) {
		$('leader_next').onclick = function() { rotateNext(); }
	}

	t = setTimeout(rotateNext,(1000*intSeconds))



	// Hot Items

	var myAjax = new Ajax.Request(
		'/holiday/results.html',
		{
			method: 'get',
			// onException: function(r,e) { alert(e); console.log(e); },
			onComplete: renderPartners
	});

}


function rotateNext() { rotateLeader('next'); }

function rotatePrevious() { rotateLeader('previous'); }

function rotateLeader(v) {
	clearTimeout(t);
	if($('leader_' + li)) { $('leader_' + li).setAttribute('class',"hidden"); }
	if($('leader_' + li)) { $('leader_' + li).setAttribute('className',"hidden"); }
	if(v == 'previous') { if(li == 1) { li = l; } else { li--; } }
	else if(v == 'next') { if(li == l) { li = 1; } else { li++; } }
	if($('leader_' + li)) {  $('leader_' + li).removeAttribute('class',"hidden"); }
	if($('leader_' + li)) {  $('leader_' + li).removeAttribute('className',"hidden"); }
	if($('leader_controller_index')) { $('leader_controller_index').innerHTML = ' '+li+' '; }
	t = setTimeout(rotateNext,(1000*intSeconds))
}




// Hot Items

function renderPartners(response)
{
	var results = '';
	eval('results = '+response.responseText);
	//	console.log(results.partner_results.keyword);
	var keyword = results.partner_results.keyword.replace("+", '&nbsp;');
	results.partner_results.partner_result = shuffle(results.partner_results.partner_result);
	for(i=0;i<results.partner_results.partner_result.length;i++) {
		var partner = results.partner_results.partner_result[i];
		if (partner.data.ItemSearchResponse.Items.Item.length > 3){
			var div = document.createElement('div');
			div.id = "hotitems_" + partner['name'];
			var container = $('hotitems');
			container.appendChild(div);
			switch(partner.name)
			{
				case "Ebay": //Ebay
					appendPartnerHeader(div,'ebay');
					partner.data.ItemSearchResponse.Items.Item.each(renderEbayItem.bind(div));
					appendPartnerFooter(div,keyword,'eBay.com','http://rover.ebay.com/rover/1/711-1751-2978-71/1?AID=5463217&amp;PID=1545655&amp;SID=hotlist&amp;mpre=http%3A//search.ebay.com/search/search.dll%3Fcgiurl%3Dhttp%3A//cgi.earthlink.ebay.com/ws/eBayISAPI.dll%26ht%3D52%26krd%3D1%26ebaytag1%3Debayreg%26MfcISAPICommand%3DGetResult%26SortProperty%3DMetaEndSort%26category0%3D%26query%3D');
					break;
				case "Amazon": //Amazon
					appendPartnerHeader(div,'amazon');
					partner.data.ItemSearchResponse.Items.Item.each(renderAmazonItem.bind(div));
					appendPartnerFooter(div,keyword,'Amazon.com','http://www.amazon.com/exec/obidos/external-search/?mode=blended&amp;tag=earth-hol-gifts-20&amp;keyword=');
					break;
				case "Shopping": //Shopping
					appendPartnerHeader(div,'shopping');
					partner.data.ItemSearchResponse.Items.Item.each(renderShoppingItem.bind(div));
					appendPartnerFooter(div,keyword,'Shopping.com','http://www.shop.earthlink.shopping.com/xFS?FN=All+Categories&amp;FD=0&amp;linkin_id=8032275&amp;KW=');
					break;
			}
		}
	}

}


function renderEbayItem(item, index)
{
//	console.log(item);

	if(index < 3) {
		var div = createHotItem({
			title: unescape(item.Title),
			titleURL: item.Link + '&amp;PID=1545655&amp;SID=hotlist',
			image: item.Thumbnail,
			description: ((item.CurrentPrice) ? '<b>Current Price $' + item.CurrentPrice + '</b><br />'  : '')
						+ 'Time Left: ' + item.EndTime,
			rating: ''
		});

		appendHotItem(this,div);
	} else { return; }
}

function renderAmazonItem(item, index)
{
//	console.log(item);

	if(index < 3) {

		var desc = 'No price listed.';
		if(item.BestNewOfferPrice){
			desc =	((item.BestNewOfferPrice) ? '<b>Price: ' + item.BestNewOfferPrice + '</b><br />' : '') +
					((item.ListPrice) ? '<strike>List Price: ' + item.ListPrice + '</strike><br />' : '') +
					((item.SaveAmount) ? 'You Save: ' + item.SaveAmount : '') +
					((item.SavePercentage) ? ' ('+ item.SavePercentage +')' : '');
		}

		var div = createHotItem({
			title: unescape(item.Title)	 ,
			titleURL: item.Link,
			image: item.Thumbnail,
			description: desc,
			rating: ''
		});
		appendHotItem(this,div);
	} else { return; }

}

function renderShoppingItem(item, index)
{
//	console.log(item);


	if(index < 3) {
		if(item.Thumbnail) {
			// alert(item.Thumbnail);
			var div = createHotItem({
				title: unescape(item.Title),
				titleURL: item.Link + '&amp;Linkin_id=8032275',
				image: item.Thumbnail,
				description: '<b>Compare Prices $' + item['MinPrice'] + ' - $' + item['MaxPrice'] + '</b>' +
					((item.Description) ? '<br />' + item.Description : ''),
				rating: ''
			});
			appendHotItem(this,div);
		}
	} else { return; }
	return;
}

function createHotItem(params)
{
	var div = document.createElement('div');
	div.className = "hotitem";
	var body = document.createElement('div');
	var imgdiv = document.createElement('div');
	imgdiv.className = "hotitem_thumbnail";
	var img = document.createElement('img');
	img.src = params.image;
	var title = document.createElement('div');
	title.className = 'hotitem_title';
	title.innerHTML = '<a href="' + params.titleURL + '">' + params.title + '</a>';
	var desc = document.createElement('div');
	desc.className = "hotitem_desc";
	desc.innerHTML = params.description;
	var rating = document.createElement('div');
	rating.className = "hotitem_rating";
	body.className = "hotitem_body";
	body.appendChild(title);
	body.appendChild(desc);
	body.appendChild(rating);
	if(params.image && params.image!='')imgdiv.appendChild(img);
	div.appendChild(imgdiv);
	div.appendChild(body);

	return div;
}

function appendHotItem(parent,div)
{
	var sep = document.createElement('div');
	sep.className = 'after';
	div.appendChild(sep);
	parent.appendChild(div);
}

function appendPartnerHeader(parent,value)
{
	var div = document.createElement('div');
	div.className = 'hotitem_partner_header';
	var a;
	a = document.createElement('a');
	a.name = value;
	var img;
	img = document.createElement('img');
	img.src = '/img/holiday/logo_' + value + '.gif';
	a.appendChild(img);
	div.appendChild(a);
	parent.appendChild(div);
}


function appendPartnerFooter(parent,search,site,url)
{
	var div = document.createElement('div');
	div.className = 'hotitem_partner_footer';
	div.innerHTML = '<a href="' + url + search + '">Find more <span class="bold">' + search + '</span> results from ' + site + '</a>';
	parent.appendChild(div);
}

function shuffle(o){
	for(var j, x, i = o.length-1; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

// Added for deals page

 function showDynCt(targetContainerId, contentString) {
  document.getElementById(targetContainerId).innerHTML = contentString.replace(/%7E/g,"~").replace(/\.0</g,".00<");
 }
 function setSubTabs(partnerTab, subTab){
  var tabList = [{"name":"Ebay","subTabs":["DailyDeals","Popular"]},{"name":"Amazon","subTabs":["Books","Music","Dvd","Electronics","Toys"]},{"name":"Shopping","subTabs":["Home","Clothing","Health","Electronics","Sports"]},{"name":"Expedia","subTabs":["Packages","Flights","Hotels","Cruises"]}];
  for (var i=0; i<tabList.length; i++) {
   document.getElementById(("subTab"+tabList[i].name)).style.display = "none";   
   document.getElementById(("dealTab"+tabList[i].name+"Container")).style.background = "url(/img/holiday/tabInactive.gif) no-repeat left";   
   document.getElementById(("dealTab"+tabList[i].name)).style.background = "url(/img/holiday/tabInactive.gif) no-repeat right";   
   document.getElementById(("dealTab"+tabList[i].name)).style.color = "#ffffff";   
   for (var n=0; n<tabList[i].subTabs.length; n++){
    document.getElementById(("dealsTab"+tabList[i].name+tabList[i].subTabs[n])).style.color = "#0000ff";   
    document.getElementById(("dealsTab"+tabList[i].name+tabList[i].subTabs[n])).style["font-weight"] = "normal";   
   }
  }
  document.getElementById(("subTab" + partnerTab)).style.display = "block";
  document.getElementById(("dealTab" + partnerTab + "Container")).style.background = "url(/img/holiday/tabActive.gif) no-repeat left";
  document.getElementById(("dealTab" + partnerTab)).style.background = "url(/img/holiday/tabActive.gif) no-repeat right";
  document.getElementById(("dealTab" + partnerTab)).style.color = "#000000";
  document.getElementById(("dealsTab" + partnerTab + subTab)).style.color = "#000000";
  document.getElementById(("dealsTab" + partnerTab + subTab)).style["font-weight"] = "bold";
  document.getElementById("dealLogo").src = "/img/holiday/logo_"+partnerTab.toLowerCase()+".gif";
  switch(partnerTab.toLowerCase()){
   case "ebay":
    document.getElementById("dealLogo").onclick=function(){location.href="http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=1&pub=5574628248&toolid=10001&campid=5336283038&customid=logo&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg"};   
   break;
   case "amazon":
    document.getElementById("dealLogo").onclick=function(){location.href="http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fhomepage.html%3Fie%3DUTF8%26%252AVersion%252A%3D1%26%252Aentries%252A%3D0&tag=earth-sp-p14-20&linkCode=ur2&camp=1789&creative=390957"};   
   break;
   case "shopping":
    document.getElementById("dealLogo").onclick=function(){location.href="http://www.shop.earthlink.shopping.com/main/linkin_id-8053797"};   
   break;
   case "expedia":
    document.getElementById("dealLogo").onclick=function(){location.href="http://www.expedia.com/pubspec/scripts/eap.asp?GOTO=EXPHOME&eapid=10720-1&mdpcid=elink.10720.1.Deals.logo"};   
   break;
  }
 }


 