var myTags = new Array();
var myComments = new Array();
var isTagEditMode = false;
var isCommentEditMode = false;
var allowRating = false;
var FavMode = 1;
var valueFav0 = '<a href="#" onclick="addFavorite(); return false;" onmouseover="chngFavIcon(\'on\');" onmouseout="chngFavIcon(\'off\');"><div class="iconMiddle"><img id="IconFavorite" src="/images/iconaddfavorites.gif" align="bottom" title="Add to my Favorites" alt="Add to my Favorites" /></div></a>'
	+ '<a href="#" onclick="addFavorite(); return false;" onmouseover="chngFavIcon(\'on\');" onmouseout="chngFavIcon(\'off\');">Add the list to my Favorites</a>';
var valueFav1 = '<a href="#" onclick="addFavorite(); return false;" onmouseover="chngFavIcon1(\'on\');" onmouseout="chngFavIcon1(\'off\');"><div class="iconMiddle"><img id="IconFavorite" src="/images/iconfavorites.gif" align="bottom" title="Remove from my Favorites" alt="Remove from my Favorites" /></div></a> This list is one of your <a href="/user.plex?link=FL" title="My Favorite Lists">Favorites</a>';
//------------------------------------------------------------------------------
function sendRequest(url, args, elId) {
	var a = {'fi': fi, t: (new Date()).getTime()};
	for (var i in args) a[i] = args[i];
	var ajax_rpc = new AjaxRpc("");
	var result = null;
	try {
		result = ajax_rpc.GET({url: url, args: a, callback: null});
	} catch (e) {return null;}
	if (elId) {
		var el = document.getElementById(elId);
		if (el) {
			if (result.TEXT) el.innerHTML = result.TEXT;
			else if (result.MESSAGE) {
				if (result.ERROR) el.innerHTML = '<p class="errormsg">' + result.MESSAGE + '</p>';
				else el.innerHTML = '<p class="okmsg">' + result.MESSAGE + '</p>';
			}
		}
	}
	return result;
}
function listPageOnload() {
	if (userSession.isLogged) {
		var ajax_rpc = new AjaxRpc("");
		var fixData = null;
		try {
			fixData = ajax_rpc.GET({url: "/listpage_fixdata.pl",
				args: {'BYKIlist': bl}, callback: null});
		} catch (e) {}

		if (fixData) {
			if (fixData.ticket) {
				if (document.getElementById('byki')) {
					document.getElementById('byki').src = ifrmSrc + '&ticket=' + fixData.ticket;
					document.getElementById('byki').style.display = 'block';
				}
			}
			if (fixData.cookieVis) {
				var exp = new Date( );
				var nowPlusOneWeek = exp.getTime( ) + (24 * 60 * 60 * 1000); // one day
				exp.setTime(nowPlusOneWeek);
				document.cookie = "Vis=" + fixData.cookieVis + "; path=/; expires=" + exp.toGMTString( );
			}
			var txt;
			if (fixData.isFavorite == 1) {
				FavMode = 1;
				txt = valueFav1;
			} else {
				FavMode = 0;
				txt = valueFav0;
			}
			document.getElementById("txtForFav").innerHTML = txt;
			if (fixData.PostedName && fixData.PostedMail) {
				var el = document.getElementById("PostedMail");
				if (el) {
					el.value = fixData.PostedMail;
					document.getElementById("PostedName").value = fixData.PostedName;
				}
			}
			allowRating = (fixData.Registred_User != 0 && fixData.LRU != 0);
			userRating = fixData.RatingValue || 0;
			setRating(fixData.RatingValue, true);
		}
	} else if (document.getElementById('byki')) {
		document.getElementById('byki').src = ifrmSrc;
		document.getElementById('byki').style.display = 'block';
		document.getElementById('rating_table').style.display = 'none';
	}
	if (bl && document.getElementById('byki')) drawRating(curRating);

	if (userSession.isLogged) {
		document.getElementById('RateThisList').style.display = '';
	} else {
		document.getElementById('loginIsRequiredToRate').style.display = '';
	}
	makeMyTags();
	makeMyComments();
	makeSharingLinks();
}
function goToRegPage() {
	document.getElementById('registrationForm').submit();
}
function showFAQContent(curobj, subobjstr, substobjstr, opt_position) {
	var opt_position = opt_position || 'leftbottom';
	var cont = document.getElementById(subobjstr).innerHTML;
	var pattern = '';
	if (/overlayclose\(\'/.test(cont)) pattern = "'" + subobjstr + "'";
	else pattern = '"' + subobjstr + '"';
	cont = cont.replace("overlayclose(" + pattern + ")", "closeFAQContent('" + substobjstr + "')");
	document.getElementById(substobjstr).innerHTML = cont;
	if (/MSIE (5\.|6)/.test(navigator.userAgent) && (substobjstr.indexOf('1') > -1)) {
		document.getElementById('SelectEmbedCode').style.display = 'none';
	}
	return overlay(curobj, substobjstr, opt_position);
}
function closeFAQContent(substobjstr) {
	if (/MSIE (5\.|6)/.test(navigator.userAgent) && (substobjstr.indexOf('1') > -1)) {
		var selectEmbed = document.getElementById('SelectEmbedCode');
		if (selectEmbed) selectEmbed.style.display = '';
	}
	overlayclose(substobjstr);
}
//------------------------------------------------------------------------------
// Favorites
function addFavorite() {
	var divTxt;
	var args = {};
	if (FavMode == 1) {
		if (!confirm('Are you sure you want to remove this list from your Favorites?')) return false;
		args = {'List': bl, 'Type': 'F'};
		divTxt = valueFav0;
		FavMode = 0;
	} else {
		args = {'List': bl};
		divTxt = valueFav1;
		FavMode = 1;
	}
	var result = sendRequest("/getusrparams.pl", args);
	if (result && !result.ERROR) {
		document.getElementById("txtForFav").innerHTML = divTxt;
	} else {
		FavMode = (FavMode ? 0 : 1);
	}
}
function chngFavIcon(state) {
	if(state == "on") document.getElementById('IconFavorite').src = '/images/iconfavorites.gif';
	else document.getElementById('IconFavorite').src = '/images/iconaddfavorites.gif';
}
function chngFavIcon1(state) {
	if(state == "on") document.getElementById('IconFavorite').src = '/images/iconremfavorites.gif';
	else document.getElementById('IconFavorite').src = '/images/iconfavorites.gif';
}
//------------------------------------------------------------------------------
// Sharing
function makeSharingLinks() {
	if (typeof(BitlyCB) != 'undefined') {
		BitlyCB.myShortenCallback = function(data) {
			var result;
			for (var r in data.results) {
				result = data.results[r];
				break;
			}
			var page_url_bit_ly = result['shortUrl'];
			document.getElementById('shareTwitter').href = "http://twitter.com/home/?status="
				+ encodeURIComponent('I found a Byki ' + category + ' lesson called "' + listTitle + '" at ' + page_url_bit_ly + '.');
		}
		BitlyClient.shorten(page_url, 'BitlyCB.myShortenCallback');
	}
	document.getElementById('shareReddit').href = "http://reddit.com/submit?url=" + page_url;
	document.getElementById('shareStumbleUpon').href = "http://www.stumbleupon.com/submit?url=" + page_url;
	document.getElementById('shareFacebook').href = "http://www.facebook.com/sharer.php?u=" + page_url;
	document.getElementById('shareDelicious').href = "http://del.icio.us/post?url=" + page_url;
	document.getElementById('shareGoogle').href = "http://www.google.com/bookmarks/mark?op=edit&bkmk=" + page_url;
	document.getElementById('shareMixx').href = "http://www.mixx.com/submit?page_url=" + page_url;
}
function emailThisList(panel) {
	if (!panel) return;
	if (!panel.isOpen) panel.onArrowClick();
	var fldPostedName = document.getElementById('PostedName');
	var fldPostedMail = document.getElementById('PostedMail');
	var fldSharedMail = document.getElementById('SharedMail');
	fldPostedName.value = trim(fldPostedName.value);
	fldPostedMail.value = trim(fldPostedMail.value);
	if (fldPostedName.value == '') fldPostedName.focus();
	else if (fldPostedMail.value == '') fldPostedMail.focus();
	else fldSharedMail.focus();
}
function checkLengthTA(a, b) {
	var b = b || 1000;
	if (a.value.length <= b) {
		return true;
	}
	a.value = a.value.substring(0, b);
	alert('Max length for this field is ' + b + '.');
	return false;
}
function checkSharedMail() {
	var fldPostedName = document.getElementById('PostedName');
	var fldPostedMail = document.getElementById('PostedMail');
	var fldSharedMail = document.getElementById('SharedMail');
	fldPostedName.value = trim(fldPostedName.value);
	fldPostedMail.value = trim(fldPostedMail.value);
	if (checkMail(fldPostedMail.value, "your Email")) {
		if (checkMailsAddress(fldSharedMail.value, "your Friends' Emails")) return true;
		fldSharedMail.focus();
		return false;
	}
	fldPostedMail.focus();
	return false;
}
function applySharingAction() {
	var fldPostedName = document.getElementById('PostedName');
	var fldPostedMail = document.getElementById('PostedMail');
	var fldSharedMail = document.getElementById('SharedMail');
	fldPostedName.value = trim(fldPostedName.value);
	fldPostedMail.value = trim(fldPostedMail.value);
	if (fldPostedName.value == '') {
		alert('Please enter your Name.');
		fldPostedName.focus();
		return;
	}
	if (!checkMail(fldPostedMail.value, "your Email")) {
		fldPostedMail.focus();
		return;
	}
	if (!checkMailsAddress(fldSharedMail.value, "your Friends' Emails")) {
		fldSharedMail.focus();
		return;
	}
	var args = {
		"PostedName": document.getElementById('PostedName').value,
		"PostedMail": document.getElementById('PostedMail').value,
		"SharedMail": document.getElementById('SharedMail').value,
		"SharedMessage": document.getElementById('SharedMessage').value
	};
	var result = sendRequest("/sharelist.pl", args, "request::sharing");
	if (result) {
		panelSimple_share_list = new CPanelSimple('share_list_panel', 'share_list_arr_d', 'share_list_arr_r', 1);
	}
}
//------------------------------------------------------------------------------
// Rating
var ratingImg = new Array();
ratingImg[1] = "/images/starred.gif";
ratingImg[2] = "/images/stargrey.gif";
ratingImg[3] = "/images/starhalf.gif";

function drawRating(rating) {
	var rating10 = rating * 10;
	var k = 0, sN = 0;
	for (var i = 0; i < 50; i = i + 10) {
		k = i + 10;
		sN++;
		var el = document.getElementById("R" + sN + bl);
		if (i >= rating10 && k > rating10) el.src = ratingImg[2];
		else if (i < rating10 && k > rating10) el.src = ratingImg[3];
		else el.src = ratingImg[1];
	}
	if (!rating) rating = 'none';
	else {
		var rNum = new Number(rating);
		rating = rNum.toFixed(1);
		if (rating == Math.floor(rating)) rating = Math.floor(rating);
	}
	document.getElementById('RatingAll').innerHTML = rating;
}
function setRating(rating, own) {
	if (!allowRating) return;
	var c = "/images/star0.gif";
	var b = "/images/star1.gif";
	if (document.getElementById("Rating").value == 1 && rating == 1) {
		c = b;
		document.getElementById("Rating").value = 0;
	} else {
		document.getElementById("Rating").value = rating;
	}
	for (var i = 1; i <= maxRating; i++) {
		var el = document.getElementById("Rating" + i);
		if (i <= rating) el.src = c;
		else el.src = b;
	}
	if (own) {
		if (!rating) rating = 'none';
		else {
			var rNum = new Number(rating);
			rating = rNum.toFixed(1);
			if (rating == Math.floor(rating)) rating = Math.floor(rating);
		}
		document.getElementById('RatingYour').innerHTML = rating;
	}
}
function rateThisList(curobj, subobjstr, opt_position) {
	setRating(userRating);
	overlay(curobj, subobjstr, opt_position);
}
function applyRatingAction(elId) {
	var rating = document.getElementById('Rating').value;
	if (!rating) return false;
	var args = {'Rating': rating};
	var result = sendRequest("/saverating.pl", args);
	if (result && result.Rating) {
		drawRating(result.Rating);
		userRating = rating;
		setRating(rating, true);
		if (elId) overlayclose(elId);
	}
}
//------------------------------------------------------------------------------
// Tags 
function makeMyTags() {
	if (userSession.isLogged) {
		document.getElementById('userTagsBlock').style.display = '';
		document.getElementById('addUserTag').style.display = '';

		myTags.length = 0;
		var user = userSession.login.toLowerCase();
		var tag2edit = document.getElementsByName('tag2edit');
		var tagUser = document.getElementsByName('tagUser');
		for (var i = 0; i < tagUser.length; i++) {
			if (user == tagUser[i].value.toLowerCase()) {
				myTags.push(tag2edit[i].id.substr(4));
			}
		}
	} else {
		document.getElementById('loginIsRequiredToTag').style.display = '';
	}
	viewEditTags(true);
}
function viewEditTags(keepStatus) {
	if (!keepStatus) isTagEditMode = !isTagEditMode;
	if (!isTagEditMode) { // show preview mode
		document.getElementById("ViewTags").style.display = 'none';
		document.getElementById("DelTags").style.display = 'none';
		document.getElementById("ChngTags").style.display = '';
		for (var i = 0; i < myTags.length; i++) {
			document.getElementById("t2e_" + myTags[i]).style.display = 'none';
		}
	} else {
		document.getElementById("ChngTags").style.display = 'none';
		document.getElementById("ViewTags").style.display = '';
		document.getElementById("DelTags").style.display = '';
		for (var i = 0; i < myTags.length; i++) {
			document.getElementById("t2e_" + myTags[i]).style.display = '';
		}
	}
}
function addTag(elId) {
	var tag = trim(document.getElementById(elId).value);
	tag = trim(tag);
	if (!tag) return;
	tag = tag.replace(/\+/g, '%2B');
	applyTagsAction({'Tag': tag});
}
function ajaxDeleteTags() {
	var args = {};
	var cnt = 0;
	for (var i = 0; i < myTags.length; i++) {
		if (document.getElementById('t2e_' + myTags[i]).checked) {
			args['tag2del_' + myTags[i]] = myTags[i];
			cnt++;
		}
	}
	if (cnt == 0) return;
	if (!confirm('Delete selected tags?')) return;
	applyTagsAction(args);
}
function applyTagsAction(args) {
	var result = sendRequest("/savetags.pl", args, "request::tags");
	if (result) makeMyTags();
}
//------------------------------------------------------------------------------
// Comments
function makeMyComments() {
	if (userSession.isLogged) {
		document.getElementById('changeCommentBlock').style.display = '';
		document.getElementById('addUserComment').style.display = '';

		myComments.length = 0;
		var user = userSession.login.toLowerCase();
		var commentUser = document.getElementsByName('commentUser');
		for (var i = 0; i < commentUser.length; i++) {
			if (user == commentUser[i].value.toLowerCase()) {
				myComments.push(commentUser[i].id.substr(4));
			}
		}
	} else {
		document.getElementById('loginIsRequiredToComment').style.display = '';
	}
	viewEditComments(true);
}
function viewEditComments(keepStatus) {
	if (!keepStatus) isCommentEditMode = !isCommentEditMode;
	if (!isCommentEditMode) { // show preview mode
		document.getElementById("ChngCmnt").style.display = '';
		document.getElementById("ViewCmnt").style.display = 'none';
		for (var i = 0; i < myComments.length; i++) {
			document.getElementById("NotEditCmntId_" + myComments[i]).style.display = '';
			document.getElementById("EditCmntId_" + myComments[i]).style.display = 'none';
		}
	} else {
		document.getElementById("ChngCmnt").style.display = 'none'; 
		document.getElementById("ViewCmnt").style.display = '';
		for (var i = 0; i < myComments.length; i++) {
			document.getElementById("NotEditCmntId_" + myComments[i]).style.display = 'none';
			document.getElementById("EditCmntId_" + myComments[i]).style.display = '';
		}
	}
}
function changeComment(type, cid, elId) {
	var msg;
	if (type == 1) msg = "Save changes?";
	else msg = "Delete this comment?";
	if (!confirm(msg)) return;
	var args = {
		'Comment': ((type == 1) ? trim(document.getElementById(elId).value) : ''),
		'cid': cid
	};
	var result = sendRequest("/savecomments.pl", args, "request::messages");
	if (result) makeMyComments();
}
function addComment(elId) {
	var comment = trim(document.getElementById(elId).value);
	if (!comment) return;
	applyCommentAction({'Comment': comment});
}
function getCommentsPage(pg) {
	applyCommentAction({'pg': pg});
}
function applyCommentAction(args) {
	var result = sendRequest("/savecomments.pl", args, "request::messages");
	if (result) makeMyComments();
}
