/**
 *	/sources/power application
 */
appSP = Object.extend (new HPEApp, {

	pageItemsPerPage:50,
	pageItemCount:0,
	pageSort:"name",
	pageCategory:0,
	pageLanguage:(userIsGuest?'':'my'),
	pageSearchText:"",
	pageFirst:0,
	xmlsiteurl:"",

	InitApp : function() {
		var html = "<form name='AppSourcesPower' id='AppSourcesPower' style='display:none' class='nomargin' onSubmit='return false;'>\
			<table border=0><tr>\
			<td align='right'>Filter list by category:</td><td>\
				<input type='button' value='<<' onClick='app.CategoryChangeButton(-1)' name='CatPrevButton' id='CatPrevButton' />\
				<select name='SPCatList' id='SPCatList' onchange='app.CategoryChange()'>\
				<option value=''>[All]</option>";
		for(var i=0;i<catList.length;i++)
			html += "<option value='" + catList[i] + "'>" + catInfo[catList[i]].display + "</option>";
		html += "</select>\
				<input type='button' value='>>' onClick='app.CategoryChangeButton(1)' id='CatNextButton' name='CatNextButton' />\
				<input type='button' value='Up' title='To the parent category' id='CatUpButton' onClick='app.UpOneCategory()' disabled='disabled' />\
			</td>\
			<td align='right' style='padding-left:10px'>by language:</td>\
			<td><select name='filter_lang' id='filter_lang' onchange='app.LanguageChange()'>\
					<option value=''>[All]</option>\
					<option value='my' style='background-color:#f6f6f6'{if not $HPEUSER.isguest} selected{/if}>[My languages]</option>\
					<option value='configure' style='background-color:#f6f6f6'>[Configure]</option>";
		for(var i=0;i<langList.length;i++)
			html += "<option value='" + langList[i].key + "'>" + langList[i].name + "</option>";
		html += "</select></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' onClick ='document.getElementById(\"search_auto_complete\").style.display=\"none\"' >";
//		this.body += getFileContent(themeRoot + '/templates/elements/sourceList.html');
		if(tplElement)
		{
			this.body += tplElement['sourceList'];
		}
		this.body += $("GlobalNavigation").innerHTML;
		this.body += "</div><div id='content'><div id='contentbreakprotect'><div id='SPMainContent' style='padding-top:5px'><p>Initializing...</p></div></div></div>";
	},

	StartApp : function(cat) {
		var elt = $("AppSourcesPower"); if(elt) elt.show();
		elt = $("AppBrSrcTab"); if(elt) elt.className = "tabon";
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;

		// Parse user lang preferences
		if (userFilterLang != '') {
			var rlangs = userFilterLang.split('|');
			var cbl = $A(document.forms['AppSourcesPower'].elements['restrictlang[]']);
			cbl.each(function(v){
				v.checked = (rlangs.indexOf(v.value)!=-1);
			});
		}

		// Switch to a given category
		if (cat) {
			this.pageCategory = cat;
			this.selectValue($("SPCatList"), this.pageCategory, true);
		}

		elt = $("SourceNavMenuList"); if(elt) elt.hide();
		this.LoadPage();
		$("kbShortcuts").hide();
	},

	SuspendApp : function() {
		var elt = $("AppSourcesPower"); if(elt) elt.hide();
		elt = $("AppBrSrcTab"); if(elt) elt.className = "tab";
		$("kbShortcuts").show();
	},

	ResumeApp : function() {
		var elt = $("AppSourcesPower"); if(elt) elt.show();
		elt = $("SourceNavMenuList"); if(elt) elt.hide();
		elt = $("AppBrSrcTab"); if(elt) elt.className = "tabon";
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;
		if(!this.pageCategory) this.pageCategory = 1;
		this.LoadPage();
		hpe.goToTop();
		$("kbShortcuts").hide();
	},

	SwitchToHTML : function() {
		document.location.href = siteHome + "sources/search/?HPEqname="+escape(this.pageSearchText)+"&HPEqwhere=nd";
	},

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

	LoadPage : function() {
		// API call parameters
		var params = {};
		params['sort'] = this.pageSort;
		if (this.pageLanguage)
			params['language'] = this.pageLanguage;
		if (this.pageCategory)
			params['category'] = this.pageCategory;
		if (this.pageSearchText && this.pageSearchText!='')
			params['search'] = this.pageSearchText;
		if (this.pageFirst>0)
			params['offset'] = this.pageFirst;
		params['limit'] = this.pageItemsPerPage;
		params['seed'] = pageLoadSeed++;

		var url = siteHome + "ajaxAPI.php?api_call=Source::list&api_format=JSON";
		for (var i in params) url += "&"+escape(i)+"="+escape(params[i]);

		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.LoadPageProcess.bind(this) });
		$("SPMainContent").innerHTML = "<P>Please wait while items are being downloaded...</p>";

		hpe.goToTop();
	},

	LoadPageProcess : function(originalRequest) {
		try { var res = eval('('+originalRequest.responseText+')'); } 
		catch(e) { $("SPMainContent").innerHTML = "<p>Failed to process data</p>"; return hpe.log(e); }

		this.pageItemsPerPage = res.pageItemsPerPage;
		this.pageItemCount = res.pageItemCount;
		this.pageFirst = res.pageFirst;

		this.pageCategory = res.pageCategory;
		this.pageLanguage = res.pageLanguage;
		this.pageSort = res.pageSort;
		this.xmlsiteurl  = res.xmlsiteurl;

		this.selectValue($("SPCatList"), this.pageCategory, true);
		this.selectValue($("filter_lang"), this.pageLanguage, true);
		this.selectValue($("sort"), this.pageSort, true);

		this.siteInfo = res.sitelist;
		for (var i=0; i<this.siteInfo.length; i++) {
			if(this.siteInfo[i].lastupdate) this.siteInfo[i].lastupd = this.siteInfo[i].lastupdate;
			if(this.siteInfo[i].lastupd) {
				this.siteInfo[i].lastupdStr = hpe.FormatLongDate(this.siteInfo[i].lastupd);
			} else {
				this.siteInfo[i].lastupd = 0;
				this.siteInfo[i].lastupdStr = "";
			}
			if(this.siteInfo[i].lastmod) {
				this.siteInfo[i].lastmodStr = hpe.FormatLongDate(this.siteInfo[i].lastmod);
			} else {
				this.siteInfo[i].lastmod = 0;
				this.siteInfo[i].lastmodStr = "";
			}
			if(!this.siteInfo[i].favicon || this.siteInfo[i].favicon == '') this.siteInfo[i].favicon = "/i/l.gif";
		}

		var html = "";
		var n = this.siteInfo.length;
		if(n == 0) {
			html += "<p>No sources found matching filters</p>";
		} else {
			var q = this.pageFirst + this.pageItemsPerPage;
			if(q > this.pageItemCount)
				q = this.pageItemCount;
			// Create pagination
			//var navpages = "<div style=\"text-align:right;padding:5px;font-weight:bold;font-size:90%\">Showing items " + (this.pageFirst + 1) + " to " +
			//		q + " of " + this.pageItemCount;
			//  "Showing sources 1 to 50 of 127 (matching 'search term') (in Category 'foo') (for language 'en')"
			var navpages = "<div style=\"text-align:right;padding:5px;font-weight:bold;font-size:90%\">Showing sources " + (this.pageFirst + 1) + " to " + q + " of " + this.pageItemCount;
			if (this.pageSearchText!='')
				navpages += " matching '"+this.pageSearchText+"'";
			if (this.pageCategory!=0)
				navpages += " in category '"+catInfo[this.pageCategory].title+"'";
			if (this.pageLanguage=='my')
				navpages += " matching your language preferences";
			else if (this.pageLanguage!='')
				navpages += " for language '"+this.pageLanguage+"'";
			if(this.pageItemCount > this.pageItemsPerPage) {
				navpages += "<span style='margin-left:20px'>";
				var minItem = this.pageFirst - this.pageItemsPerPage * 5;
				if(minItem < 0)
					minItem = 0;
				var maxItem = this.pageFirst + this.pageItemsPerPage * 5;
				if(maxItem > this.pageItemCount)
					maxItem = this.pageItemCount;
				for(i=minItem; i<maxItem; i+=this.pageItemsPerPage) {
					if(i==minItem && minItem > 0)
						navpages += "<span id=\"pagination\"><a onclick='app.ShowNextItems(0)'>&lt;&lt;</a></span>&nbsp;";
					if(i == this.pageFirst)
						navpages += "<span id=\"pagination_a\">" + (i / this.pageItemsPerPage + 1) + "</span>";
					else
						navpages += "<span id=\"pagination\"><a onclick='app.ShowNextItems(" + i + ")'>" + (i / this.pageItemsPerPage + 1) + "</a></span>";
				}
				if(i >= maxItem && maxItem < this.pageItemCount)
					navpages += "&nbsp;<span id=\"pagination\"><a onclick='app.ShowNextItems(" + (this.pageItemCount - this.pageItemCount % this.pageItemsPerPage) + ")'>&gt;&gt;</a></span>";
				navpages += "</span>";
			}
			navpages += "</div>\n";

			html += navpages;
			html += this.ShowSourcesList();
			html += navpages;
		}
		html += "</div>";

		$("SPMainContent").innerHTML = html;
	},

	ShowSourcesList : function () {
		var obj = $(app.opsSelect);
		var showMultiItemOps = 0;
		if(obj)
			showMultiItemOps = 1;
		var n = this.siteInfo.length;
		var html = "<div class=\"SourceList\">\n";
		var catname;
		var i,j;

		for (i=0; i<n; i++) {

			// Show date section (.DateAgo)
			if(this.pageSort == "byupdate") {
				var nowDate = new Date();
				var theDate = new Date(this.siteInfo[i].lastupd * 1000);
				var diffDate = nowDate.getTime() - theDate.getTime();
				var days = Math.floor(diffDate / (1000 * 60 * 60 * 24));
				var lastMidnight = nowDate.getTime() % (3600 * 1000 * 24);
				lastMidnight = nowDate.getTime() - lastMidnight;
				if(days > 1) {
					html += DisplayDateString(days + " days ago");
				} else if(theDate.getTime() < lastMidnight) {
					html += DisplayDateString("Yesterday");
				} else {
					var hours = Math.floor(diffDate / (1000 * 60 * 60));
					if(hours == 1)
						html += DisplayDateString("1 hour ago");
					else if(hours > 1)
						html += DisplayDateString(hours + " hours ago");
				}
			}

			// Show source
			//html += "<div class=\"SourceZone\""+(i % 2 ? "" : " style=\"background-color:#efefef\"")+">";
			html += "<div class='SourceZone"+(i % 2 ? "" : " SourceZoneBright")+"'>";
			if(appSV)
				html += "<div><a onClick=\"appSV.SwitchToSource(" + this.siteInfo[i].id + ")\"><big>"+this.siteInfo[i].title+"</big></a>";
			else
				html += "<div><a href=\""+siteHome+"sources/info/"+this.siteInfo[i].id+"/\" target=\"_blank\"><big>"+this.siteInfo[i].title+"</big></a>";
			if (this.siteInfo[i].explicit)
				html += " <img src=\"/i/explicit.gif\" align=\"top\" title=\"Source contains explicite material\" vspace=2>";
			if (this.siteInfo[i].regreq)
				html += " <img src=\"/i/key.gif\" align=\"top\" title=\"Registration required to read this source\">";
			
			html += " <img src=\"/i/w.gif\" align=\"baseline\" title=\"You got email alert configured for this source\" width=\"12\" height=\"12\" id='AlertIcon"+this.siteInfo[i].id+"'";
			if (!this.siteInfo[i].alert)
				html +=" style='display:none' ";
			html += ">";
				html +="<a href='"+this.siteInfo[i].feedUrl+"' id='SrcFeedIcon"+this.siteInfo[i].id+"' title='You got RSS feed configured for this source'";
				if (!this.siteInfo[i].feedUrl) html += " style='display:none' ";
				html+="><img src='/i/feed-icon16x16.png' align='baseline' border=0 hspace='2'></a>";
			html += "</div>"
			if(this.siteInfo[i].favicon)
				html += "<a href=\""+this.siteInfo[i].siteurl+"\" target=\"_blank\" style='float:left'><img onerror='this.width=1;this.height=1; this.style.display=\"none\" ' src=\""+this.siteInfo[i].favicon+"\" class=\"favicon\" border=\"0\" alt=\"\" /></a>";
			html += "<div class=\"SourceZoneMeta\"><ul><li>";
			if(this.siteInfo[i].lastmodStr)
				html += " Last changed: " + this.siteInfo[i].lastmodStr;
			if(this.siteInfo[i].popularity >= 0.01)
				 html += " &bull; Popularity: " + Math.round(this.siteInfo[i].popularity * 100) + '%';
			else html += " &bull; Popularity: n/a";
			if(this.siteInfo[i].nifcount>0)
				html += " &bull; Subscribers: " + this.siteInfo[i].nifcount;
			if(this.siteInfo[i].language)
				html += " &bull; Language: <a href=\"javascript:app.LanguageChangeDirect('"+this.siteInfo[i].language+"')\">" + this.siteInfo[i].language.toUpperCase() + "</a>";
			if(this.siteInfo[i].urating>0 && this.siteInfo[i].uratingvotes>0)
				html += " &bull; Rating: " + this.siteInfo[i].urating + ' ('+ this.siteInfo[i].uratingvotes +' votes)';
			if(this.siteInfo[i].copyright && this.siteInfo[i].copyright!='')
				html += "<li> Copyright: &quot;" + this.siteInfo[i].copyright + "&quot;";
			if (this.siteInfo[i].category && this.siteInfo[i].category.length) {
				html += "<li> Category: ";
				for (j=0; j<this.siteInfo[i].category.length; j++)
					if (catInfo[this.siteInfo[i].category[j]])
						html += (j?', ':'') + "<a href=\"javascript:app.CategoryChangeDirect("+this.siteInfo[i].category[j]+")\">"+catInfo[this.siteInfo[i].category[j]].title+"</a>";
			}
			html += "</div>";
			if(this.siteInfo[i].desc != '')
				html += "<table><tbody><tr><td class=\"Desc\">" + this.siteInfo[i].desc + "</td></tr></tbody></table>";
			html += "<div style='display:none' id='ItemOp" + this.siteInfo[i].id + "' class=\"ItemOps\"></div>";
			html += "<div>";
			html += "<a href=\"javascript:app.showSourceContent("+this.siteInfo[i].id+")\" title=\"Show 4 recent articles\" class=\"OB\">[Content]</a> &bull; ";
			html += "<a href=\"javascript:app.subscribeToSourceShow("+this.siteInfo[i].id+")\" title=\"Add source to custom page\" class=\"OB\">[Subscribe]</a> ";
			
			/*html += "<a href=\"javascript:app.watchThisSource("+this.siteInfo[i].id+","+(this.siteInfo[i].alert ? 1 : 0)+")\" class=\"OB\" title=\"Create Email Alert for this Source\" id=\"SrcAlert"+this.siteInfo[i].id+"\">["+(this.siteInfo[i].alert ? 'Unwatch' : 'Watch')+"]</a> ";*/
			
			//html += "<span id=\"SrcAlert"+this.siteInfo[i].id+"\">";
			if (this.siteInfo[i].alert)
			{
				html += "<a href=\"javascript:app.toggleAlert("+i+")\" class=\"OB\" title=\"Configure alert for this source\" id='SrcAlert"+this.siteInfo[i].id+"'>[Configure Alert]</a> ";
			}
			else
			{
				//html += "<a href=\"javascript:app.watchThisSource("+this.siteInfo[i].id+",0,'email')\" class=\"OB\" title=\"Create email alert for this source\" >[Email alert]</a> ";
				//html += "<a href=\"javascript:app.watchThisSource("+this.siteInfo[i].id+",0,'sms')\" class=\"OB\" title=\"Create sms alert for this source\" >[SMS alert]</a> ";
				html += "<a href=\"javascript:app.toggleAlert("+i+")\" class=\"OB\" title=\"Configure alert for this source\" id='SrcAlert"+this.siteInfo[i].id+"'>[Create Alert]</a> ";
			}
			//html += "</span>";
			
			html += "<a href=\"javascript:app.rateThisSourceShow("+this.siteInfo[i].id+")\" class=\"OB\" title=\"Rate this source\" id=\"SrcRate"+this.siteInfo[i].id+"\">[Rate]</a> ";
			if (this.siteInfo[i].feedUrl)
			{
				//html += "<a href=\""+this.xmlsiteurl+this.siteInfo[i].feedUrl+"\"><img src='/i/feed-icon16x16.png' style='vertical-align:middle' border=0 title='You have custom feed configured for this source'></a>";
				html += "<a href=\"javascript:app.toggleFeed("+i+")\" class=\"OB\" title=\"Create feed for this source\" id=\"SrcFeed"+this.siteInfo[i].id+"\">[Remove Feed]</a> ";
			}
			else
			{
				html += "<a href=\"javascript:app.toggleFeed("+i+")\" class=\"OB\" title=\"Create feed for this source\" id=\"SrcFeed"+this.siteInfo[i].id+"\">[Create Feed]</a> ";
			}
			
			if(HPEUserIsEditor)
				html += (" &bull; <a href=\"" + HPEEditLink + "?pg=editsite&id=" + this.siteInfo[i].id + "\" class=\"OB\" target=\"_blank\">[Edit]</a>");
			html += "</div>";
			html += "</div>";

			// Show ads
			if (!NIFNOADS)
				if (i == Math.ceil(n/2)-1)
				{
					if ($F('SPCatList')=='')
						catname = 'Top_News';
					else
						catname = escape(catInfo[$F('SPCatList')].title.replace(/ /g, '_'));
//					html += catname;
					/*html += "<div align='center'>\
<iframe SRC='http://www.newsisfree.com/ad/adpeeps.php?bfunction=showad&uid=100000&bmode=off&bzone=default&bsize=468x60&btype=4&bpos=default&ver=2.0&btarget=_blank&bzone=Feature_Feed:_'+catname' FRAMEBORDER='0' WIDTH='468' HEIGHT='60' SCROLLING='no' MARGINHEIGHT='0' MARGINWIDTH='0'>\
<ilayer SRC='http://www.newsisfree.com/ad/adpeeps.php?bfunction=showad&uid=100000&bmode=off&bzone=default&bsize=468x60&btype=4&bpos=default&ver=2.0&btarget=_blank&bzone=Feature_Feed:_'+catname' FRAMEBORDER='0' WIDTH='468' HEIGHT='60'></ilayer>\
</iframe></div>";*/
/*
					html += '<!-- START AdPeeps.com Code -->';
					html += '<p align="left">';
					html += '<SCRIPT type="text/javascript" SRC="http://www.newsisfree.com/ad/adpeeps.php?bfunction=showad&uid=100000&bmode=off&bstyle=A-&tcolor=0000FF&textcolor=000000&lcolor=499f4c&bzone=Feature_Feed:_'+catname+'&bsize=text&btype=3&bpos=default&ver=2.0&btotal=1&btarget=_top&bborder=0"></SCRIPT>';
					html += '</p>';
					html += '<!-- END AdPeeps.com Code -->';
*/
				}

		}
		html += "</div>";

		return html;
	},

	ShowNextItems : function (offset) {
		this.pageFirst = offset;
		this.LoadPage();
	},

	CategoryChange : function () {
		this.pageCategory = $F('SPCatList');
		hpe.log(this.pageCategory);
		this.pageFirst = 0;
		this.LoadPage();
		$('CatUpButton').disabled = ($F('SPCatList')=='');
	},

	CategoryChangeButton : function (shift) {
		var select = $('SPCatList');
		var curIndex = select.selectedIndex;
		if ((shift==-1 && curIndex) || (shift==1 && curIndex!=select.options.length))
		{
			select.selectedIndex = parseInt(curIndex)+parseInt(shift);
			select.onchange();
		}
	},

	CategoryChangeDirect : function (cat) {
		$('source_search').value = '';
		this.pageSearchText = '';
		this.selectValue($('SPCatList'), cat);
	},

	UpOneCategory : function () {
		var select = $('SPCatList');
		if(select) {
			var catId = select.options[select.selectedIndex].value;
			if (catId != '')
			{
				var parentId = catInfo[select.options[select.selectedIndex].value].parentid;
				if(!parentId)
					parentId = ''; // Jump to "All categories"
				this.selectValue(select, parentId);
			}
		}
	},

	FilterSort : function() {
		var elt = $('sort');
		this.pageSort = elt.value;
		this.pageFirst = 0;
		this.LoadPage();
	},

	LanguageChange : function () {
		if ($F('filter_lang') == 'configure') {
			if (userIsGuest) return this.showGuestAlert();
			hpe.Dialog.configureLanguage('filter_lang');
			return;
		}
		this.pageLanguage = $F('filter_lang');
		this.pageFirst = 0;
		this.LoadPage();
	},

	LanguageChangeDirect : function (lang) {
		$('source_search').value = '';
		this.pageSearchText = '';
		this.selectValue($('filter_lang'), lang);
	},

	SearchTextChange : function () {
		this.pageSearchText = $F('source_search');
		this.pageCategory = "";
		this.pageFirst = 0;
		this.LoadPage();
	},

	subscribeToSourceShow : function(id) {
		if (userIsGuest) return this.showGuestAlert();
		var html = '';
		html += 'Add to page ';
		html += '<select name="subscribe_'+id+'_page" id="subscribe_'+id+'_page" onChange="this.nextSibling.style.display=(this.value==-1)?\'\':\'none\'">';
		for (var i=0; i<pageList.length; i++)
			if (pageList[i].type == 'HPEPageCustom' || pageList[i].type == 1)
				html += '<option value="' + pageList[i].index + '">' + pageList[i].title + '</option>';
		html += '<option value="-1">[New page]</option>';
		html += '</select>';
		html += '<span style="display:none"> Name: <input type="text" id="subscribe_'+id+'_name" name="subscribe_'+id+'_name" value="Page '+(pageList.length+1)+'" size="10"></span>';
		html += ' <input type="button" value="Subscribe" onClick="app.subscribeToSource('+id+')">';
		hpe.PostItemOps(id, 'presubscribe', html, true);
	},

	subscribeToSource : function(id) {
		var url = siteHome + "ajaxAPI.php?api_call=Page::subscribe&api_format=JSON";
		var page = $F('subscribe_'+id+'_page');
		var post = "siteid=" + id + "&page=" + page;
		if (page == -1)
			post += "&name=" + $F('subscribe_'+id+'_name');
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.subscribeToSourceProcess.bind(this) } );
	},

	subscribeToSourceProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) { return hpe.error(e); }
		if (res.response_code>=300)
			return false;
		if (res.page_id && res.page_id>0)
			// Add new page to custom pages list
			pageList[res.page_id] = {index:res.page_id, title:res.page_name};
		hpe.PostItemOps(hpe.itemOpsId, 'presubscribe');
	},

	rateThisSourceShow : function(id) {
		if (userIsGuest) return this.showGuestAlert();
		var html = '';
		html += 'Rate this source ';
		html += '<select name="rate_'+id+'_rate" id="rate_'+id+'_rate">';
		for (var i=1; i<=5; i++)
			html += '<option value="' + i + '">' + i + '</option>';
		html += '</select>';
		html += ' <input type="button" value="Rate" onClick="app.rateThisSource('+id+')">';
		hpe.PostItemOps(id, 'prerate', html, true);
	},

	rateThisSource : function(id) {
		var rate = $F('rate_'+id+'_rate');
		hpe.clipOpItem = $("SrcRate" + id);
		hpe.clipOpItem.innerHTML = '[saving...]';
		var url = siteHome + "ajaxAPI.php?api_call=Source::rate&api_format=JSON";
		var post = "siteid=" + id + "&rate=" + rate;
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.rateThisSourceProcess.bind(this) } );
	},

	rateThisSourceProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) { return hpe.error(e); }
		if (res.response_code>=300)
			return false;
		hpe.PostItemOps(hpe.itemOpsId, 'prerate');
		if(hpe.clipOpItem) hpe.clipOpItem.innerHTML = '';
	},

	toggleAlert : function(index)
	{
		if (userIsGuest) return this.showGuestAlert();
		//get source ID by index
		var source = this.siteInfo[index].id;		
		//get source and contacts info		  
		var url = siteHome + "ajaxAPI.php?api_call=Source::getAlert&api_format=JSON&source=" + source + "&";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.toggleAlertProcess.bind(this, index) });
	},
	
	toggleAlertProcess : function(index, Request)
	{
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { return hpe.error(e) }
		var source = this.siteInfo[index].id;
		/*if (!res.alert) 
		{
			$('SrcAlert'.source).innerHTML = this.siteInfo[index].alert?'Configure Alert':'Create Alerts'; 
			return;
		}		
		*/
		var alert = res.alert;
		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, index)});
		if (alert.exists) $('removeAlertBtn').onclick = this.removeSourceAlert.bind(this, index);
		//display overlay window and set callback
		
	},

	removeSourceAlert : function(index)
	{
		lightWin.hide();
		//$('createAlertBtn').disabled = true;
		var source = this.siteInfo[index].id;		
		var url = siteHome + "ajaxAPI.php?api_call=Source::unwatch&api_format=JSON&source=" + source + "&";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this, index)});
	},
	
	alertSetupCb : function(index)
	{	
		var source = this.siteInfo[index].id;
		//get options from alert config popup
		var formdata = Form.serialize('alertConfigFrm');
//jslog.debug(formdata);
		var url = siteHome + "ajaxAPI.php?api_call=Source::watch&api_format=JSON&source=" + source + "&";
		url += formdata;
		//send ajax request
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this, index)});
		//close alert config popup
		return true;
	},
	
	watchProcess : function(index, Request)
	{
//jslog.debug('watchProcess: '+index);
//jslog.debug('watchProcess: '+this.siteInfo[index]);
		//get info about alert in response - exists for axample
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) { return hpe.error(e); }
		var alert = res.alert;
		//update siteInfo
		var source = this.siteInfo[index].id;
		this.siteInfo[index].alert = alert.exists?1:0;		 
		//set link title to [Create Alert] or [Configure Alert] respectively
		$('SrcAlert'+source).innerHTML = alert.exists?'Configure Alert':'Create Alert';
		$('AlertIcon'+source).style.display = alert.exists?'inline':'none';
		
	},
	
	toggleFeed: function(index, checkOnly)
	{	
		/*
			change [create feed] to [saving...]
		*/
		var source = this.siteInfo[index].id;
		var feedUrl = this.siteInfo[index].feedUrl;
		$('SrcFeed'+source).innerHTML = '[Saving...]';
		
		var url = siteHome + "ajaxAPI.php?api_call=Source::feed&api_format=JSON&source=" + source + "&";		
		url += "action=" + (feedUrl?'delete':'create') + "&";		
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.createFeedProcess.bind(this, index) });
	},
	
	createFeedProcess: function(index, Request)
	{
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { return hpe.error(e) }
		//404 - does not exists
		//201 - created
		//200 - exists	
		//var feedExists = (res.response_code==200 || res.response_code==201);
		var source = this.siteInfo[index].id;
		this.siteInfo[index].feedUrl = res.feedUrl; 
		if (res.feedUrl)
		{
			/*
			if feed exists - display feed icon in the title, change [saving...] to [remove feed]
			*/
			$('SrcFeedIcon'+source).href = res.feedUrl;
			$('SrcFeedIcon'+source).style.display = 'inline';			
			$('SrcFeed'+source).innerHTML = '[Remove Feed]';
			//var source = res.source;
			//var html = "<img src='/i/feed-icon16x16.png' style='vertical-align:middle' border=0>";
			//$('SrcFeed'+source).href = feedUrl;
			//$('SrcFeed'+source).innerHTML = html;
		}
		else//feed does not exists
		{
			$('SrcFeedIcon'+source).href = '';
			$('SrcFeedIcon'+source).style.display = 'none';
			$('SrcFeed'+source).innerHTML = '[Create Feed]';
		}
	},
	

	showSourceContent : function(id) {
		hpe.PostItemOps(id, 'precont', 'Loading...', false);
		var url = siteHome + "ajaxAPI.php?api_call=Source::getitems&api_format=JSON";
		var post = "siteid=" + id;
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.showSourceContentProcess.bind(this,id) } );
	},

	showSourceContentProcess : function(id, Request) {
		try { var res = eval('('+Request.responseText+')'); }
		catch(e) {
			hpe.PostItemOps(id, 'content', 'Failed to load items', true);
			return hpe.error(e);
		}
		if (res.response_code>=300 || typeof(res.items)!='object')
			return hpe.PostItemOps(id, 'content', (res.response_message!='')?res.response_message:'Failed to load items', true);
		var html = '';
		var date;
		for (var i=0; i<res.items.length; i++)
		{
			date = new Date(res.items[i].date * 1000);
			html += FmtInt(date.getMonth()+1, 2) + "/" + FmtInt(date.getDate(), 2) + "/" + FmtInt(date.getYear()-100,2) + " " +
					FmtInt(date.getHours(), 2) + ":" + FmtInt(date.getMinutes(), 2);
			html += ' - ';
			if (!NIFNOADS)
			{
				html += '<div class=KonaBody>'; 
			}
			html += '"' + res.items[i].title + '"';
			if (!NIFNOADS)
			{
				html += '</div>'; 
			}
			html += '<br />';
		}
		if (res.items.length == 0)
			html = '<i>No recent items found</i>';

		hpe.PostItemOps(id, 'content', html, true);
		//Kontera adds stuff
		if (!NIFNOADS)
		{
			initKontera(); 
		}
	}

});


function DisplayCatSources(id)
{
	appSP.pageCategory = id;
	$('source_search').value = '';
	HPEResumeApp(appSP);
}

/* ---------- Start autocomplete code ------------------- */

var ac_latency = false;
var ac_query = "";
var ac_active_row = null;

function autoComplete()
{
	var temp = $('source_search');
	ac_query = temp.value;

	if (ac_query.length<2)
	{
		Element.hide('search_auto_complete');
		return;
	}

	if (ac_latency)
	{
		clearInterval(ac_latency);
		ac_latency = false;
	}

	ac_active_row = null;
	var url = siteHome + "ajaxAPI.php?api_call=Source::autocompletename&api_format=JSON";
	ac_latency = setTimeout(function() {
		new Ajax.Request(url, {
			method:"get",
			parameters:"search="+encodeURIComponent(ac_query)+'&filter='+$('filter_lang').value,
			onSuccess:autoComplete_handleSuccess.bind(this, ac_query),
			onFailure:autoComplete_handleFailure
		});
	}, 500);
}

function setSelectionRange(input, selectionStart, selectionEnd) {
	if (input.setSelectionRange) {
		input.focus();
		var prevalue = input.value;
		input.value += ' ';
		input.setSelectionRange(selectionStart, selectionEnd);
		input.value = prevalue;
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}
function setCaretToEnd (input) {
	setSelectionRange(input, input.value.length, input.value.length);
}

function autoComplete_scroll(field, key)
{
	field.ffspecialhack = "yes";
	var active = ac_active_row;
	if (key == 13)
		autoComplete_select(active, true, field);
	if (!(key == 38 || key == 40)) {
		return;
	}
	if (38 == key) { // up
		if (active == 0 || active == null) {
			active = 9;
		} else {
			active -= 1;
		}
		autoComplete_highlight(active);
	}
	else if (40 == key) { // down
		if(active == 9 || active == null) {
			active = 0;
		} else {
			active += 1;
		}
		autoComplete_highlight(active);
	}
	setCaretToEnd($('source_search'));
	setTimeout('setCaretToEnd($("source_search"))', 20);
}

function autoComplete_handleSuccess(querystring, ajaxRequest)
{
	if ($F('source_search') != querystring)
		return;
    try {
		var res = eval('('+ajaxRequest.responseText+')');
        var layer = $('search_auto_complete');
        if (res.response_code<300 && typeof(res.sitelist)=='object' && res.sitelist.length) {
            layer.style.display = "";
            layer.innerHTML = "";
            for (var i=0; i<res.sitelist.length; i++) {
                layer.innerHTML += '<table width="100%" border="0" cellspacing="0" cellpadding="1"><tr id="row'+i+'" onmouseover="autoComplete_highlight('+i+')" onclick="autoComplete_select('+i+', true, $(\'source_search\'));"><td id="entry'+i+'">'+res.sitelist[i]+'</td></tr></table>';
            }
        }
        else {
            layer.style.display = "none";
        }
    }
    catch (ajaxException) {}
}

function autoComplete_handleFailure(ajaxRequest)
{
}

function autoComplete_select(row, close, field)
{
    field.value = field.previousvalue = $("entry" + row).innerHTML;
    if (close) {
        $('search_auto_complete').style.display = 'none';
        field.focus();
    }
	if (field.onchange)
		field.onchange();
}

function autoComplete_highlight(row)
{
    if($('search_auto_complete').style.display != 'none') {
        if(ac_active_row != null)
            $("entry" + ac_active_row).className = '';
		if (!$("entry" + row)) return;
        $("entry" + row).className = 'autocompleteHover';
        var field = $('source_search');
        //field.value = field.previousvalue = $("entry" + row).innerHTML;
        ac_active_row = row;
        setCaretToEnd($('source_search'));
    }
}

/* ---------- End autocomplete code --------------------- */

/**
 *	Calls onChange for element it ENTER is pressed
 *	Should be set as onKey(Press|Up|Down) handler
 *	For IE only! In mozilla onChange is called automatically
 */
function inputChangeOnEnter()
{
	if (window.event && window.event.keyCode==13 && window.event.srcElement && window.event.srcElement.onchange)
	{
		window.event.srcElement.onchange();
		return false;
	}
}

function dumpHash(hash)
{
	if (typeof(hash)!='object') return;
	var str='';
	for (i in hash)
		str += i+' : ('+typeof(hash[i])+') '+hash[i]+'\n';
	alert(str);
}

