function trim(str) {return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");}
function sortNumber(a, b) {return a - b;}

// class that maintains user session -------------------------
function UserSession() {
	this.login = null;
	this.error = false;
	this.isLogged = false;

	this.checkSession = function() {
		var s = document.cookie;
		var cookesPub = UserSession.checkRegExp(s,'Publish');
		var cookesUID = UserSession.checkRegExp(s,'UserId');
		var cookesErr = UserSession.checkRegExp(s,'loginErrorMessage');
		
		if (!cookesPub || cookesPub == '' || cookesPub == ',') {
			this.login = null;
			this.isLogged = false;
		} else {
			if (!cookesUID || cookesUID=='') {
				var t = cookesPub;
				var ajax_rpc = new AjaxRpc("");
				var l = ajax_rpc.GET({ url: "/getloginbypublish.pl",
					args: {Publish : t[1], t: (new Date()).getTime()}, callback: null
				});
				if (l) {
					var exp = new Date( );
					var nowPlusOneYear = exp.getTime( ) + (365.25 * 24 * 60 * 60 * 1000);
					exp.setTime(nowPlusOneYear);
					document.cookie = "UserId=" + escape(l) + "; expires=" + exp.toGMTString( );
				}
			}
			var a;
			a = UserSession.checkRegExp(document.cookie,'UserId');
			this.login = escape(a[1]);
			this.isLogged = true;
		} 
		if (cookesErr || cookesErr != '') {
			this.error = true;
			document.cookie = "loginErrorMessage=;";
		} else {
			this.error = false;
		}
		return this.isLogged;
	}		

	this.checkSessionLogin = function(myLogin, url) {
		var url = url || '/listcentral.html';
		if (!this.checkSession()) {
			window.location = '/listcentral.html';
			return false;
		}
		if (this.login.toLowerCase() != myLogin.toLowerCase()) {
			window.location = url;
			return false;
		}
		return true;
	}
}

UserSession.checkRegExp = function(str, param) {
	var r = new RegExp(param+'=([^;]+); ');
	var rl= new RegExp(param+'=([^;]+)');
	var t;
	if (r.test(str)) {
		t = r.exec(str);
	} else {
		if (rl.test(str)) {
			t = rl.exec(str);
		} else {
			t='';
		}
	}
	return t;
}

var userSession = new UserSession();
userSession.checkSession();

//-----------------------------------------------
// class that maintains feeds/news
function BykiFeed(value, type, element, width, maxLines) {
	this.type = type;
	if (!width) {
		this.width = 180;
	} else {
		this.width = width;
	}
	if (!maxLines) {
		this.maxLines = 5;
	} else {
		this.maxLines = maxLines;
	}
	switch (this.type) {
		case "FU" : // user feed
			{
				this.url = "/feeds/user/" + encodeURIComponent(value) + ".js";
				break;
			}
		case "FC" : // category feed
			{
				this.url = "/feeds/category/" + encodeURIComponent(value) + ".js";
				break;
			}
		case "FT" : // tag feed
			{
				this.url = "/feeds/tag/" + encodeURIComponent(value) + ".js";
				break;
			}
		case "FL" : // recent lists feed
			{
				this.url = "/feeds/lists.js";
				break;
			}
		case "FCL" : // recent category lists feed
			{
				this.url = "/feeds/category/" + encodeURIComponent(value) + ".js";
				break;
			}
		case "FPCL" : // the most popular category lists feed
			{
				this.url = "/feeds/category/" + encodeURIComponent(value) + "/poplists.js";
				break;
			}
		case "FPCT" : // the most popular category tags
			{
				this.url = "/feeds/category/" + encodeURIComponent(value) + "/poptags.js";
				break;
			}
		case "FMCL" : // more category lists feed
			{
				this.url = "/feeds/category/" + encodeURIComponent(value) + "/morelists.js";
				break;
			}
		case "FPL" : // the most popular lists feed
			{
				this.url = "/feeds/poplists.js";
				break;
			}
		case "FPT" : // the most popular tags
			{
				this.url = "/feeds/poptags.js";
				break;
			}
		case "FEL" : // editor picks lists
			{
				this.url = "/feeds/editpicks.js";
				break;
			}
		case "FAC" : // available categories
			{
				this.url = "/feeds/categories.js";
				break;
			}
		case "S" : // user subscriptions 
			{
				this.url = "/getfeeds.plex";
				break;
			}
		case "N" : // user news
			{
				this.url = "/getnews.plex";
				break;
			}
		default:
			this.url = "/feeds/poplists.js";
	}
	this.element = element;
}

BykiFeed.prototype.getElement = function() {
	if (typeof(this.element) == "string") {
		return document.getElementById(this.element);
	} else {
		return this.element;
	}
}

BykiFeed.prototype.display = function(woSubjName, exclude, randomDisplay) {
	var exclude = exclude || 0;
	document.body.style.cursor = 'progress';
	var ajaxRpc = new AjaxRpc("");
	var feeds = "";
	try {
		feeds = ajaxRpc.GET({ url: this.url,
			args: {t: (new Date()).getTime()}, callback: null, onError: this.onError
		});
		if (typeof(feeds) != "object") {
			try {
				feeds = eval(feeds);
			} catch(e) {
				feeds = "";
			};
		}
	} catch(e) {
		feeds = "";
	}
	document.body.style.cursor = 'auto';
	if (!feeds) return;
	if (exclude) {
		var i;
		for (i = 0; i < feeds.length; i++) {
			if (feeds[i].byki_list == exclude) break;
		}
		if (i < feeds.length) feeds.splice(i, 1);
	}
	var str = "";
	var ml = Math.min(this.maxLines, feeds.length);
	if (randomDisplay) {
		var cnt = 0, rdH = {}, rdA = new Array();
		while (cnt < ml) {
			var r = Math.floor(feeds.length * Math.random());
			if (rdH[r] == 1) continue;
			rdH[r] = 1;
			cnt++;
		}
		for (var r in rdH) rdA.push(r);
		rdA.sort(sortNumber);
		for (var i = 0; i < rdA.length; i++) {
			str += BykiFeed.getFormattedLine(feeds[rdA[i]], this.type, woSubjName);
		}
	} else {
		for (var i = 0; i < ml; i++) {
			str += BykiFeed.getFormattedLine(feeds[i], this.type, woSubjName);
		}
	}
	if (this.type == "N") {
		if (str == "") str = "No news.";
		str = '<p class="feeds">' + str + '</p>';
	} else if (this.type == "S") {
		if (str == "") str = "No activity.";
		str = '<p class="feeds">' + str + '</p>';
	} else if (this.type == "FT" || this.type == "FPT" || this.type == "FPCT") {
		if (str == "") str = "No tags.";
		str = '<p class="lists">' + str + '</p>';
	} else {
		if (str == "") str = "No lists.";
		str = '<p class="lists">' + str + '</p>';
	}
	str = '<div style="width:' + this.width + 'px;overflow:hidden;">'
		+ '<div style="width:' + this.width + 'px;overflow:visible;">' + str + '</div></div>';
	this.getElement().innerHTML = str;
}

// news types
// 1 - category (CategoryID) {creator, name, group_id, group_name, page_url, type}
// 2 - tag (WordId) {creator, name, group_id, group_name, list_id, word, page_url, type}
// 3 - user (Registred_User) {creator, name, group_id, group_name, list_id, page_url, type}
// 4 - your friend became a friend of somebody (Registred_User) {your_friend_login, another_friend_login, type}
// 5 - your friend added new category he likes to study (Registred_User) {friend_login, group_id, group_name, type}
// 6 - new language was added by TL admin (0) {type, group_id, group_name}
// 7 - new categiry was added by TL admin (0) {type, group_id, group_name}
// 8 - add language by user (Registred_User) {type, language, login}

BykiFeed.getFormattedLine = function(feed, type, woSubjName) {
	var woSubjName = woSubjName || 0;
	var line = '';
	if (type == "N" || type == "S") {
		// any kind of news
		switch (feed.type) {
			case "1" :
				line = 'A new <a href="/category/' + feed.group_name + '"> ' + feed.group_name + '</a> list - ' +
					'<a href="' + feed.page_url + '">' + feed.name + '</a> has been posted to List Central<br />';
				break;
			case "2" :
				line = 'A new list <a href="' + feed.page_url + '">' + feed.name + '</a> was tagged under ' +
					'<a href="/tag/' + feed.page_name + '">' + feed.group_name + '</a><br />';
				break;
			case "3" :
				line = '<a href="/user/' + feed.creator + '">' + feed.creator + '</a> posted a new <a href="/category/' + feed.group_name + '"> ' + feed.group_name + '</a> list - ' +
					'<a href="' + feed.page_url + '">' + feed.name + '</a><br />';
				break;
			case "4" :
				line = '<a href="/user/' + feed.your_friend_login + '">' + feed.your_friend_login + '</a> is now friend with ' +
					'<a href="/user/' + feed.another_friend_login + '">' + feed.another_friend_login + '</a><br />';
				break;
			case "6":
				line = 'Byki added <a href="/category/' + feed.group_name + '">' + feed.group_name + '</a> as a new langauge<br />';
				break;
			case "7":
				line = 'Byki added <a href="/category/' + feed.group_name + '">' + feed.group_name + '</a> as a new category<br />';
				break;
			case "8":
				line = '<a href="/user/' + feed.login + '">' + feed.login + '</a> is now interested in <a href="/category/' + feed.language + '">' + 
				feed.language + '</a><br />';
				break;
			default:
				line = '<a href="' + feed.page_url + '">' + feed.name + '</a><br />';
		}
	} else if (type == "FAC" || type == "FPT" || type == "FPCT") {
		line = '<a href="' + feed.group_page + '">' + feed.name + '</a><br />';
	} else {
		// any kinf of list feeds
		if (feed.subject_name && !woSubjName) {
			line = '<a href="' + feed.page_url + '">' + feed.name + '</a> (' + feed.subject_name + ')<br />';
		} else {
			line = '<a href="' + feed.page_url + '">' + feed.name + '</a><br />';
		}
	}
	return line;
} 

BykiFeed.prototype.onError = function(response) {
/**
 	var e = this.getElement();
	e.innerHTML = response;
/**/
	return true;
}


//-----------------------------------------------
function showUserPicture(id, maxwidth, src, w, h) {
	var	needW, needH;

	if (!src || src.length == 0) {
		src = "/images/defaultuser.jpg";
	}
	if (w > 0 && h > 0) {
		needW = maxwidth;
		needH = Math.ceil((h * maxwidth) / w);
		if (needW < 32) needW = 32;
		if (needH < 32) needH = 32;
	} else {
		needW = maxwidth;
		needH = maxwidth;
	}
	if (needW % 2 > 0) needW--;
	if (needH % 2 > 0) needH--;

	var obj = document.getElementById(id);
	obj.src = src;
	obj.style.width = needW + 'px';
	obj.style.height = needH + 'px';

	var div = document.getElementById(id + 'Div');
	div.style.width = needW + 'px';
	div.style.height = needH + 'px';

	obj.style.display = "block";
}
