/* Digit ry
* Foodlists javascript library
*
* created: 23.6.2006
* author: Jouni Koivuviita
**/


Object.extend(Digit, {

	menusOnPage:6,
	rowsOnPage:3,
	globalFoodLists:null,
	ruokalat:null,
	globalIndicator:null,
	globalAjaxRequest:null,
	globalSelectionId:null,

	initFoodList : function() {
		if(!document.getElementById || !document.createElement) return;	// Compatibility check
		
		var foodListOptions = Digit.getCookie("foodListOptions");
		if(foodListOptions) {
			var ops = foodListOptions.split(",");
			for(i=0; i < ops.length; i++) {
				var cb = $(ops[i]);
				cb.checked = true;
			}
		}
		
		Event.observe("foodListOptionsSubmit", 'click', function(){Digit.getLists(); return false;}, false);
		// TODO
		//Element.show("foodListOptions");
		Element.show("loading-menus");
		Element.hide("votelist");
		Element.hide("noScript");
		Element.hide("voteLoad");
		
		var prevListsEl = document.createElement("a");
		prevListsEl.setAttribute("href", "javascript:void(0)");
		prevListsEl.setAttribute("title", "Edelliset "+Digit.menusOnPage+" ruokalistaa");
		prevListsEl.setAttribute("id", "prevLists");		 
		prevListsEl.appendChild(document.createTextNode("« Edelliset"));
		$("prevListsDisabled").parentNode.insertBefore(prevListsEl, $("prevListsDisabled"));
		 
		var nextListsEl = document.createElement("a");
		nextListsEl.setAttribute("href", "javascript:void(0)");
		nextListsEl.setAttribute("title", "Seuraavat "+Digit.menusOnPage+" ruokalistaa");
		nextListsEl.setAttribute("id", "nextLists");		 
		nextListsEl.appendChild(document.createTextNode("Seuraavat »"));
		$("nextListsDisabled").parentNode.insertBefore(nextListsEl, $("nextListsDisabled"));
		
		Event.observe("nextLists", 'click', Digit.showNextLists, false);
		Event.observe("prevLists", 'click', Digit.showPrevLists, false);
		
		Element.hide("prevLists");
		Element.hide("nextLists");
		
		var mc = $("menus-container");
		mc.style.height = "0px";
		mc.style.overflow = "hidden";
		
		Event.observe("toggleLists", 'click', Digit.toggleLists, false);
		$("toggleLists").href = "javascript:void(null)";
		
		Digit.getLists();
		Digit.getTopRated();
	},

	getLists : function() {
		
		var l = $F('L');
		var vl = $F('VL');
		var m = $F('M');
		var g = $F('G');
		var vr = $F('VR');
		var veg = $F('VEG');
		
		var pars = "";
		
		if(l) pars += l;
		if(pars!="" && vl) pars += ",";
		if(vl) pars += vl;
		if(pars!="" && m) pars += ",";
		if(m) pars += m;
		if(pars!="" && g) pars += ",";
		if(g) pars += g;
		if(pars!="" && vr) pars += ",";
		if(vr) pars += vr;
		if(pars!="" && veg) pars += ",";
		if(veg) pars += veg;
		
		Digit.setCookie("foodListOptions",pars,168);
		if(pars != "") pars = "options=" + pars;
		
		var now = new Date();	
		pars += "&time="+now.getSeconds();
		
		globalAjaxRequest = new Ajax.Request(
									  "ruokalista/get_lists.php",
									  { 
									  	method: 'get',
									  	parameters: pars,
										onComplete: Digit.updateLists
									   });
		
		Element.hide("votelist");
		Element.show("voteInfo");
		Element.hide("menus");
		Element.show("loading-menus");
	},

	updateLists : function(originalRequest){
		if(originalRequest.responseText) Digit.globalFoodLists = Digit.parseStringToXML(originalRequest.responseText);
		else {
			Digit.closeLists();
			Element.hide("toggleLists");
		}
		 
		if(Digit.globalFoodLists) {
			globalIndicator = 0;
			globalSelectionId = null;
			 
			Element.show("nextListsDisabled");		 
			Element.hide("nextLists");	
			
			if(Digit.globalFoodLists.getElementsByTagName("ruokala").length > Digit.menusOnPage) {
				Element.hide("nextListsDisabled");
				Element.show("nextLists");
			};
			
			Element.show("prevListsDisabled");
			Element.hide("prevLists");
			Element.hide("loading-menus");
			
			Digit.showLists();
		};	
	},
	
	getTopRated : function() {
		var now = new Date();	
		var pars = "time="+now.getSeconds();
		
		AjaxRequest = new Ajax.Request(
						  "ruokalista/get_top_rated.php",
						  { 
							method: 'get',
							parameters: pars,
							onComplete: Digit.updateTopRated
						   });
	},
	
	updateTopRated : function(originalRequest) {
		var best = $("best");
		var top3 = $("top3");

		best.innerHTML = "";
	  	top3.innerHTML = "";
		
		var topRated;
		if(originalRequest.responseText) topRated = Digit.parseStringToXML(originalRequest.responseText);
		else {
			best.appendChild(document.createTextNode("Tulosta haettaessa tapahtui virhe."));
			var liEl = document.createElement("li");
			liEl.appendChild(document.createTextNode("Tuloksia haettaessa tapahtui virhe."))
			top3.appendChild(liEl);
			topRated = null;
		}
		
		if(topRated) dishes = topRated.getElementsByTagName("ruokalaji");
		
		// Todays best dish creation
		var scoreEl = document.createElement("strong");
		var scoreText = dishes[0].getAttribute("score")>0? "+"+dishes[0].getAttribute("score") : dishes[0].getAttribute("score");
		var score = document.createTextNode(scoreText);
		scoreEl.appendChild(score);
		
		var nameEl = document.createElement("span");
		nameEl.onclick = function() {Digit.changeSelection(this);};
		nameEl.title = "Äänestä tätä ruokalajia";
		nameEl.id = dishes[0].getAttribute("id");
		var name = document.createTextNode(dishes[0].getAttribute("name")+" ");
		nameEl.appendChild(name);
		
		var optsEl = document.createElement("em");
		var opts = document.createTextNode(dishes[0].getAttribute("options"));
		optsEl.appendChild(opts);
		
		var linkEl = document.createElement("a");
		linkEl.href = dishes[0].getAttribute("url");
		linkEl.title = "Siirry ruokalan sivuille";
		var linkSpan = document.createElement("span");
		var link = document.createTextNode(dishes[0].getAttribute("restaurant"));
		linkSpan.appendChild(link);
		linkEl.appendChild(linkSpan);
		
		best.appendChild(scoreEl);
		best.appendChild(nameEl);
		best.appendChild(optsEl);
		best.appendChild(linkEl);
		
		
		// Top 3 dishes creation
		if(dishes && dishes.length > 0) {
			for(var i=1; i < 4; i++) {
				var liEl = document.createElement("li");
				liEl.onclick = function() {Digit.changeSelection(this);};
				liEl.title = "Äänestä tätä ruokalajia";
				liEl.id = dishes[i].getAttribute("id");
				
				name = document.createTextNode(dishes[i].getAttribute("name")+" ");
				
				var optsEl = document.createElement("em");
				optsEl.className = "note";
				var opts = document.createTextNode(dishes[i].getAttribute("options"));
				optsEl.appendChild(opts);
				
				var scoreEl = document.createElement("strong");
				var scoreText = dishes[i].getAttribute("score")>0? "+"+dishes[i].getAttribute("score") : dishes[i].getAttribute("score");
				var score = document.createTextNode(" " + scoreText +" / " + dishes[i].getAttribute("votes") + " ääntä ");
				scoreEl.appendChild(score);
				
				var linkEl = document.createElement("a");
				linkEl.href = dishes[i].getAttribute("url");
				linkEl.title = "Siirry ruokalan sivuille";
				var link = document.createTextNode(dishes[i].getAttribute("restaurant"));
				linkEl.appendChild(link);
				
				liEl.appendChild(name);
				liEl.appendChild(optsEl);
				liEl.appendChild(scoreEl);
				liEl.appendChild(linkEl);
				
				top3.appendChild(liEl);
			}
		} else {
			var liEl = document.createElement("li");
			liEl.appendChild(document.createTextNode("Ruokalajeilla ei ole vielä positiivista tulosta."))
			top3.appendChild(liEl);
		}
	},

	/* Build a cross-browser compatible xml-dom from a given string
	**/
	parseStringToXML : function(response) {
		var xml = Try.these(
			function() { return new DOMParser().parseFromString(response, 'text/xml'); },
			function() { var xmldom = new ActiveXObject('Microsoft.XMLDOM'); xmldom.loadXML(response); return xmldom; }
			);
		return xml;
	},



	/* Actual building of html-elements and adding the list to the DOM
	**/
	showLists : function() {
		ruokalat = Digit.globalFoodLists.getElementsByTagName("ruokala");	
		var menusDiv = document.getElementById("menus");
		
		while (menusDiv.childNodes.length > 0) {
	  		menusDiv.removeChild(menusDiv.firstChild);
		};
		
		for(i=globalIndicator; i<ruokalat.length && i<globalIndicator+Digit.menusOnPage; i++) {
			
			var containerDivEl, newRow;
			if(i%parseInt(Digit.menusOnPage/Digit.rowsOnPage)==0) {
				containerDivEl = document.createElement("div");						// Div-container for each row
				containerDivEl.className = "row";
				newRow = true;
			}
			else newRow = false;
			
			var divEl = document.createElement("div");								// Create a new <div> for a new foodlist
			divEl.className = "menu"; 												// and add class="menu"
			var aEl = document.createElement("a"); 									// Create a link element for restaurants name
			aEl.setAttribute("href", ruokalat[i].getAttribute("url"));				// and set it's href
			var textEl = document.createTextNode(ruokalat[i].getAttribute("name"));	// Create the actual restaurant name
			aEl.appendChild(textEl);												// and append it to the a-element
			divEl.appendChild(aEl);													// Add the link to the menu-div
			var ulEl = document.createElement("ul");								// Create the ul-list element
					
			var currentElement = ruokalat[i].firstChild;
			if(currentElement) {
				do {
					if(currentElement.nodeType == 1) { 										// If an element node, not whitespaces
					
						var liEl = document.createElement("li");										// Create the li-element
						if(Math.floor(currentElement.getAttribute("score")/currentElement.getAttribute("votes")*100) >= 50) liEl.className = "high-rated";
						liEl.setAttribute("id", currentElement.getAttribute("id"));
						var textEl2 = document.createTextNode(currentElement.firstChild.nodeValue+" ");	// and the text for the menu-item
						if(textEl2.nodeValue.toLowerCase()!="ei tietoja. ") liEl.onclick = function() {Digit.changeSelection(this);};
						liEl.appendChild(textEl2);														// and append it
						var spanEl = document.createElement("span");									// Create a span-element for the options
						spanEl.className = "note";
						var textEl3 = document.createTextNode(currentElement.getAttribute("options")); 	// and the actual options
						spanEl.appendChild(textEl3);													// and append it
						liEl.appendChild(spanEl);														// Finally add the options after the item name
						ulEl.appendChild(liEl);															// and append the menu-item to the list
						
					};
				} while(currentElement = currentElement.nextSibling)
			};
			
			divEl.appendChild(ulEl);								// Add the full list to the menu-div
			containerDivEl.appendChild(divEl);						// Add the menu-div to the row-container
			
			if(newRow) menusDiv.appendChild(containerDivEl);		// Add the whole container to the page
		};
		
		Element.show("menus");
		
		Digit.updateIndicator();
		
		if(!Digit.getCookie("foodlistsOpen") || Digit.getCookie("foodlistsOpen") == "true") Digit.openLists();
		else Digit.closeLists();
	},



	updateIndicator : function() {
		var element = document.getElementById("foodListIndicator");
		element.removeChild(element.firstChild);
		var end = (ruokalat.length-globalIndicator > Digit.menusOnPage)? globalIndicator+Digit.menusOnPage : ruokalat.length;
		var textEl = document.createTextNode("Näytetään listat " + (globalIndicator+1) + "-" + end + " / " + Digit.globalFoodLists.getElementsByTagName("ruokala").length);
		element.appendChild(textEl);
	},


	showNextLists : function() {
		Element.hide("loading-menus");
		Element.show("nextLists");
		Element.show("prevLists");
		Element.hide("nextListsDisabled");
		Element.hide("prevListsDisabled");
		globalIndicator += Digit.menusOnPage;
		if(globalIndicator + Digit.menusOnPage >= ruokalat.length) {
			Element.hide("nextLists");
			Element.show("nextListsDisabled");
		};
		globalSelectionId = null;
		Element.hide("votelist");
		Element.show("voteInfo");
		Digit.showLists();
	},

	showPrevLists : function() {
		//Element.hide("loading-menus");
		Element.show("nextLists");
		Element.show("prevLists");
		Element.hide("nextListsDisabled");
		Element.hide("prevListsDisabled");
		globalIndicator -= Digit.menusOnPage;
		if(globalIndicator <= 0) {
			globalIndicator = 0;
			Element.hide("prevLists");
			Element.show("prevListsDisabled");
		};
		globalSelectionId = null;
		Element.hide("votelist");
		Element.show("voteInfo");
		Digit.showLists();
	},


	changeSelection : function(element) {
		if(!element.id || parseInt(element.id) == NaN) return;
		
		if(Digit.globalSelectionId != null) {
			var el = $(Digit.globalSelectionId);
			if(el) {
				if(el.className.indexOf("high-rated")>-1) el.className = "high-rated";
				else el.className = "";
			}
		}
		Digit.globalSelectionId = element.id;
		element.className += " selected";
		
		var pars = "id="+element.id;
		var now = new Date();	
		pars += "&time="+now.getSeconds();
		var ajaxCall = new Ajax.Request(
									  "ruokalista/get_vote.php",
									  { 
									  	method: 'get',
									  	parameters: pars,
										onComplete: Digit.showResult
									   });
		
		Element.hide("voteInfo");
		Element.hide("votelist");
		Element.show("voteLoad");
		
		return true;
	},

	showResult : function(originalRequest){
		var xmldoc = Digit.parseStringToXML(originalRequest.responseText);
		var score = Number(xmldoc.documentElement.getAttribute("score"));
		var votes = Number(xmldoc.documentElement.getAttribute("votes"));
		var name = xmldoc.documentElement.getAttribute("name");
		
		var votelist = $("votelist");
		
		while(votelist.childNodes.length>0) {
	  		votelist.removeChild(votelist.firstChild);
		}
		
		var nameEl = document.createTextNode(name);
		var scoreEl = document.createTextNode((score>0)? " +"+score : " "+score);
		var votesEl = document.createTextNode("Ääniä annettu yhteensä "+votes);
		
		var nameContainer = document.createElement("span");
		nameContainer.className = "name";
		nameContainer.appendChild(nameEl);
		
		var scoreContainer = document.createElement("span");	
		scoreContainer.className = (score>0)? "score-plus" : "score-minus";
		scoreContainer.appendChild(scoreEl);
		
		var votesContainer = document.createElement("span");
		votesContainer.className = "votes";
		votesContainer.appendChild(votesEl);
		
		var voteContainer = document.createElement("div");
		voteContainer.className = "vote-links";
		
		var minusEl = document.createElement("a");
		var plusEl = document.createElement("a");
		var minusText = document.createTextNode("-");
		var plusText = document.createTextNode("+");
		minusEl.setAttribute("href","javascript:Digit.setVote(-1)");
		plusEl.setAttribute("href","javascript:Digit.setVote(1)");
		minusEl.setAttribute("title","Anna valitulle ruokalajille miinus-ääni");
		plusEl.setAttribute("title","Anna valitulle ruokalajille plus-ääni");
		minusEl.className = "vote-minus";
		plusEl.className = "vote-plus";
		minusEl.appendChild(minusText);
		plusEl.appendChild(plusText);
		
		voteContainer.appendChild(minusEl);
		voteContainer.appendChild(plusEl);
		
		var container = document.createElement("p");
		var nameAndVotesContainer = document.createElement("div");
		nameAndVotesContainer.className = "name-and-votes";
		
		container.appendChild(scoreContainer);
		nameAndVotesContainer.appendChild(nameContainer);
		nameAndVotesContainer.appendChild(votesContainer);
		container.appendChild(nameAndVotesContainer);
		container.appendChild(voteContainer);
		
		votelist.appendChild(container);
		
		Element.hide("voteLoad");
		Element.show("votelist");	
	},


	setVote : function(vote) {
		if(!Digit.getCookie("foodItem_"+Digit.globalSelectionId)) {		
			var today = new Date();
			
			// Valid for 12 minutes
			Digit.setCookie("foodItem_"+Digit.globalSelectionId, vote, 0.01);
			
			var url = "/ruokalista/get_top_rated.php";
			var pars = "food=" + Digit.globalSelectionId + "&vote=" + vote + "&time=" + today.getSeconds();
			var topRatedAjax = new Ajax.Request(
									  "ruokalista/get_top_rated.php",
									  { 
									  	method: "get",
									  	parameters: pars,
										onComplete: Digit.updateTopRated
									   });
									   
			Digit.changeSelection($(Digit.globalSelectionId));
			
		} else alert("Olet jo antanut äänesi tälle ruokalajille");
	},
	
	
	openLists : function() {
		Digit.listsOpen = true;
		Element.show("foodListIndicator");
		Element.show("nextLists");
		Element.show("prevLists");
		Element.hide("nextListsDisabled");
		Element.hide("prevListsDisabled");
		if(globalIndicator + Digit.menusOnPage >= ruokalat.length) {
			Element.hide("nextLists");
			Element.show("nextListsDisabled");
		};
		if(globalIndicator <= 0) {
			globalIndicator = 0;
			Element.hide("prevLists");
			Element.show("prevListsDisabled");
		};
		Element.hide("votelist");
		Element.show("voteInfo");
		
		var menusHeight = $("menus").offsetHeight;
		var optionsHeight = $("foodListOptions").offsetHeight + 20;
		var height = (menusHeight > optionsHeight)? menusHeight : optionsHeight;
		clearTimeout(Digit.loopTimeout[0]);
		Digit.posAndSizeAnim("menus-container",null,null,null,height,0,30);
		
		$("toggleLists").innerHTML = "Piilota listat";
		
		Digit.setCookie("foodlistsOpen", "true", 168);
	},
	
	closeLists : function() {
		Digit.listsOpen = false;
		Element.hide("foodListIndicator");
		Element.hide("nextLists");
		Element.hide("prevLists");
		Element.hide("nextListsDisabled");
		Element.hide("prevListsDisabled");
		Element.hide("votelist");
		Element.show("voteInfo");
		
		clearTimeout(Digit.loopTimeout[0]);
		Digit.posAndSizeAnim("menus-container",null,null,null,0,0,30);
		
		$("toggleLists").innerHTML = "Näytä kaikki listat";
		
		Digit.setCookie("foodlistsOpen", "false", 168);
	},
	
	
	listsOpen:false,
	
	toggleLists : function() {
		if(Digit.listsOpen) {
			Digit.closeLists();
		} else {
			Digit.openLists();
		}
		return false;
	}

});

Event.observe(window, 'load', Digit.initFoodList, false);
