var hpe = new Object();
hpe.Base = function(){};
hpe.Base.prototype = { };

hpe.activeRequestCount = 0;
hpe.fontSizes = new Array('x-small','small','medium');
hpe.nonactiveM = 'x-small';
hpe.nonactiveP = 'medium';
hpe.Startup = function() {
	this.agt = navigator.userAgent.toLowerCase();
	this.log(this.agt);
	this.issafari = (this.agt.indexOf("safari") != -1);
	this.isff = (this.agt.indexOf("firefox/1") != -1);
	this.isffwin = (this.isff && this.agt.indexOf("windows") != -1);
	this.pw = this.agt.indexOf("opera")!=-1;
	this.ca = this.agt.indexOf("msie")!=-1 && (document.all&&!this.pw);
	this.screen = new Object(); 
	this.screen.bottom = function() { if (document.body.scrollHeight) return document.body.scrollHeight }
	this.screen.height = function() { if (document.body.offsetHeight) return document.body.offsetHeight }
	this.screen.visHeight = function() { if (window.innerHeight) return window.innerHeight; 
		if(document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight; 
		if (document.body.clientHeight) return document.body.clientHeight; return 0 }
	this.screen.visWidth = function() { if (window.innerWidth) return window.innerWidth; 
		if(document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth; 
		if (document.body.clientWidth) return document.body.clientWidth; return 0 }
	this.screen.width = function() { if (document.body.offsetWidth) return document.body.offsetWidth }
	this.screen.scrollTop = function() { if(document.body.scrollTop) return document.body.scrollTop; if(window.pageYOffset) return window.pageYOffset; else return 0 };

	this.windowTimer = setInterval("hpe.UpdateDynLayout()", 20);
	window.onresize = this.windowResize;

	this.prevSourceInfo = "";
	this.prevTop = -1;
	this.headerHeight =  135;
	this.prevItem = -1;
	this.currentItem = -1;
	this.clipOpItem = 0;
	this.clipped = 0;
	this.postPrevEmails = "";
	this.savedContent="";
	this.savedElement="";
	this.CurrentClipCount=0;

	this.hideItemMetaData = false;
	this.showShortDesc = false;

	this.scroll = new fx.ScrollTop({duration: 800});

	this.itemOpsId = "";

	Event.observe(document, 'keyup', this.handleKeyboard.bind(this), false);

	lightWin.init();
	if(Delicious.BlogBadge)
		Delicious.BlogBadge.init();

	this.windowResize();

	for(var i=0; i<HPEAppList.length; i++)
		HPEAppList[i].InitApp();
}
hpe.log = function (e) { jslog.info(e) }
hpe.log_response = function (res) { this.log(res.response_code + ": " + res.response_message) }
hpe.error = function (e) { jslog.error(e) }
hpe.HQb = function(el) { var Ed=el.offsetTop;if(el.offsetParent!=null)Ed+=this.HQb(el.offsetParent);return Ed }

hpe.getPageSize = function() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight) pageHeight = windowHeight; else pageHeight = yScroll;
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth) pageWidth = windowWidth; else pageWidth = xScroll;
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
hpe.smoothScrollTop = function(lnk) {
	this.scroll.clearTimer();
	this.initialHref = lnk.href;
	this.initialHash = lnk.hash;
	lnk.href = "javascript:void(0)";
	setTimeout(function(){lnk.href = lnk.initialHref;}, 200);
	this.scroll.scroll(lnk.parentNode);
}
hpe.placeSourceInfo = function(curTop) {
	var obj = $("curSourceInfo");
	if (!obj) return;
	if(curTop > 20) {
		var curSource = "";
		var curItem = 0;
		for(var i=0; i<itemInfo.length; i++) {
			try {
				var elt = $(itemInfo[i].id);
				if(elt && elt.offsetTop > curTop + 200)
				{
					if(this.currentItem != curItem)
					{
						this.currentItem = curItem;
						this.MarkCurrentItem(true);
					}
					break;
				}
				curItem = i;
				curSource = itemInfo[i].sourcekey;
			}
			catch(e) { }
		}
		if(curSource != "") {
			if(this.prevSourceInfo != curSource) {
				this.prevSourceInfo = curSource;
				var html = "&gt;&gt;&nbsp;";
				html += "<a title='Show Items for This Source' onClick=\"app.ShowSource('" + curSource + "')\">";
				obj.innerHTML = html + srcInfo[curSource].title + "</a>&nbsp;<a href=\"#top\" target=\"_self\" style=\"margin-left:10px\" onclick=\"hpe.goToTop()\"><img src=\"/i/up2.gif\" width=\"27\" height=\"13\" alt=\"top\" align=\"bottom\" vspace=\"0\" /></a>";
				obj.style.position = 'absolute';
				obj.style.top = '100px';
				obj.style.right = '15px';
				Element.show(obj);
				if (document.all)//IE
				{
					if ($("central"))
					{
						$("central").style.marginTop = '0px';					
					}
				}
			}
			return;
		}
	} else if(this.currentItem != 0)
	{
		this.currentItem = 0;
		this.MarkCurrentItem(true);
	}
	this.prevSourceInfo = "";
	Element.hide(obj);
	if (document.all)//IE
	{
		if ($("central"))
		{
			$("central").style.marginTop = '0px';
		}
	}
}
hpe.UpdateDynLayout = function() {
	try {
		var curTop = $("central").scrollTop;

		if(curTop == this.prevTop) return;
		this.prevTop = curTop;
		this.placeSourceInfo(curTop);
	} catch(e) { }
}
hpe.windowResize = function () { 
	try { hpe.UpdateDynLayout() } catch(e) {};  
	var hh = $("header").offsetHeight;
	var fh = $("ftr").offsetHeight;
	var ch = hpe.screen.visHeight() - hh - fh - 1;
	var cw = hpe.screen.visWidth() - 1;
	var elt = $("central");
	if(ch > 100) {
		elt.show();
		elt.style.maxHeight = ch + "px";
		elt.style.height = ch + "px";
		elt.style.width = cw + "px";
	} else {
		elt.hide();
	}
}
hpe.goToTop = function() { 
	$("central").scrollTop = "0px"; //Element.scrollTo("top") 
	$("curSourceInfo").hide();
}
hpe.getSel = function() {
	if (window.getSelection) {
		return window.getSelection();
	} else if (document.getSelection) {
		return document.getSelection();
	} else if (document.selection) {
		return document.selection.createRange().text;
	} else return false;
}
hpe.setCookie = function (cookieName, cookieValue, nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null) nDays = 200;
	if(nDays==0) {
		document.cookie = cookieName + "=" + escape(cookieValue);
	} else {
		expire.setTime(today.getTime() + 3600000*24*nDays);
		document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString()+";path=/";
	}
}
hpe.getCookie = function (name) {
    var index = document.cookie.indexOf(name + "=");
    if (index == -1) return null;
    index = document.cookie.indexOf("=", index) + 1;
    var endstr = document.cookie.indexOf(";", index);
    if (endstr == -1) endstr = document.cookie.length;
    var res = unescape(document.cookie.substring(index, endstr));
	return res;
}
hpe.SaveEltContent = function(id) {
	if(this.savedElement != "") {
		var elt = $(this.savedElement);
		elt.innerHTML = this.savedContent;
	}
	var elt = $(id);
	this.savedContent = elt.innerHTML;
	this.savedElement = id;
}
hpe.RestoreEltContent = function(id) {
	if(this.savedContent != "" && $(id)) {
		$(id).innerHTML = this.savedContent;
		this.savedContent = "";
		this.savedElement = "";
	}
	else alert("No saved content");
}

hpe.Collapsable = Class.create();
hpe.Collapsable.prototype = {
	setOptions: function(options) {
		this.options = {
			delay: 200, opener:"[expand]", closer:"[collapse]", remember:1,
			onComplete: function() { this.toggler.innerHTML = (this.element.offsetHeight > 0 ? this.options.closer : this.options.opener) }.bind(this)
		}
		Object.extend(this.options, options || {});
	},
	initialize: function(toggler, element, options) {
		this.element = $(element);
		this.toggler = $(toggler);
		this.setOptions(options);
		if(!this.toggler) return;
		if(this.options.remember) {
			this.fx = new fx.RememberHeight(this.element, this.options);
			if(this.fx.fx.now == 0)
				this.options.onComplete();
			else this.element.style.height = "";
		} else this.fx = new fx.Height(this.element, this.options);
		this.toggler.onclick = function() { this.fx.toggle() }.bind(this);
	}
}

hpe.Highlight = Class.create();
hpe.Highlight.prototype = Object.extend(new fx.Base(), {
	setOptions: function(options) {
		this.options = {
			delay: 500,
			onComplete: function() { Element.setStyle(this.element, Object.extend(this.oldStyle, { backgroundColor: this.options.restorecolor })); }.bind(this)
		}
		Object.extend(this.options, options || {});
	},
	initialize: function(element) {
		this.element = $(element);
		this.setOptions(options);
		// Prevent executing on elements not in the layout flow
		if(Element.getStyle(this.element, 'display') =='none') { this.cancel(); return; }
		// Disable background image during the effect
		this.oldStyle = { backgroundImage: Element.getStyle(this.element, 'background-image') };
		Element.setStyle(this.element, {backgroundImage: 'none'});
		if(!this.options.endcolor)
		  this.options.endcolor = Element.getStyle(this.element, 'background-color').parseColor('#ffffff');
		if(!this.options.restorecolor)
		  this.options.restorecolor = Element.getStyle(this.element, 'background-color');
		// init color calculations
		this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
		this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
		this.toggle();
	},
	increase: function() {
		Element.setStyle(this.element,{backgroundColor: $R(0,2).inject('#',function(m,v,i){
			return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
	},
	toggle: function() {
		if (this.now > 0) this.custom(1, 0);
			else this.custom(0, 1);
	}
});

hpe.Dialog = {
	processParam : function(parameters) {
		var windowParam = parameters && parameters.windowParameters ? parameters.windowParameters : {};
		windowParam.resizable = windowParam.resizable || false;
		windowParam.dragable = windowParam.dragable || false;
		windowParam.width = windowParam.width || 600;
		windowParam.height = windowParam.height || 400;
		windowParam.zIndex = windowParam.zIndex || 400;
		if(windowParam.height < 100)
			windowParam.height = 100;
		if(windowParam.autoSize) {
			switch(windowParam.autoSize) {
				case "full":
					windowParam.height = hpe.screen.visHeight() - 40;
					windowParam.width = hpe.screen.visWidth() - 40;
					break;
				case "small":
					windowParam.height = 200;
					windowParam.width = 300;
					break;
			}
		}
		return windowParam;
	},
	buildWindow : function(id, windowParam, content, okCB, cancelCB) {
		this.win = new Window(id, windowParam);
		if(content) this.win.getContent().innerHTML = content;
		this.win.showCenter(true);

		this.win.cancelCallback = cancelCB;
		this.win.okCallback = okCB;

		this.eventResize = this.recenter.bindAsEventListener(this);
		Event.observe(window, "resize", this.eventResize);
		Event.observe(window, "scroll", this.eventResize);

		return this.win;		
	},
	link : function(title, link, parameters) {
		// remove old dialog
		if (this.win) this.win.destroy();

		windowParam = this.processParam(parameters);
		windowParam.title = windowParam.title || title;
		var ch = windowParam.height - 10;
		var cw = windowParam.width - 10;
		var useif = hpe.isffwin || (parameters && parameters.useiframe);
		if(useif)
			var content = "<table width='100%' height='100%'><tr><td align='center'>" +
				"<iframe id='modal_popup_linkcontent' width='" + cw + "' height='" + ch + "' src='" + link + "' style='border:0'></iframe>" +
				"</td></tr></table>";
		else var content = "<div id='modal_popup_linkcontent' style='margin:5px'></div>";

		res = this.buildWindow('modal_popup', windowParam, content);

		if(!useif) new Ajax.Updater("modal_popup_linkcontent", link, {method:'get'});
		return res;
	},
	open : function(title, message, parameters) {
		// remove old dialog
		if (this.win) this.win.destroy();

		var windowParam = this.processParam(parameters);
		windowParam.title = windowParam.title || title;

		var okLabel = parameters && parameters.okLabel ? parameters.okLabel : "Ok";
		var cancelLabel = parameters && parameters.cancelLabel ? parameters.cancelLabel : "Cancel";
		var ch = windowParam.height - 50;
		var content = "<div class='message' style='height:" + ch + "px'>" + message  + "</div> <div class='buttons'><input type='button' value='" + okLabel + "' onclick='hpe.Dialog.okCallback()'/> " +
			"<input type='button' value='" + cancelLabel + "' onclick='hpe.Dialog.cancelCallback()'/></div>";

		return this.buildWindow('modal_dialog', windowParam, content, parameters.ok, parameters.cancel);
	},
	alert : function(title, message, parameters) {
		// remove old dialog
		if (this.win) this.win.destroy();

		var windowParam = this.processParam(parameters);
		windowParam.title = windowParam.title || title;

		var okLabel = parameters && parameters.okLabel ? parameters.okLabel : "Ok";
		var ch = windowParam.height - 50;
		var content = "<div class='message' style='height:" + ch + "px'>" + message  + "</div>" +
			"<div class='buttons'><input type='button' value='" + okLabel + "' onclick='hpe.Dialog.okCallback()'/></div>";

		return this.buildWindow('modal_dialog', windowParam, content, parameters.ok, parameters.cancel);
	},
	info: function(message, parameters) {    
		parameters = parameters || {};
		parameters.windowParameters = parameters.windowParameters || { width:300, height:60 };
		parameters.windowParameters.zIndex = parameters.windowParameters.zIndex || 400;
		var className = parameters.windowParameters.className || "alert_lite";

		var content = "<div id='modal_dialog_message' class='" + className + "_message'>" + message  + "</div>";
		if (parameters.showProgress)
			content += "<div id='modal_dialog_progress' class='" + className + "_progress'>	</div>";

		parameters.windowParameters.className = className;

		return this.buildWindow('modal_dialog', parameters.windowParameters, content)
	},
	configureLanguage : function(fieldname) {
		this.langField = fieldname;
		var content = "<div style='padding:5px'><form name='HPEUserLangConfig'>\
				This is the list of available languages for the channels provided by this site.<br />\
				If you wish to restrict the display to certain languages, please select them here.\
				<div class=\"languagebox\">\
					<table border=\"0\" cellpadding=\"0\" align=\"center\">";
		var lang_regex = new RegExp("(" + userFilterLang + ")");
		for(var i=0; i<langList.length; i++) {
			if(i%5 == 0) content += "<tr>";
			content += "<td><label><input type='checkbox' name='restrictlang[]' value='" + langList[i].key + "' " +
					   (lang_regex.test(langList[i].key) ? " CHECKED" : "")
					   + " /> " + langList[i].name + "</label></td>";
			if(i%5 == 4) content += "</tr>";
		}
		content += "</table></div>";
		content += "<div style='text-align:right;padding-top:10px'>select: <a onClick='hpe.Dialog.configureLanguageSelectAll()'>all</a> | <a onClick='hpe.Dialog.configureLanguageSelectNone()'>none</a></div>";
		content += "</form></div>";
		lightWin.confirm("Select Your Prefered Languages", content, {okLabel:"Save", ok:this.configureLanguageOk.bind(this), cancelLabel:"Cancel", cancel:this.configureLanguageCancel.bind(this)});
	},
	configureLanguageOk : function() {
		// Save language preferences
		var url = siteHome + "ajaxAPI.php?api_call=User::savepreferences&api_format=JSON";
		var cbl = $A(document.forms['HPEUserLangConfig'].elements['restrictlang[]']);
		userFilterLang = cbl.select(function(v){return v.checked}).pluck('value').join('|');
		var post = "filterlang=" + userFilterLang;
		var myAjax = new Ajax.Request(url, { method:'post', postBody:post, onSuccess:this.configureLanguageDone.bind(this) });

		return true;
	},
	configureLanguageDone : function(originalRequest) {
		try { var res = eval('('+originalRequest.responseText+')'); } catch(e) { return hpe.error(e); }
		if (res.response_code >= 300) return false;

		app.selectValue($(this.langField), 'my');
	},
	configureLanguageCancel : function() {
		app.selectValue($(this.langField), 'my');
	},
	configureLanguageSelectAll : function() {
		var cbl = $A(document.forms['HPEUserLangConfig'].elements['restrictlang[]']);
		cbl.each(function(v){v.checked = true});
	},
	configureLanguageSelectNone : function() {
		var cbl = $A(document.forms['HPEUserLangConfig'].elements['restrictlang[]']);
		cbl.each(function(v){v.checked = false});
	},
	close : function () {
		// remove old dialog
		if (this.win) {
			this.win.hide();
			this.win.destroy();
			Event.stopObserving(window, "resize", this.eventResize);
			Event.stopObserving(window, "scroll", this.eventResize);      	
		}
		this.win = 0;
	},
	okCallback: function() {
		if (this.win.okCallback && !this.win.okCallback(this.win))
			return;
		this.close();
	},
	cancelCallback: function() {
		if (this.win.cancelCallback)
			this.win.cancelCallback(this.win);
		this.close();
	},
	recenter: function(event) {
		var arrayPageSize = WindowUtilities.getPageSize();
		// set height of Overlay to take up whole page and show
		var w = $('overlay_modal');
		if(w) w.style.height = (arrayPageSize[1] + 'px');
		this.win.center();
	}
}
hpe.GotoLogin = function() {
	alert("You need to login for this to work!");
	document.location.href="/";
}
hpe.GotoRegister = function() {
	var confirmReg;
	confirmReg = confirm('You need to login for this to work!'+"\n"+"Do you want to register ?");
	if(confirmReg)
		document.location.href="/user/new/";
	else
		document.location.href="/";
}

hpe.requirePremium = function(feature, premium) {
	if(confirm("\"" + feature + "\".\n" + "This feature requires a premium " + premium + " subscription.\n" +
				"Do you want to know more about this?"))
		document.location.href="/about.php?what=premium";
	return false;
}
hpe.UpdatePageLists = function() {
	var url = siteHome + "ajaxAPI.php?api_call=User::getpagelist&api_format=JSON";
	var myAjax = new Ajax.Request(url, { method:'get', onSuccess:this.UpdatePageListsProcess.bind(this) });
}
hpe.UpdatePageListsProcess = function(request) {
	try { var res = eval('('+request.responseText+')'); } catch(e) { return hpe.error(e); }
	if (res.response_code >= 300) return false;

	pageList = res.pageList;
	try {
		for(var i in HPEAppStack) if(typeof HPEAppStack[i] != 'function') {
			HPEAppStack[i].UpdatePageList();
		}
	} catch(e) { hpe.log(e) }
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

fx.Scroll = Class.create();
fx.Scroll.prototype = Object.extend(new fx.Base(), {
    initialize: function(options) {
        this.setOptions(options);
    },

    scrollTo: function(el){
        var desty = Position.cumulativeOffset($(el));
        var dest = desty[1];
        var client = window.innerHeight || document.documentElement.clientHeight;
        var full = document.documentElement.scrollHeight;
        var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        if (dest+client > full) this.custom(top, dest - client + (full-dest));
        else this.custom(top, dest);
    },

    increase: function(){
        window.scrollTo(0, this.now);
    }
});
fx.ScrollTop = Class.create();
fx.ScrollTop.prototype = Object.extend(new fx.Base(), {
    initialize: function(options) {
        this.setOptions(options);
    },

    scroll: function(){
        var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        this.custom(top, 0);
    },

    increase: function(){
        window.scrollTo(0, this.now);
    }
});

// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela
var Fat = {
	make_hex : function (r,g,b) 
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function ()
	{
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_item : function (id) {
		bg = "#ffffff";
		for(var i=0; i<itemInfo.length; i++)
			if(itemInfo[i].id == id) {
				bg = (i % 2 ? "#ffffff" : "#efefef");
				break;
			}
		this.fade_element(id, 30, 1000, "#FFFF33", bg);
	},
	fade_element : function (id, fps, duration, from, to) 
	{
		if (!fps) fps = 30;
		if (!duration) duration = 1000;
		if (!from || from=="#") from = "#FFFF33";
		if (!to) to = this.get_bgcolor(id);

		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;

		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);

		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);

		var r,g,b,h;
		while (frame < frames)
		{
			if (isNaN(rt))
			{
				rt = 255;
			}
			if (isNaN(rf))
			{
				rf = 255;
			}
			if (isNaN(gf))
			{
				gf = 255;
			}
			if (isNaN(gt))
			{
				gt = 255;
			}
			if (isNaN(bf))
			{
				bf = 255;
			}
			if (isNaN(bt))
			{
				bt = 255;
			}
			
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);
		
			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame; 
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
		if(c == 'whitehit')
		{
			c = 'white';
		}
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});
Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

function FmtInt(num, npos) {
	//pos = Math.log(num) / Math.LN10;
	var str = "" + num;
	for(var i=str.length; i<npos; i++)
		str = "0" + str;
	return str;
}
function isNull(a) {
	return typeof a == 'object' && !a;
}
function trim(str)
{
	str = str.replace(/^[\r\n\s\t]+/g, '');
	str = str.replace(/[\r\n\s\t]+$/g, '');
	return str;
}
function EscapeQuotes(str) {
	var res = new String(str);
	return res.replace(/"/g, '&quot;', str);
}

//"//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

hpe.handleKeyboard = function(event) {
	if(event.altKey || event.ctrlKey || event.metaKey)
		return false;
	var elt = Event.element(event);
	var c = event.keyCode;
	if(elt.nodeName == "INPUT" || elt.nodeName == "TEXTAREA") {
		if(c == Event.KEY_ESC)
			elt.blur();
		return false;
	}
	if(app.HandleKeyboard(event))
		return false;

	switch(c) {
		case 74: // j
			if(event.shiftKey || ++this.currentItem >= itemInfo.length)
				this.currentItem = itemInfo.length - 1;
			this.MarkCurrentItem();
			return false;
		case 75: // k
			if(event.shiftKey || --this.currentItem < 0)
				this.currentItem = 0;
			this.MarkCurrentItem();
			return false;
		case 70: // f
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length)
				app.ShowSource(itemInfo[this.currentItem].sourcekey);
			return false;
		case 77: // m
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length)
				this.PostOneItemMail(itemInfo[this.currentItem].id);
			return false;
		case 65: // a
				this.ToggleCheckAllItems();
			return false;
		case 66: // b
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length)
				this.PostOneItemBlog(itemInfo[this.currentItem].id);
			return false;
		case 84: // t
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length)
				this.PostToDelIcioUs(itemInfo[this.currentItem].id);
			return false;
		case 82: //r
			if(event.shiftKey)
			{
				for (var i=0; i<itemInfo.length; i++)
				{
					hpe.VisitItem(itemInfo[i].id);
				}
			}
			else
			{
				if (itemInfo.numSelected)
				{
					for(var i=0; i<itemInfo.length; i++)
					{
						if (itemInfo[i].isChecked)
						{
							hpe.VisitItem(itemInfo[i].id);
						}
					}
					//this.MarkRead();				
				}
				else
				{
					if(this.currentItem >= 0 && this.currentItem < itemInfo.length)
					{				
						hpe.VisitItem(itemInfo[this.currentItem].id);
					}
				}
			}
			return false;
		case 67: // c
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length) {
				if(itemInfo[this.currentItem].isClip)
					this.UnClipItem(itemInfo[this.currentItem].id);
				else
					this.ClipItem(itemInfo[this.currentItem].id);
			}
			return false;
		case Event.KEY_ESC: // ESC
			if(this.Dialog.win)
				this.Dialog.cancelCallback();
			else if(this.savedContent != "")
				this.RestoreEltContent(this.savedElement);
			else this.error("no content to restore");
			return false;
		case 83: // s
			Field.activate("AppSRSimpleSearchField");
			var s = this.getSel(); this.log(s);
			if(s) $("AppSRSimpleSearchField").value = s;
			return false;
		case 79: // o
			if(this.currentItem >= 0 && this.currentItem < itemInfo.length) {
				if(!window.open(itemInfo[this.currentItem].link))
					alert("A popup blocker seems to have prevented the opening of a new window");
				hpe.VisitItem(itemInfo[this.currentItem].id);
			}
			return false;
	}
	return true;
}
hpe.getItem = function(id) {
	for(var i=0; i<itemInfo.length; i++)
		if(itemInfo[i].id == id) 
			return itemInfo[i];
	if(app == appCP) for(var p=0; p<app.pageItems.length; p++) for(var i=0; i<app.pageItems[p].items.length; i++)
		if(app.pageItems[p].items[i].id == id) 
			return app.pageItems[p].items[i];
	hpe.log("Failed to find item for id '" + id + "'");
	return null;
}
hpe.MarkCurrentItem = function(stayhere) {	
	if(this.prevItem != -1) {
		var elt = $(itemInfo[this.prevItem].id);
		if(elt) elt.removeClassName("ItemZoneMarker");
	}
	if(itemInfo.length == 0) this.currentItem = -1;
	this.prevItem = this.currentItem;

	if(this.prevItem == -1) return;

	var elt = $(itemInfo[this.currentItem].id);
	if(!elt) return;
	elt.addClassName("ItemZoneMarker");

	if(!stayhere) {
		var ct = $("central");
		if(ct)
		{
			var st = ct.scrollTop;
			var sh = ct.offsetHeight;
			var et = elt.offsetTop - ct.offsetTop - 10;
			if(et > st + sh - 30 || et < st + 10)
				ct.scrollTop = et;
		}
	}
}
hpe.MarkItem = function(itemNum,stayhere)	
{
	this.currentItem = itemNum;
	this.MarkCurrentItem(stayhere);
}
hpe.VisitItem = function (id, button) {
//	hpe.log(id);
	var obj = $(id);
	var ci = -1;
	var ping = true;
	if(obj && obj.id == id) {
		if(obj.className.indexOf("read") != -1)
			ping = false;

		for(var i=0; i<itemInfo.length; i++)
			if(itemInfo[i].id == id) {
				try { urchinTracker('/outgoing/' + itemInfo[i].link); } catch(e) { }
				ci = i;
				if(this.currentItem == i)
					break;
				this.currentItem = i;
				this.MarkCurrentItem(true);
				break;
			}
	}
	if(ping) {
		var url = siteHome + "ajaxAPI.php?api_call=Item::visit&api_format=JSON&id=" + escape(id);
		var myAjax = new Ajax.Request( url, {method: 'get'} );
		obj.className = obj.className + " read";
	}

	return true;
}
hpe.ClipItem = function (id) {
	var url = siteHome + "ajaxAPI.php?api_call=Clipping::clip&api_format=JSON&id=" + escape(id);
	var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.ProcessClipItem.bind(this) });

	this.clipOpId = id;
	this.clipOpItem = $("Clip" + id);
	this.clipOpItem.src = '/i/boclip-saving.png';
	this.clipped = 1;
	return true;
}
hpe.UnClipItem = function (id) {
	var url = siteHome + "ajaxAPI.php?api_call=Clipping::unclip&api_format=JSON&id=" + escape(id);
	var myAjax = new Ajax.Request(url, { method:'get', onComplete:this.ProcessClipItem.bind(this) });

	var obj = $(id);
	//if(obj) { var hfx = new fx.Height(obj, { delay: 500 }); hfx.toggle(); }

	this.clipOpId = id;
	this.clipped = 0;
	this.clipOpItem = $("Clip" + id);
	return true;
}
hpe.ProcessClipItem = function (request) {
	var pcc = this.CurrentClipCount;

	{ res = eval('('+request.responseText+')'); }
	if(res.response_code == 200) {
		this.CurrentClipCount = res.curClipCount;
		var clipDsp = $("AppCurClipCount");
		if(clipDsp) clipDsp.innerHTML = this.CurrentClipCount;

		clipDsp = $("AppClippingsTab");
		if(clipDsp) clipDsp.title = this.CurrentClipCount + " Clippings";
	}
	
	if(this.clipped) this.clipOpItem.src = '/i/boclip-on.png'; 
	else 
	this.clipOpItem.src = '/i/boclip-off.png';
	
	var item = this.getItem(this.clipOpId); if(!item) return;
	
	item.isClip = this.clipped;
	
	hpe.RenderItem(item, item.id);

	if(this.clipOpId && this.clipped == 1) Fat.fade_element('Body' + this.clipOpId);
	
	
	
}
hpe.CheckItem = function(id, button) {
	var item = this.getItem(id); if(!item) return;
	item.isChecked = item.isChecked ? false : true;
	if (isNaN(itemInfo.numSelected)) itemInfo.numSelected = 0;	
	itemInfo.numSelected += item.isChecked ? +1 : -1;
	if(button) button.src = item.isChecked ? '/i/check-on.png' : '/i/check-off.png';
	else {
		if(!item.cb) item.cb = $("Check" + item.id);
		if(item.cb) item.cb.src = item.isChecked ? '/i/check-on.png' : '/i/check-off.png';
	}
}
hpe.UnCheckAllItems = function() {
	for(var i=0; i<itemInfo.length; i++) {
		itemInfo[i].isChecked = false;
		if(!itemInfo[i].cb) itemInfo[i].cb = $("Check" + itemInfo[i].id);
		itemInfo[i].cb.src = '/i/check-off.gif';
	}
	itemInfo.numSelected = 0;
}
hpe.CheckAllItems = function() {
	for(var i=0; i<itemInfo.length; i++) {
		itemInfo[i].isChecked = true;
		if(!itemInfo[i].cb) itemInfo[i].cb = $("Check" + itemInfo[i].id);
		itemInfo[i].cb.src = '/i/check-on.gif';
	}
	itemInfo.numSelected = itemInfo.length;
}
hpe.ToggleCheckAllItems = function() {
	if(itemInfo.length) {
		if (itemInfo[0].isChecked) {
			this.UnCheckAllItems();
		} else {
			this.CheckAllItems();
		}
	}
}
hpe.PostItemOps = function (itemkey, opsid, html, close) {
	var itemops = $("ItemOp" + itemkey);
	if(!itemops)
		return;
	if(itemops.title == opsid) {
		itemops.style.display = "none";
		itemops.innerHTML = "<div></div>";
		itemops.title = "";
		this.itemOpsId = "";
		return;
	}
	if(close)
		html = "\n<div style='float:right'><input type='button' onclick=\"hpe.PostItemOps('" + itemkey + "', '" + opsid + "')\" value='x' style='font-size:80%' /></div>" + html;
	if(itemops.style.display != "")
		itemops.style.display = "";
	itemops.innerHTML = "<div>" + html + "</div>";
	itemops.title = opsid;
	this.itemOpsId = itemkey;
}
hpe.ExpandAllItemsDesc = function() {
	for(var i=0;i<itemInfo.length; i++)
		if(itemInfo[i].shortdesc) this.ExpandItemDesc(itemInfo[i].id);
}
hpe.ExpandItemDesc = function(id) {
	var item = this.getItem(id);
	var desc = new String(item.desc);
	desc = desc.replace(/<[aA]/g, "<a onClick=\"return hpe.VisitItem('" + id + "', this)\" target=\"_blank\"");
	var elt = $("ItemDescZone" + id);
	if(elt) elt.innerHTML = desc;
}
hpe.ExpandOrCollapse = function(id) {
	var element = $("Content" + id);
	if(element)	{
		if(element.style.display == "none")
			element.style.display = "block";
		else
			element.style.display = "none";
	}
	element = $("ContentPreview" + id);
	if(element)	{
		if(element.style.display == "none")
			element.style.display = "block";
		else
			element.style.display = "none";
	}
}
hpe.ExpandOrCollapseAll = function(action)
{
	if (action == '')
		action = "expand";

	//remember
	this.setCookie("HPECollapsExpand", action);

	for(var i=0; i<itemInfo.length; i++) {
		var element = $('Content' + itemInfo[i].id);
		if(!element) continue;
		if(action == "expand")
			element.style.display = "block";
		else
			element.style.display = "none";
		element = $('ContentPreview' + itemInfo[i].id);
		if(!element) continue;
		if(action == "expand")
			element.style.display = "none";
		else
			element.style.display = "block";
	}

}

hpe.FormatTime = function(d) {
	var date = new Date(d * 1000)
	return FmtInt(date.getHours(), 2) + ":" + FmtInt(date.getMinutes(), 2); // + ":" + FmtInt(date.getSeconds(), 2);
}
hpe.FormatLongDate = function(d) {
	d = (d+'').substr(0,10);
	var date = new Date(d * 1000)
	return FmtInt(date.getMonth()+1, 2) + "/" + FmtInt(date.getDate(), 2) + "/" + FmtInt(date.getYear() % 100, 2) + " " +
					FmtInt(date.getHours(), 2) + ":" + FmtInt(date.getMinutes(), 2);		
}
hpe.ProcessItemResponse = function (request) {
	itemInfo = new Array();
	srcInfo = new Array();
	itemInfo.numSelected = 0;
	itemInfo.length = 0;
	numSources = 0;
	this.prevItem = -1;
	this.currentItem = 0;
	this.prevDateStr = "";

	try { res = eval('(' + request.responseText + ')') } catch(e) { hpe.log(e); return false }
	if(res.response_code != 200) return res; // could process standard error codes here
	res.numSources = 0;
	for(var i=0; i<res.sources.length; i++) { // HPESI
		if(res.sources[i].lastupdate) res.sources[i].lastupd = res.sources[i].lastupdate;
		if(res.sources[i].lastupd) {
			res.sources[i].lastupdStr = this.FormatLongDate(res.sources[i].lastupd);
		} else {
			res.sources[i].lastupd = 0;
			res.sources[i].lastupdStr = "";
		}
		if(res.sources[i].lastmod) {
			res.sources[i].lastmodStr = this.FormatLongDate(res.sources[i].lastmod);
		} else {
			res.sources[i].lastmod = 0;
			res.sources[i].lastmodStr = "";
		}
		if(!res.sources[i].link && res.sources[i].id)
			res.sources[i].link = "/sources/info/" + res.sources[i].id + "/";
		if(!res.sources[i].favicon || res.sources[i].favicon == '') res.sources[i].favicon = "/i/l.gif";
		srcInfo[res.sources[i].key] = res.sources[i];
		res.numSources++;
	}
	res.sources = srcInfo;
	numSources = res.numSources;

	for(var i=0; i<res.items.length; i++) { // HPEII
		if(res.items[i].desc && res.items[i].desc.length > 250) {
			res.items[i].desc = res.items[i].desc.replace(/<(style|script)/, '<noway'); 
			res.items[i].shortdesc = res.items[i].desc.stripTags();
			if(res.items[i].shortdesc.length > 250) res.items[i].shortdesc = res.items[i].shortdesc.substr(0,247) + "...";
		}
		if(!(res.items[i].author)) res.items[i].author = ''; else res.items[i].md = 1;
		if(res.items[i].sourcetitle) res.items[i].source = res.items[i].sourcetitle;
		if(!(res.items[i].source)) res.items[i].source = '';
		res.items[i].tags = new Array();
		if(!(res.items[i].subject)) res.items[i].subject = ''; else {
			res.items[i].md = 1;
			// Split subject
			var tops = res.items[i].subject.split(',');
			for (var j=0; j<tops.length; j++) {
				tops[j] = trim(tops[j].replace('&amp;', ''));
				if (tops[j] != '')
					res.items[i].tags[res.items[i].tags.length] = tops[j];
			}
		}
		if(!(res.items[i].popularity)) res.items[i].popularity = 0; else res.items[i].md = 1;
		if(res.items[i].sourceid && !res.items[i].sourcelink)
			res.items[i].sourcelink = siteHome + "sources/info/" + res.items[i].sourceid + "/";
		res.items[i].sourcekey = res.items[i].origin;
		res.items[i].date += (HPEgmtdelta - userGmtDiff);
		res.items[i].longdate = this.FormatLongDate(res.items[i].date);
		res.items[i].isChecked = false;
		if(HPEUserIsAdmin)
		{
			if(res.items[i].x) res.items[i].x = "Last found: " + this.FormatLongDate(res.items[i].x);
			if(res.items[i].y) res.items[i].y = "First found: " + this.FormatLongDate(res.items[i].y);
		}
	}

	pageType = 'custom_flat'; if(!isNull(res.pageType)) pageType = res.pageType; else res.pageType = pageType;
	pageFirst = 0; if(res.pageFirst) pageFirst = res.pageFirst; else res.pageFirst = pageFirst;
	pageItemsPerPage = 0; if(res.pageItemsPerPage) pageItemsPerPage = res.pageItemsPerPage; else res.pageItemsPerPage = pageItemsPerPage;
	pageItemCount = 0; if(res.pageItemCount) pageItemCount = res.pageItemCount; else res.pageItemCount = pageItemCount;
	pageFilterSource = -1; if(res.pageFilterSource) pageFilterSource = res.pageFilterSource; else res.pageFilterSource = pageFilterSource;
	pageFilterPop = 0; if(res.pageFilterPop) pageFilterPop = res.pageFilterPop; else res.pageFilterPop = pageFilterPop;
	pageFilterDate = 0; if(res.pageFilterDate) pageFilterDate = res.pageFilterDate; else res.pageFilterDate = pageFilterDate;
	pageSort = 'bydate'; if(res.pageSort) pageSort = res.pageSort; else res.pageSort = pageSort;

	itemInfo = res.items;
	itemInfo.length = res.items.length;
	srcInfo = res.sources;

	return res;
}

// Item rendering
hpe.ReRenderAllItems = function() {
	for(var i=0; i<itemInfo.length; i++)
		this.RenderItem(itemInfo[i], itemInfo[i].id)
}
hpe.cancelBubble = function(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

hpe.ShowItemTools = function(id, button) {
	Element.hide(button);
	var item = this.getItem(id);
	var vm = this.hideItemMetaData;
	var vs = this.showShortDesc;
	this.hideItemMetaData = false;
	this.showShortDesc = false;
	this.RenderItem(item, item.id);
	this.hideItemMetaData = vm;
	this.showShortDesc = vs;
}

hpe.RenderItem = function(item, c) {
	var html = "<div class='ItemBody' style='padding:0px; margin:0px; width: 99%' id='Body" + item.id + "'>";

	//collapse or expand value from cookie
	var HPECollapsExpand;
	HPECollapsExpand = this.getCookie("HPECollapsExpand");
	var displayContent = 'block'; var displayHeader = 'none';
	if(HPECollapsExpand == 'collapse')
		{ displayContent = 'none'; displayHeader = 'block' }

	html +="<div id=\"Head" + item.id + "\" class=\"newsHead\" onclick=\"hpe.ExpandOrCollapse('" + item.id + "'); hpe.MarkItem('"+item.number+"');\">";
	if(item.title != "") {
		html += "<div style='float: left;'><a class='ItemTitle' href=\""+ item.link +"\" target=\"_blank\" onClick=\"hpe.cancelBubble(event); return hpe.VisitItem('" + item.id + "', this);\">" + item.title + "</a></div>\n";
		//alert(item.desc);
		var headerDescription;
		if (item.shortdesc)
			headerDescription = item.shortdesc;
		if (!headerDescription && item.desc)
			var headerDescription = item.desc.replace(/(<([^>]+)>)/ig,""); 
		if (headerDescription)
			html += "<div class='messageDescription' id='ContentPreview" + item.id + "' + style='display:" + displayHeader + "'>"+ headerDescription +"</div>";
	}
	html +="</div>";

	html +="<div id='Content" + item.id + "' style='padding: 3px; margin: 0px; display: " + displayContent + "; ' onClick=\"hpe.MarkItem('"+item.number+"',true)\">";
	html += "<div class=\"ItemZonePub\">";
	html += "<div style='text-align: right; float:right'>";
	html += "<img class=\"ICB\" id=\"Check" + item.id + "\" onClick=\"app.CheckItem('" + item.id + "', this)\" src=\"/i/check-off.png\" style='float:none; cursor: pointer;' hspace=5 /> ";
	html += "<img onClick=\"hpe.ShowItemShareTools('" + item.id + "')\" width='48' src=\"/i/boshare.png\" style='float:none; cursor: pointer;' hspace=2 />";
//	if(isPremiumPortal) {
		if(item.isClip)
			html += ("<img onClick=\"return hpe.UnClipItem('" + item.id + "')\" width='38' id=\"Clip" + item.id + "\" src=\"/i/boclip-on.png\" alt=\"Clip\" style='float:none; cursor: pointer;' hspace=2 />");
		else
			html += ("<img onClick=\"return hpe.ClipItem('" + item.id + "')\" width='38' id=\"Clip" + item.id + "\" src=\"/i/boclip-off.png\" alt=\"Clip\" style='float:none; cursor: pointer;' hspace=2 />");
//	}
	if((hpe.hideItemMetaData && item.md) || (hpe.showShortDesc && item.shortdesc)) 
		html += "<img class=\"SIT\" id=\"Check" + item.id + "\" onClick=\"hpe.ShowItemTools('" + item.id + "', this)\" src=\"/i/boadd.png\" style='float:none; cursor: pointer;' hspace=5 /> ";
	html += "</div>"

	if(srcInfo[item.sourcekey]) {
		srcInfo[item.sourcekey].inList = 1;
		html += "<a href=\"" + srcInfo[item.sourcekey].link + "\" target=\"_blank\">";
		if(srcInfo[item.sourcekey].favicon != "")
			html += '<img border=0 src="' + srcInfo[item.sourcekey].favicon + '" vspace="0" class="favicon" />';
		else
			html += '<img border=0 src="/i/l.gif" vspace="0" class="favicon" />';
		
		html += "</a> Found in <a title='Show Source Details' href='"+siteHome +"sources/info/" + item.sourcekey + "/' >" + srcInfo[item.sourcekey].title + "</a> ";
		//html += "</a> Found in <a title='Show Source Details' onClick=\"app.ShowSourceDetails('" + item.sourcekey + "')\">" + srcInfo[item.sourcekey].title + "</a> ";
		//html += "</a> Published in <a title='Show Items for This Source' onClick=\"app.ShowSourceDetails('" + item.sourcekey + "')\">" + item.sourcetitle + "</a> ";
	}
	else html += "Published ";
	html += " on " + item.longdate + " ";
	if(!hpe.hideItemMetaData) {
		if(item.author != '') {
			if (srcInfo[item.sourcekey])
				html += "by: <a title='Find items by same author' onClick=\"appSR.LaunchAuthorSearch('" + escape(item.author.replace("'","\\'")) + "', '" + srcInfo[item.sourcekey].language + "')\">" + item.author + "</a>";
			else html += "by: <a onClick=\"appSR.LaunchAuthorSearch('" + escape(item.author.replace("'","\\'")) + "')\">" + item.author + "</a>";
		}
		if(item.popularity) {
			popStr = Math.round(item.popularity * 100);
			html += " &bull; Popularity: " + popStr + "% ";
		}
		if(item.source != '' && item.source != srcInfo[item.sourcekey].title)
			html += " &bull; Source: <a title='Visit original source' href=\"" + item.sourcelink + "\" target=\"_blank\">" + item.source + "</a>";
	}

	if (app == appCP)
		html += " &bull; <a href=\"javascript:app.unsubscribeFromSource('" + srcInfo[item.sourcekey].id + "', this)\">[unsubscribe]</a> ";
	else
		html += " &bull; <a href=\"javascript:app.subscribeToSourceShow('"+item.id+"')\" title=\"Add source to custom page\" class=\"OB\">[subscribe]</a> ";

	html += " <a href=\"" + item.link + "\" onClick=\"return hpe.VisitItem('" + item.id + "', this)\" TARGET=\"_blank\">[permalink]</a> ";
	if(HPEUserIsEditor && srcInfo[item.sourcekey]) {
		if(item.sourceid)
			html += (" <A href=\"" + HPEEditLink + "?pg=editsite&id=" + item.sourceid + "\" class=\"OB\" target=\"_blank\">[edit]</a>");
		var regex = new RegExp(/^i,([0-9]+)/);
		var m = regex.exec(item.id);
		if(m != null)
			html += (" <a title='" + item.id + "\n" + item.x + "\n" + item.y + "' href=\"http://newmetasiets1.insign.ch/cgi-bin/siets/sem.cgi?catid=10010500&Token=&lang=&i=newsisfree&s=0&cr=yes&cr=no&sc=retrieve&dc=retrieve&id=" + m[1] + "\" target=\"_blank\" class=\"OB\">[siets]</a> ");
	}

	html += "</div>";

//	html += "<br clear='all'/>";

	html += "<div style='display:none;font-size:100%' id='ItemShareTools" + item.id + "' class=\"ItemOps\"></div>";
	html += "<div style='display:none;font-size:100%' id='ItemShareOps" + item.id + "' class=\"ItemOps\"></div>";

	if(item.desc != "") 
	{
		if(hpe.showShortDesc && item.shortdesc) 
		{
			html += "<table><tr><td class=\"Desc\" id=\"ItemDescZone" + item.id + "\">";
			if (!NIFNOADS)
				html += '<div class=KonaBody>';
			html += item.shortdesc;
			if (!NIFNOADS)
				html += '</div>';
			html += "&nbsp;(more)</td></tr></table>";
		} 
		else 
		{
			var desc = new String(item.desc);
			desc = desc.replace(/<[aA]/g, "<a onClick=\"return hpe.VisitItem('" + item.id + "', this)\" target=\"_blank\"");
			html += "<table><tr><td class=\"Desc\" id=\"ItemDescZone" + item.id + "\">";
			if (!NIFNOADS)
				html += '<div class=KonaBody>';
			html += desc;
			if (!NIFNOADS)
				html += '</div>';
			html += "</td></tr></table>";
		}
	}
	else html += "<div id=\"ItemDescZone" + item.id + "\"></div>";

	html += '<div>';
	
	if(!hpe.hideItemMetaData) {
		var mhtml = this.WriteEnclosures(item);
		if(item.tags.length > 0) {
				mhtml += " <span class=\"Subject\">Topic(s): ";
			for (var j=0; j<item.tags.length; j++) {
					if (srcInfo[item.sourcekey])
					mhtml += '<a onClick="appSR.LaunchTopicSearch(\'' + escape(item.tags[j].replace("'","\\'")) + '\', \'' + srcInfo[item.sourcekey].language + '\')">' + item.tags[j] + '</a>';
					else mhtml += '<a onClick="appSR.LaunchTopicSearch(\'' + escape(item.tags[j].replace("'","\\'")) + '\')">' + item.tags[j] + '</a>';//that's for debugging
					if (j<(item.tags.length-1))
						mhtml += ", ";
				}
				mhtml += "</span>";
			}
		if(mhtml != "")
			html += "<div class='ItemZoneMeta'>" + mhtml + "</div>";
	}

	// outbrain
	if(outbrain['IsVisible']) {
		var outbrainLink = encodeURIComponent(item.link);
		var outbrainUser = encodeURIComponent(userID);
		//html += renderStars(item.id,rating,count,url,source);
		html += '<div id="ratingConteiner'+item.id+'" class="ratingBlock">';
		html += renderStars(item);
		html += '</div>';
/*			
		html += '<div id="clear"></div>';
// related items 		
//		html += '<div class="outbrainRelatedItems"><span class="outbrainRelatedItemsHeader" title="click here to find out" onClick="hpe.getOutbrainRelatedItems(\''+outbrainLink+'\',\'OutbrainRelatedItems_'+item.id+'\');">Our readers also recommend</span><div class="outbrainRelatedItemsBody" id="OutbrainRelatedItems_'+item.id+'" style="display: none;"></div></div>';

		html += '<div class="outbrainIframe" id="IframeConteiner_'+item.id+'" name="IframeConteiner_'+item.id+'">';
		html += '		<iframe id="Iframe_'+item.id+'" name="Iframe_'+item.id+'" src="'+siteHome+'widget/outbrain_frame.php?link='+outbrainLink+'&user='+outbrainUser+'&newsid='+ item.id +'&source='+ item.sourcekey +'" framespacing="0" frameborder="no" scrolling="no" onload="//frameLoader(\'IframeConteiner_'+item.id+'\',\'Iframe_'+item.id+'\')"></iframe>';
//			html + hpe.outbrainImageMap(outbrainUser, outbrainLink);
		html += '</div>';
*/		
		
	}
	
	html += '<div id="clear"></div></div>';
	
	// Show clip annotation
	if (item.isClip) {
		if(!item.annotation) item.annotation = "";
		html += "<div id=\"ItemAnnot" + item.id + "\" class=\"ItemOps\"" + (( item.annotation=="")?' style="display:none"':'') + ">" + item.annotation + "</div>";
	}

	html += "<div id=\"ItemOp" + item.id + "\" class=\"ItemOps\" style=\"display:none\"></div>";
    html += "</div></div>";

	if(c) {
		var elt = $(c);
		if(elt) elt.innerHTML = html;
	}
	return html;
}

hpe.outbrainImageMap = function(user, url)
{
	
	var outbrainUrl = (outbrain['testMode']) ? "http://test.odb.outbrain.com/utils/odb" : "http://odb.outbrain.com/utils/odb";
	var voteSrc = outbrainUrl+"/vote.do?partner="+outbrain['partnerKey']+"&url="+url+"&username="+user;
	var imgSrc = outbrainUrl+'?key='+outbrain['partnerKey']+'&method=get_score&format=image&img_set=2&user='+user+'&url='+url;
	
	var html = '';
	html += '<img src="'+imgSrc+'" width="300" height="28" border="0" usemap="#outbrainMap" />';
	html += '<map name="outbrainMap" id="outbrainMap">';
	html += '	<area shape="rect" coords="0,0,1,1"    href= "'+voteSrc+'&numStars=0" />';
	html += '	<area shape="rect" coords="2,0,20,28"  href= "'+voteSrc+'&numStars=1" />';
	html += '	<area shape="rect" coords="20,0,38,28" href= "'+voteSrc+'&numStars=2" />';
	html += '	<area shape="rect" coords="38,0,55,28" href= "'+voteSrc+'&numStars=3" />';
	html += '	<area shape="rect" coords="55,0,72,28" href= "'+voteSrc+'&numStars=4" />';
	html += '	<area shape="rect" coords="72,0,91,28" href= "'+voteSrc+'&numStars=5" />';
	html += '</map>';
	
	return html;
}

hpe.getOutbrainRelatedItems = function(voteUrl, conteiner)
{
	var url = siteHome + "ajaxAPI.php?api_call=Outbrain::relatedItems&api_format=JSON&url="+voteUrl;
	
	if($(conteiner))
	{
		var $cntObj = $(conteiner);
		// download on expand		
		if($cntObj.style.display == "none")
		{
			$cntObj.style.display = "block";
			
			var myAjax = new Ajax.Request( url, {method: 'get', onSuccess: this.outbrainItemsProcess.bind(this,conteiner)} );
			$(conteiner).innerHTML = 'Loading ...';
		}
		else
		{
			$cntObj.style.display = "none";
		}
	}
}

hpe.outbrainItemsProcess = function(conteiner, transport)
{
	var cntObj = $(conteiner);

	try 
	{ 
		var res = eval('('+transport.responseText+')'); 
	} 
	catch(e) 
	{ 
		//alert(e);
		cntObj.innerHTML = "Failed to process response";
		//cntObj.innerHTML = transport.responseText;
		return hpe.log(e); 
	}

	var html = '';
	var item;
	if(res.response_code==200) 
	{
		if(res.items)
		{
			for(i in res.items)
			{
				item = 	res.items[i];
			
//alert(item.url);
				if(item.link && item.desc && item.title && item.author && item.rating)
				{
//					try
//					{
						html += '<div><a href="' + item.link + '" title="'+item.desc+'">' + item.title + '</a>&nbsp;(' + item.author + ')&nbsp;<b>rated ' + item.rating.content + '</b>&nbsp;by&nbsp;' + item.rating.count + '&nbsp;readers like you</div>';
//					}
//					catch(e)
//					{
//						alert(e);
//					}
				}
			}
		}
		else
		{
			html = 'There is no related news'
		}
	}
	else
	{
		html = 'There is no related news'
	}

	cntObj.innerHTML = html;
	//alert(html);
}




hpe.DisplayDateString = function(str) {
	if(isNull(this.prevDateStr) || this.prevDateStr != str) {
		this.prevDateStr = str;
		return "<div class=\"DateAgo\">" + str + "</div>\n";
	}
	return ""
}
hpe.ShowItemList = function() {
	var n = itemInfo.length;
	var html = "<div class=\"ItemList\">\n";
	var keywordString = '';
	this.prevDateStr = '';
	
	for(var i=0; i<n; i++) {
		// Show date section (.DateAgo)
			switch(pageSort)
			{
				case  "bydate" :
					{
						var nowDate = new Date();
						var theDate = new Date(itemInfo[i].date * 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 += this.DisplayDateString(days + " days ago");
						} else if(theDate.getTime() < lastMidnight) {
							html += this.DisplayDateString("Yesterday");
						} else {
							var hours = Math.floor(diffDate / (1000 * 60 * 60));
							if(hours == 1)
								html += this.DisplayDateString("1 hour ago");
							else if(hours > 1)
								html += this.DisplayDateString(hours + " hours ago");
						}
						break;
					}
				case  "OBdate" :
					{
						try
						{
							timestamp = itemInfo[i]['rating']['time'];
							var nowDate = new Date();
							var theDate = new Date(timestamp * 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 += this.DisplayDateString(days + " days ago");
							} else if(theDate.getTime() < lastMidnight) {
								html += this.DisplayDateString("Yesterday");
							} else {
								var hours = Math.floor(diffDate / (1000 * 60 * 60));
								if(hours == 1)
									html += this.DisplayDateString("1 hour ago");
								else if(hours > 1)
									html += this.DisplayDateString(hours + " hours ago");
							}
						}
						catch(error){};
						break;
					}
				
				case  "OBrating" :
					{
						try
						{
							var stars = itemInfo[i]['rating']['stars'];
							if(stars > 1)
							{
								html += this.DisplayDateString(stars+" stars");
							}
							else
							{
								html += this.DisplayDateString(stars+" star");
							}
						}
						catch(error){};
						break;
					}			
					
			}

		// Show news item (.ItemZone)
		html += "<div class=\"ItemZone " + itemInfo[i].classname + (itemInfo[i].read ? " read" : "") + "\" id=\"" + itemInfo[i].id + "\" >"; //"" + (i % 2 ? "" : "style=\"background-color:#efefef\"") + ">";
		itemInfo[i].number = i;
		html += hpe.RenderItem(itemInfo[i]);
		html += "</div>";

		keywordString += (' '+itemInfo[i].title);
		
		if(!NIFNOADS && i%10 == 0) {
			keywordString = encodeURIComponent(keywordString);
			html += "<div align='center'>\
			<div class='googleAdvertisement'>\
			<iframe id='a1dc8db5' name='a1dc8db5' style='margin-top:5px' src='http://www.newsisfree.com/ads/adframe.php?n=a1dc8db5&what=zone:13&keywords="+keywordString+"' framespacing='0' frameborder='no' scrolling='no' width='468' height='60'><a href='http://www.newsisfree.com/ads/adclick.php?n=a1dc8db5' target='_blank'><img src='http://www.newsisfree.com/ads/adview.php?what=zone:13&n=a1dc8db5' border='0' alt=''></a>";
			//html += ('<br><br>'+keywordString);			
			html += "</iframe></div></div>";
			keywordString = '';
		}
	}//for
	html += "</div>";
	return html
}
hpe.ToggleMP3Player = function(key, i) {
	var item = this.getItem(key);
	var ohtml = "MP3 Player:&nbsp;<object type='application/x-shockwave-flash' data='/dewplayer.swf?son=" + escape(item.enclosure[i].url) + "' width='200' height='20' id='dewplayer'>" +
				"<param name='movie' value='/dewplayer.swf?son=" + escape(item.enclosure[i].url) + "' /></object>";
	if(item.enclosure[i].length)
		ohtml += "&nbsp;" + item.enclosure[i].length + " bytes";
	ohtml += "&nbsp;[<a href=\"" + item.enclosure[i].url + "\" target='_blank'>direct link</a>]";
	hpe.PostItemOps(key, "enc" + i, ohtml, 1);
	return false;
}
hpe.ToggleQTPlayer = function(key, i) {
	var item = this.getItem(key);
	var ohtml = "<p align=\"center\"><OBJECT CLASSID=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" WIDTH=\"320\" HEIGHT=\"256\" CODEBASE=\"http://www.apple.com/qtactivex/qtplugin.cab\">" +
				"<PARAM name=\"SRC\" VALUE=\"" + item.enclosure[i].url + "\">" +
				"<PARAM name=\"AUTOPLAY\" VALUE=\"true\"><PARAM name=\"CONTROLLER\" VALUE=\"true\">" +
				"<EMBED SRC=\"" + item.enclosure[i].url + "\" AUTOPLAY=\"true\" CONTROLLER=\"true\" WIDTH=\"320\" HEIGHT=\"256\"></EMBED>" +
				"</OBJECT></p>" +
				"QT Movie Player:&nbsp;";
	if(item.enclosure[i].length)
		ohtml += item.enclosure[i].length + " bytes&nbsp;";
	ohtml += "&nbsp;[<a href=\"" + item.enclosure[i].url + "\" target='_blank'>direct link</a>]";
	hpe.PostItemOps(key, "enc" + i, ohtml, 1);
	return false;
}
hpe.WriteEnclosures = function(item) {
	if(!item.enclosure) return "";
	var ne = item.enclosure.length;
	if(ne) {
		var ehtml = '<span class="Enclosure">Enclosure(s): ';
		for(var i=0; i<ne; i++) {
			if(item.enclosure[i].link == "")
				continue;

			var icon = "disk";
			var file = new String(item.enclosure[i].url);
			var ops = " href=\"" + item.enclosure[i].url + "\"";

			var mp3regex = /.mp3$/;
			if(mp3regex.test(item.enclosure[i].url))
				ops = " onclick=\"hpe.ToggleMP3Player('" + item.id + "', " + i + ")\"";
			var movregex = /.(mov|m4b)$/;
			if(movregex.test(item.enclosure[i].url))
				ops = " onclick=\"hpe.ToggleQTPlayer('" + item.id + "', " + i + ")\"";

			var type = new String(item.enclosure[i].type);
			if(/audio/.test(type)) {
				icon = "sound";
			} else if(type.substr(0,5) == "image" || type.substr(0,7) == "jpg/gif") {
				icon = "picture";
				ops += " onclick=\"lightWin.image(this); return false\"";
			}
			else if(type.substr(0,5) == "video")
				icon = "movie";
			ehtml += "<a target=\"new\" title=\"" + type;
			if(item.enclosure[i].length) ehtml += ", " + item.enclosure[i].length + " bytes";
			ehtml += "\"; " + ops + "><img src=\"/i/" + icon + ".gif\" width='11' height='11' align='absmiddle'></a>&nbsp;";
		}
		ehtml += ('</span>');
		return ehtml;
	}
	return ""
}


hpe.ShowItemShareTools = function(id) {
	var elt = $('ItemShareTools' + id);
	if(isNull(elt)) { hpe.log("no elt for item '" + id + "'"); return; }
	if(elt.style.display != "none") { elt.hide(); return; }
	var item = this.getItem(id);
	var topHtml = "";
//	if(Delicious.BlogBadge)
//		topHtml += "<div id='DeliciousDiv' style='padding-left:20px'></div>"
//	topHtml += "<iframe src='http://digg.com/api/diggthis.php?u="+escape(item.link)+"' height='80' width='52' frameborder='0' scrolling='no' align='right'></iframe>";
	topHtml += "<div class=\"Post\" style='clear:both;padding-top:5px'>";
	topHtml += "<div 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 + " " + 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 += "<li style='margin-left:10px'><a id='akst_technorati' href='http://www.technorati.com/faves?add=" + escape(item.link) + "' target='_blank' title='Technorati'></a></li>";
	topHtml += "<li><a id='akst_newsvine' href='http://www.newsvine.com/_wine/save?u=" + escape(item.link) + "' target='_blank' title='Newsvine'></a></li>";
	topHtml += "<li><a id='akst_furl' href='http://furl.net/storeIt.jsp?u=" + escape(item.link) + "' target='_blank' title='Furl'></a></li>";
	topHtml += "<li><a id='akst_netscape' href='http://www.netscape.com/submit/?U=" + escape(item.link) + "' target='_blank' title='Netscape'></a></li>";
	topHtml += "<li><a id='akst_yahoo_myweb' href='http://myweb2.search.yahoo.com/myresults/bookmarklet?u=" + escape(item.link) + "' target='_blank' title='Yahoo! MyWeb'></a></li>";
	topHtml += "<li><a id='akst_stumble' href='http://www.stumbleupon.com/submit?url=" + escape(item.link) + "' target='_blank' title='StumbleUpon'></a></li>";
	topHtml += "<li><a id='akst_google_bmarks' href='http://www.google.com/bookmarks/mark?op=edit&bkmk=" + escape(item.link) + "' target='_blank' title='Google Bookmarks'></a></li>";
	topHtml += "<li><a id='akst_reddit' href='http://reddit.com/submit?url=" + escape(item.link) + "' target='_blank' title='Reddit'></a></li>";
	topHtml += "<li><a id='akst_tailrank' href='http://tailrank.com/share/?link_href=" + escape(item.link) + "' target='_blank' title='Tailrank'></a></li>";
	topHtml += "<li><a id='akst_magnolia' href='http://ma.gnolia.com/bookmarklet/add?url=" + escape(item.link) + "' target='_blank' title='ma.gnolias'></a></li>";
	topHtml += "<li><a id='akst_blinklist' href='http://blinklist.com/index.php?Action=Blink/addblink.php&Url=" + escape(item.link) + "' target='_blank' title='Blinklist'></a></li>";
	topHtml += "</ul></div>";

	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> ");
	if(item.comments)
		topHtml += ("<a href=\"" + item.comments + "\" title=\"Post a Comment\" target=\"_blank\"><img width='62' src=\"/i/bocomment.png\" /></a> ");
	if(isPremiumPortal) {
		if (item.isClip && this.AnnotateClipShow)
			topHtml += "<a onClick=\"hpe.AnnotateClipShow('" + item.id + "')\" title=\"Add or edit annotation\"><img width='58' src=\"/i/boannotate.png\" /></a> ";
		if(srcInfo[item.sourcekey] && srcInfo[item.sourcekey].id)
			topHtml += ("<a onClick=\"hpe.FindSimilarItems('" + item.id + "')\"><img width='46' src=\"/i/bosimilar.png\" /></a> ");
		topHtml += "<a onClick=\"hpe.FindYQItems('" + item.id + "')\"><img width='88' src=\"/i/boyq.png\" /></a> ";
//		topHtml += "<a onClick=\"hpe.ShowStikkit('" + item.id + "')\"><img width='48' src=\"/i/stikkit.png\" /></a> ";
	}
	topHtml += "</div>";
	elt.innerHTML = topHtml;
	elt.show();
}
hpe.GetItemPostBody = function(id) {
	var item = this.getItem(id);
	var bodyhtml = "<p>In <a href=\"" + item.sourceLink + "\">" + (item.sourcetitle ? item.sourcetitle : srcInfo[item.sourcekey].title) + "</a>: ";
	bodyhtml += "<a href=\"" + item.link + "\">" + item.title + "</a>";
	if(item.desc != "") bodyhtml += ("\n<blockquote>" + item.desc + "</blockquote>");
	bodyhtml += "</p>\n\n";
	return bodyhtml;
}
hpe.PostOneItemMail = function(id) {
	/*
	var ids = new Array();
	for(var i=0; i<itemInfo.length; i++) {
		if(itemInfo[i].isChecked)
			ids.push(itemInfo[i].id);
	}
	if(ids.length){ this.PostItemsMail(ids, 0); return;}
	*/
	var html  = "<form id=\"PostItemsForm\" name=\"PostItemsForm\" style=\"padding:10px 5px 10px 5px\" onSubmit=\"return hpe.PostItemsMailNow()\"><table>";
	html += "<tr><th align=\"right\" nowrap>Your Email:</th><td><input type=\"text\" size=\"30\" name=\"MailSender\"";
	if(!userIsGuest)
		html += " value=\"" + userName + "<" + userEmail + ">\"";
	html += " READONLY /></td></tr>\n";
	html += "<tr><th align=\"right\">To:</th><td><input type=\"text\" size=\"30\" id=\"MailToField\" name=\"MailTo\" value=\"" + this.postPrevEmails + "\" onKeyUp='getRecent(this);'/>" +
			"<span id='MailToField_error' class='errormsg hidden'>Need to enter a valid email address!</span></td></tr>\n";
	html +='<tr><td>&nbsp;</td><td><div id="recent" style=""></div></td></tr>';

	var item = this.getItem(id);
	html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Subject:</th><td><input type=\"text\" size=\"30\" name=\"MailSubject\" value=\"";
	html += EscapeQuotes(item.title);
	html += "\"></td></tr>\n";
	html += "<tr valign=\"top\"><th align=\"right\">Body:</th>";
	html += "<td id=\"DisplayBody" + id + "\">";
	html += "<textarea cols=\"60\" rows=\"9\" name=\"MailBody\" id=\"MailBody\" class='editzone' style='display:none'>" + hpe.GetItemPostBody(id) + "</textarea>";
	html += "<div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + hpe.GetItemPostBody(id) + "</div>";
	html += "</td></tr>\n";
	html += "</table></form>";

	lightWin.confirm("Post Item to Mail", html, {okLabel:"Send", ok:hpe.PostItemsMailNow});
	Field.focus("MailToField");
	//tinyMCE.execCommand("mceAddControl", false, "MailBody");
}
hpe.PostItemsMail = function (ids, splitItems) {
	if(ids.length == 0) {
		alert("No items selected!");
		return;
	}
	
	var html  = "<form id=\"PostItemsForm\" name=\"PostItemsForm\" onSubmit=\"return hpe.PostItemsMailNow()\"><table>";
	html += "<tr><th align=\"right\" nowrap>Your Email:</th><td>";
	if(ids.length > 1) {
		html += "<span style='float:right;padding:3px'>";
		if(splitItems)
			html += "<input type=\"checkbox\" onClick=\"hpe.PostItems('ma', 0)\" />";
		else
			html += "<input type=\"checkbox\" onClick=\"hpe.PostItems('ma', 1)\" CHECKED />";
		html += " Merge Items in Single Mail</span>\n";
	}

	html += "<input type=\"text\" size=\"30\" name=\"MailSender\"";
	if(!userIsGuest)
		html += " value=\"" + userName + "<" + userEmail + ">\"";
	html += " READONLY /></td></tr>\n";
	html += "<tr><th align=\"right\">To:</th><td><input type=\"text\" size=\"30\" id=\"MailToField\" name=\"MailTo\" value=\"" + this.postPrevEmails + "\" onKeyUp='getRecent(this);'/>" +
			"<div id='MailToField_error' class='errormsg hidden'>Need to enter a valid email address!</div></td></tr>\n";
	html +='<tr><td>&nbsp;</td><td><div id="recent" style=""></div></td></tr>';
	var deschtml = "";
	for(var j in ids) if(typeof ids[j] != 'function') {
		var item = this.getItem(ids[j]);
		if(splitItems) {
			html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\" nowrap>&bull; Subject:</th>" +
					"<td><input type=\"text\" size=\"30\" name=\"MailSubject\" value=\"" +
					EscapeQuotes(item.title) + "\"></td></tr>\n";
			html += "<tr valign=\"top\"><th align=\"right\">Body:</th>";
			html += "<td id=\"DisplayBody" + ids[j] + "\">";
			html += "<textarea style='display:none' cols=\"100\" rows=\"10\" name=\"MailBody\" id=\"MailBody" + ids[j] + "\">" + hpe.GetItemPostBody(id) + "</textarea>";
			html += "<div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + hpe.GetItemPostBody(id) + "</div>";
			html += "</td></tr>\n";
		} else {
			if(deschtml == "") {
				html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Subject:</th><td><input type=\"text\" size=\"30\" name=\"MailSubject\" value=\"";
				if(ids.length == 1) {
					html += EscapeQuotes(item.title);
				} else {
					html += ids.length + " news items for you";
				}
				html += "\"></td></tr>\n";
			}
			deschtml += hpe.GetItemPostBody(ids[j]);
		}
	}
	if(!splitItems) {
		html += "<tr valign=\"top\"><th align=\"right\">Body:</th>";
		html += "<td id=\"DisplayBodyBundled\"><textarea style='display:none' cols=\"100\" rows=\"20\" name=\"MailBody\" id=\"MailBody\">" + deschtml + "</textarea><div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + deschtml + "</div></td></tr>";
	}

	html += "</table></form>\n";

	lightWin.confirm("Post Item to Mail", html, {okLabel:"Send", ok:hpe.PostItemsMailNow});
	Field.focus("MailToField");
	/*
	if(splitItems) {
		for(var j in ids) if(typeof ids[j] != 'function')
			tinyMCE.execCommand("mceAddControl", false, "MailBody" + ids[j])
	} else tinyMCE.execCommand("mceAddControl", false, "MailBody");
	*/
};
hpe.PostItemsMailNow = function (button) {
	var form = $("PostItemsForm");

	var post = new String;
	var to = "";
	if(form) {
		var ne = form.elements.length;
		for(ie=0; ie<ne; ie++) {
			if(form.elements[ie].name == "MailSender")
				post += form.elements[ie].name + "=" + escape(form.elements[ie].value) + "&";
			else if(form.elements[ie].name == "MailSubject" || form.elements[ie].name == "MailBody")
				post += form.elements[ie].name + "[]=" + escape(form.elements[ie].value) + "&";
			else if(form.elements[ie].name == "EditedBody" && form.elements[ie].value != "")
				post += "MailBody[]=" + escape(form.elements[ie].value) + "&";
			else if(form.elements[ie].name == "MailTo") {
				var regex = /.+@.+\..+/;
				if(regex.test(form.elements[ie].value)) {
					to = form.elements[ie].value;
					this.postPrevEmails = to;
					post += form.elements[ie].name + "=" + escape(form.elements[ie].value) + "&";
				}
			}
		}

		if(to == "") {
			// alert("Need to enter an email address!");
			Element.removeClassName('MailToField_error', 'hidden');
			Field.focus("MailToField");
			return false;
		}
		post += "-----------------------------7d325a200432--\n";
		var url = siteHome + "ajaxAPI.php?api_call=Item::postmail&api_format=JSON";
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: hpe.PostItemsProcess} );
		lightWin.wait("Posting Items to Mail");
		return false;
	}
	else hpe.log("Failed to find mail form");
	return false;
}
hpe.PostItemsProcess = function (request) {
	lightWin.hide();
	hpe.UnCheckAllItems();

	try { var res = eval('('+request.responseText+')'); } 
	catch(e) { alert("Failed to process response"); return hpe.log(e); }

	if(res.response_code==200) {
		if(res.post_result) {
			lightWin.alert("Posted Items", res.post_result);
		} else alert("Items were posted successfully"); 
		return
	}
	if(res.response_code==510) {		
		alert("Item not sent: you have not enough credits on your sms alerts balance."); 
		return
	}
	if(res.response_code>=500) {
		if(res.post_result) {
			lightWin.alert("Posted Items", res.post_result);
		} else alert("Failed to post items"); 
		return
	}
	if(res.response_code>=300) { hpe.GotoLogin(); return }
}
hpe.PostOneItemBlog = function (id) {
	if (blogList.length<1) return;

	var html  = "<form id=\"PostItemsForm\" name=\"PostItemsForm\" style=\"padding:10px 5px 10px 5px\" onSubmit=\"return hpe.PostItemsBlogNow()\"><table>";
	var deschtml = "";
	var item = this.getItem(id);
	html += "<tr><tr><th align=\"right\">Title:</th><td><input type=\"text\" size=\"40\" name=\"BlogTitle\" id=\"BlogTitle" + id + "\" value=\"";
	html += EscapeQuotes(item.title);
	html += "\" /></td></tr>\n";
	html += "<tr><th align=\"right\">Link:</th><td><input type=\"text\" size=\"40\" name=\"BlogLink\" value=\"";
	html += EscapeQuotes(item.link);
	html += "\" /></td></tr>\n";

	html += "<tr valign=\"top\"><th align=\"right\">Body:</th><td id=\"DisplayBody" + id + "\">";
	html += "<textarea style='display:none' cols=\"60\" rows=\"9\" name=\"BlogBody\" id=\"BlogBody\">" + hpe.GetItemPostBody(id) + "</textarea>";
	html += "<div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + hpe.GetItemPostBody(id) + "</div>";
	html += "</td></tr>\n";
	html += "</table><table style=\"padding-left:20px\">\n";
	html += "<tr><td colspan=\"4\"><small><em>Choose one or more blogs you want to post to.<br />If the password is not stored in your settings, you'll have to type it in now</em></small></td></tr>\n";
	for(var i in blogList) if(typeof blogList[i] != 'function') {
		html += "<tr><td><input type=\"checkbox\" name=\"BlogIndex" + i + "\" value=\"" + i + "\" /></td>\n";
		html += "<td style=\"padding-left:10px\" nowrap>\n";
		html += "<a href=\"/weblog/edit/" + i + "/\" target=\"_blank\" title=\"Edit This Blog Info\">" + blogList[i].title + "</a></td>\n";
		html += "<td style=\"padding-left:20px\">";
		if(blogList[i].hasPasswd)
			html += "</td><td><input type=\"hidden\" name=\"BlogPassword" + i + "\" />";
		else
			html += "<small><em>Password:&nbsp;</em></td><td width=\"100%\"><input type=\"password\" size=\"10\" name=\"BlogPassword" + i + "\" /></small>";
		html += "</td></tr>\n";
	}
	html += "</table></form>";

	lightWin.confirm("Post Item to your Blog", html, {okLabel:"Send", ok:hpe.PostItemsBlogNow});
	Field.focus("BlogTitle" + id);
	//tinyMCE.execCommand("mceAddControl", false, "BlogBody");
}
hpe.PostItemsBlog = function (ids, splitItems) {
	if (blogList.length < 1) return;
	if(ids.length == 0) {
		alert("No items selected!");
		return;
	}

	var html  = "<form id=\"PostItemsForm\" name=\"PostItemsForm\" onSubmit=\"return hpe.PostItemsBlogNow()\"><table>";
	var deschtml = "";
	for(var j in ids) if(typeof ids[j] != 'function') {
		var item = this.getItem(ids[j]);
		if(splitItems) {
			html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Item " + j + ", Title:</th>" +
					"<td><input type=\"text\" size=\"40\" name=\"BlogTitle\" value=\"" +
					EscapeQuotes(item.title) + "\"></td></tr>\n";
			html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Item " + j + ", Link:</th>" +
					"<td><input type=\"text\" size=\"40\" name=\"BlogLink\" value=\"" +
					EscapeQuotes(item.link) + "\"></td></tr>\n";

			html += "<tr valign=\"top\"><th align=\"right\">Body:</th><td id=\"DisplayBody" + item.id + "\">";
			html += "<textarea style='display:none' cols=\"100\" rows=\"10\" name=\"BlogBody\" id=\"BlogBody" + item.id + "\">" + hpe.GetItemPostBody(item.id) + "</textarea>";
			html += "<div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + hpe.GetItemPostBody(item.id) + "</div>";
			html += "</td></tr>\n";
		} else {
			if(deschtml == "") {
				html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">&nbsp; Title:</th>" +
						"<td><input type=\"text\" size=\"40\" name=\"BlogTitle\" value=\"";
				if(ids.length == 1) {
					html += EscapeQuotes(item.title) + "\"></td></tr>\n";
					html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Link:</th>" +
							"<td><input type=\"text\" size=\"40\" name=\"BlogLink\" value=\"" +
							EscapeQuotes(item.link) + "\"></td></tr>\n";
				} else {
					html += ids.length + " news items for you\"></td></tr>\n";
					html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Link:</th>" +
							"<td><input type=\"text\" size=\"40\" name=\"BlogLink\" value=\"\"></td></tr>\n";
				}
			}
			deschtml += hpe.GetItemPostBody(ids[j]);
		}
	}
	if(!splitItems) {
		html += "<tr valign=\"top\"><th align=\"right\">Body:</th>";
		html += "<td id=\"DisplayBodyBundled\"><textarea style='display:none' cols=\"100\" rows=\"20\" id=\"BlogBody\" name=\"BlogBody\">" + deschtml + "</textarea><div style='border: 1px solid; overflow: auto; width: 480px; height: 300px; padding: 5px;'>" + deschtml + "</div></td></tr>";
	}

	if(ids.length > 1) {
		html += "<tr><td colspan=\"2\"><p>";
		if(splitItems)
			html += "<input type=\"checkbox\" onClick=\"hpe.PostItems('bl', 0)\" />";
		else
			html += "<input type=\"checkbox\" onClick=\"hpe.PostItems('bl', 1)\" CHECKED />";
		html += " Merge Items in Single Post</p></td></tr>\n";
	}

	html += "<tr><td colspan=\"2\"><p>";
	html += "<table style=\"padding-left:20px\">\n";
	html += "<tr><td colspan=\"4\"><small><em>Choose one or more blogs you want to post to.<br />If the password is not stored in the database, you'll have to type it in now</em></small></td></tr>\n";
	for(var i in blogList) if(typeof blogList[i] != 'function') {
		html += "<tr><td><input type=\"checkbox\" name=\"BlogIndex" + i + "\" value=\"" + i + "\" /></td>\n";
		html += "<td style=\"padding-left:10px\" nowrap>\n";
		html += "<a href=\"/weblog/edit/" + i + "/\" target=\"_blank\" title=\"Edit This Blog Info\">" + blogList[i].title + "</a></td>\n";
		html += "<td style=\"padding-left:20px\">";
		if(blogList[i].hasPasswd)
			html += "</td><td><input type=\"hidden\" name=\"BlogPassword" + i + "\" />";
		else
			html += "<small><em>Password:&nbsp;</em></td><td width=\"100%\"><input type=\"password\" size=\"10\" name=\"BlogPassword" + i + "\" /></small>";
		html += "</td></tr>\n";
	}
	html += "</table></p></td></tr>\n";
	html += "</table></form>\n";

	lightWin.confirm("Post Items to your Blog", html, {okLabel:"Send", ok:hpe.PostItemsBlogNow});
	/*
	if(splitItems) {
		for(var j in ids) if(typeof ids[j] != 'function')
			tinyMCE.execCommand("mceAddControl", false, "BlogBody" + ids[j])
	} else tinyMCE.execCommand("mceAddControl", false, "BlogBody");
	*/
}
hpe.PostItemsBlogNow = function (button) {
	var form = $("PostItemsForm");

	var post = new String;
	var blogs = new Array;
	if(form) {
		var ne = form.elements.length;
		var curBlog = -1;
		for(ie=0; ie<ne; ie++) {
			if(form.elements[ie].name == "BlogTitle" || form.elements[ie].name == "BlogLink" || form.elements[ie].name == "BlogBody")
				post += form.elements[ie].name + "[]=" + escape(form.elements[ie].value) + "&";
		}

		foundBlog = 0;
		for(ib=0; ib<blogList.length; ib++) {
			for(ie=0; ie<ne; ie++) {
				if(form.elements[ie].name == "BlogIndex" + ib && form.elements[ie].checked) {
					post += "blog[]=" + ib + "&";
					foundBlog++;

					ie++;
					if(ie < ne && form.elements[ie].name == "BlogPassword" + ib) {
						if(blogList[ib].hasPasswd)
							break;
						if(form.elements[ie].value != "") {
							post += "blogpasswd[" + ib + "]=" + escape(form.elements[ie].value) + "&";
							break;
						}
					}
					alert("Need to provide a password for blog '" + blogList[ib].title + "'");
					return false;
				}
			}
		}
		if(foundBlog == 0) {
			alert("Select a blog!");
			return false;
		}
		var url = siteHome + "ajaxAPI.php?api_call=Item::postblog&api_format=JSON";
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: hpe.PostItemsProcess} );
		lightWin.wait("Post Items to Blog");
		return false;
	}
	else hpe.log("Failed to find form");
	return true;
}
hpe.PostItems = function (where, splitItems) {
	var ids = new Array();
	for(var i=0; i<itemInfo.length; i++) {
		if(itemInfo[i].isChecked)
			ids.push(itemInfo[i].id);
	}
	if(ids.length) {
		switch(where) {
			case "ma" : this.PostItemsMail(ids, splitItems); break;
			case "bl" : this.PostItemsBlog(ids, splitItems); break;
		}
	}
	else alert("Need to select one or more items.\n (use the checkboxes)");
}

/*Send item over sms*/
hpe.PostItemSms = function(id)
{
	var item = this.getItem(id);
	var html  = "<form id=\"PostItemsForm\" name=\"PostItemsForm\" style=\"padding:10px 5px 10px 5px\" onSubmit=\"return hpe.PostItemSmsNow()\"><table width='600px'>";	
	html += "<tr><th align=\"right\" nowrap>To mobile number:</th><td><input type=\"text\" size=\"30\" id=\"SmsToField\" name=\"SmsTo\" value=\"\" onKeyUp='getRecent(this);'/>" +
			"<span id='SmsToField_error' class='errormsg hidden'>Need to enter a valid mobile phone number!</span></td></tr>\n";
	html +='<tr><td>&nbsp;</td><td><div id="recent" style=""></div></td></tr>';

	var item = this.getItem(id);
	html += "<tr><td colspan=\"2\">&nbsp;</td></tr><tr><th align=\"right\">Subject:</th><td>";
	html += item.title;
	html += "<input type='hidden' name='subject' value=\""+EscapeQuotes(item.title.stripTags())+"\"></td></tr>\n";
	html += "<tr valign=\"top\"><th align=\"right\">Body:</th>";
	html += "<td id=\"DisplayBody" + id + "\"><input type=\"hidden\" name='text' value=\""+EscapeQuotes(item.shortdesc?item.shortdesc:item.desc)+"\">";
	//html += hpe.GetItemPostBody(id);
	html += item.shortdesc?item.shortdesc:item.desc;
	html += "</td></tr>\n";
	html +="<tr><td align='right'>Link:</td><td><input type='hidden' name='link' value=\""+EscapeQuotes(item.link)+"\">"+item.link+"</td></tr>";
	html += "</table></form>";

	lightWin.confirm("Post Item to mobile phone", html, {okLabel:"Send", ok:hpe.PostItemSmsNow});
	Field.focus("SmsToField");
}
hpe.PostItemSmsNow = function (button) {
	if (!userCanSendSms) {
		alert('Can not send sms: sms credit balance is too low');
		return;
	}
	var form = $("PostItemsForm");

	var post = new String;
	var to = "";
	if(form) {
		var ne = form.elements.length;
		for(ie=0; ie<ne; ie++) {
			if(form.elements[ie].name == "subject" || form.elements[ie].name == "text" || form.elements[ie].name == "link")
				post += form.elements[ie].name + "=" + escape(form.elements[ie].value) + "&";			
			else if(form.elements[ie].name == "SmsTo") {
				var regex = /^[0-9]+$/;
				if(regex.test(form.elements[ie].value)) {
					to = form.elements[ie].value;
					this.postPrevSms = to;
					post += form.elements[ie].name + "=" + escape(form.elements[ie].value) + "&";
				}
			}
		}

		if(to == "") {
			// alert("Need to enter an email address!");
			Element.removeClassName('SmsToField_error', 'hidden');
			Field.focus("SmsToField");
			return false;
		}
		post += "-----------------------------7d325a200432--\n";
		var url = siteHome + "ajaxAPI.php?api_call=Item::postsms&api_format=JSON";
		var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: hpe.PostItemsProcess} );
		lightWin.wait("Posting item to mobile phone");
		//alert(post);
		return false;
	}
	else hpe.log("Failed to send sms");
	return false;
}

hpe.FindSimilarItems = function(id) {
	var item = this.getItem(id);
	var post = "language=" + srcInfo[item.sourcekey].language + "&query=" + escape(item.title);

	var url = siteHome + "ajaxAPI.php?api_call=Item::similar&api_format=JSON&id=" +  id;
	var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: hpe.FindSimilarItemsProcess} );

	hpe.PostItemOps(id, "presimilar", "<p>Searching for similar items...</p>");
}
hpe.FindSimilarItemsProcess = function(request) {
	try { var res = eval('('+request.responseText+')') } 
	catch(e) { hpe.PostItemOps(hpe.itemOpsId, "similar", "<p>Failed to process data...</p>", 1); return hpe.error(e); }

	if(isNull(res.similarItems) && res.similarItems.length == 0) {
		hpe.PostItemOps(hpe.itemOpsId, "similar", "<p>Found no similar items</p>", 1); 
		return;
	}

	shtml = "<b>Similar Items</b><div style=\"white-space:normal\">\n";

	shtml = "<b>Similar Items</b>\n<table cellspacing='0' cellpadding='1'>";
	for(var i in res.similarItems) if(typeof res.similarItems[i] != 'function') {
		if(res.similarItems[i].title == "")
			continue;
		shtml += "<div  class='similaritems " + (i % 2 ? "bg01" : "bg02") + "' >" +
				 "<a href=\"/click/i," + res.similarItems[i].id + "," + res.similarItems[i].sourceid + "/\" target=\"_blank\"><b>" + res.similarItems[i].title + "</b></a><br />\n" +
				 "<div style=\"font-size:90%\"><em> in <a href=\"/sources/info/" + res.similarItems[i].sourceid + "/\" target=\"_blank\">" + res.similarItems[i].source + "</a></em></div></div>\n";
	}
	shtml += "</table>";
	hpe.PostItemOps(hpe.itemOpsId, "similar", shtml, 1);
}

hpe.FindYQItems = function(id) {
	var item = this.getItem(id);
	if(this.savedElement == "ItemDescZone" + id) {
		this.RestoreEltContent("ItemDescZone" + id);
		return;
	}

	var url = siteHome + "ajaxAPI.php?api_call=Item::yq&api_format=JSON&id=" +  id + "&lang=" + srcInfo[item.sourcekey].language;
	var post = "context=" + escape(item.title);
	var desc = new String(item.desc);
	post += "+" + escape(desc.replace(/<[^>]+>/g, " "));

	var myAjax = new Ajax.Request( url, {method: 'post', postBody: post, onSuccess: hpe.FindYQItemsProcess} );

	hpe.PostItemOps(id, "preyq", "<p><a href=http://yq.search.yahoo.com/splash/start.html target=_blank>" +
			"<img src=http://us.i1.yimg.com/us.yimg.com/i/us/search/gr/yq_small.gif width=21 height=16 /></a> " +
			"Searching for Y!Q items...</p>");
}
hpe.FindYQItemsProcess = function(request) {
	try { var res = eval('('+request.responseText+')'); } 
	catch(e) { hpe.PostItemOps(hpe.itemOpsId, "yq", "<p>Failed to process data...</p>", 1); return hpe.error(e); }
//	hpe.PostItemOps(hpe.itemOpsId, "yq", request.log, 1); 

	if(isNull(res.yqItems) || res.yqItems.length == 0) {
		hpe.PostItemOps(hpe.itemOpsId, "yq", "<p>Y!Q returned no items</p>", 1); 
		return;
	}

	var shtml = "<a href=http://yq.search.yahoo.com/splash/start.html target=_blank>" +
			"<img src=http://us.i1.yimg.com/us.yimg.com/i/us/search/gr/yq_small.gif width=21 height=16 /></a> " +
			"<b>Y!Q Contextual Search Results</b><div style=\"white-space:normal\">\n";

	for(var i in res.yqItems) if(typeof res.yqItems[i] != 'function') {
		shtml += "<div class='similaritems " + (i % 2 ? "bg01" : "bg02") + "'>" +
				 "<a href=\"" + res.yqItems[i].link + "\" target=\"_blank\"><b>" + res.yqItems[i].title + "</b></a><br />\n" +
				 "<div style=\"font-size:90%\">" + res.yqItems[i].desc + "</div></div>\n";
	}

	shtml += "</div><div style=\"text-align:right;font-size:80%;padding-top:5px\">powered by Yahoo! Search</a></div>\n";
	hpe.PostItemOps(hpe.itemOpsId, "yq", shtml, 1);
}

hpe.StyleSheet_makeCompatible=function(style)
{
  
  if (typeof style.cssRules == 'undefined' && typeof style.rules != 'undefined')
    style.cssRules = style.rules;

  
  /*if (typeof style.insertRule == 'undefined' && typeof style.addRule != 'undefined')
    style.insertRule = StyleSheet_insertRule;
  if (typeof style.deleteRule == 'undefined' && typeof style.removeRule != 'undefined')
    style.deleteRule = style.removeRule;

  if (typeof style.cssRules == 'undefined' || typeof style.insertRule == 'undefined'
      || typeof style.deleteRule == 'undefined')
    return null;
  else*/
    return style;
}

hpe.addStyleSheet = function(url)
{
  var style;
  var id = 'fontResizeStyle';
  if (typeof url == 'undefined')
  {
    style = document.createElement('style');
  }
  else
  {
  	style = document.getElementById(id);
  	if(!style)
  	{	
	    style = document.createElement('link');
	    style.rel = 'stylesheet';
	    style.type = 'text/css';
	    style.id = id;
	    
	    document.getElementsByTagName('head')[0].appendChild(style);
  	}
    style.href = url;
  }
    
  style = document.createElement('style');

  return this.StyleSheet_makeCompatible(style);
}

hpe.changeFontStyle = function(current,level)
{
	prev = current;
//	for(i=0;i<this.fontSizes.length;i++)
//	{
	var i=0;
	var done = false;
	while(i<this.fontSizes.length && done == false)
	{
		if(this.fontSizes[i] == current)
		{
			done = true;
			if (level && i != (this.fontSizes.length-1))
			{
				current = this.fontSizes[++i];
			}
			else if (!level && i != 0)
			{
				current = this.fontSizes[--i];
			}
			//alert(prev+"  "+current);
			if (current != prev)
			{
				//change stylesheet
				//alert('/HPE/local/' + current + '.css');
				this.configureFontSize(current);
				curFontSize = current;
				
				if (this.nonactiveM != curFontSize)
					html = '<a href="javascript:void(0)" onClick="hpe.changeFontStyle(curFontSize,0);"><img src="/i/fontsize_minus.gif" width="16" height="10" alt="decrease font size" border="0"></a>';
				else
					html = '<img src="/i/fontsize_minus.gif" width="16" height="10" alt="decrease font size" border="0">';

				if (this.nonactiveP != curFontSize)
					html += '<a href="javascript:void(0)" onClick="hpe.changeFontStyle(curFontSize,1);"><img src="/i/fontsize_plus.gif" width="16" height="10" alt="increase font size" border="0"></a>';
				else
					html += '<img src="/i/fontsize_plus.gif" width="16" height="10" alt="increase font size" border="0">';
				//change user prefs
				document.getElementById('fontsize').innerHTML = html;
				
				this.addStyleSheet('/HPE/local/' + current + '.css');
			}
			else
			break;
		}
		i++;
	}
//	}
}

hpe.configureFontSize = function(fontsize)
{
	// Save fontsize preferences
	var url = siteHome + "ajaxAPI.php?api_call=User::savepreferences&api_format=JSON&fontsize="+fontsize;
	var myAjax = new Ajax.Request(url, { method:'get', onSuccess:this.configureFontSizeDone });
	return true;
}

hpe.configureFontSizeDone = function(originalRequest) 
{
	
	try { var res = eval('('+originalRequest.responseText+')'); } catch(e) { return; }
		
	if (res.response_code >= 300) return false;
}

//by Dofer (v.kislichenko) - not subscribed users can add sources
hpe.remSources = function(form, name)
{
	var res = Array();
	var reusult = '';
	elementAr = document.forms[form].elements[name+'[]'];
	
	if(elementAr)
	{
		for (i in elementAr)
		{
			if(elementAr[i].checked)
			{
				res.push(elementAr[i].value);
			}
		}
		
		if(res.length > 0)
		{
			reusult = res.join(',');
			// save to cookies
			hpe.setCookie("HPESavedSources", reusult);
		}
	}
}

// application base class -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

HPEAppList = new Array();

HPEApp = Class.create();
Object.extend(HPEApp.prototype, {

	opsSelect:"",

	initialize : function() {
		HPEAppList[HPEAppList.length] = this;
	},

	InitApp : function() {
	},

	SwitchToHTML : function() {
		document.location.href = siteHome;
	},

	ShowBackMessage : function() {
		var elt = $("ApplicationBackButton");
		if(!elt) return;
		elt.innerHTML = "<a class=\"OB\" href=\"#\" onClick=\"HPEBackApp()\">[back to previous level]</a>";
		Element.show(elt);
	},

	LaunchOps : function () {
		var elt = $(this.opsSelect);
		this.LaunchDefaultOps(elt);
		elt.selectedIndex = 0;
	},

	LaunchDefaultOps : function (elt) {
	},

	HandleKeyboard : function(event) {
		return false;
	},

	LanguageChange : function (field) {
		if(isNull(field)) field = 'filter_lang';
		if ($F(field) == 'configure') {
			if (userIsGuest) return this.showGuestAlert();
			hpe.Dialog.configureLanguage(field);
		}
	},

	showGuestAlert : function () {
		if (confirm('This action requires you to login.\nDo you want to proceed to login page?'))
			window.location = siteHome;
	},

	/**
	 *	Get/set <select> value
	 *
	 *	@param	object	$sel	Reference to <select> object
	 *	@param	string	$value	New value (optional)
	 *	@param	string	$noevent	Supress onChange event calling (optional)
	 *	@param	string	$def	Default value, if $value isn't found (optional)
	 *	@return	string	Old <select> value
	 */
	selectValue : function(sel, value, noevent, def) {
		var selval = (sel.selectedIndex>=0) ? sel.options[sel.selectedIndex].value : false;

		if (typeof(value) == 'undefined') return selval;

		var f = false;
		for (var i=0; i<sel.options.length; i++) {
			if (sel.options[i].value == value) {
				sel.selectedIndex = i;
				if (!noevent && sel.onchange)	// Call onChange handler
					sel.onchange();
				f = true;
				break;
			}
		}
		if (!f) {
			if (typeof(def)!='undefined')
				this.selectValue(sel, def, noevent);
			else {
				sel.selectedIndex = 0;
				if (!noevent && sel.onchange)
					sel.onchange();
			}
		}

		return selval;
	},
	
	UpdatePageList : function() {
	}

});

HPEItemApp = Class.create();
Object.extend(HPEItemApp.prototype, new HPEApp);
Object.extend(HPEItemApp.prototype, {

	hideItemMetaData : false,
	showShortDesc : false,

	CheckItem : function(id, button) {
		hpe.CheckItem(id, button);
	},

	UnCheckAllItems : function() {
		hpe.UnCheckAllItems();
	},

	CheckAllItems : function() {
		hpe.CheckAllItems();
	},

	LaunchDefaultOps : function (elt) {
		if(elt.value == "PostItems2Mail")
			hpe.PostItems('ma', 0);
		else if(elt.value == "PostItems2Blog")
			hpe.PostItems('bl', 0);
		else if(elt.value == "UnCheckAllItems")
			app.UnCheckAllItems();
		else if(elt.value == "CheckAllItems")
			app.CheckAllItems();
	},

	ShowSource : function (id) {
		if(srcInfo[id]) {
			appSV.pageCurrentSource = srcInfo[id].id;
			HPEResumeApp(appSV);
		} else {
			for(var i in srcInfo) if(typeof srcInfo[i] != 'function') {
				if(srcInfo[i].id == id || srcInfo[i].key == id) {
					appSV.pageCurrentSource = srcInfo[i].id;
					HPEResumeApp(appSV);
					return;
				}
			}
		}
	},

	ShowSourceDetails : function (srcId) {
		if(!srcInfo[srcId]) {
			for(var i in srcInfo) if(typeof srcInfo[i] != 'function') {
				if(srcInfo[i].id == id || srcInfo[i].key == id) {
					scrId = i;
					break;
				}
			}
		}
		switch(srcInfo[srcId].srctype) {
			case "HPEItemsCategory" :
				appCB.pageId = srcInfo[srcId].cat; HPEResumeApp(appCB); break;
			case "HPEItemsSource" :
				appSV.pageCurrentSource = srcInfo[srcId].id; HPEResumeApp(appSV); break;
			case "HPEItemsRSS" :
				appSV.pageCurrentSource = srcInfo[srcId].key; HPEResumeApp(appSV); break;
			default:
				hpe.log("Failed to find info for source " + srcId + " of type '" + srcInfo[srcId].srctype + "'");
				alert("No further information about this source is available");
		}
	},
	
	ToggleShortDesc : function () {
		this.showShortDesc = !(this.showShortDesc);
		hpe.showShortDesc = this.showShortDesc;
//		this.setCookie("HPEShowShortDesc", this.showShortDesc ? "1" : "0");
		hpe.ReRenderAllItems();
	},

	ToggleItemMetaData : function () {
		hpe.hideItemMetaData = this.hideItemMetaData = !(this.hideItemMetaData);
//		this.setCookie("HPEHideItemMetaData", app.hideItemMetaData ? "1" : "0");
		hpe.ReRenderAllItems();
	},

	SetItemToolState : function () {
		hpe.showShortDesc = this.showShortDesc; // = this.getCookie("HPEShowShortDesc") == "1" ? 1 : 0;
		var elt = $("HPEToggleShortDesc");
		if(elt) elt.checked = this.showShortDesc ? true : false;
		hpe.hideItemMetaData = this.hideItemMetaData; // this.getCookie("HPEHideItemMetaData") == "1" ? 1 : 0;
		elt = $("HPEToggleItemMetaData");
		if(elt) elt.checked = this.hideItemMetaData ? false : true;
	},

	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 item = hpe.getItem(id);
		var page = $F('subscribe_'+id+'_page');
		var post = "siteid=" + srcInfo[item.sourcekey].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');
	}


});

var app = null;
var HPEAppStack = new Array();
function HPEResumeApp(newapp, resetStack) {
	if(resetStack) {
		while(HPEAppStack.length) HPEAppStack.pop();
		var elt = $("ApplicationBackButton");
		if(elt) Element.hide(elt);
	}
	var same = (app == newapp);
	if(!same) {
		var i = HPEAppStack.length;
		if(isNull(resetStack) || !resetStack) {
			if(i == 0)
				HPEAppStack.push(app);
		}
	}
	try{ app.SuspendApp(same); } catch(e) { hpe.error("HPEResumeApp Suspend: " + e) }
	var prevapp = app;
	app = newapp;
	app.ResumeApp(same);
	try { prevapp.ShowBackMessage(); } catch(e) { hpe.error("HPEResumeApp ShowBackMsg: " + e) }

	if(!same || HPEAppStack.length == 0)
		HPEAppStack.push(app);
}
function HPEBackApp() {
	var i = HPEAppStack.length;
	if(i > 1) {
		var curapp = HPEAppStack.pop();
		try{ curapp.SuspendApp(false); } catch(e) { hpe.error("HPEBackApp Suspend: " + e) }
		app = HPEAppStack.last();
		app.ResumeApp(false);

		if(HPEAppStack.length > 1) {
			try{ HPEAppStack[HPEAppStack.length - 2].ShowBackMessage(); } catch(e) { hpe.error("HPEBackApp: " + e) }
		} else {
			var elt = $("ApplicationBackButton");
			if(elt) Element.hide(elt);
		}
	}
}

Ajax.Responders.register({
  onCreate: function(request, transport) {
	hpe.activeRequestCount++;
	hpe.log("CREATE Ajax req " + hpe.activeRequestCount + ": " + request.url);
	if(hpe.activeRequestCount > 1) return;
	var elt = $("loadmark");
	if(elt) elt.style.display="inline";
  },
  onComplete: function(request, transport) {
	if(hpe.activeRequestCount) hpe.activeRequestCount--;
	hpe.log("COMPLETE Ajax req " + hpe.activeRequestCount);
	if(transport.responseText == "invaliduser") {
// [ua] Dofer <start>	
		//check if not logedin user tying to add sources
		HPESavedSources = hpe.getCookie("HPESavedSources");
		if (HPESavedSources)
		{
			hpe.GotoRegister();
		}	
		else
		{
			hpe.GotoLogin();
		}
// [ua] Dofer <end>			
		return;
	}
	if(hpe.activeRequestCount != 0) return;
	var elt = $("loadmark");
	if(elt) Element.hide(elt);
  },
  onException: function(request, e) {
	switch(request.transport.responseText) {
		case "invaliduser": {
				alert("You need to login for this to work!");
				document.location.href="/";
				return;
			}
		case "error":
		case "done":
			break;
		default: {
			var msg =  "Ajax exception for request " + request.url + ": " + e.name + ", " + e.message;
			if (e.fileName) msg += "\n"+"In file "+ e.fileName;
			if (e.lineNumber) msg += ' at line '+ e.lineNumber;
			if (e.stack) msg += "\n"+' stack is '+ e.stack;
			msg += "\n"+ request.transport.responseText;
			hpe.error(msg);
			hpe.activeRequestCount--;
		}
	}
	if(hpe.activeRequestCount != 0) return;
	var elt = $("loadmark");
	if(elt) Element.hide(elt);
  }
});

