appSR = Object.extend (new HPEItemApp, {
	
	opsSelect:"OtherOpsSearch",
	pageFirst:0,
	showShortDesc : true,
	pageItemsPerPage:0,
	pageItemCount:0,
	pageSort:"bydate",
	pageFilterSource:-1,
	advancedMode:0,
	feedUrl:'',
	alert:{
		exists:0,
		contacts:{email:0, jabber:0, sms:0},
		usedContacts:{email:'', jabber:'', sms:''},
		active:0
	},

	InitApp : function() {
		var html = "<form id='AppSearchTools' style='display:none' class='nomargin'><table width='100%' height='27' border='0' cellspacing='0' cellpadding='0'><tr>\
			<td align='left'>\
				<input type='button' value='Show All' onClick='app.ShowAllResults()' id='AppSearchShowAll' />\
			</td>\
			<td id='AppSearchToolSubscribe' style='padding-left:30px'>Save results to Custom Page <select name=\"searchsubscribe_page\" id=\"searchsubscribe_page\" onChange=\"this.nextSibling.style.display=(this.value==-1)?\'\':\'none\'\">'";
			for (var i=0; i<pageList.length; i++)
				html += '<option value="' + pageList[i].index + '">' + pageList[i].title + '</option>';
			html += "<option value='-1'>[New page]</option></select><span style='display:none'>\
			Name: <input type='text' id='searchsubscribe_page_name' name='searchsubscribe_page_name' value='Page " +
			(pageList.length+1) + "' size='10'> </span>\
			<input type='button' value='Subscribe' onClick='app.subscribeToSearch()'></td>\
			<td><span id='feedControls' >\
				<a href='' target='_blank' id='pageRssLink_srh' style='border:none;visibility:hidden'>\
				<img src='/i/feed-icon16x16.png' style='vertical-align:middle;' hspace=2 id='pageRssIcon_srh' border=0>\
				</a>\
				<input type='button' value='Create Feed' onclick='app.toggleFeed(!app.feedUrl)' disabled id='createFeedButton_srh'>\
				</span>\
				<input type='button' value='Create Alert' disabled onclick='app.watch(app.alert)' id='createAlertBtn_srh' style='margin-left:15px'>\
			</td><td width=100% align=right>\
				<input type='button' value='Reload' onClick='app.Reload()' />\
			</td></tr></table></form>";

		var elt = $("tabbarmiddle");
		if(!elt) { hpe.error("Failed to find tabbarmiddle"); return }
		new Insertion.Bottom(elt, html);

/*
		this.body = "<div id='infocol-l' style='padding:5px'>\
			<div class='box1' style='margin-top:5px'>\
				<div class='hdrbox1'>News Search</div>\
				<div class='cntbox1'><ul>\
				<li class='boxlist'> <a href='/searchstats/?flag=1'>Popular Searches</a></li>\
				<li class='boxlist'> <a href='/searchstats/?flag=0'>Popular Keywords</a></li>\
				</ul></div>\
				<div class='cntbox1' id='AppSearchSources'></div>\
				<div style='background-color:white; padding:2px 0 2px 0; font-size:100%'>\
				<div class='cpb'><a onClick='app.ShowMapView()' title='Honeycomb, powered by the Hive Group'><img src='/i/hc.gif' width=18 height=14 align='left' hspace=3 /> Show Map View</a>\
					<div class='cpbdesc'>See a graphical representation of current news</div></div>\
				</div>\
				<div class='cntbox1' id='PowerAppItemOptions'>\
					<form><table>\
					<tr><td><input type='checkbox' name='HPEToggleShortDesc' id='HPEToggleShortDesc' onClick='app.ToggleShortDesc()' /></td>\
						<td>Show short item description</td></tr>\
					<tr><td><input type='checkbox' name='HPEToggleItemMetaData' id='HPEToggleItemMetaData' onClick='app.ToggleItemMetaData()' /></td>\
						<td>Show item meta data (topics, enclosures...)</td></tr>\
					</table></form>\
					<div style='padding:5px;font-size:90%'>You are using the <b>advanced</b> view, switch to <a href='#' onClick='app.SwitchToHTML()'>plain&nbsp;html</a> view</div>\
					</div>\
				<div class='cntbox1' id='ApplicationBackButton' style='display:none;text-align:center'></div>\
			</div><br />";
*/
		this.body = "<div id='infocol-l' style='padding:5px'>";
		//this.body += getFileContent(themeRoot + '/templates/elements/newsSearch.html');
		if(tplElement)
		{
			this.body += tplElement['newsSearch'];
		}
		this.body += $("GlobalNavigation").innerHTML;
		this.body += "</div><div id='content'><div id='contentbreakprotect'>";
		this.body += "<div id='APPSRBox' style='margin:10px'>\
			<div class='box1'>\
				<form id='APPSRForm' name='APPSRForm' class='nomargin' target='_blank' onSubmit='app.DoSearch(); return false;'>\
				<div class='hdrbox1'>Advanced search</div>\
				<div class='cntbox1'>\
					<table width='100%'>\
					<tr><td>Query: <input type='text' size='30' name='AppSRAdvancedSearchField' id='AppSRAdvancedSearchField' />\
						<a onClick='app.ToggleDisplayAdvanced()'>[Advanced search]</a></td>\
					  <td align='right'><input type='submit' value='Search'>\
					  </td>\
				</tr>\
				</table></div>\
				<div id='SecAdvSearchZone' style='display:none'><div class='cntbox1'><p>\
				<input type='checkbox' id='as_exact' name='as_exact' checked /><label for='as_exact'>Exact Match</label>\
				<input type='checkbox' id='as_synonym' name='as_synonym' style='margin-left:20px' /><label for='as_synonym'>Use Synomyms</label>\
				<input type='checkbox' id='as_relevance' name='as_relevance' style='margin-left:20px' /><label for='as_relevance'>Search by relevance</label>\
				<input type='checkbox' id='as_intitle' name='as_intitle' style='margin-left:20px' /><label for='as_intitle'>Search in titles only</label>\
				</p>\
				<table><tr valign='top'>\
					<td>Category:</td>\
					<td><select MULTIPLE cols='20' size='8' id='as_category' name='as_category' style='margin-bottom:5px'>\
					  <option value='' selected>[Any]</option>";
		for(var i=0;i<catList.length;i++)
			this.body += "<option value='" + catList[i] + "'>" + catInfo[catList[i]].display + "</option>";
		this.body += "</select><br /></td>\
					<td style='padding:0 20px 0 20px;text-align:right;'>\
					<div style='width:105%'>\
					  Source name: <input type='text' id='as_source' name='as_source' size='25' /><br />\
					  Author: <input type='text' name='as_author' id='as_author' size='25' /><br />\
					  Topics: <input type='text' name='as_topics' id='as_topics' size='25' /><br />\
					  Date (YYYY/MM/DD):&nbsp;from <input type='text' id='as_date_from' name='as_date_from' size='10' />\
					  <a href=\"javascript:document.getElementById('as_date_from').value = ''; NewCal('as_date_from','yyyymmdd',false,24)\"><img src='/siets/cal.gif' width='16' height='16' border='0' alt='Pick a date' /></a><br />\
					  to <input type='text' id='as_date_to' name='as_date_to' size='10' />\
					  <a href=\"javascript:document.getElementById('as_date_to').value = ''; NewCal('as_date_to','yyyymmdd',false,24)\"><img src='/siets/cal.gif' width='16' height='16' border='0' alt='Pick a date' /></a>\
					</div>\
					</td>\
					<td rowspan='2'>Language: <select size='1' id='as_language' name='as_language' onchange='app.LanguageChange(this)'>\
						<option value='any' >[Any]</option>\
						<option value='my'  selected style='background-color:#f6f6f6'>[My languages]</option>\
						<option value='configure' style='background-color:#f6f6f6'>[Configure]</option>";
		for(var i=0;i<langList.length;i++)
			this.body += "<option value='" + langList[i].key + "'>" + langList[i].name + "</option>";
		this.body += "</select><br /><br />\
						Popularity: <input type='hidden' name='as_pop_to' id='as_pop_to' value='1' />\
					    <select name='as_pop_from' id='as_pop_from'>\
					    <option value='' selected>[Any]</option><option value='0.1'>&gt; 10%</option>\
					    <option value='0.2'>&gt; 20%</option><option value='0.3'>&gt; 30%</option>\
					    <option value='0.4'>&gt; 40%</option><option value='0.5'>&gt; 50%</option>\
					    <option value='0.6'>&gt; 60%</option><option value='0.7'>&gt; 70%</option>\
					    <option value='0.8'>&gt; 80%</option><option value='0.9'>&gt; 90%</option>\
					    </select><br /><br /><br />\
						Num. Items: <select id='as_numitems' name='as_numitems'>\
						<option value='10'>10</option>\
						<option value='25'>25</option>\
						<option value='50' selected>50</option>\
						<option value='100'>100</option>\
						</select>\
					</td></tr>\
				</table></div></div></form>\
			</div>\
		<br /></div>";
		this.body += "<div id='SRHMainContent' style='padding-top:5px'><p>Initializing...</p></div></div></div>";
	},

	StartApp : function(query) {
		var elt = $("AppSearchTools"); if(elt) elt.show();
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;
		elt = $("AppSRSimpleSearchField"); elt.value = query;

		this.SetItemToolState();
		this.LaunchNewSearch();
	},

	SuspendApp : function (same) {
		Element.hide("AppSearchTools");
		Element.show("searchform");
		if (!same) this.AdvFormReset();
	},

	ResumeApp : function (same) {
		Element.show("AppSearchTools");
		Element.hide("searchform");
		var elt = $("MainBody"); if(elt) elt.innerHTML = this.body;
		$("AppSearchSources").innerHTML = "";
		$("SRHMainContent").innerHTML = "";
		this.SetItemToolState();
		hpe.goToTop();
	},

	SwitchToHTML : function() {
		var elt = $("AppSRAdvancedSearchField");
		document.location.href = siteHome + "siets/?type=search&search=Search&query=" + escape(elt.value);
	},

	ShowBackMessage : function() {
		var elt = $("ApplicationBackButton");
		if(!elt) return;
		elt.innerHTML = "<a class=\"OB\" href=\"#\" onClick=\"HPEBackApp()\">[Go to search screen]</a>";
		Element.show(elt);
	},

	ToggleDisplayAdvanced : function() {
		this.advancedMode = !this.advancedMode;
		if(this.advancedMode)
			$("SecAdvSearchZone").show();
		else
			$("SecAdvSearchZone").hide();
	},

	LaunchSetup : function() {
		HPEResumeApp(this);
		this.AdvFormReset();
		if(this.advancedMode)
			$("SecAdvSearchZone").show();
		else
			$("SecAdvSearchZone").hide();
/*
		if(this.advancedMode) {
			if(this.fx.fx.now == 0) this.fx.fx.toggle();
		} else {
			if(this.fx.fx.now != 0) this.fx.fx.toggle();
		}
*/
		var elt = $("AppSRAdvancedSearchField");
		elt.value = $("AppSRSimpleSearchField").value;
	},

	LaunchNewSearch : function(adv) { 
		if(adv) this.advancedMode = 1; else this.advancedMode = 0;
		this.LaunchSetup();
		this.Reload();
		return false;
	},

	LaunchAuthorSearch : function(author) {
		this.advancedMode = 1;
		$("AppSRSimpleSearchField").value = "";
		this.LaunchSetup();
		$("as_author").value = author;
		this.Reload();
	},

	LaunchTopicSearch : function(topic) {
		this.advancedMode = 1;
		$("AppSRSimpleSearchField").value = "";
		this.LaunchSetup();
		$("as_topics").value = topic;
		this.Reload();
	},

	Reload : function () {
		this.pageId = 0;
		this.DoSearch(this.pageId);
	},

	genUrlParam : function () {
		var url = "";

		if (this.advancedMode)
		{
			elt = $("AppSRAdvancedSearchField");
			if(elt) {
				if (elt.value != "")
					url += "q=" + escape(elt.value) + "&";
				else
					url += "q=" + escape(" ") + "&";
			}
			else return false;
			if ($F("as_numitems") != "") url += "numitems=" + $F("as_numitems") + "&";

			var urlparams = "";
			var as_language = '';
			switch($F("as_language"))
			{
				case "": 
					as_language = "my";
					break;
				case "any": 
					as_language = "";
					break;
				default:
					as_language = $F("as_language");
					break	
			}
			if (as_language!="") urlparams += "as_language=" + as_language + "&";
			if ($F("as_source")!="") urlparams += "as_sourcename=" + escape($F("as_source")) + "&";
			var celt = $("as_category")
			if (celt)
				for (var i=0; i<celt.options.length; i++)
					if (celt.options[i].selected && celt.options[i].value!="")
						urlparams += "as_category%5B%5D=" + celt.options[i].value + "&";
			if ($F("as_pop_from")!="") urlparams += "as_pop_from=" + $F("as_pop_from") + "&";
			if ($F("as_author")!="") urlparams += "as_author=" + $F("as_author") + "&";
			if ($F("as_topics")!="") urlparams += "as_topics=" + $F("as_topics") + "&";
			if ($F("as_date_from")!="") urlparams += "as_date_from=" + escape($F("as_date_from").replace(/\//g ,".")) + "&";
			if ($F("as_date_to")!="") urlparams += "as_date_to=" + escape($F("as_date_to").replace(/\//g ,".")) + "&";

			// Check for required fields
			if (elt.value == "" && urlparams == "") {
				alert("Please type a search string or some search criteria");
				elt.focus();
				return;
			}

			if ($("as_relevance").checked) urlparams += "as_relevance=1&";
			if ($("as_intitle").checked) urlparams += "as_intitle=1&";
			if ($("as_exact").checked) urlparams += "as_exact=1&";
			else urlparams += "as_exact=0&";
			if ($("as_synonym").checked) urlparams += "as_synonym=1&";

			url += urlparams;

		} else {
			elt = $("AppSRAdvancedSearchField");
			if(!elt) return false;

			if(elt.value == "") {
				alert("Please type a search string");
				elt.focus();
				return false;
			}
			elt.blur();

			url += 'q=' + escape(elt.value) + "&";
		}

		if(this.pageFilterSource != -1)
			url += "source_id=" + this.pageFilterSource + "&";

		return url;
	},

	DoSearch : function (page) {
		var elt = $("AppSearchShowAll");
		elt.disabled = this.pageFilterSource == -1;
		
		this.pageId = page;

		// Compose serch URL
		var p = this.genUrlParam();

		if(!p) return;
		if(this.pageId) p += "respage=" + this.pageId;

		var url = siteHome + "ajaxAPI.php?api_call=Item::search&api_format=JSON&" + p;
		var myAjax = new Ajax.Request(url, { method:'post', onComplete:this.DoSearchProcess.bind(this) });

		//Element.hide("itemmark");
		$("SRHMainContent").innerHTML = "<p>Searching...</p>";
		$("AppSearchSources").innerHTML = "<p>Loading Sources...</p>";
		$('createAlertBtn_srh').disabled = true;
		$('createFeedButton_srh').disabled = true;
	},

	DoSearchProcess : function (request) {
		srcInfo = new Array();
		itemInfo = new Array();
		numSources = 0;

		var res = hpe.ProcessItemResponse(request);
		if(!res || res.response_code != 200) {
			$("SRHMainContent").innerHTML = "<p>No items found</p>";
			return;
		}
//jslog.debug('DoSearchProcess::Feed Url is: '+res.feedUrl);
		this.feedUrl = res.feedUrl;
		this.updateFeedControls(this.feedUrl);
		this.alert = res.alert;
		this.updateAlertControls(this.alert);
		
		this.pageFilterSource = res.pageFilterSource;
		this.pageFirst = res.pageFirst;
		this.pageItemsPerPage = res.pageItemsPerPage;
		this.pageItemCount = res.pageItemCount;

		var q = res.pageFirst + res.pageItemsPerPage;
		if(q > res.pageItemCount)
		{
			q = res.pageItemCount;
		}
		if (res.pageItemCount == 0)
		{
			var html = "<p>No items found</p>";
		}
		else
		{
		var navpages = "<div class='CPBITEMTOOLS'><ul><li class='pl'>Showing items " + ((res.pageItemCount > 0)?(res.pageFirst + 1) : 0) + " to " + q + " of " + res.pageItemCount;
		if(res.pageItemCount > res.pageItemsPerPage) {
			navpages += "<span style='margin-left:20px'>";
			var minItem = res.pageFirst - res.pageItemsPerPage * 5;
			if(minItem < 0) minItem = 0;
			var maxItem = res.pageFirst + res.pageItemsPerPage * 5;
			if(maxItem > res.pageItemCount) maxItem = res.pageItemCount;
			for(var i = minItem; i < maxItem; i += res.pageItemsPerPage)
			{
				if(i == minItem && minItem > 0)
				{
					navpages += "<span id=\"pagination\"><a onclick='app.DoSearch("+ (i / (res.pageItemsPerPage * 2)) +")'>&lt;&lt;</a></span>&nbsp;";
				}
				if(i == res.pageFirst)
				{
					navpages += "<span id=\"pagination_a\">" + (i / res.pageItemsPerPage + 1) + "</span>";
				}
				else
				{
					navpages += "<span id=\"pagination\"><a onclick='app.DoSearch(" + i / (res.pageItemsPerPage * 2) + ")'>" + (i / res.pageItemsPerPage + 1) + "</a></span>";
				}
			}
				
			if(i >= maxItem && maxItem < res.pageItemCount)
			{
				navpages += "&nbsp;<span id=\"pagination\"><a onclick='app.DoSearch(" + i / (res.pageItemsPerPage * 2) + ")'>&gt;&gt;</a></span>";
			}
			navpages += "</span>";
		}
		navpages += "</li>";
		navpages += "<li>Select: <a onClick='app.CheckAllItems()'>all</A> | <a onClick='app.UnCheckAllItems()'>none</a></li>";
		navpages += "<li>With selected: <a onClick=\"hpe.PostItems('ma', 0)\">mail</A> | <a onClick=\"hpe.PostItems('bl', 0)\">blog</a>";
		navpages += "<li>Select: <a onClick='app.CheckAllItems()'>all</A> | <a onClick='app.UnCheckAllItems()'>none</a></li>";
		navpages += "<li>All Items: <a href='javascript: hpe.ExpandOrCollapseAll(\"expand\");'>expand</a> | <a href='javascript: hpe.ExpandOrCollapseAll(\"collapse\");'>collapse</a></li>";
		navpages += "</ul><br clear='both'></div>";

		var html = navpages + "<div id=\"SearchResults\">" + hpe.ShowItemList() + "</div>\n" + navpages;
		html += "<p align='center'><small>Search powered by <a href='http://www.siets.biz/'>SIETS</a> &bull; Add NewsIsFree to your <a href=javascript:addEngine('nif-firefox','png','News')>Firefox Search</a></small></p>";
		}
		if (itemInfo.length == 0)
		{
			html = "<p>No items found</p>";
		}
		$("SRHMainContent").innerHTML = html;
		savedElement = "";
		savedContent = "";
		this.BuildSourceList();
		hpe.MarkCurrentItem(false);
		//Kontera adds stuff
		if (!NIFNOADS)
		{
			initKontera(); 
		}
	},	
	
	BuildSourceList : function () {
		var shtml = "";
		var elt = $("PageList");
		if(numSources) {
			shtml += "Results in:<ul>\n";
			var ndx = 0;
			var foundOldSrc = 0;
			for(var i in srcInfo) if(typeof srcInfo[i] != 'function') {
				id = srcInfo[i].id;
				var mod = "";
				if(srcInfo[i].lastmod)
					mod = ' (changed ' + srcInfo[i].lastmodStr + ')';
				shtml += ('<li id="' + i + '" class="boxlist"><a class="' + id + '" title="' + srcInfo[i].title + mod);
				shtml += ('" onClick="app.ShowSource(\'' + i + '\')">');
				if(ndx == this.pageFilterSource)
					shtml += '<b>' + srcInfo[i].title + '</b></a></li>\n';
				else
					shtml += srcInfo[i].title + '</a></li>\n';
				ndx++;
			}
			shtml += "</ul>";
		}
		$("AppSearchSources").innerHTML = shtml;
		var elt = $("SecPageToolsZone"); if(elt && elt.style.height != "0px") elt.style.height = "";
	},

	ShowSource : function (id) {
		this.pageFilterSource = srcInfo[id].id;
		$("as_source").value = srcInfo[id].title;
		this.pageId = 0;
		this.DoSearch(this.pageId);
	},

	ShowAllResults : function () {
		this.pageFilterSource = -1;
		$("as_source").value = "";
		this.pageId = 0;
		this.DoSearch(this.pageId);
	},

	GenerateRSS : function () {
		if(isPremiumExport) {
			var url = siteHome + "siets/?" + this.genUrlParam();
			if(!window.open(url))
				alert("A popup blocker prevented the opening of the new window");
		} else hpe.requirePremium("Custom RSS Feeds", "Export");
	},

	ShowMapView : function () {
		if(isPremiumNewsmap) {
			var url = siteHome + "ajaxAPI.php?api_call=Newsmap::gensearchmap&api_format=JSON";
			var post = this.genUrlParam();
			if(!post) return;
			var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.ShowMapViewProcess.bind(this) } );
			lightWin.wait("Loading map view");
		} else {
			hpe.requirePremium("Newsmap for Search Results", "Newsmap");
			$("APPCPBToggleMap").disabled = 1;
		}
	},

	ShowMapViewProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { lightWin.alert("error", Request.responseText); return hpe.error(e) }
		lightWin.hide();
		if (res.response_code>=300) {
			alert("Failed to generate map");
			hpe.log_response(res);
		} else {
			if(appLK) {
				appLK.LoadLink(res.htmlfile);
			} else {
				var t = "Newsmap for search results";
				lightWin.link(t, res.htmlfile, {fullSize:1, useiframe:hpe.isffwin});
			}
		}
	},

	HandleKeyboard : function(event) {
		var c = event.keyCode;
		switch(c) {
		case 65: // a
			this.ToggleAdvanced();
			return true;
		case 74: // j
			if(event.shiftKey)
				hpe.currentItem = itemInfo.length - 1;
			else if(++hpe.currentItem >= itemInfo.length) {
				if(this.pageFirst + this.pageItemsPerPage < this.pageItemCount) {
					var ni = this.pageFirst + this.pageItemsPerPage;
					if(ni > this.pageItemCount)
						ni = this.pageItemCount - this.pageItemCount % this.pageItemsPerPage;
					app.DoSearch(ni/this.pageItemsPerPage+1);
				}
				else hpe.currentItem--;
			}
			hpe.MarkCurrentItem();
			return true;
		case 75: // k
			if(event.shiftKey)
				hpe.currentItem = 0;
			else if(--hpe.currentItem < 0) {
				if(this.pageFirst) {
					var ni = this.pageFirst - this.pageItemsPerPage;
					if(ni < 0)
						ni = 0;
					app.DoSearch(ni/this.pageItemsPerPage+1);
				}
				else hpe.currentItem = 0;
			}
			hpe.MarkCurrentItem();
			return true;
		case 81: // r
			this.Reload();
			return true;
		}
		return false;
	},

	AdvFormReset : function(partial) {
		$("AppSRAdvancedSearchField").value = "";
		$("as_source").value = "";
		$("as_author").value = "";
		$("as_topics").value = "";
		var celt = $("as_category")
		if (celt)
			for (var i=0; i<celt.options.length; i++)
					celt.options[i].selected=false;
		if (partial) return;
//		document.forms["APPSRForm"].reset();
		$("APPSRForm").reset();
	},

	subscribeToSearch : function() {
		if(!isPremiumPortal) { hpe.requirePremium("Subscribe to Search Results", "Portal"); return }
		if(!itemInfo.length) { alert("No items to save"); return }
		var page = $F('searchsubscribe_page');
		var url = siteHome + "ajaxAPI.php?api_call=Item::subscribe_search&api_format=JSON" + "&page=" + page;
		var post = this.genUrlParam();
		if(!post) return;
		if (page == -1) post += "&name=" + $F('searchsubscribe_page_name');
		var myAjax = new Ajax.Request( url, {method: 'get', parameters: post, onSuccess: this.subscribeToSearchProcess.bind(this) } );
	},

	subscribeToSearchProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) { return hpe.error(e); }
		if (res.response_code>=300)
			return false;
		hpe.UpdatePageLists();
		$("AppSourceToolSubscribe").hide();
	},

	UpdatePageList : function() {
		var l = $('searchsubscribe_page');
		l.options.length = pageList.length;
		for(var i in pageList)
			l.options[i] = new Option(pageList[i].title, pageList[i].id);
	},
	
	createFeed: function(action)
	{
		var urlAction;
		if (action == undefined)
		{
			urlAction = 'check';
		}
		else if (action)
		{
			urlAction = 'create';
		}
		else//false == 0 == delete
		{
			urlAction = 'delete';
		}		
		var p = this.genUrlParam();
		if(!p) return;		
		var url = siteHome + "ajaxAPI.php?api_call=Item::feed&api_format=JSON&" + p;
		url += "action=" + urlAction + "&";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.createFeedProcess.bind(this, urlAction)});
	},
	
	createFeedProcess : function(action, Request)
	{
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { return hpe.error(e) }
		//404 - does not exists
		//201 - created
		//200 - exists
		var feedExists, feedUrl;	
		if (action == 'delete')
		{
			feedExists = 0;
		}
		else
		{
			feedExists = (res.response_code==200 || res.response_code==201);
			feedUrl = res.feed_url;
		}
		this.feedExists = feedExists;		 
		$('feedControls').style.display = 'inline';//show controls
		$('pageRssIcon_srh').style.visibility = feedExists ? 'visible' : 'hidden';		 
		$('pageRssLink_srh').href = feedExists ? feedUrl : '';
		$('genSearchFeed').value = feedExists ? 'Remove RSS Feed' : 'Generate RSS Feed';
	},
	
	/*
	checks if the custom feed created for the page and if checkOnly is false, creates the feed
	if action is set and =1 - feed will be created
	if action is set and =0 - feed will be deleted
	if action is notset  - feed will only be checked
	*/
	toggleFeed : function(action)
	{		
	
//jslog.debug('toggleFeed');		
		var p = this.genUrlParam();
		if(!p) return;		
		$('createFeedButton_srh').disabled = true;		
		var urlAction;
		if (action == undefined)
		{
			urlAction = 'check';
		}
		else if(action)
		{
			urlAction = 'create';
		}
		else
		{
			urlAction = 'delete';
		}
		var url = siteHome + "ajaxAPI.php?api_call=Item::feed&api_format=JSON&" + p;		
		url += "action=" + urlAction + "&";		
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.toggleFeedProcess.bind(this) });
	},
	
	toggleFeedProcess : function(Request)
	{
//jslog.debug('toggleFeedProcess');
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { return hpe.error(e) }
		//404 - does not exists
		//201 - created
		//200 - exists/deleted
//jslog.debug('toggleFeedProcess::feedUrl is:'+res.feedUrl);
		this.feedUrl = res.feedUrl;
		this.updateFeedControls(this.feedUrl);		
	},
	
	watch : function(alert)
	{
	
//jslog.debug('watch');
		
		if (userIsGuest) return this.showGuestAlert();
		if (alert==undefined)
		{ 
			alert = 
			{
				exists:0,
				contacts:{email:0, jabber:0, sms:0},
				usedContacts:{email:'', jabber:'', sms:''},
				active:0
			};
		}			
		var html = '<center><form style="display:block;width:150px" id="alertConfigFrm"><input type="hidden" name="useEmail" value="do_not_use"><input type="hidden" name="useJabber" value="do_not_use"><input type="hidden" name="useSms" value="do_not_use"><input type="hidden" name="active" value="'+(alert.exists?'0':'1')+'">';
		html += '<table>';
		
		html +='<tr><td><label for="useEmail">Email</label></td><td><input type="checkbox" name="useEmail" id="useEmail" value="'+((alert.usedContacts.email!='do_not_use' && alert.usedContacts.email)?alert.usedContacts.email:0)+'"';
		if (alert.contacts.email && alert.usedContacts.email!='do_not_use') html +=' checked';
		if (!alert.contacts.email) html += ' disabled';
		html +='></td></tr>';
		
		html +='<tr><td><label for="useJabber">Jabber or Gmail</label></td><td><input type="checkbox" name="useJabber" id="useJabber" value="'+((alert.usedContacts.jabber!='do_not_use' && alert.usedContacts.jabber)?alert.usedContacts.jabber:0)+'"';
		if (alert.contacts.jabber && alert.usedContacts.jabber!='do_not_use') html +=' checked';
		if (!alert.contacts.jabber) html += ' disabled';
		html +='></td></tr>';
		
		html +='<tr><td><label for="useSms">Mobile Phone (SMS)</label></td><td><input type="checkbox" name="useSms" id="useSms" value="'+((alert.usedContacts.sms!='do_not_use' && alert.usedContacts.sms)?alert.usedContacts.sms:0)+'"';
		if (alert.contacts.sms && alert.usedContacts.sms!='do_not_use') html +=' checked';
		if (!alert.contacts.sms) html += ' disabled';
		html +='></td></tr>';
		
		if (alert.exists)//draw 'active' and 'remove' inputs
		{
			html +='<tr><td><label for="active">Alert active</label></td><td><input type="checkbox" name="active" id="active" value="1"';
			if (alert.active) html +=' checked ';
			html +='></td></tr>';
			html +='<tr><td colspan="2" align="center"><input type="button" value="Remove alert" id="removeAlertBtn"></td></tr>';
		}
		html +='</form></center>';
		lightWin.confirm('Alert options', html, {cancelLabel:'Cancel', okLabel:'Save', ok:this.alertSetupCb.bind(this)});
//jslog.debug($('removeAlertBtn'));
		if (alert.exists) $('removeAlertBtn').onclick = this.removeAlert.bind(this);		
	},

	watchProcess : function(Request)
	{	
//jslog.debug('watchProcess');	
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) { return hpe.error(e); }
		/*if (res.response_code>=300)
			return false;*/
		this.alert = res.alert;
		this.updateAlertControls(this.alert);
	},
	
	/*
	* enables feed button after the default disabled state set before the request
	* if non-empty feedUrl given, binds it to the rss icon and displays it, sets feed button text to 'remove feed'
	* otherwise hides RSS image, disables a link to RSS and changes	feed button text 'create feed'
	*/
	updateFeedControls : function(feedUrl)
	{
//jslog.debug('updateFeedControls:: called with feedUrl: '+feedUrl);
		var btn = $('createFeedButton_srh');
		var lnk = $('pageRssLink_srh');
		var img = $('pageRssIcon_srh');
		btn.disabled = false;
		if (feedUrl)
		{
			btn.value = 'Remove feed';
			lnk.href = feedUrl;
			lnk.style.visibility = 'visible';

		}
		else
		{
			btn.value = 'Create Feed';
			lnk.href = '#';
			lnk.style.visibility = 'hidden';
		}
	},
	
	/*
	* sets title at alert button to Create Alert in a case no alerts configured, or Configure Alert if at
	* least one configured 
	*/
	updateAlertControls : function(alert)
	{
		$('createAlertBtn_srh').disabled = false;
		if (alert.exists)		
		{
			$('createAlertBtn_srh').value = 'Configure Alert'; 
		}
		else
		{
			$('createAlertBtn_srh').value = 'Create Alert';
		}
	},
	
	removeAlert : function()
	{
//jslog.debug('removeAlert');	
		lightWin.hide();
		var p = this.genUrlParam();
		$('createAlertBtn_srh').disabled = true;
		var url = siteHome + "ajaxAPI.php?api_call=Item::unwatch&api_format=JSON&" + p;
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this)});
	},
	
	alertSetupCb : function(params)
	{	
		$('createAlertBtn_srh').disabled = true;
		var p = this.genUrlParam();
		//get options from alert config popup
		var formdata = Form.serialize('alertConfigFrm');
//jslog.debug(formdata);		
		var url = siteHome + "ajaxAPI.php?api_call=Item::watch&api_format=JSON&" + p + "&";;
		url += formdata;		
		//send ajax request
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this)});
		//close alert config popup	
		return true;	
	}
});
