// Kelkoo "MP3 players / multimedia" category
var kelkooCatId = "122701";

var proxyURL = '/common/kelkooXML/xmlProxy.php?url=';

// XML dealing functions
function loadXMLDoc(url, doFunc, param) {
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {// only if req shows "loaded"
			if (req.status == 200) {// only if "OK"
				doFunc(req.responseXML, param);
			} else {
				alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	}
	req.open("GET", url, true);
	req.send(null);
}


// interface functions

function displayBestPrices(query, catIdForced) {
	var div = document.getElementById("kelkooPopup");
	updatePopupPosition();
	// div.style.visibility="visible";
	// FlorentS fix
	div.style.display="block";
	div.innerHTML = '<div id="frame">'+
					'<div id="frame2">'+
						'<div id="topPopup">'+
							'<div id="queryName">'+query.toUpperCase()+'</div>'+
							'<div id="closeWindow"><a href="javascript:closePopup()">FERMER</a></div>'+
						'</div>'+
						'<div id="popContent" class="offerStyle">'+
							'<div id="offerListLoading">chargement ...</div>'+
						'</div>'+
					'</div>'+
				'</div>';
	/*var q = (ie) ? query : encodeURIComponent(query);*/
	
	var myId = (catIdForced=='' || catIdForced==null) ? kelkooCatId : catIdForced;
	
	// var url = 'http://export.kelkoo.fr/ctl/exportSearch?partner=generationmp3&siteSearchQuery='+encodeURIComponent(query)+'&partnerId=96909673&partner=kelkoo&catId='+myId;
	var url = '/V3/productSearch?query=' + encodeURIComponent(query) + '&category=' + myId + '&sort=default_ranking&logicalType=and&start=1&results=20&show_products=1&show_subcategories=0&show_refinements=1';
	
	loadXMLDoc(proxyURL+encodeURIComponent(url), displayBestPrices_Content, document.getElementById("popContent"));
}

function showDesc(node) {
	showtip(node, node.nextSibling.firstChild.nodeValue, "250", "left");
}

function displayBestPrices_Content(feed, container) {
	var node = feed.getElementsByTagName("Products")[0];	
	var content = '<div class="offerListFrame"><div class="offerList">' + getBestPrices_List(node) + '</div></div>';
	container.innerHTML = content;
}

function getBestPrices_List(node) {
	var resultNodes = node.getElementsByTagName("Offer");
	var ln = resultNodes.length;
	var content = '';	
	for (var z=0; z<ln; z++) {
	/*for (var z=node.firstChild; z!=null; z=z.nextSibling) {*/
		if (resultNodes[z].getElementsByTagName("Image")) {
			// API V3
			var url = resultNodes[z].getElementsByTagName("Url")[1].firstChild.nodeValue;
			var img = resultNodes[z].getElementsByTagName("Image")[0];
			var price = resultNodes[z].getElementsByTagName("Price")[1].firstChild.nodeValue;
			var titre = resultNodes[z].getElementsByTagName("Title")[0].firstChild.nodeValue;
			var desc = resultNodes[z].getElementsByTagName("Description")[0];
		} else {
			// API V2
			var url = resultNodes[z].getElementsByTagName("Url")[0].firstChild.nodeValue;
			var img = resultNodes[z].getElementsByTagName("ListImage")[0];
			var price = resultNodes[z].getElementsByTagName("Price")[0].firstChild.nodeValue;
			var titre = resultNodes[z].getElementsByTagName("ProductName")[0].firstChild.nodeValue;
			var desc = resultNodes[z].getElementsByTagName("Summary")[0];
		}
		img = img ? img.getElementsByTagName('Url')[0].firstChild.nodeValue : '';
		var marchand = resultNodes[z].getElementsByTagName("Merchant")[0];
		marchand = marchand ? marchand.getElementsByTagName("Name")[0].firstChild.nodeValue : '';
		desc = desc && desc.firstChild ? desc.firstChild.nodeValue : '';
		content += '<div class="offer">' +
					'<div class="firstRow">'+
						'<a href="'+url+'" target="_blank"><img src="'+img+'" width="50" height="50"/></a>'+
					'</div>' +
					'<div class="secondRow">'+
						'<a href="'+url+'" target="_blank">'+
							'<div class="price">'+price+' &#8364;</div>' +
							'<div class="title">'+titre + '</div>' +
							'<div class="marchand">'+marchand+'</div>'+
						'</a>'+
					'</div>' +
					'<div class="thirdRow">'+
						'<div class="seeOffer">'+
							'<a href="'+url+'" target="_blank">Voir l\'offre</a>'+
						'</div>' +
						((desc) ? 
						'<div class="moreInfo">'+
							'<a href="'+url+'" target="_blank" onMouseOver="showDesc(this)">+d\'infos</a>'+
							'<div style="display:none;">'+desc+'</div>'+
						'</div>' : '') +
					'</div>' +
					'<div style="clear:both;"></div>' +
				'</div>';
	}
	return (node.childNodes.length==0) ? "Pas de resultats" : content;
}

function displayPush(feed, node) {
	var offer = feed.getElementsByTagName("Product")[0];
	if (!offer) {
		return;
	}
	if (offer.getElementsByTagName("Image")[0]) {
		// API V3
		var imgURL = offer.getElementsByTagName("Image")[0];
		var price = offer.getElementsByTagName("Price")[1].firstChild.nodeValue;
		var titre = offer.getElementsByTagName("Title")[0].firstChild.nodeValue;
	} else {
		// API V2
		var imgURL = offer.getElementsByTagName("ListImage")[0];
		var price = offer.getElementsByTagName("Price")[0].firstChild.nodeValue;
		var titre = offer.getElementsByTagName("ProductName")[0].firstChild.nodeValue;
	}
	imgURL = imgURL ? imgURL.getElementsByTagName('Url')[0].firstChild.nodeValue : '';
	var cat = offer.getElementsByTagName("Category")[0].getAttribute("id");
	var compareURL = offer.getElementsByTagName("CompareUrl")[0];
	if (compareURL) {
		var url = compareURL.firstChild.nodeValue;
	} else {
		var url = 'http://fr.kelkoo.com/ctl/do/search?siteSearchQuery='+titre+'&catId='+cat+'&kpartnerid=96909673&partner=kelkoo';
	}	
	var content = document.createElement("div");
	
	content.innerHTML = '<div class="offerPush">' +
					'<div class="pushFirstRow">' +
						'<a href="'+url+'" target="_blank"><img src="'+imgURL+'" width="50" /></a>' +
					'</div>' +
					'<div class="pushSecondRow"><a href="'+url+'" target="_blank">'+
						'<div class="price">'+price+' &#8364;</div>' +
						'<div class="title">'+titre + '</div>' +
					'</a></div>' +
					'<div class="offerPushList">'+
						'<a href="'+node.getAttribute("href")+'">Cliquez ici pour afficher les meilleurs prix</a>'+
					'</div>' +
				'</div>';
				
	var align = node.getAttribute("myAlign");
	if (align=="center") {
		content.firstChild.style.margin = "3px auto 3px";
	} else {
		content.style.styleFloat = align; // ie
		content.setAttribute("style","float:"+align); // moz
	}	
	
	node.parentNode.insertBefore(content, node);
	node.parentNode.removeChild(node);
}

function displayListe(feed, node) {
	var container = document.createElement("div");
	container.className = "offerListEmbedded";
	container.innerHTML = '<div class="offerStyle">'+getBestPrices_List(feed.getElementsByTagName("Products")[0])+'</div>';
	node.parentNode.insertBefore(container, node);
	node.parentNode.removeChild(node);
}	

function updatePopupPosition() {
	ie = window.ActiveXObject ? true : false;
	var div = document.getElementById("kelkooPopup");
	if (div) {
		//div.style.top = (getScrollTop() + 200) +"px";
		// IE6 detection
		if (ie & !(window.XMLHttpRequest)) {
			div.style.position = 'absolute';
			div.style.top = (document.documentElement.scrollTop + 20) + 'px';
		} else if (ie) {	
			div.style.top = '20px';
		} else {
			div.style.top = (self.innerHeight/2 - 200) + 'px';
		}
		//div.style.top = ie ? ietruebody().scrollTop+(ietruebody().clientHeight/2)-200+"px" : self.innerHeight/2-200+"px";
	}
}

function closePopup() {
	var div = document.getElementById("kelkooPopup");
	div.innerHTML = "";
	// div.style.visibility="hidden";
	// FlorentS fix
	div.style.display = 'none';
}

function setOfferLinks() {
	var l = document.links.length;
	// duplicate of the array so that the links list doesn't get realtime uptdated when dynamic building the thing
	var linksArray = new Array();
	for (var z=0; z<l; z++) {
		linksArray.push(document.links[z]);
	}	
	for (z=0; z<l; z++) {
		var str = linksArray[z].getAttribute("href");
		var first = str.lastIndexOf("/", str.length);
		var hrefString = str.slice((first==-1)?0:first+1, str.length);
		var node = linksArray[z];
		if (hrefString.slice(0,6)=="kelkoo") {
			var splitStr = hrefString.split(":");
			var newStr = (splitStr.length>1) ? splitStr[1] : node.firstChild.nodeValue;
			var catIDForced = (splitStr.length>2 && splitStr[2]!="left" && splitStr[2]!="right" && splitStr[2]!="center") ? splitStr[2] : '';
			if (splitStr.length>3) {
				catIDForced = splitStr[3];
			}			
			node.setAttribute("href", "javascript:displayBestPrices('"+newStr.replace(/'/g,"\\'")+"','"+catIDForced+"')");
			node.setAttribute("query", newStr);
			node.onmouseover = function() {
				showOfferTip(this, this.getAttribute("query"));
			}
			if (node.firstChild.nodeValue=="push") {
				if (splitStr.length>2) {
					var myAlign = splitStr[2];
				} else {
					var myAlign = "left";
				}
				node.setAttribute("myAlign", myAlign);
				node.setAttribute("style", "border: 1px dotted #CCC;padding-left:3px;padding-right:3px;");
				node.innerHTML = newStr.toUpperCase() + ' : Cliquez pour afficher les meilleurs prix !';
				var q = newStr; // (ie) ? newStr : encodeURIComponent(newStr);
				var catIDForced = (splitStr.length>3) ? splitStr[3] : '';
				catIDForced = (catIDForced=='') ? kelkooCatId : catIDForced;
				// var url = 'http://export.kelkoo.fr/ctl/exportSearch?partner=generationmp3&siteSearchQuery='+q+'&partnerId=96909673&partner=kelkoo&catId='+catIDForced+'&nbresult=1';
				var url = '/V3/productSearch?query=' + encodeURIComponent(q) + '&category=' + catIDForced + '&sort=default_ranking&logicalType=and&start=1&results=1&show_products=1&show_subcategories=0&show_refinements=1';
				loadXMLDoc(proxyURL+encodeURIComponent(url), displayPush, node);
			}
			if (node.firstChild.nodeValue=="liste") {
				var p = '';
				if (splitStr.length>2) {
					// p = '&nbresult='+splitStr[2];
					p = splitStr[2];
				}
				node.innerHTML = newStr.toUpperCase() + ' : Chargement de la liste des prix...';
				var q = splitStr[1]; //encodeURIComponent(splitStr[1]);
				// var url = 'http://export.kelkoo.fr/ctl/exportSearch?partner=generationmp3&siteSearchQuery='+q+'&partnerId=96909673&partner=kelkoo&catId='+kelkooCatId+p;
				var url = '/V3/productSearch?query=' + encodeURIComponent(q) + '&category=' + kelkooCatId + '&sort=default_ranking&logicalType=and&start=1&results= ' + p + '&show_products=1&show_subcategories=0&show_refinements=1';
				loadXMLDoc(proxyURL+encodeURIComponent(url), displayListe, node);
			}
		}
		if (node.firstChild && node.firstChild.nodeValue=="podcast_player") {
			var file = node.getAttribute("href");
			var content = document.createElement("div");
			content.innerHTML = '<object type="application/x-shockwave-flash" data="/common/player.swf?pod='+encodeURIComponent(file)+'" width="238" height="17">'+
						'<param name="movie" value="/common/player.swf?pod='+encodeURIComponent(file)+'" />'+
						'<param name="bgcolor" value="#FFF" />'+
						'</object>';
			node.parentNode.insertBefore(content, node);
			node.parentNode.removeChild(node);
		}
	}	
}

function showOfferTip(node, texte) {
	var str = node.getAttribute("href");
	var startIndex = str.indexOf("'", 0);
	var endIndex = str.lastIndexOf("'", str.length);
	var query = str.slice(startIndex+1, endIndex);
	var txt = "<div id='toolTipQueryName'>"+unescape(texte).toUpperCase()+"</div>Cliquez pour afficher les meilleurs prix de ce produit";
	showtip(node, txt, "150", "center");
}

window.onscroll = function() {
	updatePopupPosition();
}


function displayPodcastSelectionList(response, container) {
	var fileNodes = response.documentElement.getElementsByTagName("file");
	var ulDiv = document.createElement("div");
	ulDiv.style.marginTop = "5px";
	var ln = fileNodes.length;
	for (var z=0; z<ln; z++) {
		var node = fileNodes[z];
		var liDiv = document.createElement("div");
		liDiv.setAttribute("url", node.getAttribute("url"));		
		liDiv.style.cursor = "pointer";
		liDiv.style.background = "url(/common/images/speaker.gif) no-repeat 0 1px";
		liDiv.style.paddingLeft = "16px";
		liDiv.onmouseover = function() {
			if (this.getAttribute("selected")!=1) this.style.color = "#F60";
		}
		liDiv.onmouseout = function() {
			if (this.getAttribute("selected")!=1) this.style.color = "#333";
		}
		liDiv.onclick = function() {
			unselectAll();
			this.style.color = "#0099FF";
			this.setAttribute("selected", 1);
			var file = this.getAttribute("url");
			var podPlayer = document.getElementById("podPlayer");			
			podPlayer.style.marginTop = "5px";
			podPlayer.SetVariable("/fileChange:pod", encodeURIComponent(file));
			podPlayer.TPlay("/fileChange");
		}
		liDiv.appendChild(document.createTextNode(node.firstChild.nodeValue));
		ulDiv.appendChild(liDiv);
	}
	container.appendChild(ulDiv);
	var podPlayer = document.getElementById("podPlayer");
	
	function unselectAll() {
		var nodes = ulDiv.childNodes;
		var ln = nodes.length;
		for (var z=0; z<ln; z++) {
			nodes[z].setAttribute("selected", 0);
			nodes[z].style.color = "#333";
		}
	}
	
}


function loadXMLDoc2(url, doFunc, param) {
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {// only if req shows "loaded"
			if (req.status == 200) {// only if "OK"
				doFunc(req.responseXML, param);
			} else {
				alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	}
	req.open("GET", url, true);
	req.send(null);
}


function loadPodcastSelection(id) {	
	loadXMLDoc2(podcastSelectionFile, displayPodcastSelectionList, document.getElementById(id));
}

