appCP = Object.extend (new HPEItemApp, {

	pageId:0,
	pageType:"",
	pageTitle:"",
	pageEditLink:"",
	pageLayoutLink:"",
	prevPageId:0,
	pageSubId:-1,
	pageCompact:"no",
	pageFirst:0,
	pageItemsPerPage:0,
	pageItemCount:0,
	pageSort:"bydate",
	pageFilterPop:"0",
	pageFilterDate:"0",
	pageFilterSource:-1,
	pageCurrentSource:-1,
	pageShowUnReadItems:0,
	subPageId:-1,
	opsSelect:"OtherOpsCustom",
	deleteReadItems:0,
	optOn:0,
	feedUrl:'', //==url of the feed if the rss feed is created for the page, 0 otherwise
	alert:{
		exists:0,
		contacts:{email:0, jabber:0, sms:0},
		usedContacts:{email:'', jabber:'', sms:''},
		active:0
	},
	inlineEditor: null,
	oldPageName: '',
	skipSourceListRebuild: false,

	InitApp : function() {
		var html = "<form id='AppCustomBlogTools' style='display:none' class='nomargin'><table height='27' border='0' cellspacing='0' cellpadding='0' width='100%'><tr>\
			<td><input type='button' value='<<' onClick='app.PageJumpButton(-1)' id='PagePrevButton' name='PagePrevButton' />\
			<input type='button' value='>>' onClick='app.PageJumpButton(+1)' id='PageNextButton' name='PageNextButton' /></td>\
			<td style='padding-left:10px'><input type='checkbox' name='HPECPBGetReadOnly' id='HPECPBGetReadOnly' onClick='app.ToggleReadMode(this)' CHECKED />\
			<label for='APPCPBGetReadOnly'>Show only unread items</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\
			<input id='APPCPBMarkAllRead' type='button' onclick='app.MarkRead(2)' value='Mark All Read >>' />\</td>\
			<td style='padding-left:10px'>\
				<a href='' target='_blank' id='pageRssLink' style='border:none;visibility:hidden'>\
					<img src='/i/feed-icon16x16.png' style='vertical-align:middle;' hspace=2 id='pageRssIcon' border=0>\
				</a>\
				<input type='button' value='Create Feed' onclick='app.toggleFeed(!app.feedUrl)' disabled id='createFeedButton'>\
			</td>\
			<td style='padding-left:20px'><input type='button' value='Create Alert' disabled ";
			html +="onclick='app.watch(app.alert)' id='createAlertBtn'>\</td>\
			<td align=right width='100%'><input type='button' value='Reload' onClick='app.Reload()' />\
			<select id='OtherOpsCustom' onChange='app.LaunchOps()'>\
			<option>Other Actions</option>\
			<option value='CatchUp'>Catch Up</option>\
			<option value='---'>&nbsp;&nbsp;---</option>\
			<option value='EditThisPage'>Edit This Page</option>\
			<option value='Subscribe'>More Content</option>\
			<option value='ManagePages'>Manage Pages</option>\
			</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'>";
		//this.body += getFileContent(themeRoot + '/templates/elements/customPageBrowser.html');
		if(tplElement)
		{
			this.body += tplElement['customPageBrowser'];
		}
		this.body += $("GlobalNavigation").innerHTML;
		this.body += "</div><div id='content'><div id='contentbreakprotect'><div id='CPBMainContent' style='padding-top:5px'><p>Initializing...</p></div></div></div>";

	},

	StartApp : function(pid, voter) {
		this.pageId = -1;
		var elt = $("AppCustomBlogTools"); if(elt) Element.show(elt);
		elt = $("AppCustomBlogTab"); if(elt) elt.className = "tabon";
		elt = $("MainBody"); if(elt) elt.innerHTML = this.body;

		this.pageShowUnReadItems = hpe.getCookie("HPECPBpageShowUnReadItems") == "1" ? 0 : 1;
		elt = $("HPECPBGetReadOnly"); if(elt) elt.checked = this.pageShowUnReadItems ? false : true;
		
		this.SetItemToolState();
		
		if(voter && voter.length > 0){
			this.LoadDocumentRatings(voter);
			return;
		}
		
		if(pid == 'home') this.Home();
			else this.LoadPage(isNull(pid) ? 0 : pid);
	},

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

		this.pageCurrentSource=-1;
		this.SetItemToolState();
		this.LoadPageButton(-1);
		this.UpdatePageList();
		this.optOn=false;

		hpe.goToTop();
	},

	SuspendApp : function() {
		var elt = $("AppCustomBlogTab"); if(elt) elt.className = "tab";
		elt = $("AppCustomBlogTools"); if(elt) Element.hide(elt);
		this.pageCurrentSource=-1;
	},

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

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

	LoadPage : function(pageid) {
		if(userIsGuest) { hpe.GotoLogin(); return }
		var url = siteHome + "ajaxAPI.php?api_call=Page::load&api_format=JSON&page=" + pageid + "&pageShowUnReadItems=" + (this.pageShowUnReadItems ? 1 : 0) + "&";
		var postBody = "";
		if(pageid == this.pageId) {
			url += "sort=" + this.pageSort + "&";
			url += "filter_pop=" + this.pageFilterPop + "&";
			url += "filter_date=" + this.pageFilterDate + "&";
			if(this.pageFirst)
				url += "first=" + this.pageFirst + "&";
			if(this.pageFilterSource != -1)
				url += "filter_source=" + this.pageFilterSource + "&";
		}
		if(this.markItemsRead > 0) {
			postBody += "markread=1&pageread="+this.pageId+"&";
			postBody += this.CollectSelectedItemToPost("markread", this.markItemsRead == 2);
			pageList[this.pageId].numUnreadItems -= this.numCollectedItems;
			this.markItemsRead = 0;
		}
		else if(this.markItemsRead < 0) {
			postBody += "markunread=1&pageread="+this.pageId+"&";
			postBody += this.CollectSelectedItemToPost("markunread", this.markItemsRead == -2);
			pageList[this.pageId].numUnreadItems -= this.numCollectedItems;
			this.markItemsRead = 0;
		}
		url += "seed=" + pageLoadSeed;
		pageLoadSeed++;

		var myAjax = new Ajax.Request(url, { method:'post', postBody:postBody, onComplete:this.LoadPageProcess.bind(this) });

		$("CPBMainContent").innerHTML = "<P>Please wait while items are being downloaded...</p>";

		srcInfo = new Array();
		itemInfo = new Array();
		prevDateStr = "";

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

		this.pageId = pageid;
		this.prevPageId = this.pageId;
		this.UpdatePageList();

		var select = $("CPBPageList");
		if(select) {
			if(this.pageId != select.selectedIndex)
				select.selectedIndex = this.pageId;
		}
		var bts = $("pagebuttons");
		if(bts) {
			var nc = bts.childNodes.length;
			var cp = -1;
			for(var i=0; i<nc; i++) {
				if(bts.childNodes[i].nodeName == "LI") {
					if(cp == pageid) bts.childNodes[i].className = "current";
					else bts.childNodes[i].className = "";
					cp++;
				}
			}
		}
		var shtml = "";
		if (!this.skipSourceListRebuild) {
			for(var e=0; e<pageList.length; e++) {
				if(e == pageid) {
					shtml += "";
					shtml += "<p align='center'>Loading Sources...</p>\n";
				} else shtml += "";
			}
			$("AppCustomBlogSources").innerHTML = shtml;
		}
		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
	},

	LoadPageProcess : function(originalRequest) {
		var mc = $("CPBMainContent"); if(!mc) return;

		var res = hpe.ProcessItemResponse(originalRequest);
		if(!res || res.response_code != 200) {
			mc.innerHTML = "<p>Failed to process data</p>"; return;
		}

		this.pageFilterPop = res.pageFilterPop;
		this.pageFilterDate = res.pageFilterDate;
		this.pageFilterSource = res.pageFilterSource;
		this.pageFirst = res.pageFirst;
		this.pageItemsPerPage = res.pageItemsPerPage;
		this.pageItemCount = res.pageItemCount;
		this.pageSort = res.pageSort;
		pageList[this.pageId].numUnreadItems = res.numUnreadItems;
		if(itemInfo.length == 0)
			pageList[this.pageId].numUnreadItems = 0;
		pageList[this.pageId].numTotalItems = res.numTotalItems;
		this.feedUrl = res.feedUrl;
		this.updateFeedControls(this.feedUrl);
		this.alert = res.alert;
		this.updateAlertControls(this.alert);
		$('APPCPBMarkAllRead').disabled = false;
		$('HPECPBGetReadOnly').disabled = false;
		
		app.insertEditOption(document.getElementById('OtherOpsCustom'),'Edit This Page', 'EditThisPage');

		var html = "";
		if(pageType == "custom_flat") {
			var n = itemInfo.length;
			if(n == 0) {
				if(!this.pageShowUnReadItems)
					html += "<div id='noitemmsg'>Found No Unread Items</div>" +
						 	"<p>Read items were hidden from this list, use the check box above to show entire list.</p>";
				else html += "<div id='noitemmsg'>Found No Items</div>";
				html += "<p>No unread items were found matching filters. Click on source name on the left to see all items for that source.</p><p><form>";
				if(this.pageFilterSource != -1) {
					html += "<input type='button' onClick='app.ShowSource(-1)' value='Show All Sources' /> ";
					html += "<input type='button' onClick='app.ShowSourceDetails(" + this.pageFilterSource + ")' value='Show Source Details' /> ";
					if(this.pageFilterPop > 0 || this.pageFilterDate > 0)
						html += "<input type='button' onClick='app.ShowAllSource()' value='Remove Filters and Show All Items for This Source' /> ";
				} else {
					if(this.pageFilterPop > 0 || this.pageFilterDate > 0)
						html += "<input type='button' onClick='app.ShowAllSource()' value='Remove Filters and Show All Items' /> ";
				}
				html += "</form></p>";
			} else {
				var q = this.pageFirst + this.pageItemsPerPage;
				if(this.pageItemCount < this.pageItemsPerPage)
					this.pageItemCount = itemInfo.length;
				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='padding-left:20px'>";
					var minItem = parseInt(this.pageFirst,10) - this.pageItemsPerPage * 5;
					if(minItem < 0) minItem = 0;
					var maxItem = parseInt(this.pageFirst,10) + this.pageItemsPerPage * 5;
					if(maxItem > this.pageItemCount) maxItem = pageItemCount;
					for(i=minItem; i<maxItem; i+=this.pageItemsPerPage) {
						if(i==minItem && minItem > 0) navpages += "<a onclick='app.ShowNextItems(0)' id=\"pagination\">&lt;&lt;</a>&nbsp;";
						if(i == this.pageFirst)
							navpages += "<span id=\"pagination_a\">" + (i / this.pageItemsPerPage + 1) + "</span>";
						else
							navpages += "<a onclick='app.ShowNextItems(" + i + ")' id=\"pagination\">" + (i / this.pageItemsPerPage + 1) + "</a>";
					}
					if(i >= maxItem && maxItem < this.pageItemCount)
						navpages += "&nbsp;<a onclick='app.ShowNextItems(" + (this.pageItemCount - this.pageItemCount % this.pageItemsPerPage) + ")' id=\"pagination\">&gt;&gt;</a>";
					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> | <a onClick='app.MarkRead()'>mark read</A> | <a onClick='app.MarkUnRead()'>mark unread</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>";
				navpages += "<br clear='both'></div>";
				html += navpages + hpe.ShowItemList() + navpages + "<br />";
			}
			html += "</div>";
		} else {
			html = "<p>Don't know what to do...</p>";
			hpe.log("Unhandled page type '" + pageType + "'");
		}
		
		mc.innerHTML = html;
		//Kontera adds stuff
		if (!NIFNOADS)
			try { initKontera(); } catch(e) { }
		savedElement = "";
		savedContent = "";

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

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

		elt = $("HPECPBsort");
		for(e=0; elt && e<elt.options.length; e++)
			if(elt.options[e].value == this.pageSort) {
				elt.selectedIndex = e;
				break;
			}
		if (!this.skipSourceListRebuild)
			this.BuildSourceList(this.pageId);
		else
			this.skipSourceListRebuild = false;
		hpe.MarkCurrentItem(false);

		this.UpdatePageList();
	},

	BuildSourceList : function (pid) {
		var shtml = "";
		if(numSources) {			
			shtml += "On This Page:\n";
			var cndx = 0;
			var foundOldSrc = 0;
			for(ndx in srcInfo) if(typeof srcInfo[ndx] != 'function') {
				src = srcInfo[ndx];
				var id = "";
				var mod = "";				
				if(src.lastmod)
					mod = ' (changed ' + src.lastmodStr + ')';
				if(!src.inList) {
					if(id != "broken")
						id = "old";
					shtml += '<table width="194" id="so' + src.key + '" class="dragboxlist"';
					/*if(this.pageFilterSource == -1) {
						shtml += ' style="display:none"';
						foundOldSrc++;
					}*/
					shtml += '><tr valign="top"><td width="16"><img onerror="this.width=1;this.height=1" src="'+src.favicon+'" align="top" title="drag to another page" class="dragHandle" height="16" width="16"></td><td><a class="' + id + '" title="' + src.title + mod;
				}
				else shtml += ('<table width="194" id="so' + src.key + '" class="dragboxlist"><tr><td width="16"><img onerror="this.width=1;this.height=1" src="'+src.favicon+'" align="top" title="drag to another page" class="dragHandle" height="16" width="16"></td><td><a class="' + id + '" title="' + src.title + mod);
				shtml += '" onClick="app.ShowSource(\'' + src.key + '\')">';
				if(cndx == this.pageFilterSource || src.key == this.pageFilterSource)
					shtml += '<b>' + src.title + '</b></a>';
				else
					shtml += src.title + '</a>';
				cndx++;
				shtml +='</td><td width="16"><img src="/i/del.gif" align="top" title="delete source from page" class="delsrc" id="dso'+src.key+'" style="cursor:pointer" /></td></tr></table>\n';
			};		
			shtml += "<div align='center' style='padding:5px'>";
			if(foundOldSrc)
				shtml += "<a href=\"#\" onClick=\"app.ShowAllSourceList(this)\">[show hidden]</a> ";
			if(this.pageFilterSource != -1)
				shtml += "<a href=\"#\" onClick=\"app.ShowSource(-1)\">[load all]</a> ";
			shtml += "</div>";
		}
		shtml +="<div align='center'><img src='/i/del.gif' onClick='app.deleteCurrentPage()' style='cursor:pointer' /> Delete page</div>";
		$("AppCustomBlogSources").innerHTML = shtml;
		var elt = $("SecPageToolsZone"); if(elt && elt.style.height != "0px") elt.style.height = "";

		if (!document.all) {
			$$('.dragboxlist').each(function(el) {		
		        new Draggable(el.id, {handle:'dragHandle', constraint:'vertical', revert:true});
	    	});
    	}
    	$$('.delsrc').each(function(el) {		
	        el.onclick = function() {
	        	if (!confirm('Are you sure to remove this source from the page?'))
	        		return false;
	        	this.skipSourceListRebuild = true;
	        	$(el.id.substr(1)).remove();//dso132432=>so132432
				var url = siteHome + "ajaxAPI.php?api_call=Page::removesource&api_format=JSON&page=" + this.pageId+'&source='+el.id.substr('dso'.length);
				new Ajax.Request(url, { method:'get', onSuccess: this.Reload.bind(this)});
			}.bind(this)
    	}.bind(this));
    	
	},

	ToggleReadMode : function(button, noreload) {
		this.pageShowUnReadItems = !(button.checked);
		if(noreload == null || noreload == 0)
			this.LoadPage(this.pageId);
		hpe.setCookie("HPECPBpageShowUnReadItems", this.pageShowUnReadItems ? "0" : "1", 7);
	},

	MarkRead : function (all) {
		if(postBody == "") return;
		if(this.pageShowUnReadItems) {
			var postBody = this.CollectSelectedItemToPost("markread", all);
			var url = siteHome + "ajaxAPI.php?api_call=Page::markread&api_format=JSON&onpage=" + this.pageId;
			var myAjax = new Ajax.Request(url, { method:'post', postBody:postBody });
		} else {
			this.markItemsRead = all ? 2 : 1;
			if(all == 2 && this.pageItemCount <= this.pageItemsPerPage)
				this.PageJumpButton(1); else this.LoadPage(this.pageId);
		}
	},

	MarkUnRead : function (all) {
		if(postBody == "") return;
		if(this.pageShowUnReadItems) {
			var postBody = this.CollectSelectedItemToPost("markunread", all);
			var url = siteHome + "ajaxAPI.php?api_call=Page::markunread&api_format=JSON&onpage=" + this.pageId;
			var myAjax = new Ajax.Request(url, { method:'post', postBody:postBody });
		} else {
			this.markItemsRead = all ? -2 : -1;
			this.LoadPage(this.pageId);
		}
	},

	CollectSelectedItemToPost : function (varname, all) {
		var fi = false;
		var postBody = "";
		this.numCollectedItems = 0;
		for(var i in itemInfo) if(typeof itemInfo[i] != 'function' && itemInfo[i].id)
			if(all || itemInfo[i].isChecked) {
				postBody += "item_id[]=" + itemInfo[i].id + "&"; fi = true;
				if(varname == "markread") {
					itemInfo[i].read =  1;
					var elt = $(itemInfo[i].id);
					Element.addClassName(elt, "read");
				} else if(varname == "markunread") {
					itemInfo[i].read =  0;
					var elt = $(itemInfo[i].id);
					Element.removeClassName(elt, "read");
				}
				hpe.CheckItem(itemInfo[i].id);
				this.numCollectedItems++;
			}
		if(itemInfo.length && !fi) {
			alert("You need to select items first!");
			return "";
		}
		return postBody;
	},

	ShowMapView : function () {
		if(isPremiumNewsmap) {
			var url = siteHome + "ajaxAPI.php?api_call=Newsmap::gencustompagemap&api_format=JSON";
			var post = "page=" + this.pageId;
			var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.ShowMapViewProcess.bind(this) } );
//			hpe.Dialog.info("Loading map view", { showProgress: 1 });
			lightWin.wait("Loading map view");
		} else {
			hpe.requirePremium("Newsmap for Custom Page", "Newsmap");
			$("APPCPBToggleMap").disabled = 1;
		}
	},

	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 = "News Map Viewer";
				var pl = $("CPBPageList");
				if(pl) t = "Newsmap for custom page '" + pl.options[pl.selectedIndex].text + "'";
				lightWin.link(t, res.htmlfile, {fullSize:1, useiframe:hpe.isffwin});
			}
		}
	},

	GenerateRSS : function() {
		if(isPremiumExport) {
			if(!window.open(siteHome + "user/rss/#pages"))
				alert("A popup blocker seems to have prevented the opening of a new window");
		} else hpe.requirePremium("Custom RSS Feeds", "Export");
	},

	PageListChange : function () {
		var select = $("CPBPageList");
		if(select) {
			if(this.pageId != select.selectedIndex)
				this.LoadPage(select.selectedIndex);
		}
	},

	Reload : function() {
		if(this.pageId == 'clip')
			this.LoadClippings();
		else if(this.pageId == 'home')
			this.Home();
		else
			this.LoadPageButton(-1)
	},

	LoadPageButton : function (pageid) {
		if(pageid == -1 || pageid == 'home' || pageid == 'clip') {
			pageid = this.prevPageId;
			this.pageId = -1;
		}
		this.LoadPage(pageid);
	},

	PageJumpButton : function (skip) {
		var pg = 0;
		if(this.pageId != -1 && this.pageId != 'home' && this.pageId != 'clip')	{
			pg = this.pageId + skip;
			if(pg < 0)
				pg = pageList.length - 1;
			if(pg >= pageList.length)
				pg = 0;
		}
		this.pageFilterSource = -1;
		this.LoadPage(pg);
	},

	ShowSource : function (srcId, inPage) {
		this.pageFirst = 0;
		if(srcId == -1) {
			this.pageFilterSource = -1;
			this.LoadPage(this.pageId);
			return true;
		}
		var cndx = 0;
		for(var i in srcInfo) if(typeof srcInfo[i] != 'function') {
			if(srcInfo[i].id == srcId || srcInfo[i].key == srcId) {
				this.pageFilterSource = srcInfo[i].key;
				this.LoadPage(this.pageId);
				return true;
			}
			cndx++;
		}
	},

	ShowAllSource : function () {
		this.pageFirst=0;
		this.pageFilterPop = 0;
		this.pageFilterDate = 0;
		this.LoadPage(this.pageId);
	},

	ShowAllSourceList : function (button) {
		for(var i in srcInfo) if(typeof srcInfo[i] != 'function') {
			var elt = $("so" + srcInfo[i].key);
			if(elt)
				elt.style.display = "";
		}
		button.style.display = "none"
		var elt = $("SecPageToolsZone"); if(elt && elt.style.height != "0px") elt.style.height = "";
	},

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

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

	FilterPop : function () {
		var elt = $("HPECPBfilter_pop");
		this.pageFilterPop = elt.value;
		this.pageFirst=0;
		this.LoadPage(app.pageId);
	},

	FilterDate : function () {
		var elt = $("HPECPBfilter_date");
		this.pageFilterDate = elt.value;
		this.pageFirst=0;
		this.LoadPage(app.pageId);
	},

	SaveFilterSettings : function() {
		var url = siteHome + "ajaxAPI.php?api_call=Page::save&api_format=JSON&page=" + this.pageId + "&";
		url += "sort=" + this.pageSort + "&";
		url += "filter_pop=" + this.pageFilterPop + "&";
		url += "filter_date=" + this.pageFilterDate + "&";

		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.OpsSaveSettingsProcess.bind(this) });
	},
	
	deleteCurrentPage : function()
	{
		if (confirm('Are you sure to delete page '+pageList[this.pageId].title+' ?'))
		{
			var newPageList = new Array;
			var pageBlockOldId;
			var pageBlockId;
			for(var i=0; i<pageList.length; i++)
			{
				pageBlockOldId = 'cpage_'+i;
				if (i != this.pageId)
				{
					pageList[i].index = newPageList.length;
					newPageList[newPageList.length] = pageList[i];										
					pageBlockId = 'cpage_'+newPageList.length;
					$(pageBlockOldId).id = pageBlockId;
				}
				else
				{					
					Droppables.remove($(pageBlockOldId));
					$(pageBlockOldId).remove();
				}
			}
			pageList = newPageList;
			var url = siteHome + "ajaxAPI.php?api_call=Page::deletepage&api_format=JSON&page=" + this.pageId;
			var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.LoadPageButton.bind(this, 0) });
		}		
	},

	LaunchOps : function () {
		var elt = $(this.opsSelect);
		switch(elt.value) {
			case "SaveSettings":
				this.SaveFilterSettings();
				break;
			case "CatchUp":
				var url = siteHome + "ajaxAPI.php?api_call=Page::markallread&api_format=JSON&page=" + this.pageId;
				var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.Reload.bind(this) });
				break;
			case "EditThisPage":
				if(!window.open(siteHome + "user/custom/content/" + appCP.pageId))
					alert("A popup blocker seems to have prevented the opening of a new window");
				break;
			case "Subscribe":
				if(!window.open(siteHome + "user/sub/"))
					alert("A popup blocker seems to have prevented the opening of a new window");
				break;
			case "ManagePages":
				if(!window.open(siteHome + "user/pages/"))
					alert("A popup blocker seems to have prevented the opening of a new window");
				break;
			default:
				this.LaunchDefaultOps(elt);
		}
		elt.selectedIndex = 0;
	},

	OpsSaveSettingsProcess : function (Request) {
		try { var res = eval('('+Request.responseText+')') }
		catch(e) { hpe.log(Request.responseText); return hpe.error(e) }
		if(res.response_code == 200)
			alert("Saved current page filter settings");
		else
			alert("Failed to save filter settings");
	},

	HandleKeyboard : function(event) {
		var c = event.keyCode;		
		switch(c) {
		case 52: // $
		case 48: // )
		case 221: // ]
			app.MarkRead(2);
			return true;
		case 76: // l
			this.PageJumpButton(1);
			return true;
		case 72: // h
			this.PageJumpButton(-1);
			return true;
		}
		return false;
	},
	
	InlineEditorKeyDown : function(event) {
		var c = event.keyCode;
		if (c == 13)//enter - save
		{
			this.hideInlineEditor(this.inlineEditor);
			return true;
		}
		else if (c == 27)//esc - just hide inline editor and restore initial value
		{
			this.hideInlineEditor(this.inlineEditor, true);
			return true;
		}
	},
	
	showInlineEditor : function(elt, editor) {	
		var s = elt.innerHTML;		
		elt.onclick=null;
		edt = editor.cloneNode(true);
		//edt.style.visibility = 'visible';
		edt.value =	s;
		this.oldPageName = s;
		edt.onkeydown = this.InlineEditorKeyDown.bindAsEventListener(this);
		//elt.firstChild.innerHtml;
		elt.innerHTML = '';
		elt.appendChild(edt);
		edt.style.width = '110px';
		edt.style.display='inline';
		this.inlineEditor = edt;
		//elt.innerHTML = html;
		this.pageEdit = edt;
		edt.focus();
	},
	
	hideInlineEditor : function(edt, doNotSave) {
		if (!this.inlineEditor) return;
		edt.up().onclick = this.showInlineEditor.bind(this, edt.up(), $('inlineEditor'));
		if (doNotSave)
			s = this.oldPageName;
		else {
			s = edt.value.strip();
			s = s.empty()?'Unnamed page':s;
		}
		edt.up().innerHTML = s;
		pageList[this.pageId].title = s;
		edt = null;
		this.inlineEditor = null;
		//send ajax request here if needed
		if (!(doNotSave || this.oldPageName==s)) {
			var url = siteHome + "ajaxAPI.php?api_call=Page::renamecustompage&api_format=JSON";
			var post = "page=" + this.pageId;//only current page is editable
			post +='&name='+s;
			var myAjax = new Ajax.Request(url, {method: 'post', postBody: post});
		}		 
	},

	UpdatePageList : function() {
		var html = "<input type='text' id='inlineEditor'>";
		html += "<div onClick='app.Home()' style='cursor:pointer'><table class='subMenuItem";
		if(this.pageId == 'home')
			html += ' subMenuItemSelected';
		html += "'><tr><td width='16'><img src='/i/house.gif' align='top' /></td>\
			<td width='100%' align='left'>";
		if(this.pageId == 'home')
			html += '<b>';
		html += "Home</td></tr></table></div>";
		html += '<div id="pagelistSortable"  style="margin:0px;padding:0px;font-size:100%;">';
		for(var i=0; i<pageList.length; i++) {
			html += '<div id="cpage_'+pageList[i].index+'" class="pageNavItem"><table width="194" class="subMenuItem';
			if (pageList[i].index == this.pageId)
				html += ' subMenuItemSelected';
			html +='"><tr><td width="16">';
			if(pageList[i].index == this.pageId)
				html += "<img src='/i/folder_page.gif' title='drag to sort' align='top' class='sortHandle'/></td><td style='font-weight:bold'><span class='editContentCell'>" + pageList[i].title + "</span>";
			else
				html += "<img src='/i/folder.gif' align='top' title='drag to sort' class='sortHandle'/></td><td id='pageLink_"+pageList[i].index+"' class='pageLink'>" + pageList[i].title;
			html += "</td><td width='16'>";
			if (pageList[i].index == this.pageId)
				html += '<img src="/i/pencil.gif" onClick="app.ToggleOptions()" style="cursor:pointer">';
			else if(pageList[i].numUnreadItems)
				html += pageList[i].numUnreadItems;
			else
				html += '&nbsp;';
			html += "</td></tr></table></div>";
		}
		html += '</div>';
		html += "<div onClick='app.LoadClippings()' style='cursor:pointer'><table class='subMenuItem";
		if(this.pageId == 'clip')
				html += ' subMenuItemSelected';
		html += "'><tr><td width='16'><img src='/i/attach.gif' align='top' /></td>\
				<td width='100%' align='left'>";
		if(this.pageId == 'clip')
			html += '<b>';
		html += "Clippings</td><td width='16' id=\"AppCurClipCount\">" + (hpe.CurrentClipCount ? hpe.CurrentClipCount : "") + "</td></tr></table></div>";
		html += '</div>';		

		if(outbrain['IsVisible']) {	
			if(ratingConfig['visibleRN']) {
				html += "<div onClick='app.RecommendedNews()' style='cursor:pointer'><table class='subMenuItem";
				if(this.pageId == 'recommendedNews')
						html += ' subMenuItemSelected';
				html += "'><tr><td width='16'><img src='/i/star_s.gif' align='top' /></td>\
						<td width='100%' align='left'>";
				if(this.pageId == 'recommendedNews')
					html += '<b>';
				html += "Recommended News";
				
				if(hpe.CurrentRecommendedNewsCount)
					html += " (<span id=\"AppCurRecommendedNewsCount\">" + hpe.CurrentRecommendedNewsCount + "</span>)</td></tr></table></div>";
				else
					html += " <span id=\"AppCurRecommendedNewsCount\"></span></td></tr></table></div>";
			}
			
			html += "<div onClick='app.mostRatedNews()' style='cursor:pointer'><table class='subMenuItem";
			if(this.pageId == 'mostRatedNews')
					html += ' subMenuItemSelected';
			html += "'><tr><td width='16'><img src='/i/star_s.gif' align='top' /></td>\
					<td width='100%' align='left'>";
			if(this.pageId == 'mostRatedNews')
				html += '<b>';
			html += "Highest Rated News";

			if(hpe.CurrentMostRatedNewsCount)
				html += " (<span id=\"AppCurMostRatedNewsCount\">" + hpe.CurrentMostRatedNewsCount + "</span>)</td></tr></table></div>";
			else
				html += " <span id=\"AppCurMostRatedNewsCount\"></span></td></tr></table></div>";

			html += "<div onClick='app.LoadDocumentRatings()' style='cursor:pointer'><table class='subMenuItem";
			if(this.pageId == 'documentRating')
					html += ' subMenuItemSelected';
			html += "'><tr><td width='16'><img src='/i/star_s.gif' align='top' /></td>\
					<td width='100%' align='left'>";
			if(this.pageId == 'documentRating')
				html += '<b>';
			html += "Your Rated News";

			if(hpe.CurrentRatingsCount)
				html += " (<span id=\"AppCurRatingsCount\">" + hpe.CurrentRatingsCount + "</span>)</td></tr></table></div>";
			else
				html += " <span id=\"AppCurRatingsCount\"></span></td></tr></table></div>";
		}

		$("AppCustomBlogPages").innerHTML = html;	
		if (!document.all)
			Sortable.create("pagelistSortable",{tag:'div', constraint:'vertical', handle:'sortHandle', onUpdate:this.pagesOrderChanged.bind(this)});

    	$$('.editContentCell').each(function(el) {		
	        el.onclick = function() { app.showInlineEditor(this, $('inlineEditor')); }
    	});
    	$$('.pageLink').each(function(el) {		
	        el.onclick = function() {
				$pageId = parseInt(this.id.substr('pageLink_'.length));
	            app.LoadPageButton($pageId);	            
	            return false;
	        }
    	});

    	if(!document.all) {
	    	$$('.pageNavItem').each(function(el) {
	    		Droppables.add(el.id,{accept:'dragboxlist', hoverclass:'curDroppable', onDrop:function(draggable, droppable){
					if (droppable.id != 'cpage_'+this.pageId) {
						draggable.remove();
						this.skipSourceListRebuild = true;
						var url = siteHome + "ajaxAPI.php?api_call=Page::movesource&api_format=JSON&topage=" + droppable.id.substr('cpage_'.length)+'&source='+draggable.id.substr('so'.length)+'&page='+this.pageId;
						new Ajax.Request(url, { method:'get', onSuccess: this.Reload.bind(this)});
					}
				}.bind(this)});
	    	}.bind(this));
	    }
	},
	
	pagesOrderChanged : function(container) {
		var idList = new Array();
		var pageListNew = new Array(); 
		var i=0;
		var pageId;			
		(container.immediateDescendants().each(function(elt){
			idList[i] = elt.id.substr('cpage_'.length);
			jslog.debug(i+': '+this.pageId+' '+idList[i]);
			if (this.pageId == idList[i])
				pageId = i;
			elt.id = 'cpage_'+i;
			pageListNew[i] = pageList[idList[i]];
			pageListNew[i].index = i;
			i++;
		}.bind(this)));
		this.pageId = pageId;
		this.prevPageId = pageId; 
		pageList = pageListNew;
		var url = siteHome + "ajaxAPI.php?api_call=Page::cpsort&api_format=JSON&order=" + idList.join(',');
		var myAjax = new Ajax.Request(url, { method:'get'});
	},

	ToggleOptions : function(b) {
		var elt = $("AppCustomBlogOptShow");
		var opts = $$("div.cpbopt");
		if(this.optOn) {
			this.optOn = false;
			opts.each(function(s){s.hide()});
		} else {
			this.optOn = true;
			opts.each(function(s){s.show()});
		}
	},

/*
	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) {
		$('createFeedButton').disabled = true;
		var url = siteHome + "ajaxAPI.php?api_call=Page::feed&api_format=JSON&page=" + this.pageId + "&";
		var urlAction;
		if (action == undefined)
			urlAction = 'check';
		else if(action)
			urlAction = 'create';
		else
			urlAction = 'delete';
		url += "action=" + urlAction + "&";
		url += "page=" + this.pageId + "&";
		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);
	},

	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 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)});
		if (alert.exists) $('removeAlertBtn').onclick = this.removePageAlert.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) {
		var btn = $('createFeedButton');
		var lnk = $('pageRssLink');
		var img = $('pageRssIcon');
		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').disabled = false;
		if (alert.exists)
		{
			$('createAlertBtn').value = 'Configure Alert';
		}
		else
		{
			$('createAlertBtn').value = 'Create Alert';
		}
	},

	alertSetupCb : function(params)
	{
		$('createAlertBtn').disabled = true;
		//get options from alert config popup
		var formdata = Form.serialize('alertConfigFrm');
//jslog.debug(formdata);
		var url = siteHome + "ajaxAPI.php?api_call=Page::watch&api_format=JSON&page=" + this.pageId + "&";
		url += formdata;
		//send ajax request
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this)});
		//close alert config popup
		return true;
	},

	removePageAlert : function()
	{
//jslog.debug('removePageAlert');
		lightWin.hide();
		$('createAlertBtn').disabled = true;
		var url = siteHome + "ajaxAPI.php?api_call=Page::unwatch&api_format=JSON&page=" + this.pageId + "&";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.watchProcess.bind(this)});
	},

	unsubscribeFromSource : function(id) {
		if(!confirm("Are you sure you want to unsubscribe from this source?")) return;
		var url = siteHome + "ajaxAPI.php?api_call=Page::unsubscribe&api_format=JSON";
		var page = appCP.pageId;
		var post = "siteid=" + id + "&page=" + page;
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: this.unsubscribeFromSourceProcess.bind(this) } );
	},

	unsubscribeFromSourceProcess : 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);
			app.LoadPageButton(res.page_id);
	},

	Home : function() {
		var url = siteHome + "ajaxAPI.php?api_call=Page::home&api_format=JSON";
		var myAjax = new Ajax.Request(url, { method:'post', onComplete:this.HomeProcess.bind(this) });
		$("CPBMainContent").innerHTML = "<p>Load latest items...</p>";

		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
		$('APPCPBMarkAllRead').disabled = true;
		$('HPECPBGetReadOnly').disabled = true;
		
		app.removeEditOption(document.getElementById('OtherOpsCustom'));

		if(this.pageId != 'home' && this.pageId != 'clip')
			this.prevPageId = this.pageId;
		this.pageId = 'home';
		this.UpdatePageList();
		if(this.optOn) this.ToggleOptions();
		var elt = $("AppCustomBlogOptShow");
		var opts = $$("div.cpbopt");
		hpe.goToTop();
	},

	HomeProcess : function(Request) {
		try { var res = eval('('+Request.responseText+')'); } catch(e) { return hpe.error(e); }
		if(res.response_code != 200) {
			$("CPBMainContent").innerHTML = "<p>Failed to load items...</p>";
			return;
		}

		var html=""; var ns=0; var ni=0;
		for(var i=0; i<pageList.length; i++) {
			html += "<table width='100%' border=0 cellspacing=0 style='padding:5px'><tr class='newsListItem'>";
			html += "<td width=20><img src='/i/folder.gif' /></td><td class='subNewsListItem'>";
			html += "<a onClick='app.LoadPageButton(" + i + ")'>" + pageList[i].title + "</a></td>";
			html += "<td align=right nowrap><small>" + res.pages[i].numUnreadItems + " unread items in " + res.pages[i].numTotalItems + " from " + res.pages[i].numSources + " sources</td>";
			html += "</tr><tr valign=top><td rowspan=2 colspan=2><ul>";
			for(var j=0; j<res.pages[i].items.length; j++) {
				pageList[i].numUnreadItems = res.pages[i].numUnreadItems;
				pageList[i].numTotalItems = res.pages[i].numTotalItems;
				html += "<li id='" + res.pages[i].items[j].id + "'><a";
				if(!res.pages[i].items[j].read) html += " style='font-weight:bold'";
				html += " onClick=\"return hpe.VisitItem('" + res.pages[i].items[j].id + "', this)\"";
				html += " onMouseOver=\"return app.ShowHomeItemDetails(" + i + "," + j + ")\"";
				html += " href=\"" + res.pages[i].items[j].link + "\" target=\"_blank\" class='ItemTitle'>";
				html += res.pages[i].items[j].title + "</a>";
				html += " in " + res.pages[i].items[j].sourcetitle;
				html += "</li>";
				if(res.pages[i].items[j].desc) {
					res.pages[i].items[j].desc = res.pages[i].items[j].desc.stripTags();
					if(res.pages[i].items[j].desc.length > 250)
						res.pages[i].items[j].desc = res.pages[i].items[j].desc.substr(0,247) + "...";
				}
			}
			html += "</ul></td><td id='itemDetail" + i + "' class='newsItemDetail'></td></tr>";
			html += "<tr valign=bottom><td id='homeItemDetailOps" + i + "' class='newsHomeItemDetail'></td></tr></table>";
			ns += res.pages[i].numSources;
			ni += res.pages[i].numTotalItems;
		}
		html += "<P align='center'>You are subscribed to " + ns + " sources, containing " + ni + " items.</p>";
		$("CPBMainContent").innerHTML = html;

		this.pageItems = res.pages;
		this.activePageItem = new Array();
		for(var i=0; i<pageList.length; i++) {
			this.activePageItem[i] = false;
			this.ShowHomeItemDetails(i, 0);
		}
		this.UpdatePageList();
	},

        ShowHomeItemDetails : function(p, i) {
                var elt = $('itemDetail' + p); if(!elt) { hpe.log("no item " + p); return }
                var item = this.pageItems[p].items[i];
                elt.innerHTML = item.desc + "<br /><br /><small>" + hpe.FormatLongDate(item.date) + "</small>";
                var topHtml = "";
                
                
                if(outbrain['IsVisible'])
				{
					var outbrainLink = encodeURIComponent(item.link);
					//var outbrainLink = siteHome+'click/'+item.id+'/';
					var outbrainUser = encodeURIComponent(userID);
					
					var renderData = new Object;
					renderData['p'] = p;
					renderData['i'] = i;
					
					topHtml += '<div id="ratingConteiner'+item.id+'">';
					//topHtml += renderStarsHome(item,p,i);
					topHtml += renderStars(item,renderData);
					topHtml += '</div>';
				}
                
                topHtml += "<span id='akst_social' style='float:right'><ul>";
                topHtml += "<li><a id='akst_delicious' href='http://del.icio.us/post?v=4;url=" + escape(item.link) + ";title=" + escape(item.title) + "' target='_blank' title='del.ico.us'></a></li>";
                topHtml += "<li><a id='akst_digg' href='http://digg.com/submit?phase=2&url=" + escape(item.link) + "' target='_blank' title='Digg'></a></li>";
		topHtml += "<li><a id='akst_twitter' href='http://twitter.com/home?status=" + escape(item.title) + " " + escape(item.link) + "' target='_blank' title='twitter'></a></li>";
                topHtml += "<li><a id='akst_facebook' href='http://www.facebook.com/share.php?u=" + escape(item.link) + "' target='_blank' title='facebook'></a></li>";
                topHtml += "</ul></span>";
                if(isPremiumPortal)
                        topHtml += "<a onClick=\"return hpe.PostItemSms('" + item.id + "')\"><img width='38' src=\"/i/sms.png\" /></a> ";
                topHtml += "<a onClick=\"hpe.PostOneItemMail('" + item.id + "')\"><img width='35' src=\"/i/bomail.png\" /></a> ";
                if(blogList.length)
                        topHtml += "<a onClick=\"hpe.PostOneItemBlog('" + item.id + "')\"><img width='35' src=\"/i/boblog.png\" /></a>";
                elt = $('homeItemDetailOps' + p);
                elt.innerHTML = topHtml;
                if(this.activePageItem[p]) {
                        elt = $(this.activePageItem[p]);
                        //if(elt) elt.style.backgroundColor = "white";
                        if(elt) elt.className = "newsItemRowOff";
                }
                elt = $(item.id);
                //if(elt) elt.style.backgroundColor = "#F3F3E7";	//ECEFFF clasName
                if(elt) elt.className = "newsItemRowOn";
                this.activePageItem[p] = this.pageItems[p].items[i].id;
        },
	
	subcribeSource : function() {
		var url = siteHome + "ajaxAPI.php?api_call=User::subscribeSources&api_format=JSON&sub_search="+document.getElementById('sub_search').value;
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.subcribeSourceProcess.bind(this) });
		$("CPBMainContent").innerHTML = "<p>Loading...</p>";
		
		hpe.goToTop();
	},
	
	subcribeSourceProcess : function (request) {
		var mc = $("CPBMainContent");
		
		try 
		{
			var res = eval('('+request.responseText+')'); 
		} 
		catch(e) 
		{
			mc.innerHTML = "<p>Failed to process data</p>"; 
			return hpe.error(e); 
		}
		
		if(!res || res.response_code != 200)
		{
			mc.innerHTML = "<p>Failed to process data</p>"; 
			return;
		}
		$searchstr = document.getElementById('sub_search').value;
		//if search is a keyword
		var html = '';
		try
		{
			if (res.response_message && (res.response_message=='keyword')) {
				mc.innerHTML = "<p>No items found matching filter</p>"; 
				return;
				/*
				app.SuspendApp(this);
				app = appSP;
				app.StartApp(0);
				$("source_search").value = $searchstr;
				app.SearchTextChange();
				*/
			}
			else if (res.response_message && (res.response_message=='url')) {
				html += '<div class="Section"><h1>&gt; Subscribe to a Source</h1><DIV style="padding:0px 10px 0px 10px">';
				if (res.sub_message) 
				{
					if (res.sub_message ==  "open_parse_failed")
					{
						mc.innerHTML = '<div class="Section"><h1>&gt; Subscribe to a Source</h1><DIV style="padding:0px 10px 0px 10px"><b>Sorry. Our parser couldn\'t open the URL or parse the resulting data. Reason could be that there is a network issue or that there is an error in the feed\'s XML. Please contact the site provider and ask about feed details (RSS or Atom Version).</b></div></div>';
						return;
					}
				}
				else
				if(res.sub_id) 
				{
					html += '<form action="'+siteHome+'user/sub/" method="POST"  style="border: 1px solid silver; padding:5px;"><input type="hidden" name="src[]" value="'+res.sub_id+'" />Subscribe to <a target="_blank" href="'+siteHome+'sources/info/'+res.list_sources[0].id+'/"><b>'+list_sources[0].title+'</b></a>(<a href="'+list_sources[0].link+'">view site</a>).';
				}
				else if (res.list_sources.length) 
				{
					html += '<form action="'+siteHome+'user/sub/" method="POST"  style="border: 1px solid silver; padding:5px;">';
					for(i=0;i<res.list_sources.length;i++) 
					{
						source = res.list_sources[i];
						html += '<input type="checkbox" name="src[]" value="'+source.id+'" /><a href="'+siteHome+'sources/info/'+source.id+'/"><b>'+source.title+'</b></a>(<a href="'+source.link+'">view site</a>).<br />';
					}
					if (res.list_sources_countwarn)
					{
						html += '<em>Your search generated more results than we can list here, please refine your search</em>';
					}
				}
				else if (res.ext_alternates)
				{
					html += '<p>The link you entered does not seem to be valid RSS or ATOM file. However, we did find the following alternate file(s) (Via Auto-Discovery):</p>';
					html += '<form action="'+siteHome+'user/sub/" method="POST">';
					for(i=0;i<res.ext_alternates.length;i++) 
					{
						alternate = res.ext_alternates[i];
						html += '<input type="radio" name="url" value="'+alternate.link+'" /> '+alternate.title+' <a href="'+alternate.link+'" title="'+alternate.type+'"><img src="'+siteHome+'HPE/Images/feed-icon16x16.png" width="14" height="14" hspace="10"/></a><br />';
					}
					html += '<p>Please select the feed you would like add to your page and click <input type="submit" name="sub_url" value="Subscribe" />';
				}
				else if (res.ext_source) 
				{
					html += '<FORM ACTION="'+siteHome+'user/sub/" METHOD="POST"  style="border: 1px solid silver; padding:5px;">';
					html += '<input type="hidden" name="extrss_rss" value="'+res.ext_source.source+'" />';
					html += '<input type="hidden" name="extrss_url" value="'+res.ext_source.source+'" />';
					html += 'Subscribe to <input name="extrss_title" type="text" value="'+res.ext_source.title+'" />';
					html += '<a target="_blank" href="'+res.ext_source.source+'"><img src="'+siteHome+'HPE/Images/feed-icon16x16.png" width="14" height="14" hspace="10"/></a>';

					if(res.ext_source_items) 
					{ 
						html += '<p>Most recent items are:<ul>';
						for(i=0;i<res.ext_source_items.length;i++) 
						{
							item = res.ext_source_items[i];
							html += '<li> <a href="'+item.link+'">';
							if (item.title != "")
							{
								html += item.title;
							}
							else
							{
								html +='<em>No Title</em>';
							}
							html += '</a></li>';
						}
						html += '</ul></p>';
					}
				}
				else if (res.list_sources_urlnothingfound)
				{
					mc.innerHTML = '<div class="Section"><h1>&gt; Subscribe to a Source</h1><DIV style="padding:0px 10px 0px 10px"><br /><b>Sorry. Nothing Found</b></div></div>';
					return;
				}
				if (res.showpagelist) 
				{
					html += '<p>Select the page you would like to add this content to: <SELECT name="pageid">';
					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" selected>[New page]</option>';
					html += '</select><input type="submit"  name="addsrc" value="Subscribe"></p>';
				}
				
				html += '</form></div></div>';
			}	
		}catch (e)
		{
			mc.innerHTML = "<p>No items found matching filter</p>"; 
			return;
		}
			
		mc.innerHTML = html; 
		return; 
	},

	LoadClippings : function () {
		var url = siteHome + "ajaxAPI.php?api_call=Clipping::get&api_format=JSON";
		var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.LoadClippingsProcess.bind(this) });
		$("CPBMainContent").innerHTML = "<p>Loading Clippings...</p>";
		if(this.pageId != 'home' && this.pageId != 'clip')
			this.prevPageId = this.pageId;
		this.pageId = 'clip';
		this.UpdatePageList();
		if(this.optOn) this.ToggleOptions();

		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
		$('APPCPBMarkAllRead').disabled = true;
		$('HPECPBGetReadOnly').disabled = true;
		
		app.removeEditOption(document.getElementById('OtherOpsCustom'));

		hpe.goToTop();
	},

	LoadClippingsProcess : function (request) {
		var mc = $("CPBMainContent");
		var res = hpe.ProcessItemResponse(request);
		if(!res || res.response_code != 200) {
			mc.innerHTML = "<p>Failed to process data</p>"; return;
		}
		for(i=0; i<itemInfo.length; i++)
			itemInfo[i].isClip = 1;
		hpe.CurrentClipCount = itemInfo.length;
		

		var html = ""; 
		
		if (hpe.CurrentClipCount == 0){
			html += "<div class='PowerAppItemListTitle'>No Clippings Found</div>"
		}else{
			html += "<div class='PowerAppItemListTitle'>Current Clippings</div>"
		}
		html += hpe.ShowItemList();
		this.UpdatePageList();

		mc.innerHTML = html;
		savedElement = "";
		savedContent = "";
		hpe.MarkCurrentItem(false);
	},
	
	// outbrain
	LoadDocumentRatings : function (voter) {
		
		var element;
		var i;
		var query = '';
		var filter = new Object;
//		var toCookie = new Object;
		
		//get filter from cookie
		var fromCookie = new Object;
		var valAr = new Array();
		var keyAr = new Array();
		savedFilter = hpe.getCookie("outbrainFilter");

		if(typeof(savedFilter) == "string" && savedFilter.length > 0) {
			valAr = savedFilter.split(';');
			
			for(i in valAr) {
				if(typeof(valAr[i]) == "string" && valAr[i].length > 0) {
					keyAr = valAr[i].split('=');
					if(typeof(keyAr[0]) != "undefined" && typeof(keyAr[1]) != "undefined")
						fromCookie[ keyAr[0] ] = keyAr[1];
				}
			}
		}
				
		// sortBy
		element = $('sortBy');
		if(element)
			filter['sort'] = element.value;
		else {
			if(fromCookie['sort'])
				filter['sort'] = fromCookie['sort'];
		}
		
		// orderBy
		element = $('orderBy');
		if(element)
			filter['order'] = element.value;
		else {
			if(fromCookie['order'])
				filter['order'] = fromCookie['order'];
		}
		
		for(i in filter) {
			if(typeof(filter[i]) != "function")
				query += "&"+i+"="+filter[i];
		}
		
		if(voter && voter.length > 0)
			query += "&voter="+voter;

		savedFilter = '';
		for(i in filter) {
			if(typeof(filter[i]) != "function")
				savedFilter += ";"+i+"="+filter[i];
		}

		if(savedFilter.length > 0) hpe.setCookie("outbrainFilter", savedFilter);
		
		var randomValue = "&r="+Math.random()*10; // aviod cashing
		var url = siteHome + "ajaxAPI.php?api_call=Outbrain::DocumentRatings&api_format=JSON"+query+randomValue;
		//var url = siteHome + "ajaxAPI.php?api_call=Clipping::get&api_format=JSON";
		//var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.LoadDocumentRatingsProcess.bind(this) });
		var myAjax = new Ajax.Request(url, { method:'post', onSuccess:this.LoadDocumentRatingsProcess.bind(this) });

		var filterMenu = '\
			<div class="box1" style="padding-bottom: 5px;">\
				<div class="hdrbox1">Your Rated News Filter</div>\
				<div class="cntbox1">\
					<div style="float: left;">\
						Sort By: &nbsp;  \
						<select name="sortBy" id="sortBy">\
<!--							<option value="popularity" >popularity</option>	-->\
							<option value="rating" '+ ((filter['sort'] == 'rating') ? 'selected' : '')  +' title="sort by the average document rating">rating</option>\
							<option value="date" '+ ((filter['sort'] == 'date') ? 'selected' : '')  +' title="sort by date of the last time the document was rated">date</option>\
<!--							<option value="num-ratings">num-ratings</option>	-->\
						</select>\
					</div>\
					<div style="float: left;  margin-left: 15px;">\
						Order By: &nbsp;\
						<select name="orderBy" id="orderBy">\
							<option value="desc" '+ ((filter['order'] == 'desc') ? 'selected' : '')  +'>descending</option>\
							<option value="asc" '+ ((filter['order'] == 'asc') ? 'selected' : '')  +'>ascending</option>\
						</select>\
					</div>\
					<div style="float: left;  margin-left: 15px;">\
						<input type="button" value="Filter" onClick="javascript: app.LoadDocumentRatings()" />\
					</div>\
					<br clear="all" />\
				</div>\
			</div>\
			<div id="CPBRatingContent" name="CPBRatingContent"><p>Loading Ratings...</p></div>\
						';		
		
		$("CPBMainContent").innerHTML = filterMenu;
		
		// saved filter from cookie
		if($('sortBy') && fromCookie['sort'])
		{
			//$('sortBy').selectedIndex = fromCookie['sort'];
		}
		
		if($('orderBy') && fromCookie['order'])
		{
			//$('orderBy').selectedIndex = fromCookie['order'];
		}
		
		
		if(this.pageId != 'home' && this.pageId != 'documentRating')
			this.prevPageId = this.pageId;
		this.pageId = 'documentRating';
		this.UpdatePageList();
		if(this.optOn) this.ToggleOptions();

		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
		$('APPCPBMarkAllRead').disabled = true;
		$('HPECPBGetReadOnly').disabled = true;
		
		app.removeEditOption(document.getElementById('OtherOpsCustom'));
	
		hpe.goToTop();
	},

	LoadDocumentRatingsProcess : function (request) {
		var res;
		try
		{
			res = hpe.ProcessItemResponse(request);
		}
		catch(e) {};
/*
		if(!res || res.response_code != 200) {
			mc.innerHTML = "<p>Failed to process data</p>"; return;
		}
*/
		hpe.CurrentRatingsCount = itemInfo.length;
		
		if (hpe.CurrentRatingsCount == 0){
			$("CPBRatingContent").innerHTML = "No Items Found";
		}else{
			$("CPBRatingContent").innerHTML = hpe.ShowItemList();
		}
			
		this.UpdatePageList();
		
		savedElement = "";
		savedContent = "";
		hpe.MarkCurrentItem(false);
	},
	
// recomendations	
	RecommendedNews : function () {
		
		var randomValue = "&r="+Math.random()*10; // aviod cashing
		var url = siteHome + "ajaxAPI.php?api_call=Outbrain::RecommendedNews&api_format=JSON"+randomValue;
		var myAjax = new Ajax.Request(url, { method:'post', onSuccess:this.RecommendedNewsProcess.bind(this) });
	
		if(this.pageId != 'home' && this.pageId != 'recommendedNews')
			this.prevPageId = this.pageId;
		this.pageId = 'recommendedNews';
		this.UpdatePageList();
		if(this.optOn) this.ToggleOptions();

		$("CPBMainContent").innerHTML = '<div id="CPBRatingContent" name="CPBRatingContent"><p>Loading Ratings...</p></div>';
		
		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
		$('APPCPBMarkAllRead').disabled = true;
		$('HPECPBGetReadOnly').disabled = true;
		
		app.removeEditOption(document.getElementById('OtherOpsCustom'));
	
		hpe.goToTop();
	},

	RecommendedNewsProcess : function (request) {
		var mc = $("CPBRatingContent");
		var res;
		
		try { res = hpe.ProcessItemResponse(request); } catch(e) {};
		hpe.CurrentRecommendedNewsCount = itemInfo.length;
		
		var html = ""; 
		
		if (hpe.CurrentRecommendedNewsCount == 0){
			html += "No Items Found";
		}else{
			html += hpe.ShowItemList();
		}
		this.UpdatePageList();
		
		mc.innerHTML = html;
		savedElement = "";
		savedContent = "";
		hpe.MarkCurrentItem(false);
	},
// most Rated news

	mostRatedNews : function () {
		
		var element;
		var i;
		var query = '';
		var filter = new Object;
//		var toCookie = new Object;
		
		//get filter from cookie
		var fromCookie = new Object;
		var valAr = new Array();
		var keyAr = new Array();
		savedFilter = hpe.getCookie("outbrainFilter");

		if(typeof(savedFilter) == "string" && savedFilter.length > 0) {
			valAr = savedFilter.split(';');
			
			for(i in valAr) {
				if(typeof(valAr[i]) == "string" && valAr[i].length > 0) {
					keyAr = valAr[i].split('=');
					if(typeof(keyAr[0]) != "undefined" && typeof(keyAr[1]) != "undefined")
						fromCookie[ keyAr[0] ] = keyAr[1];
				}
			}
		}
				
		// sortBy
		element = $('sortBy');
		if(element)
			filter['sort'] = element.value;
		else {
			if(fromCookie['sort'])
				filter['sort'] = fromCookie['sort'];
		}
		
		// orderBy
		element = $('orderBy');
		if(element)
			filter['order'] = element.value;
		else {
			if(fromCookie['order'])
				filter['order'] = fromCookie['order'];
		}
		
		for(i in filter){
			if(typeof(filter[i]) != "function")
				query += "&"+i+"="+filter[i];
		}
		
		//save filter to cookie

		savedFilter = '';
		for(i in filter){
			if(typeof(filter[i]) != "function")
				savedFilter += ";"+i+"="+filter[i];
		}

		if(savedFilter.length > 0)
			hpe.setCookie("outbrainFilter", savedFilter);
		
		var randomValue = "&r="+Math.random()*10; // aviod cashing
		var url = siteHome + "ajaxAPI.php?api_call=Outbrain::mostRatedNews&api_format=JSON"+query+randomValue;
		var myAjax = new Ajax.Request(url, { method:'post', onSuccess:this.mostRatedNewsProcess.bind(this) });

		var filterMenu = '\
			<div class="box1" style="padding-bottom: 5px;">\
				<div class="hdrbox1">Highest Rated News Filter</div>\
				<div class="cntbox1">\
					<div style="float: left;">\
						Sort By: &nbsp;  \
						<select name="sortBy" id="sortBy">\
<!--							<option value="rating" >popularity</option>	-->\
							<option value="rating" '+ ((filter['sort'] == 'rating') ? 'selected' : '')  +' title="sort by the average document rating">rating</option>\
							<option value="date" '+ ((filter['sort'] == 'date') ? 'selected' : '')  +' title="sort by date of the last time the document was rated">date</option>\
<!--							<option value="num-ratings">num-ratings</option>	-->\
						</select>\
					</div>\
					<div style="float: left;  margin-left: 15px;">\
						Order By: &nbsp;\
						<select name="orderBy" id="orderBy">\
							<option value="desc" '+ ((filter['order'] == 'desc') ? 'selected' : '')  +'>descending</option>\
							<option value="asc" '+ ((filter['order'] == 'asc') ? 'selected' : '')  +'>ascending</option>\
						</select>\
					</div>\
					<div style="float: left;  margin-left: 15px;">\
						<input type="button" value="Filter" onClick="javascript: app.mostRatedNews()" />\
					</div>\
					<br clear="all" />\
				</div>\
			</div>\
			<div id="CPBRatingContent" name="CPBRatingContent"><p>Loading Ratings...</p></div>\
						';		
		
		$("CPBMainContent").innerHTML = filterMenu;

		if(this.pageId != 'home' && this.pageId != 'mostRatedNews')
			this.prevPageId = this.pageId;
		this.pageId = 'mostRatedNews';
		this.UpdatePageList();
		if(this.optOn) this.ToggleOptions();

		$('createAlertBtn').disabled = true;
		$('createFeedButton').disabled = true;
		$('APPCPBMarkAllRead').disabled = true;
		$('HPECPBGetReadOnly').disabled = true;
		
		app.removeEditOption(document.getElementById('OtherOpsCustom'));
	
		hpe.goToTop();
	},

	mostRatedNewsProcess : function (request) {
		var res;
		
		try { res = hpe.ProcessItemResponse(request); } catch(e) {};
		hpe.CurrentMostRatedNewsCount = itemInfo.length;
		
		if (hpe.CurrentMostRatedNewsCount == 0){
			$("CPBRatingContent").innerHTML = "No Items Found";
		}else{
			$("CPBRatingContent").innerHTML = hpe.ShowItemList();
		}
		
		
		this.UpdatePageList();
		
		savedElement = "";
		savedContent = "";
		hpe.MarkCurrentItem(false);
		
	},
		
	insertEditOption: function (theSel, newText, newValue)
	{

	  if (theSel.length == 0) 
	  {
	    var newOpt1 = new Option(newText, newValue);
	    theSel.options[0] = newOpt1;
	    theSel.selectedIndex = 0;
	  }
	  else 
	  if (theSel.selectedIndex != -1) 
	  {
	  	editLabel = theSel.options[3].value;
	  	if (editLabel == 'EditThisPage')
	  	{
	  		return true;
	  	}
	    var selText = new Array();
	    var selValues = new Array();
	    var selIsSel = new Array();
	    var newCount = -1;
	    var newSelected = -1;
	    var i;
	    for(i=0; i<theSel.length; i++)
	    {
	      newCount++;
	      if (newCount == position) 
	      {
	        selText[newCount] = newText;
	        selValues[newCount] = newValue;
	        selIsSel[newCount] = false;
	        newCount++;
	        newSelected = newCount;
	      }
	      selText[newCount] = theSel.options[i].text;
	      selValues[newCount] = theSel.options[i].value;
	      //selIsSel[newCount] = theSel.options[i].selected;
	    }
	    for(i=0; i<=newCount; i++)
	    {
	      var newOpt = new Option(selText[i], selValues[i]);
	      theSel.options[i] = newOpt;
	      //theSel.options[i].selected = selIsSel[i];
	    }
	  }
	},


	removeEditOption: function(theSel)
	{
		position = 3;
	  	editLabel = theSel.options[position].value;
	  	if (editLabel != 'EditThisPage')
	  	{
	  		return true;
	  	}
	  var selIndex = position;
	  if (selIndex != -1) 
	  {
	    for(i=theSel.length-1; i>=0; i--)
	    {
	      if(i == selIndex)
	      {
	        theSel.options[i] = null;
	      }
	    }
	  }
	}	
});

