appCB = Object.extend (new HPEItemApp, {

	pageFilterLang:"en",
	pageFilterDateRange:"w",
	pageSort:"bydate",
	pageFirst:0,
	pageId:1,
	pageFilterSource:-1,
	opsSelect:"OtherOpsCat",
	feedUrl:'', //==url of the feed if the rss feed is created for the page, 0 otherwise

	InitApp : function () {
		if(!userIsGuest) this.pageFilterLang="my";
		var html = "<form id='AppCatBrowseTools' style='display:none' class='nomargin'><table height='27' border='0' cellspacing='0' cellpadding='0'><tr>\
			<td>Category:<select name='CatList' id='CatList' onchange='app.CategoryChange()'>";
			for(var i=0;i<catList.length;i++)
				html += "<option value='" + catList[i] + "'>" + catInfo[catList[i]].display + "</option>";
			html += "</select> <input type='button' value='Up' id='up_cat' onClick='app.UpOneCategory()' /></td>\
			<td align='left' style='padding-left:10px'>Sort by:</td>\
			<td><select name='HPECPBsort' id='HPECPBsort' onchange='app.FilterSort()'>\
			<option value='bydate'>Date</option><option value='bysource'>Source</option><option value='bypop'>Popularity</option>\
			</select></td>\
			<td style='padding-left:10px'>Language:<select name='APPCBfilter_lang' id='APPCBfilter_lang' onchange='app.LanguageChange(this)'>\
				<option value=''>[All languages]</option>\
				<option value='my' style='background-color:#f6f6f6'" + (userIsGuest ? "" : "selected") + ">[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>\
			<td align='left' style='padding-left:10px'>Date:</td>\
			<td><select name='APPCBfilter_daterange' id='APPCBfilter_daterange' onchange='app.FilterDateRange()'>\
				<option value='a'>Any</option> <option value='t'>Today</option> <option value='y'>Yesterday</option> <option value='w' selected>This Week</option>\
				<option value='pw'>Last Week</option> <option value='m'>This Month</option> <option value='pm'>Last Month</option>\
			</select></td>\
			<td style='padding-left:10px'>\
				<a href='' target='_blank' id='catRssLink' style='border:none;visibility:hidden'>\
					<img src='/i/feed-icon16x16.png' style='vertical-align:middle;' hspace=2 id='catRssIcon' border=0>\
				</a>\
				<input type='button' value='Create Feed' onclick='app.toggleFeed(!app.feedUrl)' disabled id='createCatFeedButton'>\
			</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'>";
		if(tplElement)
			this.body += tplElement['newsItemBrowser'];
		this.body += $("GlobalNavigation").innerHTML;
		this.body += "</div><div id='content'><div id='contentbreakprotect'><div id='CATMainContent' style='padding-top:5px'><p>Initializing...</p></div></div></div>";
	},

	StartApp : function (cat, lang) {
		var elt = $("AppCatBrowseTools"); elt.show();
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;		
		this.pageId = cat;
		if(lang) this.pageFilterLang = lang;
		this.SetItemToolState();
		this.ResumeApp();
	},

	SuspendApp : function () {
		var elt = $("AppCatBrowseTools"); elt.hide();
		elt = $("AppBrItemTab"); if(elt) elt.className = "tab";
	},

	ResumeApp : function () {
		var elt = $("AppCatBrowseTools"); elt.show();
		elt = $("AppBrItemTab"); if(elt) elt.className = "tabon";
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;

		var select = $("CatList");
		if(select && select.value != this.pageId) {
			for(i=0; i<select.length; i++)
				if(select.options[i].value == this.pageId) {
					select.selectedIndex = i;
					break;
				}
		}
		if(!this.pageFilterLang) this.pageFilterLang = "en";
		select = $("APPCBfilter_lang");
		if(select && select.value != this.pageFilterLang) {
			for(i=0; i<select.length; i++)
				if(select.options[i].value == this.pageFilterLang) {
					select.selectedIndex = i;
					break;
				}
		}
		
		if ((this.pageFirst % this.pageItemsPerPage) == 0)
		{
			this.pageFirst = this.pageFirst / this.pageItemsPerPage;
		}		

		this.SetItemToolState();
		this.LoadCategory(this.pageId);
		hpe.goToTop();
	},

	SwitchToHTML : function() {
		if(this.pageId >= 0)
			document.location.href = siteHome + "sources/browse/" + this.pageId + "/";
		else
			document.location.href = siteHome + "sources/browse/";
	},

	ShowBackMessage : function() {
		var elt = $("ApplicationBackButton");
		if(!elt) return;
		var pl = $("CatList");
		if(pl)
			elt.innerHTML = "Back to Category:<br /><a class=\"OB\" href=\"#\" onClick=\"HPEBackApp()\">[" + pl.options[pl.selectedIndex].text + "]</a>";
		else
			elt.innerHTML = "<a class=\"OB\" href=\"#\" onClick=\"HPEBackApp()\">[Back to Category]</a>";
		Element.show(elt);
	},

	LoadCategory : function (pageid) {
		var url = siteHome + "ajaxAPI.php?api_call=Category::getitems&api_format=JSON&id=" + pageid + "&";
		if(pageid == this.pageId) {
			url += "filter_daterange=" + this.pageFilterDateRange + "&";
			url += "sort=" + this.pageSort + "&";
			if(this.pageFirst)
				url += "first=" + this.pageFirst + "&";
			if(this.pageFilterSource != "")
				url += "filter_source=" + this.pageFilterSource + "&";
		}
		url += "filter_lang=" + this.pageFilterLang + "&";
		url += "seed=" + pageLoadSeed + "&";
		pageLoadSeed++;

		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.LoadCategoryProcess.bind(this) });
		$("CATMainContent").innerHTML = "<P>Please wait while items are being downloaded...</p>";
		$("AppCatBrowseSources").innerHTML = "<p>Loading Sources...</p>";
		window.title = "Loading...";
		srcInfo = new Array();
		itemInfo = new Array();
		prevDateStr = "";

		hpe.goToTop();
		if(pageid == this.pageId)
			return;

		this.pageId = pageid;
		this.prevPageId = pageid;

		var select = $("CatList");
		if(select && select.value != this.pageId) {
			for(i=0; i<select.length; i++)
				if(select.options[i].value == this.pageId) {
					select.selectedIndex = i;
					break;
				}
		}
	},

	LoadCategoryProcess : function (request) {
		var res = hpe.ProcessItemResponse(request);
		if(!res || res.response_code != 200) {
			$("AppCatBrowseSources").hide();
			$("CATMainContent").innerHTML = "<p>No items found</p>"; return;
		}

		this.pageFilterPop = res.pageFilterPop;
		this.pageFilterDate = res.pageFilterDate;
		this.pageFilterSource = res.pageFilterSource;
		this.pageFirst = res.pageFirst;
		this.feedUrl = res.feedUrl;

		res.pageItemsPerPage = res.numitems_per_page;
		this.pageItemsPerPage = res.pageItemsPerPage;
		this.pageFirst = this.pageFirst * this.pageItemsPerPage;
		
		var n = itemInfo.length;
		
		this.pageItemCount = res.pageItemCount;

		var pl = $("CatList");
		var html = "<div class='PowerAppItemListTitle'>Items for category " + pl.options[pl.selectedIndex].text;
		html += "<div style='font-weight:normal;padding:5px'>See <a href='/sources/power/?cat=" + this.pageId + "' target='_blank'>all sources in this category</a>."
		html += "</div></div>"; 
		
		if(n == 0) {
			html += "<p>No items found matching filters</p>";
		} else {
			var q = this.pageFirst + this.pageItemsPerPage;
			/*
			var q = this.pageFirst + n;
			if(q > this.pageItemCount)
				q = this.pageItemCount;
			*/
			var navpages = "<div class='CPBITEMTOOLS'><ul><li class='pl'>Showing items " + (this.pageFirst + 1) + " to " + q + " of " + this.pageItemCount;
			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("+(i / this.pageItemsPerPage)+")'>&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 / this.pageItemsPerPage) + ")'>" + (i / this.pageItemsPerPage + 1) + "</a></span>";
				}
				if(i>=maxItem && maxItem < this.pageItemCount)
					navpages += "&nbsp;<span id=\"pagination\"><a onclick='app.ShowNextItems(" + (i / this.pageItemsPerPage) + ")'>&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>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>";
			html += navpages + hpe.ShowItemList() + navpages;
		}
		html += "</div>";

		$("CATMainContent").innerHTML = html;
		savedElement = "";
		savedContent = "";		
		var elt = $("APPCBfilter_daterange");
		for(var e=0; elt && e<elt.options.length; e++)
			if(elt.options[e].value == this.pageFilterDateRange) {
				elt.selectedIndex = e;
				break;
			}

		elt = $("APPCBfilter_lang");
		for(var e=0; elt && e<elt.options.length; e++)
			if(elt.options[e].value == this.pageFilterLang) {
				elt.selectedIndex = e;
				break;
			}

		var select = $("CatList");
		elt = $("up_cat");
		if(elt && select) {
			var parentId = catInfo[select.options[select.selectedIndex].value].parentid;
			elt.disabled = parentId == 0;
		}

		elt = $("HPECPBsort");
		for(e=0; elt && e<elt.options.length; e++)
			if(elt.options[e].value == this.pageSort) {
				elt.selectedIndex = e;
				break;
			}

		this.BuildSourceList();
		hpe.MarkCurrentItem(false);
		//Kontera adds stuff
		if (!NIFNOADS)
			try { initKontera(); } catch(e) { }
		this.updateFeedControls(this.feedUrl);
	},

	BuildSourceList : function () {
		var shtml = "";
		var elt = $("PageList");
		if(numSources) {
			shtml += "On This Page:<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 + '" onClick="app.ShowSource(\'' + srcInfo[i].key + '\')">' + srcInfo[i].title + '</a></li>\n';
				ndx++;
			}
			shtml += "</ul>";
			shtml += "<p align=center><a onClick=\"window.open('/user/sub/?cat=" + this.pageId + "')\" title='Add this content to a custom page' class='OB'>[subscribe]</a></p>";
		}
		$("AppCatBrowseSources").innerHTML = shtml;
		var elt = $("SecPageToolsZone"); if(elt && elt.style.height != "0px") elt.style.height = "";
	},

	ShowMapView : function () {
		if(isPremiumNewsmap) {
			var url = siteHome + "ajaxAPI.php?api_call=Newsmap::gencatmap&api_format=JSON&cat=" + this.pageId + "&lang=" + this.pageFilterLang;
			var myAjax = new Ajax.Request( url, {method:'get', onSuccess: this.ShowMapViewProcess.bind(this) } );
			lightWin.wait("Loading map view");
		} else {
			hpe.requirePremium("Newsmap for Category items", "Newsmap");
		}
	},

	ShowMapViewProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { 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 = "Category News Map Viewer";
				var pl = $("CatList");
				if(pl) t = "News Map for Category '" + pl.options[pl.selectedIndex].text + "'";
				lightWin.link(t, res.htmlfile, {fullSize:1, useiframe:hpe.isffwin});
			}
		}
	},

	ShowNextItems : function (itemId) {
		this.pageFirst = itemId;
		this.LoadCategory(this.pageId);
	},

	Reload : function() {
		this.LoadCategoryButton(-1);
	},

	CategoryChange : function () {
		var select = $("CatList");
		if(select) {
			if(this.pageId != select.value) {
				this.pageFirst = 0;
				app.LoadCategory(select.value);
			}
		}
	},

	LoadCategoryButton : function (catid) {
		if(catid == -1)
			catid = this.pageId;
		this.pageFirst = 0;
		this.LoadCategory(catid);
	},

	UpOneCategory : function () {
		var select = $("CatList");
		if(select) {
			var parentId = catInfo[select.options[select.selectedIndex].value].parentid;
			if(parentId) {
				this.pageFirst = 0;
				app.LoadCategory(parentId);
			}
		}
	},

	LanguageChange : function () {
		if ($F('APPCBfilter_lang') == 'configure') {
			if (userIsGuest) return this.showGuestAlert();
			hpe.Dialog.configureLanguage('APPCBfilter_lang');
			return;
		}
		var select = $("APPCBfilter_lang");
		if(select) {
			if(this.pageFilterLang != select.value) {
				this.pageFilterLang = select.value;
				this.pageFirst = 0;
				app.LoadCategory(this.pageId);
			}
		}
	},

	FilterDateRange : function () {
		var select = $("APPCBfilter_daterange");
		if(select) {
			if(this.pageFilterDateRange != select.value) {
				this.pageFilterDateRange = select.value;
				this.pageFirst = 0;
				app.LoadCategory(this.pageId);
			}
		}
	},

	FilterSort : function () {
		var elt = $("HPECPBsort");
		this.pageSort = elt.value;
		this.pageFirst=0;
		app.LoadCategory(this.pageId);
	},

/*
	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)
	{
		$('createCatFeedButton').disabled = true;
		var url = siteHome + "ajaxAPI.php?api_call=Category::feed&api_format=JSON&id=" + this.pageId + "&";
		var urlAction;
		if (action == undefined)
			urlAction = 'check';
		else if(action)
			urlAction = 'create';
		else
			urlAction = 'delete';
		url += "action=" + urlAction + "&";
		url += "filter_lang=" + this.pageFilterLang + "&";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.toggleFeedProcess.bind(this, urlAction) });
	},

	toggleFeedProcess : function(action, Request)
	{
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { return hpe.error(e) }
		//404 - does not exists
		//201 - created
		//200 - exists/deleted
		this.feedUrl = res.feedUrl;
		this.updateFeedControls(this.feedUrl);
	},

	/*
	* 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)
	{
		var btn = $('createCatFeedButton');
		var lnk = $('catRssLink');
		var img = $('catRssIcon');
		btn.disabled = !isPremiumExport;
		if (feedUrl && isPremiumPortal) {
			btn.value = 'Remove feed';
			lnk.href = feedUrl;
			lnk.style.visibility = 'visible';
		} else {
			btn.value = 'Create Feed';
			lnk.href = '#';
			lnk.style.visibility = 'hidden';
		}
	},

	HandleKeyboard : function(event) {
		var c = event.keyCode;
		switch(c) {
		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.ShowNextItems(ni);
				}
				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.ShowNextItems(ni);
				}
				else hpe.currentItem = 0;
			}
			hpe.MarkCurrentItem();
			return true;
		case 85: // u
			this.UpOneCategory();
			return true;
		case 76: // l
			nextPage = parseInt(pageFirst, 10) + 1;
			app.ShowNextItems(nextPage);
			return true;
		case 72: // h
			if (pageFirst > 0)
			{
				prevPage = parseInt(pageFirst, 10) - 1;
				app.ShowNextItems(prevPage);
			}
			return true;
			
		}
		return false;
	}

});


function DisplayCatItems(id, lang)
{
	appCB.pageId = id;
	if(lang) appCB.pageFilterLang = lang;
	HPEResumeApp(appCB);
}
