// My Search Object
// (C) Copyright 2008, AMR Systems, LLC
// Author: Nick Benik
// Last Update: 7-17-2007
// Last Update By: Al Sierra 03-11-09

var MySearch = {
	_dispmode:'ALL', // can be ALL, STARTERS, ENTREES, DESSERTS
	_pagecnt: 0,
	_pagecurrent: 1,
	_dishestotal: 0,
	_NOWdishes: 0,
	_pairings: [],
	_c_excludes: [],
	_dishes: [],
	_keyword: '',
	init: function() {
		// this is the initializer for the search object and only fires when
		// the Javascript file is loaded
		var page = getCookie('currentpage');
		//alert("PAGE Number: " + page);
		var temp = getCookie('searchmode');
		var keyword = getCookie('keyword');
		if (temp!==null) { this.SearchMode(temp,false); }
		if (page!==null) { this._pagecurrent=page; }
		if (keyword!==null) { 
			if(keyword == 'undefined'){
				this._keyword=''; 
			} else {
				this._keyword=keyword; 
				if(this._keyword != ''){
					$('keyword_input').value = this._keyword;
					$('keyword_input').style.color = '#FF9900';				
				}
			}
		}
		this.GetResults.call(this);
	},
	SearchMode: function(setmode, dosearch) {
		var t, tid;
		// this set's the search mode and fires new search if it was changed
		if (setmode != 'ALL' && setmode!='STARTERS' && setmode!='ENTREES' && setmode!='DESSERTS') { return false; }
		//if (setmode == this._dispmode) { return false; }
		// update the HTML (first turn off the old selection, then turn on new selection)
		tid = this._id_2_tab(this._dispmode);
		if (setmode == this._dispmode) { $(tid).style.cursor='default';return false; }
		$(tid).style.cursor='pointer';
		setTimeout("changeTabs('"+tid+"', false)",250);
		tid = this._id_2_tab(setmode);
		changeTabs(tid, true);
		$(tid).style.cursor='default';
		setTimeout("$('"+tid+"').blur()",100);
		// save change to search mode
		this._dispmode = setmode;
		setCookie('searchmode',setmode,120,'/',document.domain,false);
		if (dosearch) {
			// do search, save mode & page
			this._pagecurrent = 1;
			setCookie('currentpage',1,120,'/',document.domain,false);
			//Set Refresh Banner Ad's to true
			BannerRefresh.SetRefresh();
			// refresh search
			this.GetResults.call(this);
		}
	},
	PrevPage: function() {
		if (this._pagecurrent > 1) { 
			this._pagecurrent = this._pagecurrent - 1;
			this.SetPage(this._pagecurrent);
		}
	},
	NextPage: function() {
		//if (this._pagecurrent < this._pagecnt - 1) {
		if (this._pagecurrent < this._pagecnt) { 
			this._pagecurrent = this._pagecurrent + 1;
			this.SetPage(this._pagecurrent);
		}
	},
	SetPage: function(pagenum) {
		pagenum = pagenum * 1;
		if (pagenum < 1) {
			pagenum = 1;
		} else if (pagenum > this._pagecnt) {
			pagenum = this._pagecnt;
		}
		this._pagecurrent = pagenum;
		//alert("setPage number to: " + pagenum);
		setCookie('currentpage',pagenum,120,'/',document.domain,false);
		//alert("setPage cookie: " + getCookie('currentpage'));
		//Set Refresh Banner Ad's to true
		BannerRefresh.SetRefresh();
		// reissue search
		this.GetResults.call(this);
	},
	//Addition by AL  3-11-09
	SubmitKeyword: function() {
		//$('search_btn_keyword_img').style.cursor='wait';
		var keyword;
		keyword = $('keyword_input').value;
		if(keyword == 'Enter Keyword'){
			keyword = '';
			$('keyword_input').focus()
			$('search_btn_keyword_img').style.cursor='pointer';
			return false;
		}
		this._keyword = keyword;
		//Set Refresh Banner Ad's to true
		BannerRefresh.SetRefresh();
		// issue search
		this._pagecurrent = 1;
		setCookie('currentpage',1,120,'/',document.domain,false);
		this.GetResults.call(this);
	},
	//Addition by AL  3-11-09
	CancelKeyword: function() {
		//if(!confirm("Are you sure you want to cancel this keyword search?")){return false;}
		//$('cancel_btn_keyword_img').style.cursor='wait';
		this._keyword = '';
		// Set Page and Reissue results without keyword parameter
		this._pagecurrent = 1;
		setCookie('currentpage',1,120,'/',document.domain,false);
		this.GetResults.call(this);
		$('keyword_input').value = 'Enter Keyword';
		$('keyword_input').style.color = '#CCCCCC';
	},
	GetResults: function() {
		//return false;
		deleteCookie('currentpage','/',document.domain);
		var ingr, hingr, exingr, params; 
		
		//added by assaf
		if (MyKitchen._ingredients==""){
			this._keyword = '';
			setCookie('keyword',this._keyword,120,'/',document.domain,false);
			}
		
		// get the inputs for the search call
		ingr = MyKitchen.GetIngredients();
		ingr = ingr.join('|');
		hingr = MyKitchen.GetHighlighted();
		hingr = hingr.join('|');
		exingr = MyKitchen.GetExclude();
		exingr = exingr.join('|');	
		
		// Perform Search
		params = $H({kitchen:ingr, 
					 focus:hingr,
					 exclude:exingr,
					 kw:this._keyword,
					 smode:this._dispmode,
					 page:this._pagecurrent}).toQueryString();
		params = params + "&UID="+jsUID + "&seed="+getCookie('seed');

		// Added by Assaf, use GET request if URL is short, for performance boost
		if (params.length<2000) {
			new Ajax.Request(
				'/575/main_search.asp?'+params,
				{
					method:'get',
					//postBody: params,
					onSuccess: MySearch._CBS_search,
					onFailure: MySearch._CBF_search,
					onError: MySearch._CBE_search
				}
			);
		} else  {
			new Ajax.Request(
				'/575/main_search.asp',
				{
					method:'post',
					postBody: params,
					onSuccess: MySearch._CBS_search,
					onFailure: MySearch._CBF_search,
					onError: MySearch._CBE_search
				}
			);
		}
	},
	_id_2_tab: function(idname) {
		switch (idname) {
			case "ALL":
				return 'tab0';
			case "STARTERS":
				return 'tab1';
			case "ENTREES":
				return 'tab2';
			case "DESSERTS":
				return 'tab3';
		}
	},
	_CBS_search: function(t) {
		// Call-Back Success for the GetResults AJAX call
		try {
			var robj = eval("("+t.responseText+")");
		} catch(e) {
			alert("Sorry, there was an error contacting the website. \nPlease reload the page."); 
			return false;
		}
		var t = MySearch;
		t._pairings = robj.paired;
		t._dishes = robj.results;
		t._pagecurrent = robj.ThisPage;
		//added 09-18-2007 by ct
		//reset cookie page number
		
		//deleteCookie('currentpage','/',document.domain);
		setCookie('currentpage',t._pagecurrent,120,'/',document.domain,false);
		//Addition by AL  3-11-09
		setCookie('keyword',t._keyword,120,'/',document.domain,false);
		//alert("_CBS_search cookie: " + getCookie('currentpage'));

		t._pagecnt = robj.TotalPages;
		t._dishestotal = robj.TotalDishes;
		t._DishesUserCanMake = robj.DishesUserCanMake;

		// render the AJAX results
		t._render_pairings.call(t);
		t._update_common_excludes.call(t);		
		t._render_results.call(t);
		// scroll to the top of the page (show first result)
		scroll(0,0);
	},
	_CBE_search: function(t) {
		// Call-Back Error for the GetResults AJAX call
		alert("Sorry, there was an error contacting the website. \nPlease press F5 to reload the page."); 
	},
	_CBF_search: function(t) {
		// Call-Back Failure for the GetResults AJAX call
		alert("Sorry, there was a failure while contacting the website. \nPlease press F5 to reload the page."); 
	},
	_render_pairings: function() {
		var ps, w, m, l, p, i, s, cloneDIV;
		// clear out the parent container DIV
		p = $('recommended_content');
		while( p.hasChildNodes() ) { p.removeChild( p.lastChild ); }
		// generate dynamic ranking bands
		m=0;
		for (i=0,l=this._pairings.length; i < l; i++) {
			if (m < this._pairings[i].Weight) { m=this._pairings[i].Weight }
		}
		ps = [];
		i = m/5;
//		i = i.toFixed();  Thanks Safari!
		ps[1] = i*1;
		ps[2] = i*2;
		ps[3] = i*3;
		ps[4] = i*4;		
		// populate
		for (i=0,l=this._pairings.length; i < l; i++) {
			cloneDIV = $('recommended_template').cloneNode(true);
			// do strength
			w=this._pairings[i].Weight;
			if (w < ps[1]) {
				m = 5;
			} else if (w < ps[2]) {
				m = 4;
			} else if (w < ps[3]) {
				m = 3;
			} else if (w < ps[4]) {
				m = 2;
			} else {
				m = 1;
			}
			// deal with DOM stuff
			cloneDIV.className = 'recommended_level'+m;
			cloneDIV.lastChild.innerHTML = this._pairings[i].Name;
			// add a space so IE performs line wraps
			s = document.createTextNode(" ");
			p.appendChild(cloneDIV);
			p.appendChild(s);
			cloneDIV.show();
		}
	},
	_render_results: function() {
		var l, i, i2, p, p2, t, n,cloneDIV, DivNodes;
		// clear out the parent container DIV
		p = $('search_results_content');
		while( p.hasChildNodes() ) { p.removeChild( p.lastChild ); }
		
		// render search results header DIV
		cloneDIV = $('search_results_header').cloneNode(true);
		cloneDIV.id = '';
		//alert("kitchen ingredients: " +MyKitchen._ingredients);
		

		//if the kitchen is empty, prompt the user to add ingredients, first
		//if no recipes are found but the kitchen isnt empty, print a different message
		
		if (this._dishestotal == 0) {
			if (MyKitchen._ingredients=="") {
				cloneDIV.innerHTML = 'First time here? <a href="/tour.asp">click here to watch a brief video tour</a><br><br>Supercook is a new recipe search engine that finds recipes you can make with only the ingredients you have at home.  To begin, simply start adding ingredients you have in the green box on the top left. The more ingredients you add, the better the results will be.<br/><br/><br/>';
				//Addition by AL  3-11-09: Set keyword to empty and default everything associated to the keyword
				//$('search_results_keyword').style.display = 'none';	
				$('keyword_input').value = 'Enter Keyword';
				$('keyword_input').style.color = '#CCCCCC';
				this._keyword = '';
				setCookie('keyword',this._keyword,120,'/',document.domain,false);

				$('a_recommended').style.display='none';					
				//*/			
			} else {
				if (this._keyword.length>0) {
					cloneDIV.innerHTML = 'No "'+ this._keyword+'" recipes found.<br><br>To cancel your keyword search, click the "Cancel" button in the "Keyword Search" section on the left';
				}else{
					cloneDIV.innerHTML = 'No recipes found.';
				}
				
				//Addition by AL  3-11-09: Display Keyword
				$('a_recommended').style.display = 'block';
			}
		} else {
			
			//alert(this._dispmode);
			if (this._dispmode == "ALL") {
				rName = "recipe";
			}
			if (this._dispmode == "STARTERS") {
				rName = "starter";
			}
			if (this._dispmode == "ENTREES") {
				rName = "entrée";
			}
			if (this._dispmode == "DESSERTS") {
				rName = "dessert";
			}

			if (this._DishesUserCanMake > 1) {
				//makes the plural out of the noun above
				addS = "s";
			} else {
				addS = "";
			}
			
			if (this._dishestotal > 1) {
				addRS = "s";
			} else {
				addRS = "";
			}
			
			var to_append;
			to_append='';
			
			if (this._keyword.length>0){ to_append= ' "'+this._keyword+'"'; }	

			if (this._DishesUserCanMake == 0) {
				if (this._dishestotal==2000){
					cloneDIV.innerHTML = 'Top '+this._dishestotal+to_append+' recipes returned';
				}else {
					cloneDIV.innerHTML = 'Found '+this._dishestotal+to_append+' recipe'+addRS+'.';
				}
			} else if (this._dishestotal==2000){
					cloneDIV.innerHTML = 'Top '+this._dishestotal+to_append+' recipes returned.<br />You can make <span class=\"search_results_header_hl\">'+this._DishesUserCanMake+'</span> '+rName+addS+' right now!';
			} else {
					cloneDIV.innerHTML = 'Found '+this._dishestotal+to_append+' recipe'+addRS+'.<br />You can make <span class=\"search_results_header_hl\">'+this._DishesUserCanMake+'</span> '+rName+addS+' right now!';
					}
			
			//Addition by AL  3-11-09
			if (MyKitchen._ingredients!="") { $('a_recommended').style.display = 'block'; }
		}
		//Addition by AL  3-11-09
		//$('search_btn_keyword_img').style.cursor='pointer';
		//$('cancel_btn_keyword_img').style.cursor='pointer'; 
		//*/
		p.appendChild(cloneDIV);
		cloneDIV.show();
		
		// render the dishes returned
		var thref;
		for (i=0,l=this._dishes.length;i<l; i++) {
			cloneDIV = $('search_results_template').cloneNode(true);
			cloneDIV.id = this._dishes[i].URL;
			if (i % 2 == 1) {
				cloneDIV.className = 'search_results_onRow';
			} else {
				cloneDIV.className = 'search_results_offRow';
			}
			
			////if (this._dishes[i].URL.indexOf('martha') > 0) { cloneDIV.className = 'search_results_featuredRow';}
			
			
			DivNodes = cloneDIV.getElementsByClassName('search_results_dishName');
			DivNodes[0].firstChild.innerHTML = this._dishes[i].Name;
			DivNodes[0].firstChild.href = this._dishes[i].URL.replace('~','&');
			
			//added by assaf
			DivNodes = cloneDIV.getElementsByClassName('search_results_domain');

			///if (this._dishes[i].URL.indexOf('martha') > 0) {
			///    DivNodes[0].innerHTML = '<font color="red" face="arial">Featured Recipe</font>&nbsp;&nbsp;&nbsp;' + this._dishes[i].URL.replace('~','&').match(/:\/\/(.[^/]+)/)[1];
			///    } else {
			///        DivNodes[0].innerHTML= this._dishes[i].URL.replace('~','&').match(/:\/\/(.[^/]+)/)[1];
			///    }
			
			DivNodes[0].innerHTML = this._dishes[i].URL.replace('~','&').match(/:\/\/(.[^/]+)/)[1];
		
			
			DivNodes = cloneDIV.getElementsByClassName('search_results_suggest');
			if (!this._dishes[i].Needed) {
				DivNodes[0].innerHTML = "<div style='margin-top:5px;'><img src='/images/ok_16.gif' alt='ok' width='16' height='16' align='texttop' /> &nbsp; You have everything needed for this recipe!</div>";
			} else {
				DivNodes[0].innerHTML = "You will also need:";
				// add the needed LIs
				p2 = cloneDIV.getElementsByTagName('UL');
				p2 = p2[0];
				for (i2=0;i2<this._dishes[i].Needed.length;i2++) {
					n = $('search_results_needed').cloneNode(true);
					n.id='';
					n.lastChild.innerHTML=this._dishes[i].Needed[i2];
					p2.appendChild(n);
					n.show();
				}
			}
			// work with the "SAVE(D)" image
			var timg = cloneDIV.getElementsByTagName('IMG');
			timg[timg.length-1].parentNode.id='dishid-'+this._dishes[i].UID;
			delete thref;
			if (this._dishes[i].Saved == 1) { 
				// this dish is already saved
				tnode = timg[timg.length-1];
				tnode.src = '/images/saved_btn.gif';
				tnode.alt = 'Saved';
				tnode.style.cursor='default';
				// remove the javascript functions (step 1)
				thref = timg[timg.length-1].parentNode;				
			}
			// get the thumbnail image reference
			DivNodes = cloneDIV.getElementsByClassName('search_results_image');
			if (this._dishes[i].Thumb) { 
				DivNodes[0].firstChild.lastChild.src = this._dishes[i].Thumb;
				DivNodes[0].firstChild.href = this._dishes[i].URL.replace('~','&');
			} else {
				// default image based on type of dish
				switch (this._dishes[i].Dish) {
					case 'STARTER':
						t = '/images/search_starter.jpg';
						break;
					case 'ENTREE':
						t = '/images/search_entree.jpg';
						break;
					case 'DESSERT':
						t = '/images/search_dessert.jpg';
						break;
					default:
						t = '/images/search_default.jpg';
						break;
				}
				//alert(DivNodes[0].firstChild.src);
				//DivNodes[0].firstChild.src = t;
				DivNodes[0].firstChild.lastChild.src = t;
				DivNodes[0].firstChild.href = this._dishes[i].URL.replace('~','&');
			}
			p.appendChild(cloneDIV);
			cloneDIV.show();

		}
		// build page listing
		if (i % 2 == 1) {
			n = 'search_results_onRow';
		} else {
			n = 'search_results_offRow';
		}
		// basic containters and label
		cloneDIV = Builder.node('div',{className:n});
		p.appendChild(cloneDIV);
		n = Builder.node('div',{className:'search_results_pagination'});
		cloneDIV.appendChild(n);
		cloneDIV = n;
		n = Builder.node('div',{className:'search_results_page_number_name'});
		cloneDIV.appendChild(n);
		// [Previous] link
		n = Builder.node('div',{className:'search_results_nav_links'});
		n.innerHTML = "&laquo; <a class='pagination' id='nextpglink' name='nextpglink' href='Javascript:void(0)' onclick='MySearch.PrevPage()'>Previous</a>";
		cloneDIV.appendChild(n);
		
		// build the page linkbar
		if (this._pagecnt < 13) {
			// scenario 1: 20 or less pages
			for (i=1,l=this._pagecnt+1; i < l; i++) {
				if (i == this._pagecurrent) {
					n = Builder.node('div',{className:'search_results_page_number_selected'});
					n.innerHTML=i;
				} else {
					n = $('search_results_page_number_template').cloneNode(true);
					n.id = '';
					n.firstChild.innerHTML=i;
				}
				cloneDIV.appendChild(n);
				n.style.display='';
			}			
		} else {
			if (this._pagecurrent < 11 ) {
				// scenario 2: 1,2,3,4,5...last
				for (i=1; i < 12; i++) {
					if (i == this._pagecurrent) {
						n = Builder.node('div',{className:'search_results_page_number_selected'});
						n.innerHTML=i;
					} else {
						n = $('search_results_page_number_template').cloneNode(true);
						n.id = '';
						n.firstChild.innerHTML=i;
					}
					cloneDIV.appendChild(n);
					n.style.display='';
				}
				// add dotted div
				n = $('search_results_page_dots_template').cloneNode(true);
				n.id = '';
				cloneDIV.appendChild(n);
				n.style.display='';
				// last page
				n = $('search_results_page_number_template').cloneNode(true);
				n.id = '';
				n.firstChild.innerHTML=this._pagecnt;
				cloneDIV.appendChild(n);
				n.style.display='';
			} else if ((this._pagecnt - this._pagecurrent) < 11) {
				// scenario 3: 1...12,13,14,15,last
				// first page
				n = $('search_results_page_number_template').cloneNode(true);
				n.id = '';
				n.firstChild.innerHTML='1';
				cloneDIV.appendChild(n);
				n.style.display='';
				// add dotted div
				n = $('search_results_page_dots_template').cloneNode(true);
				n.id = '';
				cloneDIV.appendChild(n);
				n.style.display='';
				// last 20 pages (including selected page)
				if (this._pagecurrent < (this._pagecnt - 11)) {
					m = this._pagecurrent;
				} else {
					m = this._pagecnt - 11;
				}
				for (i=m,l=this._pagecnt+1; i < l; i++) {
					if (i == this._pagecurrent) {
						n = Builder.node('div',{className:'search_results_page_number_selected'});
						n.innerHTML=i;
					} else {
						n = $('search_results_page_number_template').cloneNode(true);
						n.id = '';
						n.firstChild.innerHTML=i;
					}
					cloneDIV.appendChild(n);
				n.style.display='';
				}
			} else {
				// scenario 4: 1...12,13,14,15...last
				// first page
				n = $('search_results_page_number_template').cloneNode(true);
				n.id = '';
				n.firstChild.innerHTML='1';
				cloneDIV.appendChild(n);
				n.style.display='';
				// add dotted div
				n = $('search_results_page_dots_template').cloneNode(true);
				n.id = '';
				cloneDIV.appendChild(n);
				n.style.display='';
				// center pages
				for (i=this._pagecurrent-5 , l=this._pagecurrent+6; i < l; i++) {
					if (i == this._pagecurrent) {
						n = Builder.node('div',{className:'search_results_page_number_selected'});
						n.innerHTML=i;
					} else {
						n = $('search_results_page_number_template').cloneNode(true);
						n.id = '';
						n.firstChild.innerHTML=i;
					}
					cloneDIV.appendChild(n);
					n.style.display='';
				}
				// add dotted div
				n = $('search_results_page_dots_template').cloneNode(true);
				n.id = '';
				cloneDIV.appendChild(n);
				n.style.display='';
				// last page
				n = $('search_results_page_number_template').cloneNode(true);
				n.id = '';
				n.firstChild.innerHTML=this._pagecnt;
				cloneDIV.appendChild(n);
				n.style.display='';
			}
		}
		// [Next] link
		n = Builder.node('div',{className:'search_results_nav_links'});
		n.innerHTML = "<a class='pagination' id='nextpglink' name='nextpglink' href='Javascript:void(0)' onclick='MySearch.NextPage()'>Next</a> &raquo;";
		cloneDIV.appendChild(n);
		
	},
	_update_common_excludes: function() {
		this._set_common_excludes();
		var temparr = this._c_excludes;
		var excludearr = MyKitchen.GetExclude();
		for (var x=0; x < excludearr.length;x++){
			temparr = temparr.without(excludearr[x]);
		}
		this._c_excludes = temparr;
		this._render_common_excludes();
	},
	_set_common_excludes: function() {
		this._c_excludes.clear();
		this._c_excludes.push('All meat','All dairy','All fish','All shellfish','All gluten','All nuts');
		
	},
	_render_common_excludes: function() {
		var p, i, s, cloneDIV;
		// clear out the parent container DIV
		p = $('c_exclude_content');
		while( p.hasChildNodes() ) { p.removeChild( p.lastChild ); }		
		// populate
		for (i=0,l=this._c_excludes.length; i < l; i++) {
			cloneDIV = $('c_exclude_template').cloneNode(true);
			// deal with DOM stuff
			cloneDIV.lastChild.innerHTML = this._c_excludes[i];
			// add a space so IE performs line wraps
			s = document.createTextNode(" ");
			p.appendChild(cloneDIV);
			p.appendChild(s);
			cloneDIV.show();
		}
	}	
}
