var ajaxFrame_id = 0;
var lockedTopicVote = false;
var topicVoteData = null;
var action = '', actionData = '';
var editData = {};
var creditMembers = 0;
var totalCredits = 0;
var flashes = {};
var main_flash = false;
var fl_params = {};
var fl_options_lock = false;
var domain_ext = document.domain.match (/.*\.(com|org)/)[1];

function htmlspecialchars(str,typ)
{
	if(typeof str=="undefined") str="";
	if(typeof typ!="number") typ=2;
	typ=Math.max(0,Math.min(3,parseInt(typ)));
	var html=new Array();
	html[38]="&amp;"; html[60]="&lt;"; html[62]="&gt;";
	if(typ==1 || typ==3) html[39]="&#039;";
	if(typ==2 || typ==3) html[34]="&quot;";
	for(var i in html) eval("str=str.replace(/"+String.fromCharCode(i)+"/g,\""+html[i]+"\");");
	return str;
}

function ajax(url, vars, callbackFunction)
{
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");

	request.open("POST", url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {

			if (request.responseText){

				callbackFunction(request.responseText);
			}
		}
	}

	var parameters = '';
	if (vars != null) {
		for (var value in vars) {
			if (parameters != '') parameters+='&';
			parameters+=value+'='+encodeURI (vars[value]);
		}
		request.setRequestHeader("Content-length", parameters.length);
	}

	request.send(parameters);
}

function ajaxFrame (url)
{
	++ajaxFrame_id;

	if (url.indexOf ('?') > -1) url+='&frame_id='+ajaxFrame_id;
	else url+='?frame_id='+ajaxFrame_id;

	var iframe = document.createElement('iframe');

	iframe.setAttribute('src', url);
	iframe.setAttribute('id','ajaxFrame_'+ajaxFrame_id);
	iframe.style.display = 'none';
	document.body.appendChild (iframe);
}

function destroy_ajaxFrame (frameId)
{
	var iframe = document.getElementById ('ajaxFrame_'+frameId);
	if (navigator.appName != 'Opera') iframe.parentNode.removeChild (iframe);
}


function findPosition( oElement )
{
	if( typeof( oElement.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;
		}
		return [ posX, posY ];
	} else {
		return [ oElement.x, oElement.y ];
	}
}

function setCookie( name, value, expires, path, domain, secure )
{
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function delCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function reply_box (path, deep, topic_id, title)
{
	var elm = document.getElementById (path);
	if (document.getElementById ('post_box'+path) != null) var post = document.getElementById ('post_box'+path); else {
		var post = document.createElement('div');
		post.setAttribute('id', 'post_box'+path);
		post.innerHTML = '<form method="post" action="http://members.sharenator.'+domain_ext+'/post_it.php"><div class="lbox_in in"><div class="comtop"><div class="lb_left"></div><h2>Post a response </h2></div><div class="response"><input class="response_field"  name="title" value="'+htmlspecialchars (title, 3)+'" /><textarea name="text" rows="4" cols="10" class="response_field"></textarea><input type="hidden" value="'+path+'" name="path" /><input type="hidden" value="'+topic_id+'" name="topic_id" /></div><div class="response_bottom"><input type="submit" name="advanced" class="go_advanced" value="Go Advanced" onclick="this.parentNode.parentNode.parentNode.action=\'http://members.sharenator.'+domain_ext+'/advanced_post.php\'"/><input type="submit" class="post" value="Post" onclick="return check_login()" /></div></div></form>';
		elm.appendChild (post);
	}
	var pos = findPosition (post);
	window.scrollTo(0, pos[1] - 110);
	post.getElementsByTagName ('textarea')[0].focus ();
}

function set_login_msg ()
{
	var nick = getCookie ('nick');

	if (nick == null) {
		document.getElementById ('login_msg').innerHTML = '<b>You\'re not logged in!</b> <a href="http://members.sharenator.com/enter/">Log in</a> or <a href="http://members.sharenator.com/enter/">register</a>!';
		return;
	}
	document.getElementById ('login_msg').innerHTML = "<b>Welcome, <a style=\"text-decoration: none;\" href=\"http://www.sharenator.com/profile/"+nick+"/\">" + nick + "</a></b> (<a style=\"text-decoration: none;\" href=\"http://members.sharenator.com/logout.php\">Log Out</a>)";
	document.getElementById ('profile_link').href = 'http://www.sharenator.com/profile/'+getCookie ('nick')+'/';
	document.getElementById ('favorites_link').href = 'http://www.sharenator.com/profile/'+getCookie ('nick')+'/favorites/';
}

function favorite ()
{
	var oElement = document.getElementById ('fav_btn');
	if (getCookie ('nick') == null) {
		login_box ();
		action = 'favorite';
		return;
	}

	if (oElement.className=='favorite add') {
		// adding
		ajaxFrame ('http://members.sharenator.'+domain_ext+'/favorite.php?action=1&topic_id='+topic_id);
	} else {
		// removing
		ajaxFrame ('http://members.sharenator.'+domain_ext+'/favorite.php?action=0&topic_id='+topic_id);
	}
}

function favorited (action, frame_id)
{
	destroy_ajaxFrame (frame_id);
	var oElement = document.getElementById ('fav_btn');

	if (action == -1) {
		alert ('Oooops! Some kind of system error');
	}

	if (action == 1) {
		oElement.className = 'favorite remove';
	}

	if (action == 0) {
		oElement.className = 'favorite add';
	}
}

function setVotesInfo (votes_data, topic_data, is_favorited)
{
	for (var post_id in votes_data) {
		var vb1 = document.getElementById ('vb1_'+post_id);
		if (!vb1) continue;
		var vb2 = document.getElementById ('vb2_'+post_id);

		if ( votes_data[post_id].vote != '0') {

			var parent = vb1.parentNode || vb1.parentElement;
			if (parent.className != 'comtop') {
				vb2.style.background = 'url(/images/s.gif) -170px -993px no-repeat';
				vb1.style.borderLeft = '#c3c3c3 solid 1px';
			} else {
				vb2.style.background = 'url(/images/s.gif) -170px -524px no-repeat';
			}
			vb1.style.background = 'url(/images/s.gif) 100% -500px no-repeat';

			vb2.childNodes[0].onmouseover = function () {};
			vb2.childNodes[2].onmouseover = function () {};
			vb2.childNodes[0].onmouseout = function () {};
			vb2.childNodes[2].onmouseout = function () {};
		} else {
			vb1.style.background = '';
			vb2.style.background = '';

			vb2.childNodes[0].onmouseover = function (event) {vote_hover (this, 0, 1)};
			vb2.childNodes[0].onmouseout =  function (event) {vote_hover (this, 0, 0)};
			vb2.childNodes[2].onmouseover = function (event) {vote_hover (this, 1, 1)};
			vb2.childNodes[2].onmouseout =  function (event) {vote_hover (this, 1, 0)};
		}

		if (votes_data[post_id].vote == '-') {
			vb2.childNodes[0].style.background = 'url(/images/s.gif) -167px -286px no-repeat';
			vb2.childNodes[2].style.background = 'url(/images/s.gif) -167px -592px no-repeat';
		} else
		if (votes_data[post_id].vote == '+') {
			vb2.childNodes[2].style.background = 'url(/images/s.gif) -167px -627px no-repeat';
			vb2.childNodes[0].style.background = 'url(/images/s.gif) -154px -286px no-repeat';
		} else {
			vb2.childNodes[2].style.background = 'url(/images/s.gif) -167px -573px no-repeat';
			vb2.childNodes[0].style.background = 'url(/images/s.gif) -167px -557px no-repeat';
		}

		if (votes_data[post_id].time > topic_time) document.getElementById (post_id).innerHTML = (votes_data[post_id].votes>0)?'+'+votes_data[post_id].votes:votes_data[post_id].votes;
	}

	if (topic_data != null) {
		if (document.getElementById ('topic_votes') == undefined) return;
		if (topic_data.time > topic_time)
		document.getElementById ('topic_votes').innerHTML = topic_data.votes;

		topicVoteData = topic_data;

		// set to 0
		tv_hover ('l', 3, false);
		tv_hover ('r', 3, false);

		if (topic_data.action != 0) {
			if (topic_data.action < 0) {
				for (var i=1; i <= topic_data.action*-1; ++i) {
					document.getElementById ('tv_l'+i).className = 'v_l' + i + ' v_l' + i + '_2';
				}
			} else {
				for (var i=1; i <= topic_data.action; ++i) {
					document.getElementById ('tv_r'+i).className = 'v_r' + i + ' v_r' + i + '_2';
				}
			}
		}
	}

	if (is_favorited != null && is_favorited) {
		document.getElementById ('fav_btn').className = 'favorite remove';
	}
}

function updateVotesInfo ()
{
	var nick = getCookie ('nick');
	var key  = getCookie ('key');

	if (nick == null || key == null) return;

	var file = nick+'_'+topic_id+'_'+key;
	var url = 'http://www.sharenator.'+domain_ext+'/votes/'+file;

	ajax (url, null,
	function (responseText) {
		var votes_data = {};
		var topic_data = null;
		var is_favorited = false;
		var lines = responseText.split ("\n");
		for (var i=0; i < lines.length; ++i) {
			if (lines[i].length > 0) {
				var data = lines[i].split(';');
				if (data[0] == 'p') {
					// post
					votes_data[data[2]] = {'vote':data[1], 'votes':data[3], 'time':data[4]};
				} else
				if (data[0] == 't') {
					// topic
					topic_data = {'action':data[1], 'votes':data[2], 'time':data[3]};
				} else
				if (data[0] == 'f') {
					is_favorited = (data[1] == '1');
				}
			}
		}
		topicVoteData = topic_data;
		setVotesInfo (votes_data, topic_data, is_favorited);
	});
}

function checkPosition ()
{
	if(typeof topic_id == "undefined") return;
	if (getCookie ('mysql_error')!=null) {
		alert ("Oooops! Mysql is down");
		delCookie ('mysql_error', '/', 'sharenator.'+domain_ext)
	}
	ieFlashHack ();
	unhide_edits ();
	updateVotesInfo ();
	var post_id = getCookie ('post_scroll_id');

	if (post_id == null) return;
	var pos = findPosition (document.getElementById (post_id));
	window.scrollTo(0, pos[1] - 10);

	delCookie ('post_scroll_id', '/', 'sharenator.'+domain_ext);
}

function unhide_edits ()
{
	var nick = getCookie ('nick');
	if (nick != null) {
		var edits = document.getElementsByName (getCookie ('nick'));
		for (var i=0; i<edits.length; ++i) {
			edits[i].style.display = '';
		}
	}
}

function vote (post_id, votes)
{
	if (getCookie ('nick') == null) {
		login_box ();
		action = 'vote';
		actionData = {'post_id':post_id, 'votes':votes};
		return;
	}
	ajaxFrame ('http://members.sharenator.'+domain_ext+'/vote.php?post_id='+post_id+'&votes='+votes+'&topic_id='+topic_id);
}

function voted (data, post_id, symbol, frame_id)
{
	destroy_ajaxFrame (frame_id);
	if (!parseInt(data) && data != 0) {
		if (data == "ERR_MYSQL") {
			alert ("Oooops! Mysql is down");
		} else {
			alert ('ERROR: '+data);
		}
		return;
	}

	var vinfo = {};
	vinfo[post_id] = {'vote':symbol, 'votes':data, 'time':topic_time+1};
	setVotesInfo (vinfo);
}

function topic_vote (votes)
{
	if (lockedTopicVote) return;
	if (getCookie ('nick') == null) {
		login_box ();
		action = 'topic_vote';
		actionData = {'votes': votes};
		lockedTopicVote = true;
		return;
	}

	lockedTopicVote = true;
	ajaxFrame ('http://members.sharenator.'+domain_ext+'/topic_vote.php?post_id=0&votes='+votes+'&topic_id='+topic_id);
}

function topic_voted (action, votes, frame_id)
{
	if (votes == "ERR_MYSQL") {
		alert ("Oooops! Mysql is down");
		lockedTopicVote = false;
		destroy_ajaxFrame (frame_id);

		return;
	}
	destroy_ajaxFrame (frame_id);
	topicVoteData = {'action':action, 'votes':votes, 'time':topic_time+1};
	setVotesInfo (null, topicVoteData);
	lockedTopicVote = false;
}

function scrollPositionY ()
{
	var Y = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape, Opera
		Y = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		Y = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE sux
		Y = document.documentElement.scrollTop;
	}
	return Y;
}

function pageHeight ()
{
	t1 = document.body.scrollHeight;
	t2 = document.body.offsetHeight;

	return (t1>t2)?document.body.scrollHeight:document.body.offsetHeight+10;
}

function close_box ()
{
	var div = document.getElementById ('transparent_body');
	document.body.removeChild (div);
	var div = document.getElementById ('login_layer');
	document.body.removeChild (div);
	window.onscroll = function () {};
	if (lockedTopicVote) lockedTopicVote = false;
	if (main_flash) load_main_flash ();
}

function login_box ()
{
	close_flashes ();
	var box_html = '<div class="login_box" style="height: 330px;"><div class="left">\
			<div class="rt"><div class="rt_right"></div></div>	\
			<div class="lbox">	\
			<form action="http://members.sharenator.'+domain_ext+'/register.php" target="actionFrame" method="POST">\
			<div class="comtop"><div class="lb_left"></div><h2>Register</h2></div>\
				<div class="response" style="height:250px;">\
				<div class="reg_left">\
					Username:<br />\
					<input class="register_field" name="username" value=""><br />\
					Password:<br />\
					<input class="register_field" name="pass1" value="" type="password"><br />\
					Retype password:<br />\
					<input class="register_field" name="pass2" value="" type="password"><br />\
					e-mail (<b>optional</b>):<br />\
					<input class="register_field" name="email" value=""><br /><br />\
					<input type="checkbox" name="remember_me" checked/> Remember me	<br />\
					<input type="checkbox" name="acc_rules"/> I accept the <a href="http://www.sharenator.com/rules.html" target="_blank">Rules</a>.\
				</div>\
				<div class="reg_right"><br />\
					<div id="register_err">\
					<p class="space">\
					<b>Registration is quick and easy</b><br /><br /></p>\
					<p class="space">Once you have entered your username and password, you will be able to login and use your account instantly.<br /><br />\
					By entering your e-mail address you will receive important notifications about your account. If you forget your account password, your details will be sent to this email address.\
				</p>\
				</div>\
				</div></div>\
				<div class="response_bottom"><input type="submit" class="post" name="register" value="Register >>" /></div>\
			</div>\
			</form>\
			<div class="brt"><div class="brt_right"></div></div>\
		</div>\
		<div class="right">\
		<div class="rt"><div class="rt_right"></div></div>\
			<div class="right_articles">\
			<form action="http://members.sharenator.'+domain_ext+'/login.php" target="actionFrame"  method="POST">\
				<p><b>Have an account already? Log in:</b> </p>\
				<p class="space">\
					Username:<br />\
					<input type="hidden" name="ajax_login">\
					<input class="login_field" name="username" value=""><br />\
					Password:<br />\
					<input class="login_field" name="password" value="" type="password"><br />\
					<input type="checkbox" name="remember_me" checked /> Remember me	<br />\
					<div id="login_error" style="color:red"></div>\
					<br />\
<div class="response_bottom"><p class="space"><input type="submit" class="post" style="float:left" value="Login >>" /></p></div>\
</form>\
<iframe name="actionFrame" style="display: none"></iframe>\
<br />\
</p>\
<br><br><center>[<a href="#" onclick="close_box(); return false;">CLOSE WINDOW</a>]</center>\
</div>\
<div class="brt2"><div class="brt_right"></div></div>\
	</div></div></div>';

	var divBox = document.createElement('div');

	divBox.setAttribute ('id', 'transparent_body');
	//divBox.style.top = scrollPositionY ()+'px';
	divBox.style.height = pageHeight ()+'px';

	var layer = document.createElement('div');

	function setLayerPosition ()
	{
		var Y = scrollPositionY ();
		var pHeight = pageHeight ();

		document.getElementById ('login_layer').style.top = (Y+100)+'px';
	}

	layer.setAttribute ('id', 'login_layer');
	layer.innerHTML = box_html;
	document.body.appendChild (layer);
	document.body.appendChild (divBox);
	setLayerPosition ();

	window.onscroll = setLayerPosition;
}

function exec_act ()
{
	if (action == 'vote') {
		vote (actionData.post_id, actionData.votes);
	}
	if (action == 'topic_vote') {
		lockedTopicVote = false;
		topic_vote (actionData.votes);
	}
}

function set_success_login_msg (username)
{
	var layer = document.getElementById ('login_layer');
	layer.innerHTML = '<div class="login_box" style="height: 170px; width: 400px;">\
	<div class="rt"><div class="rt_right"></div></div>\
			<div class="lbox">\
			<div class="comtop"><div class="lb_left"></div><h2>Welcome!</h2></div>\
			<p class="space">You are now logged in as <b>'+username+'</b>. You can continue doing whatever you were doing before this login box interrupted you. <br /><br /></p>\
			<center>(<a href="" onclick="checkPosition(); exec_act (); close_box(); return false;">Close this window</a>)</center>\
			</div>\
			<div class="brt"><div class="brt_right"></div></div></div>';

	if (document.getElementById ('visits_count')) document.getElementById ('visits_count').innerHTML = '';
}

function ajax_login (success_login, username)
{
	if (!success_login) {
		document.getElementById ('login_error').innerHTML = 'Wrong Username or Password';
	} else {
		set_login_msg ();
		set_success_login_msg (username);
	}
}

function ajax_register (success, username, errors)
{
	if (!success) {
		document.getElementById ('register_err').innerHTML = errors;
		document.getElementById ('register_err').style.color = 'red';
	} else {
		set_login_msg ();
		set_success_login_msg (username);
	}
}

function check_login ()
{
	if (getCookie ('nick') == null) {
		action = '';
		login_box ();
		return false;
	}
	return true;
}

function closeEdit (post_id)
{
	var rBody = document.getElementById ('body_'+post_id);
	rBody.innerHTML = editData[post_id];
}

function onEdit (responseText) {
	if (responseText == 'mysql_error') {
		alert ('Oooops! Mysql is down');
		return;
	}
	data+="\n";
	var data = responseText.split ("\n", 3);

	var post_id = data[0];
	var title = data[1];
	var original = responseText.substr (post_id.length + title.length+2);

	var rBody = document.getElementById ('body_'+post_id);
	editData[post_id] = rBody.innerHTML;

	rBody.innerHTML = '<div class="comtop"><div class="lb_left"></div><h2>Edit a response </h2></div>\
	<form action="http://members.sharenator.'+domain_ext+'/edit_it.php" method="post">\
	<div class="response">\
	<input type="hidden" name="post_id" value="'+post_id+'">\
	<input type="hidden" name="topic_id" value="'+topic_id+'">\
	<input class="response_field" name="title" value="'+title+'">\
		<textarea rows="4" class="response_field" name="text">'+original+'</textarea>\
		<div class="response_bottom"><input type="submit" name="advanced" class="go_advanced" value="Go Advanced" onclick="this.parentNode.parentNode.parentNode.action=\'http://members.sharenator.'+domain_ext+'/advanced_edit.php\'"><input type="submit" value="Cancel" class="post" onclick="return closeEdit ('+post_id+');"><input type="submit" value="Save Changes" class="post"></div></form>';

	rBody.getElementsByTagName ('textarea')[0].focus();
}

function editResponse (post_id)
{
	/*
	var titleEl = document.getElementById ('title_'+post_id);
	titleEl.innerHTML = '<form><input type="text" class="input_search">';
	*/

	ajax ('http://www.sharenator.'+domain_ext+'/response_text.php?id='+post_id, null, onEdit);
}

function editPost ()
{
	if (domain_ext == 'org') alert ('Sorry, you can\'t edit Original Post');
	else document.location = 'http://members.sharenator.com/edit_topic.php?id='+topic_id;
}

function credits_add_field (member, percentage)
{
	++creditMembers;
	document.getElementById ('creditUsers').value = creditMembers;

	var member_code = document.getElementById ('read_member').cloneNode(true);
	member_code.id = 'member_'+creditMembers;
	member_code.style.display = 'block';
	var new_member = member_code.childNodes;
	for (var i=0; i < new_member.length; ++i) {
		var theName = new_member[i].name
		if (new_member[i].id) new_member[i].innerHTML = creditMembers;
		if (theName) {
			new_member[i].name = theName + creditMembers;
			if (theName == 'member_username' && member != undefined) new_member[i].value = member;
			if (theName == 'member_percentage' && percentage != undefined) new_member[i].value = percentage;
		}
	}
	var insertHere = document.getElementById('write_member');
	insertHere.parentNode.insertBefore(member_code,insertHere);
}

function credits_remove_field (self)
{
	--creditMembers;
	document.getElementById ('creditUsers').value = creditMembers;

	var number = -1;
	for (var i=0; i < self.childNodes.length; ++i) {
		if (self.childNodes[i].id) number = self.childNodes[i].innerHTML;
	}
	self.parentNode.removeChild (self);

	number = parseInt (number);
	if (number <= creditMembers) {
		for (var i=number+1; i<=creditMembers+1; ++i) {
			var member = document.getElementById ('member_'+i);
			member.id = 'member_'+(i-1);
			for (var n=0; n < self.childNodes.length; ++n) {
				if (member.childNodes[n].id) member.childNodes[n].innerHTML = i-1;
				if (member.childNodes[n].name) member.childNodes[n].name=member.childNodes[n].name.replace (/\d/g, '')+(i-1);
			}
		}
	}

	count_credits ();
}

function post_topic ()
{
	return (check_login() && count_credits (true));
}

function count_credits (check_empty)
{
	totalCredits = 0;
	for (var i=1; i<=creditMembers; ++i) {
		var member = document.getElementById ('member_'+i);
		for (var n=0; n<member.childNodes.length; ++n) {
			if (member.childNodes[n].name && member.childNodes[n].name.substr (0, 17) == 'member_percentage') {
				var value = member.childNodes[n].value;
				// check if value is numeric
				if (! (check_empty?value.match ( /^\d+$/ ):value.match ( /^\d*$/ )) ) {
					// set bad input message
					document.getElementById ('credits_msg').innerHTML = '<font color="red">Bad input data</font>';
					return false;
				}
				if (!parseInt (value)) {
					document.getElementById ('credits_msg').innerHTML = '&nbsp;';
					return false;
				}
				totalCredits+=parseInt (value);
			}
		}
	}
	var result = false;
	var msg = '';
	if (totalCredits > 99) {
		msg = '<font color="red">You can\'t give more than 99 percents of points</font>';
		result = false;
	}
	else {
		msg = 'Points you will gain: '+(100-totalCredits)+'%.';
		result = true;
	}

	document.getElementById ('credits_msg').innerHTML = msg;
	return result;
}

function set_credits_msg (msg)
{
	document.getElementById ('credits_msg').innerHTML = '<font color="red">'+msg+'</font>';
}


function update_time ()
{
	var dateParts = currentDate.match (/^(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
	var currentTime = new Date (dateParts[1], dateParts[2]-1, dateParts[3], dateParts[4], dateParts[5]).getTime ()/1000;

	var htmlObj = document.getElementsByTagName ('span');
	for (var i=0; i<htmlObj.length; ++i) {
		if (htmlObj[i].id && htmlObj[i].id == 'timestamp') {
			strDate = htmlObj[i].innerHTML;
			var dateParts = strDate.match (/^(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
			if (!dateParts) continue;
			var oDate = new Date (dateParts[1], dateParts[2]-1, dateParts[3], dateParts[4], dateParts[5]);

			var timeStamp = oDate.getTime ()/1000;

			var difference = currentTime - timeStamp;

			var text = '';
			var value = 0;

			if (difference/60 < 60) {
				// show minutes
				value = Math.floor(difference/60);
				if (value <= 0) text = 'Just now';
				else
				if (value == 1) text = value+' minute ago';
				else text = value+' minutes ago';
			} else
			if (difference/3600 < 24) {
				// show hours
				value = Math.floor(difference/3600);
				if (value == 1) text = value+' hour ago';
				else text = value+' hours ago';
			} else
			if (difference/86400 < 30) {
				// show days
				value = Math.floor(difference/86400);
				if (value == 1) text = value+' day ago';
				else text = value+' days ago';
			} else
			if (difference/2592000 < 12) {
				// show months
				value = Math.floor(difference/2592000);
				if (value == 1) text = value+' month ago';
				else text = value+' months ago';
			} else {
				// show years
				value = Math.floor(difference/31104000);
				if (value == 1) text = value+' year ago';
				else text = value+' years ago';
			}

			htmlObj[i].innerHTML = text;
		}
	}
}

function edit_profile (username, is_favorite)
{
	var nick = getCookie('nick');
	if (nick == null) return;
	if (username.toLowerCase() == nick.toLowerCase()) {
		if (document.getElementById ('edit_profile')) document.getElementById ('edit_profile').style.display = '';

		if (!is_favorite) {
			document.getElementById ('profile_menu').childNodes[0].innerHTML = '<b>Profile</b>';
			document.getElementById ('profile_menu').className = 'li_current';
			document.getElementById ('profile_menu').innerHTML+='<span class="cl"></span>';
		} else {
			document.getElementById ('favorites_menu').childNodes[0].innerHTML = '<b>Favorites</b>';
			document.getElementById ('favorites_menu').className = 'li_current';
			document.getElementById ('favorites_menu').innerHTML+='<span class="cl"></span>';
		}
	}
}

function profile_view ()
{
	if (!check_login ()) return false;

	document.location = 'http://www.sharenator.com/profile/'+getCookie ('nick')+'/';

	return false;
}

function rankFind ()
{
	var query = document.getElementById ('login_box').value;
	query = query.replace (/[^a-zA-Z0-9]/g, '');
	document.getElementById ('login_box').value = query;
	if (query.length < 4) {
		document.getElementById ('search_error').innerHTML = '<br>Username must be at least 4 symbols length';
	} else {
		document.location = 'http://www.sharenator.com/ranks/'+query + '/';
	}
}

function close_flashes ()
{
	for (var id in flashes) {
		var p_tags = document.getElementsByTagName ('p');
		for (var i=0; i<p_tags.length; ++i) {
			if (p_tags[i].id == id) {
				p_tags[i].innerHTML = flashes[id].html;
				p_tags[i].onclick   = flashes[id].click;
			}
			document.getElementById (id).innerHTML = flashes[id].html;
			document.getElementById (id).onclick = flashes[id].click;
		}
	}
}

function load_main_flash ()
{
	main_flash = true;
	document.getElementById ('flash_1').onclick ();
}

function load_flash (self, url, width, height)
{
	flashes [self.id] = {html:self.innerHTML, click:self.onclick};
	self.innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+width+'" height="'+height+'">\
	<param name="movie" value="'+url+'"></param><embed src="'+url+'" type="application/x-shockwave-flash" quality="high" width="'+width+'" height="'+height+'" menu="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
	self.onclick = function () {};
}

function flash_options (self, url, width, height, post_id)
{
	if (fl_options_lock) return;
	fl_options_lock = true;
	fl_params = {'fl_object':self, 'url':url, 'width': width, 'height':height};

	var layer = document.createElement('div');
	layer.setAttribute ('id', 'fl_options_box');
	layer.className = 'flash_layer';
	var pos = findPosition (self);
	var x = pos[0] + (self.offsetWidth-400)/2;
	var y = pos[1] + (self.offsetHeight-60)/2;

	layer.style.top = y+'px';
	layer.style.left = x+'px';
	layer.style.width = '500px';

	var flash_id = url.match (/http:\/\/files.sharenator.com\/redirect-(\d+)/i);
	if (flash_id == null) {
		flash_id = url.match (/http:\/\/files\.sharenator\.com\/(?:.*)-(\d+).swf/i);
	}
	if (flash_id != null) flash_id = flash_id[1];

	var new_window_url = ((post_id != null)?post_id+'/':'') + flash_id + '.html';

	layer.innerHTML = '<div class="flash_options"><a href="" onclick="fl_options_load(); return false;">Load Flash</a>&nbsp&nbsp<a href="'+new_window_url+'">New Window</a>&nbsp&nbsp<a href="" onclick="fl_options_close(); return false;">Close</a></div>';
	document.body.appendChild (layer);
}

function fl_options_close ()
{
	var fl_box = document.getElementById ('fl_options_box');
	document.body.removeChild (fl_box);
	fl_options_lock = false;
}

function fl_options_load ()
{
	fl_options_close ();
	load_flash (fl_params.fl_object, fl_params.url, fl_params.width, fl_params.height);
}

function vote_hover (self, action, over)
{
	if (action) {
		if (over) self.style.background = 'url(/images/s.gif) -167px -609px no-repeat'; // plus hover
		else self.style.background = 'url(/images/s.gif) -167px -573px no-repeat'; // plus
	} else {
		if (over) self.style.background = 'url(/images/s.gif) -167px -543px no-repeat'; // minus hover
		else self.style.background = 'url(/images/s.gif) -167px -557px no-repeat'; // minus
	}

}

function tv_reset (ignoreData)
{
	if (ignoreData == null && topicVoteData != null) setVotesInfo (null, topicVoteData);
	else {
		tv_hover ('l', 3, false);
		tv_hover ('r', 3, false);
	}
}

function tv_hover (direction, length, on, reset)
{
	if (reset) tv_reset (true);
	if (length > 0) {
		var color = (direction=='r')?'#6EAF20':'#FF6446';
		document.getElementById ('votenum').innerHTML = '<span style="color: '+color+'">'+((direction=='r')?'+':'-')+length+"</span>";
		for (var i=1; i<=length; ++i) {
			var el = document.getElementById ('tv_'+direction+i);
			if (on) {
				el.className = 'v_' + direction + i + ' v_' + direction + i + '_3';
			} else {
				el.className = 'v_' + direction + i + ' v_' + direction + i + '_1';
			}
		}
	}
	if (!on) document.getElementById ('votenum').innerHTML = '';
}

function visits_count ()
{
	if (getCookie ('nick') != null) return;
	var visits = getCookie ('visits');
	if (visits == null) visits = 1;
	else ++visits;

	setCookie('visits', visits, 366*10, '/', 'sharenator.'+domain_ext);

	var box = '<div class="rt"><div class="rt_right"></div></div>\
		<div class="right_articles">\
				<p><b>It\'s your #'+visits+' visit here. '+(visits>1?'It\'s about time to stop lurking!':'')+'</b></p>\
				<p>Sharenator.com is all about sharing, voting, competing and simply having fun. Who\'s the best at posting the coolest stuff? Join now and benefit from all of sharenator\'s features available only to members. Be the Sharenator!</p>\
			<p><a href="#" onclick="login_box(); return false;"><u><b>Click to join</b></u></a> - it\'s quick and easy.<br>\
			Have an account already? <a href="#" onclick="login_box(); return false;"><u>Log-in here</u></a>.</p>\
			</div>\
			<div class="brt2"><div class="brt_right"></div></div>';

	document.getElementById ('visits_count').innerHTML = box;
}

function googleTopAd (mode)
{
	if (mode == 0) {
		// channel
		if (typeof rUserChannel != 'undefined') return rUserChannel;
		if (getCookie ('rWebChannel')  != null) return getCookie ('rWebChannel');
		return '7238073075'; // default channel
	}
	if (mode == 1) {
		// publisher id
		if (typeof rUserPublish != 'undefined')          return rUserPublish;
		if (getCookie ('rWebPublish')  != null) return getCookie ('rWebPublish');
		return 'pub-1852068214622502'; // default publisher
	}
}

function googleRightAd (mode)
{
	if (mode == 0) {
		// channel
		if (getCookie ('rWebChannel')  != null) return getCookie ('rWebChannel');
		return '7238073075'; // default channel
	}
	if (mode == 1) {
		// publisher id
		if (getCookie ('rWebPublish')  != null) return getCookie ('rWebPublish');
		return 'pub-1852068214622502'; // default publisher
	}
}

function ieFlashHack ()
{
	if (navigator.appName == 'Microsoft Internet Explorer') {
		objects = document.getElementsByTagName("object");
		for (var i = 0; i < objects.length; i++) {
			if (objects[i].parentElement.tagName.toLowerCase() != 'p')
			objects[i].outerHTML = objects[i].outerHTML;
		}
	}
}

function unhide_post (self, html)
{
	var p = self;
	for (var i=0;i<2;++i) {
		p = p.parentNode || p.parentElement;
	}
	for (var i=0;i<p.childNodes.length; ++i) {
		if (p.childNodes[i].id == 'hdiv') {
			p.childNodes[i].style.display = '';
			p.childNodes[i].innerHTML+=html;
			unhide_edits ();
			update_time ();
		}
	}
	(self.parentNode || self.parentElement).innerHTML = '';
}

function check_org_login ()
{
	var nick = getCookie ('nick');
	var key = getCookie ('key');
	if (nick==null) {
		var iframe = document.createElement('iframe');
		iframe.setAttribute('src', 'http://members.sharenator.com/get.html');
		iframe.setAttribute('id','sessionFrame');
		iframe.style.display = 'none';
		document.body.appendChild (iframe);
	}
}

function check_com_login ()
{
	var nick = getCookie ('nick');
	var key = getCookie ('key');
	if (nick==null) {
		var iframe = document.createElement('iframe');
		iframe.setAttribute('src', 'http://members.sharenator.org/get.html');
		iframe.setAttribute('id','sessionFrame');
		iframe.style.display = 'none';
		document.body.appendChild (iframe);
	}
}

function random_button ()
{
	var flash = document.getElementsByName ('random_flash')[0].checked;
	var videos = document.getElementsByName ('random_videos')[0].checked;
	var pics = document.getElementsByName ('random_pics')[0].checked;

	if (!flash && !videos && !pics) {
		alert ('You have to select at least one category');
		return false;
	}

	var params = '';
	if (flash) params+= 'flash=1';
	if (flash && videos) params+='&';
	if (videos) params+= 'videos=1';
	if ((flash || videos) && pics) params+='&';
	if (pics) params+= 'pics=1';

	document.location = "http://members.sharenator.com/random.php?"+params;

	return false;
}

function random_button_link ()
{
	var flash = getCookie('ignore_flash')==null;
	var videos = getCookie('ignore_videos')==null;
	var pics = getCookie('ignore_pics')==null;

	if (!flash && !videos && !pics) {
		alert ('You have to select at least one category');
		return false;
	}

	var params = '';
	if (flash) params+= 'flash=1';
	if (flash && videos) params+='&';
	if (videos) params+= 'videos=1';
	if ((flash || videos) && pics) params+='&';
	if (pics) params+= 'pics=1';

	document.location = "http://members.sharenator.com/random.php?"+params;

	return false;
}

function set_category (self)
{
	var name = self.name.substr (7)

	var com_url = 'http://www.sharenator.com/set_category.php?'+name+'='+(self.checked+0);
	var iframe = document.createElement('iframe');
	iframe.setAttribute('src', com_url);
	iframe.setAttribute('id','setCategoryFrameCom');
	iframe.style.display = 'none';
	document.body.appendChild (iframe);

	var org_url = 'http://www.sharenator.org/set_category.php?'+name+'='+(self.checked+0);
	var iframe = document.createElement('iframe');
	iframe.setAttribute('src', org_url);
	iframe.setAttribute('id','setCategoryFrameOrg');
	iframe.style.display = 'none';
	document.body.appendChild (iframe);
}