function changeLang(lg){
	if(lg!=lang)
		$('div#alert').load(host+'ajax/',{url:'language', lang:lg}, function(response){ window.location.reload(); });
	return false;
}

function alert(msg) {
  if(openIMGfired){
	restoreDefaultAlert();
  }
  $('#alert')
    .jqmShow()
	.find('a.jqmClose').css('display','block').end()
    .find('div.jqmAlertContent')
      .html(msg);
 }
 function status(msg) {
  if(openIMGfired){
	restoreDefaultAlert();
  }
  if(msg==null){
	$('#alert').hide();
	return false;
  }
  $('#alert')
    .jqmShow()
  	.find('a.jqmClose').hide().end()
    .find('div.jqmAlertContent')
      .html(msg);
 }

function blockscreen(){
	$('body').append('<div id="blockscreen" style="position:absolute;z-index:1999;left:0;top:0;height:'+$(document).height()+'px;width:'+$(document).width()+'px;">&nbsp;</div>');
}
function unblockscreen(){
	$('#blockscreen').remove();
}

function login(){
	status(LANG.login.authorizing);
	var pw = $('input#password').val();
	var user = $('input#login').val();
	if(pw.length<3 || pw.length>16 || user.length>16 || user.length<3 || !/^[a-zA-Z0-9\-_\.]+/.test(user)){
		alert(LANG.login.wrong);
		return false;
	}
	var result = $.ajax({url:host+'/login/',data:{page:'login',login:user, password:pw } , type:'POST', async:false}).responseText;
	result = eval('(' + result + ')');
	if(!result.auth){
		alert(result.error_message);
		return false;
	}
	status(LANG.login.done);
	window.location.reload();
	return true;
}

function logout(){
	status(LANG.login.quit);
	var result = $.ajax({url:host+'/login/',data:{"logout": "please"} , type:'POST', async:false}).responseText;
	result = eval('(' + result + ')');
	if(result.logout){
		status(LANG.login.reload);
		window.location.reload();
	} else {
		alert(result.error_message);
	}
	return false;
}

function vote(id,aid){
	var poll = parseInt(id);
	var answer_id = parseInt(aid);
	$.post(host + 'polls/', { "id": poll, "answer_id": answer_id }, function(res){
			if(res.success && res.data) {
				for(var a in res.data.answers) {
					a = res.data.answers[a];
					var answerDiv = $("#answer_" + a.id);
					answerDiv.find('.percentage_bar > img').attr("width", a.percentage);
					answerDiv.find('.amount').text(a.votes);
				}
			}
		}, "json")

	return false;
}

/* Comments */
function addComment(id){
	var comment = $('textarea#comment').val();
	id = parseInt(id);
	if(comment.length>0){
		$('div#comment_form').hide();
		$('div#center div.loader').show();
		blockscreen();
		$.post(document.URL,{ "id":id, "comment":comment}, 
			function(result){
				$('div#center div.loader').hide();$('div#comment_form').show();unblockscreen();
				if(result.comments){
					$('div#comments').html(result.comments);
				}
			}, "json"
		);
		$('textarea#comment').val('');
	}
	return false;
}
function editComment(id,cid){
	cid = parseInt(cid);
	var comment = $('div#comment_'+cid).html();
	$('div#moderator').hide();
	if(typeof myParser == 'undefined'){
		myParser = new BBCode({tagsSingle:["img", "br", "hr"]});
 
 
                        myParser.addRule({
                            appliesToHTML:function(el){return (el.tagName.toLowerCase() == "a" && typeof el.href !== "undefined");},
                            toBBStart:function(el){
                                    return "[url="+ (el.href.indexOf(" ")>=0?"\""+el.href+"\"":el.href) +"]";
                             },toBBEnd:function(el){
                                     return "[/url]";
                        },
                        appliesToBB:function(el){return el.data.tag == "url"},
                        toHTMLStart:function(el){
                            return '<a href="'+el.data.params.url+'">'},
                        toHTMLEnd:'</a>'
                        });
 
 
 
                        myParser.addRule({
                            appliesToHTML:function(el){return el.tagName.toLowerCase() == "strong" ||el.tagName.toLowerCase() == "b"  ;},
                            toBBStart:"[b]",toBBEnd:"[/b]",
                            appliesToBB:function(el){return el.data.tag== "b" ;},
                            toHTMLStart:'<b>',
                            toHTMLEnd:'</b>'
                        });
					
 myParser.addRule({
                            appliesToHTML:function(el){return el.tagName.toLowerCase() == "u" ;},
                            toBBStart:"[u]",
                            toBBEnd:"[/u]",
                            appliesToBB:function(el){return el.data.tag=="u";},
                            toHTMLStart:"<u>",
                            toHTMLEnd:'</u>'
 
                    });
					myParser.addRule({
                            appliesToHTML:function(el){return el.tagName.toLowerCase() == "img" ;},
                            toBBContent:function(el){return "[img="+el.src+"]"},
                            appliesToBB:function(el){return el.data.tag=="img";},
                            toHTMLContent:function(el){return "<img src=\""+el.data.params.img+"\">";}
 
                    });
					myParser.addRule({
                            appliesToHTML:function(el){return el.tagName.toLowerCase() == "br" ;},
                            toBBContent:function(el){return ""},
                            appliesToBB:function(el){return el.data.tag=="[br]";},
                            toHTMLContent:function(el){return "<br />";}
 
                    });
					myParser.addRule({
                            appliesToHTML:function(el){return el.tagName.toLowerCase() == "hr" ;},
                            toBBContent:function(el){return "-----"},
                            appliesToBB:function(el){return el.data.tag=="-----";},
                            toHTMLContent:function(el){return "<hr />";}
 
                    });
					
					};
	$('div#comment_'+cid).html('<textarea style="background-color:#D1D1D1;border:0;width:100%;height:100px;" id="comment_edit"></textarea>');
	$('textarea#comment_edit').val($.trim(myParser.toBBCode(comment)));	
	document.getElementById('comment_edit').focus();
	$('textarea#comment_edit').blur(function(){
			$('div#comment_form').hide();
			$('div#center div.loader').show();
			document.getElementById('comment_edit').disabled = 1;
			blockscreen();
			$.post(document.URL, {url:'editComment', "id":id, "cid":cid, "comment":$(this).val()},
				function(result){
					var text = $('textarea#comment_edit').val(); $('textarea#comment_edit').parent().html(text.replace(/\</g,'&lt;').replace(/\>/g,'&gt;').replace(/\n/g,'<br />\n')); $('div#center div.loader').hide();$('div#comment_form').show();unblockscreen();
					if(result.comments){
						$('div#comments').html(result.comments);
					}
				}, "json"
			);	

		});
	return false;
}
function deleteComment(section,id){
	id = parseInt(id);
	$('div#comment_form').hide();
	$('div#center div.loader').show();
	blockscreen();
	$.post(document.URL ,{"id": section, "did":id}, 
		function(result){
			$('div#center div.loader').hide();$('div#comment_form').show();unblockscreen();
			if(result.comments){
				$('div#comments').html(result.comments);
			}
		}, "json"
	);
	
	return false;
}
function deletePost(id){
	id = parseInt(id);
	$('div#comment_form').hide();
	$('div#center div.loader').show();
	blockscreen();
	$.post(document.URL ,{"post_delete": true, "post_id": id }, 
		function(result){
			$('div#center div.loader').hide();$('div#comment_form').show();unblockscreen();
			if(result == "deleted"){
				window.location.href = host + "forum/";
			}
		}//, "json"
	);
	
	return false;
}
/* Forum */
function addThread(){
	var title = $('input#thread_title').val();	
	var body = $('textarea#thread').val();
	if(title.length>0 && body.length>0){
		$('div#thread_form').hide();
		$('div#center div.loader').show();
		blockscreen();
		$('div#dumb').load(document.URL, {title:title, body:body}, function(response){ if(parseInt(response)>0){window.location.href = host+'forum/'+parseInt(response)+'/';}else{$('div#center div.loader').hide();$('div#thread_form').show();unblockscreen();} });	
	}

	return false;	
}
var editing_thread = false;
function editThread(id){
	if(editing_thread){
		return false;
	}
	var text = $('div.textbox:first > div.textbox_content > div').text();
	var title = $('div#center > div:eq(1)').text();
	$('div#moderator').hide();
	$('div#comments').hide();
	$('div#comment_form').hide();
	$('div.textbox:first > div.textbox_content > div').html('<textarea style="background-color:transparent;border:0;width:100%;height:100px;" id="thread_edit"></textarea>');
	$('div#center > div:eq(1)').html('<input type="text" id="topic" name="topic" value="'+title+'" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);" />');
	$('textarea#thread_edit').val($.trim(text));	
	document.getElementById('thread_edit').focus();
	$('div#comments').before('<div style="clear:left;display:block;margin-left:10px;" id="save_thread"><a href="#save" onclick="return saveThread('+id+');"><img src="'+host+'img/'+lang+'/button_save.gif" alt="" /></a></div>');
	editing_thread = true;
	return false;
}
function deleteThread(id){
	$('div#comments').hide();
	$('div#comment_form').hide();
	$('div#center div.loader').show();
	blockscreen();
	$.post(host+'ajax/',{url:'deleteThread',id:id},function(r){if(r=='true'){window.location.href = host+'forum/';}});
	return false;
}
function saveThread(id){
	$('div#center div.loader').show();
	blockscreen();
	var text = $('textarea#thread_edit').val();
	var title = $('input#topic').val();
	$.post(host+'ajax/',{url:'editThread',id:parseInt(id),title:title,body:text},function(r){if(r!='true'){} else { window.location.reload(); }});
	return false;
}
/* User */
var ui_enabled = true;
var avatar_uploading = false;
function editUser(){
	if(!ui_enabled)return false;
	ui_enabled = false;
	$('div#comments').hide();
	$('div#comment_form').hide();

	//Loading special area
	$.getScript(host+'scripts/jquery.fileupload.js',function(){
		$('div#user_action').html('<div id="browse_avatar" style="float:none;margin-bottom:-8px;position:relative;z-index:51;"><img style="cursor:pointer;" src="'+host+'img/'+lang+'/button_browse.gif" height="15" alt="" /><img height="12" style="display:none;" class="loader" width="100" alt="" src="'+host+'img/loader.gif"/><br /><span style="color:gray">'+LANG.user.avatar+'</span></div>');
		var upload = new AjaxUpload($('div#browse_avatar > img'), {action: host+'ajax/', name:'avatar', data:{url:'upload_avatar',HTTP_X_REQUESTED_WITH:1}, 
			onSubmit:function(file,ext){
				if(ext!='jpg' && ext!='png' && ext!='jpeg' && ext!='gif'){ return false; }
				$('div#browse_avatar > img:first').hide();
				$('div#browse_avatar > img.loader').show();
				avatar_uploading = true;
			},
			onComplete: function(file,response){
				if(ui_enabled==false){
					$('div#browse_avatar > img:first').show();
					$('div#browse_avatar > img.loader').hide();
				} else {
					$('div#browse_avatar').remove();
				}
				avatar_uploading = false;
				
				if(response.substr(0,4)=='true'){
					document.getElementById('avatarimg').src = host + "userfiles/img/content/user/thumb_" + response.substr(4) + ".png";
				} else {
					return false;
				}
			}
		});
	});

	// Setting textarea 
	var user_info = $.trim($('div#user_info').text());
	$('div#user_info').html('<textarea style="background-color:transparent;border:0;width:100%;height:100px;" id="user_info_edit"></textarea>');
	$('textarea#user_info_edit').val(user_info);

	var name = $.trim($('div#name').text());
	$('div#name').html('<input type="text" name="name" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;" />');
	$('div#name > input').val(name);

	var age = $.trim($('div#age').text());
	$('div#age').html('<input type="text" name="age" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;" />');
	$('div#age > input').val(age);

	var gender  = $.trim($('div#gender').text());
	$('div#gender').html('<div style="margin-top:-3px;"><input type="radio" name="gender" value="male" style="background-color:transparent;" />'+LANG.user.male+' <input type="radio" name="gender" style="background-color:transparent;" value="female" />'+LANG.user.female+'</div>');
	if(gender.toLowerCase()=='male'){
		$('div#gender > div > input[value="male"]').attr("checked","1");
	} else if(gender.toLowerCase()=='female'){		
		$('div#gender > div > input[value="female"]').attr("checked","1");
	}

	var location = ($('div#country > img').attr("src")).substr(-6,2);
	$('div#country').html('<input type="hidden" id="location_id" name="locationid" value="" /><a href="#lv" id="lang_lv" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/lv.gif" width="18" height="12" alt="" /></a><a href="#ru" id="lang_ru" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ru.gif" width="18" height="12" alt="" /></a><a href="#lt" id="lang_lt" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/lt.gif" width="18" height="12" alt="" /></a><a href="#ee" id="lang_ee" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ee.gif" width="18" height="12" alt="" /></a><a href="#by" id="lang_by" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/by.gif" width="18" height="12" alt="" /></a><a href="#ua" id="lang_ua" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ua.gif" width="18" height="12" alt="" /></a><a href="#eu" id="lang_eu" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/eu.gif" width="18" height="12" alt="" /></a>');
	$('input#location_id').val(location);
	$("div#country > a").css("opacity",0.3);
	$("a#lang_"+location).css("opacity",1);
	
	var city  = $.trim($('div#city').text());
	$('div#city').html('<input type="text" name="city" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;" />');
	$('div#city > input').val(city);

	var mail  = $.trim($('div#mail').text());
	$('div#mail').html('<input type="text" name="mail" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;" />');
	$('div#mail > input').val(mail);
	
	$('div#name').parent().parent()
				.children('div:last').hide().end()
				.children('div:visible:last').hide().end()
				.append('<div style="padding: 6px 0pt 0pt 8px; height: 16px; width: 327px; background-color: rgb(222, 222, 222);"><div style="margin-left:-5px;">'+LANG.user.newpw+':</div><div id="new_password" style="float: right; width: 260px;"><input type="password" style="border: 0pt none ; padding: 3px; width: 116px; height: 10px; background-color: transparent; background-image: url(' + host + 'img/bg_field.gif); margin-top: -2px;" value="" name="pw"/></div></div>')
				.append('<div style="padding: 6px 0pt 0pt 8px; height: 16px; width: 327px; background-color: rgb(216, 216, 216);"><div style="margin-left:-5px;">'+LANG.user.newpw+':</div><div id="repeat_password" style="float: right; width: 260px;"><input type="password" style="border: 0pt none ; padding: 3px; width: 116px; height: 10px; background-color: transparent; background-image: url(' + host + 'img/bg_field.gif); margin-top: -2px;" value="" name="pw"/></div></div>');
	
	$('div#center').append('<div style="clear:both;margin:10px;display:block;" id="save_user"><a href="#save" onclick="return saveUser();"><img src="'+host+'img/'+lang+'/button_saveprofile.gif" height="15" alt="" /></a></div>');

	return false;
}
function changeProfileLoc(lang){
	$('input#location_id').val((lang.href).substr(-2));
	$('div#country > a').css("opacity",0.3);
	$(lang).css("opacity",1);
	return false;
}
function saveUser(){
	
	var user_info = $('textarea#user_info_edit').val();
	var name = $('div#name > input').val();
	var age = parseInt($('div#age > input').val());
	var gender = $('div#gender > div > input[checked]').val();
	var city = $('div#city > input').val();
	var mail = $('div#mail > input').val();
	var location = $('div#country > input#location_id').val();
	var newpw = $('div#new_password > input').val();
	var newpw2 = $('div#repeat_password > input').val();
	
	if(age>100 || age<0){
		alert(LANG.user.tooold);
		return false;
	}
	if(!/^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/.test(mail)){
		alert(LANG.user.wrongemail);
		return false;
	}
	if(newpw.length>0){
		if(newpw.length<3 || newpw.length>16){
			alert(LANG.reg.shortpassword);
			return false;
		}
		if(newpw!==newpw2){
			alert(LANG.reg.pwdoesntmatch); 
			return false;
		}
	}
	
	if(typeof(gender)=='undefined'){
		var gender = '';
	}

	$('div#save_user').hide();		

	$('div#center div.loader').show();
	blockscreen();
	$('div#dumb').load(host+'ajax/',{url:'update_user', name:name, age:age, gender:gender, city:city, mail:mail, info:user_info, location:location, password:newpw}, function(response){ 
									unblockscreen();
									$('div#center div.loader').hide();
									if(response!='true'){
										alert(LANG.user.error);
										$('div#save_user').show();
										return;
									}
									$('div#save_user').remove();
									$('div#user_info').html(user_info.replace(/\</g,'&lt;').replace(/\>/g,'&gt;').replace(/\n/ig,"<br />\n"));
									$('div#name').text(name);
									$('div#age').text(age);
									$('div#country').html('<img src="'+host+'img/flags/'+location+'.gif" width="8" height="8" alt="" />');
									$('div#gender').text(gender);
									$('div#city').text(city);
									$('div#mail').text(mail);	
									$('div#comments').show();
									$('div#comment_form').show();
									$('div#new_password').parent().remove();
									$('div#repeat_password').parent().remove();
									$('div#name').parent().siblings('div:last').show().end()
														  .siblings('div:hidden:last').show();
									if(!avatar_uploading){
										$('div#browse_avatar').remove();
									} else {
										$('div#browse_avatar > img:first').remove();
									}
									ui_enabled = true;
								});

	return false;
}

/* Teams */
function searchTeam(){
	var search = $('input#search').val();
	$('div#search_bar').slideUp("slow",function(){
		$('div#center > div.loader').show();
		$('div#search_result').load(host+'ajax/',{url:'search_team', search:search},function(response){
			if(response!='false'){
				$('div#search_label > span').text($('div#search_result').find("div.tm_block").length);
			} else {
				$('div#search_result').html('');
				$('div#search_label > span').text(0);
			}
			$('div#center > div.loader').hide();
			$('div#search_bar').slideDown("slow");
		});
	});
	return false;
}
var tm_enabled = true;
var avatar_uploading = false;
function editTeam(){
	if(!tm_enabled)return false;
	tm_enabled = false;
	$('div#comments').hide();
	$('div#comment_form').hide();
	$('div#karma').parent().hide();

	//Loading special area
	$.getScript(host+'scripts/jquery.fileupload.js',function(){
		$('div#team_action').html('<div id="browse_avatar" style="float:none;margin-bottom:-8px;position:relative;z-index:51;"><img style="cursor:pointer;" src="'+host+'img/'+lang+'/button_browse.gif" height="15" alt="" /><img height="12" style="display:none;" class="loader" width="100" alt="" src="'+host+'img/loader.gif"/><br /><span style="color:gray">'+LANG.team.avatar+'</span></div>');
		var upload = new AjaxUpload($('div#browse_avatar > img'), {action: host+'ajax/', name:'avatar', data:{url:'upload_team_avatar'}, 
			onSubmit:function(file,ext){
				if(ext!='jpg' && ext!='png' && ext!='jpeg' && ext!='gif'){ return false; }
				$('div#browse_avatar > img:first').hide();
				$('div#browse_avatar > img.loader').show();
				avatar_uploading = true;
			},
			onComplete: function(file,response){
				if(tm_enabled==false){
					$('div#browse_avatar > img:first').show();
					$('div#browse_avatar > img.loader').hide();
				} else {
					$('div#browse_avatar').remove();
				}
				avatar_uploading = false;
				if(response=='true'){
					document.getElementById('avatarimg').src = document.getElementById('avatarimg').src + '#';
				} else {
					return false;
				}
			}
		});
	});

	var name = $.trim($('div#name').text());
	$('div#name').html('<input type="text" name="name" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;" />');
	$('div#name > input').val(name);

	$('div.team_options').append('<div style="height:16px;width:100%;background-color:#DEDEDE;padding:6px 0 0 8px;"><div>Invite:</div><div style="float:right;width:180px;" id="invite"><input type="text" name="invite" value="" style="padding:3px;width:116px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field.gif);margin-top:-2px;float:left;" /> <a href="#" style="float:left;width:17px;height:15px;margin-top:-2px;" onclick="return inviteTeamMember();"><img src="'+host+'img/button_plus.gif" width="17" height="15" alt="" /></a></div></div>');

	$('span.team_member').append(' <a href="#" style="width:17px;height:15px;margin-top:-2px;" onclick="return removeTeamMember(this);"><img src="'+host+'img/button_minus.gif" width="10" height="9" alt="" /></a>');

	var location = ($('div#country > img').attr("src")).substr(-6,2);
	$('div#country').html('<input type="hidden" id="location_id" name="locationid" value="" /><a href="#lv" id="lang_lv" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/lv.gif" width="18" height="12" alt="" /></a><a href="#ru" id="lang_ru" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ru.gif" width="18" height="12" alt="" /></a><a href="#lt" id="lang_lt" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/lt.gif" width="18" height="12" alt="" /></a><a href="#ee" id="lang_ee" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ee.gif" width="18" height="12" alt="" /></a><a href="#by" id="lang_by" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/by.gif" width="18" height="12" alt="" /></a><a href="#ua" id="lang_ua" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/ua.gif" width="18" height="12" alt="" /></a><a href="#eu" id="lang_eu" onclick="return changeProfileLoc(this);"><img src="'+host+'img/reg/active_flags/eu.gif" width="18" height="12" alt="" /></a>');
	$('input#location_id').val(location);
	$("div#country > a").css("opacity",0.3);
	$("a#lang_"+location).css("opacity",1);
	
	team_points_info = $('div#points').html();
	team_points_nan = parseInt(team_points_info);
	$('div#points').html('<div>convert</div><input type="text" id="amount" name="amount" value="'+team_points_nan+'" style="float:left;padding:3px;width:20px;height:10px;border:0;background-color:transparent;background-image: url('+host+'img/bg_field2.gif);margin:-2px 2px 0 2px;overflow:hidden;" /><div> points to coins </div><div><a href="#" style="float:left;width:17px;height:15px;margin-top:-2px;margin-left:2px;" onclick="return convertPointsToCoins();" title="Exchange rate: 100 points = 1 coin"><img src="'+host+'img/button_plus.gif" width="17" height="15" alt="Exchange rate: 100 points = 1 coin" /></a></div>');
	
	$('div#center').append('<div style="clear:left;margin:5px;" id="save_team"><a href="#save" onclick="return saveTeam();"><img src="'+host+'img/'+lang+'/button_saveprofile.gif" height="15" alt="" /></a></div><div style="float:right;clear:right;margin:5px;" id="drop_team"><a href="#drop" onclick="return dropTeam();"><img src="'+host+'img/'+lang+'/button_dropteam.gif" alt="" /></a></div>');

	return false;
}
function saveTeam(){
	//Saving team
	var name = $('div#name > input').val();
	var location = $('div#country > input#location_id').val();
	
	if(name.length==0)
		return false;

	$('div#save_team').hide();		
	$('div#drop_team').hide();
	
	$('div#center div.loader').show();
	blockscreen();
	$('div#dumb').load(host+'ajax/',{url:'update_team', name:name, location:location}, function(response){ 
									unblockscreen();$('div#center div.loader').hide();
									if(response!='true'){
										alert('Error!<br />Please try again.');
										$('div#save_team').show();
										$('div#drop_team').show();
										return;
									}
									$('div#save_team').remove();
									$('div#drop_team').remove();
									$('div#name').text(name);
									$('div#country').html('<img src="'+host+'img/flags/'+location+'.gif" width="8" height="8" alt="" />');
									$('div#points').html(team_points_nan+team_points_info.substr((team_points_info.indexOf(' '))));
									$('div#comments').show();
									$('div#comment_form').show();
									$('div#karma').parent().show();
									$('div#invite').parent().remove();
									$('span.team_member > a:last').remove();
									if(!avatar_uploading){
										$('div#browse_avatar').remove();
									} else {
										$('div#browse_avatar > img:first').remove();
									}
									tm_enabled = true;
								});
	return false;
}
function dropTeam(){
	$.post(host+'ajax/',{url:'drop_team'}, function(r){if(r=='true'){window.location.href = host;}});
	return false;
}

function inviteTeamMember(){
	if(tm_enabled)
		return false;

	var mem_id = $('div#invite > input').val();

	if(mem_id.length>0){
		$('div#save_team').hide();		
		$('div#center div.loader').show();
		blockscreen();

		$('div#dumb').load(host+'ajax/', {url:'update_team_new_member', id: mem_id}, function(response){
				$('div#save_team').show();
				$('div#center div.loader').hide();
				unblockscreen();
				if(response.substr(0,5)!='false'){
					alert(LANG.team.invitesent);
					$('div#invite > input').val('');
					$('span#team_members').html(response);
					$('span.team_member').append(' <a href="#" style="width:17px;height:15px;margin-top:-2px;" onclick="return removeTeamMember(this);"><img src="'+host+'img/button_minus.gif" width="10" height="9" alt="" /></a>');
				} else {
					alert(LANG.team.membererror);
				}
				
			});
	}

	return false;
}
function acceptInvitation(id){
	blockscreen();
	$.post(host+'ajax/',{url:'accept_team_invitation',id:id},function(r){ 
		if(r=='true'){
			window.location.href = host+'myteam/';
		} else if(r=='iamcm'){
			alert(LANG.team.iamcm);
		}else{
			alert(LANG.team.failed);
		}
		unblockscreen();
	});
	return false;
}

function updateKarma(tid,type){
	tid = parseInt(tid);
	if(type){
		type=1;
	} else {
		type=0;
	}
	$.post(host+'ajax/', {url:'update_team_karma', id:tid, type:type}, function(res){ if(res!='false'){ $('div#karma > span.stats').text(res); if(parseInt(res)>0){ $('div#karma > span.stats').css('color','blue'); }else {$('div#karma > span.stats').css('color','gray');}}});
	
	return false;
}

function removeTeamMember(node){
	if(tm_enabled)
		return false;

	var mem_id = $(node).parent().attr("id");
	mem_id = parseInt(mem_id.substr(7));

	if(mem_id>0){
		$('div#save_team').hide();		
		$('div#center div.loader').show();
		blockscreen();

		$('div#dumb').load(host+'ajax/', {url:'update_team_remove_member', id: mem_id}, function(response){
				$('div#save_team').show();
				$('div#center div.loader').hide();
				unblockscreen();
				if(response.substr(0,5)!='false'){
					$('span#team_members').html(response);
					$('span.team_member').append(' <a href="#" style="width:17px;height:15px;margin-top:-2px;" onclick="return removeTeamMember(this);"><img src="'+host+'img/button_minus.gif" width="10" height="9" alt="" /></a>');
				} else {
					alert(LANG.team.memberdel);
				}
			});
	}

	return false;
}

/* Buddies */
function toggleBuddy(id){
	$('div#dumb').load(host+'ajax/', {url:'togglebuddy', buddy:parseInt(id)}, function(response){if(response=='true')window.location.reload();});
	return false;
}
/* PM's */
var checked_msg_reciever = false;
var new_msg_form = false;
function checkReciever(id,status){
	if(typeof(id)!='undefined'){
		id = 'input#'+id;
	} else {
		id = 'input#to';
	}
	if(typeof(status)!='undefined'){
		status = 'div#'+status;
	} else {
		status = 'div#status';
	}
	checked_msg_reciever = false;
	$('div#small_loader').show();
	var login = $(id).val();
	$('div#new_msg > div > a').fadeTo('slow',0.5);
	$.post(host+'ajax/', {url:'check_login', login:login}, function(response){ 
		if(response=='false'){
			checked_msg_reciever=true;
			$(status).css("color","green").text(LANG.pm.recok).show();
			$('div#new_msg > div > a').fadeTo('fast',1);
		} else {
			$(status).css("color","red").text(LANG.pm.recwrong).show();
		}
		$('div#small_loader').hide();
	});
}

function sendMsg(remove_form){
	if(!checked_msg_reciever){
		return false;
	}

	var message = $('textarea#message').val();
	var login = $('input#to').val();
	var subject = $('input#subject').val();
	
	if(message.length == 0 || subject.length == 0){
		$('div#status').css("color","red").text(LANG.pm.subempty).show();
		return false;
	}
	$('div#loader').show();
	blockscreen();
	$.post(host+'ajax/', {url:'msg_send', to:login, msg:message, title:subject}, function(response){ if(new_msg_form!=false){remove_form=false;$('div#new_msg').html(new_msg_form);new_msg_form=false;} if(remove_form){$('div#new_msg').remove();$('div#center > *:not(:first)').fadeIn("fast",function(){$('div#loader').hide();});} else { if(response=='true'){$('input#to').val('');$('input#subject').val('');$('textarea#message').val(''); $('div#status').css("color","green").text(LANG.pm.sent).show(); } else { $('div#status').css("color","red").text(LANG.pm.error).show(); }} $('div#loader').hide(); unblockscreen();});

	return false;
}

var open_swap = 'inbox';
var swapping = false;
function swapDivs(to){
	if(swapping)return false;
	if(new_msg_form!=false){remove_form=false;$('div#new_msg').html(new_msg_form);new_msg_form=false;}
	if(open_swap!=to){
		swapping = true;
		$('div#'+open_swap).fadeOut("fast",function(){ $('div#'+to).fadeIn("fast",function(){swapping = false;});});
		open_swap = to;
	}
	return false;
}
function sendPM(login,reply){
	$('div#loader').show();
	blockscreen();
	$.post(host+ 'ajax/', {url: 'msg_form'}, function(response){
		if(response.length>32){
			$('div#loader').hide();
			if(reply){
				new_msg_form = $('div#new_msg').html();
				$('div#new_msg').replaceWith(response);
				$('div#new_msg').css("marginTop",0);
				$('div#new_msg input#subject').val('RE: '+$('div#view_msg input[name=subject]').val());
			} else {
				$('div#center').append(response);
			}
			$('div#new_msg input#to').val(login);
			$('div#center > *:not(:first)').fadeOut("fast");
			$('div#center > div#new_msg, div#mail_menu').fadeIn("slow");
			checked_msg_reciever = true;
			open_swap = 'new_msg';
			unblockscreen();
		}
	});
	
	return false;
}
function openMsg(id){
	blockscreen();
	$.post(host+'ajax/',{url:'msg_view',id:id}, function(resp){
		var container = $('div#view_msg');
		if(container.length==0){
			$('div#center').append(resp);
		} else {
			container.replaceWith(resp);
		}
		swapDivs('view_msg');
		unblockscreen();
	});
	return false;
}
function deleteMSG(id){
	blockscreen();
	$.post(host+'ajax/',{url:'msg_delete',id:id},function(r){
		window.location.reload();
	});
	return false;
}


/* Shop */
function purchaseItem(id, title, auth){
	if(auth == 0){
		//$("#reg_form").overlay({ load: true});
		$("#reg_button").overlay().load();
		//$("#reg_form").overlay({ "mask": "#000", "effect": "apple", "load": true });
	} else {
		$("#shop_purchase h2 > span").text(title);
		$("#shop_purchase #makepurchase").click(function(e){
			e.preventDefault();
			e.stopPropagation();
			$.post(document.URL, { "purchase": id, "name": $("#shop_purchase input[name=\"name\"]").val(), "address": $("#shop_purchase input[name=\"address\"]").val(), "phone": $("#shop_purchase input[name=\"phone\"]").val(), "notes": $("#shop_purchase textarea").val() }, function(res){
				if(res.success){
					$("#shop_purchase").overlay().close();
					alert("order placed");
				}
			}, "json");
		});
		$("#shop_purchase").overlay().load();
	}
	return false;
}

function confirmCoinCode(){
	var to = $('input#to').val();
	var code = $('input#unlock_code').val();
	var price = $('select#price').val();
	if(code.length==0 || to.length==0){
		return false;
	}
	blockscreen();
	$('div#loader').show();
	$.post(host+'ajax/',{url:'coins',to:to,code:code,price:price}, function(resp){
			if(resp!='true'){ 
				$('div#status').css({color:'red'}).text(LANG.coins.wrongcode);
			}else{
				$('div#status').css({color:'green'}).text(LANG.coins.correct+'`'+to+'`');
				$('input#unlock_code').val('');
				$('select#price').val('');
			}
			$('div#loader').hide();unblockscreen(); 
		});
	
	return false;
}

function transferCoins(){
	if(!checked_msg_reciever){
		return false;
	}
	var to = $('input#to_user').val();
	var amount = parseInt($('input#amount').val());
	if(to.length==0 || amount<1 || isNaN(amount)){
		return false;
	}
	blockscreen();
	$('div#loader').show();
	$.post(host+'ajax/',{url:'coins_transfer',to:to,amount:amount}, function(resp){
			if(resp!='true'){ 
				if(resp=='1'){
					$('div#status2').css({color:'red'}).text(LANG.coins.wronguser);
				}else if(resp=='2'){
					$('div#status2').css({color:'red'}).text(LANG.coins.notenought);
				}
			}else{
				$('div#status2').css({color:'green'}).text(LANG.coins.correct+'`'+to+'`');
				$('input#amount').val('');
			}
			$('div#loader').hide();unblockscreen(); 
		});
	
	return false;
}

var team_points_info = null;
var team_points_nan = 0;
function convertPointsToCoins(){
	var amount = parseInt($('input#amount').val());
	if(amount<1 || amount>team_points_nan || isNaN(amount)){
		if(amount>team_points_nan){
			alert(LANG.team.notenought);
		}
		return false;
	}
	blockscreen();
	$('div#loader').show();
	$.post(host+'ajax/',{url:'coins_from_tp',amount:amount}, function(resp){
			if(resp.substr(0,4)!='true'){ 
				if(resp=='0'){
					alert(LANG.team.notenought);
				}
			}else{
				team_points_nan = resp.substr(4);
				alert(LANG.coins.exchanged);
				$('input#amount').val(team_points_nan);
			}
			$('div#loader').hide();
			unblockscreen(); 
		});
	
	return false;
}

var file_temp = '';
var file_open = false;
/* Files  */
function openFSection(node,text){
	if(file_open!=false){
		$(file_open).find('div.text').html(file_temp);
		$(file_open).animate({height:'39px'}, 100);
		file_temp = '';
	}
	if(file_open == node){
		file_open = false;
		return true;
	}
	var textnode = $(node).find('div.text');
	file_temp = textnode.html();
	textnode.html(unescape(text));
	var newheight = $(node).children('div.description').height()+9;
	if(newheight>39){
		$(node).animate({height:newheight}, 100);
		file_open = node;
	} else {
		$(node).find('div.text').html(file_temp);
		file_open = false;
		file_temp = '';
	}
	return true;
}

var file_section_open = false;
/* Files  */
function openFileSection(node){
	return openSectionI(node,'fsection_');
}
function openSectionI(node,pre){
	node = 'div#'+pre+node;
	if(file_section_open!=false){
		if(file_section_open==node){
			$(node).slideUp(700);
			file_section_open = false;
		} else if($(node).find(file_section_open).length > 0) {
			$(node).slideUp(700,function(){ 
				$(file_section_open).hide()
				file_section_open = false;
			});
		} else if($(node).parents(file_section_open).length > 0) {
			$(node).slideDown(700);
			file_section_open = node;
		} else {
			$(file_section_open).slideUp(700, function(){
				$(node).slideDown(700);
				file_section_open = node;
			});
		}
	} else {
		$(node).slideDown(700);
		file_section_open = node;
	}
	return true;
}

function openMarketSection(node){
	return openSectionI(node,'market_');
}

/* fix */
function preventBubbling(e){
	if (e.stopPropagation) e.stopPropagation();
	else window.event.cancelBubble = true;
}

/* Video */
function rateVideo(id,type){
	id = parseInt(id);
	if(type){
		type=1;
	} else {
		type=0;
	}
	$.post(host+'ajax/', {url:'video_rate', id:id, type:type}, function(res){ if(res!='false'){ $('span#video_rating').text(res);if(parseInt(res)>0){ $('span#video_rating').css('color','blue'); }else {$('span#video_rating').css('color','gray');}}});
	
	return false;
}
function deleteVideo(id){
	blockscreen();
	$('div#video_'+id+' div.small_loader').show();
	$.post(host+'ajax/', {url:'video_delete', id:id}, function(res){ if(res!='false'){ $('div#myvideos').replaceWith(res); } $('div#video_'+id+' div.small_loader').hide();unblockscreen();});
	return false;
}
function editVideo(id,category){
	$('div.editDIV').siblings().show().end().remove();
	$('div#video_'+id+' div.info').hide().parent().append('<div class="editDIV" style="width:359px;margin:2px;"><div style="width:210px;clear:both;margin-top:5px;"><div style="margin: 2px; height: auto; width: 200px; clear: left;" class="textbox"><div class="tb_corner tb_lt"/><div class="topline"/><div class="tb_corner tb_rt"/><div class="lineleft divheightfix"/><div class="textbox_content"><div style="margin: 2px; width: 196px; height: auto; color: gray; font-weight: bold;"><label for="title">Title</label><input type="text" style="border: 0pt none ; margin: 0pt 0pt 0pt 3px; color: gray; background-color: transparent; width: 150px;" value="' + $('div#video_'+id+' div.info span.title').text() + '" class="title" id="video_'+id+'_title" name="title" maxlength="30" /></div></div><div class="lineright divheightfix"/><div class="tb_corner tb_lb"/><div class="bottomline"/><div class="tb_corner tb_rb"/></div></div><div style="width:210px;clear:both;"><div style="margin: 2px; height: auto; width: 200px; clear: left;" class="textbox"><div class="tb_corner tb_lt"/><div class="topline"/><div class="tb_corner tb_rt"/><div class="lineleft divheightfix"/><div class="textbox_content"><div style="margin: 2px; width: 196px; height: auto; color: gray; font-weight: bold;"><label for="category">Category</label><select style="border: 0pt none ; margin: 0pt 0pt 0pt 3px;padding:0; color: gray; background-color:#D6D6D6; width: 147px;" class="category" id="video_'+id+'_category" name="category"><option value="games">Games</option><option value="movies">Movies</option><option value="trailers">Trailers</option><option value="music">Music</option><option value="fun">Fun</option><option value="other" selected="1">Other</option></select></div></div><div class="lineright divheightfix"/><div class="tb_corner tb_lb"/><div class="bottomline"/><div class="tb_corner tb_rb"/></div></div><div style="position:absolute;bottom:4px;right:5px"><a href="#save" onclick="return saveVideo(\'' + id + '\');"><img src="' + host +'img/' + lang + '/button_save.gif" alt="" /></a></div></div>');
	// # video_'+id+'_category
	var select = $('#video_'+id+'_category')[0];
	for(i in select.options){
		if(select.options[i].value == category){
			select.selectedIndex = i;
		}
	}
	return false;
}
function saveVideo(id){
	blockscreen();
	$('div#video_'+id+' div.small_loader').show();
	$('div#video_'+id).find('div.info').show().end().find('div.editDIV').hide();
	$.post(host+'ajax/', {url:'video_save', id:id, title:$('input#video_'+id+'_title').val(), category:$('select#video_'+id+'_category').val()}, function(res){
		if(res!='false'){ 
			$('div#myvideos').replaceWith(res); 
		} else if(id.substr(0,4)=='temp') {
			$('div#video_'+id+' div.editDIV').remove();
		} else {
			$('div#video_'+id).find('div.info').hide().end().find('div.editDIV').show();
		}
		$('div#video_'+id+' div.small_loader').hide();
		unblockscreen();
	});
}
function refreshVideoListing(page,type){
	$.post(host+'ajax/', {url:'video_get', page_num:page, type:type},function(res){
		if(res.length>0){
			$('#video_'+type).replaceWith(res);
			$('#video_'+type+'_'+page).css('fontWeight','bold');
		}
	});
	return true;
}

/* Totalisator */
function refreshLots(id){
	$('div#totalisator_loader').show();
	if(typeof(id)=='undefined'){
		id = 0;
	}
	$.post(host+'ajax/',{url:'totalisator_refresh',id:id},function(res){
		window.setTimeout("$('div#totalisator_loader').hide()",500);
		$('div#totalisator_handler').replaceWith(res.substr(res.indexOf('<')));
		window.setTimeout("refreshLots(" + id + ")",10000);
	});
}
function placeBet(id,side,action){
	if(typeof(action)!='undefined' && action==false){
		return false;
	}
	if(side!=2){
		side = 1;
	}
	var ratio = parseFloat($('div#lot_'+id+' span.r'+side).text());
	var amount = parseInt($('div#lot_'+id+' input.amount').val());
	if(ratio>0 && amount>0){
		side = side - 1;
		$('div#totalisator_loader').show();
		$.post(host+'ajax/',{ url:'totalisator_place_bet', id:id, side:side, ratio:ratio, amount:amount}, function(res){
			$('div#totalisator_loader').hide();
			var st = res.substr(0,res.indexOf('<'));
			if(st=='true'){
				alert('Bet placed');
			} else if(st=='1'){
				alert('Rate changed');
			} else if(st=='0'){
				alert('Not enought coins');
			}
			$('div#totalisator_handler').replaceWith(res.substr(res.indexOf('<')));
			$('div#lot_'+id+' input.amount')[0].focus();
		});
	}
	
	return false;
}
var opened_bid_list = false;
function showBids(node){
	var node = $(node);
	var bids = node.find('div.bids');
	opened_bid_list = 'bids_opened_' + node[0].id;
	node.next().after('<div class="bids_opened_' + node[0].id + '" style="width:100%;clear:both;height:' + (bids.height()-12) + 'px"></div>');
	bids.show();
}
function hideBids(node){
	var node = $(node);
	node.siblings('div.bids_opened_' + node[0].id).remove();
	opened_bid_list = false;
	node.find('div.bids').hide();
}

/* image viwer */
var openIMGfired = false;
var AlertTitle = '';
function openIMG(url) {
  openIMGfired = true;
  $('div.jqmAlertTitle > h1').text('');
  var img = document.createElement('img');
  $(img).bind('load',function(){
	$('div.jqmAlertWindow').css('width',(this.width+40)+'px');
	$('#alert').css({position:'fixed',top:'70px'}).show(500);
	var offset = $('#alert').offset();
	$('#alert').css({position:'absolute',top:offset.top+'px'});
	window.setTimeout("$('#alert').jqmShow()",510);
  }).attr('src',host+url);
  $('#alert').find('a.jqmClose').css('display','block').end()
				.find('div.jqmAlertContent').html(img);
 }
function restoreDefaultAlert(){
	openIMGfired = false;
    $('div.jqmAlertTitle > h1').text(AlertTitle);
	$('#alert').css({position:'fixed',top:'26%'}).find('div.jqmAlertWindow').css('width','400px');
}
/* banners */
function refreshBanner(pos){
	if(ib_pass){
		return false;
	}
	$.post(host+'ajax/',{url:'get_banner',pos:pos},function(resp){
		if(resp.length>0 && resp!='false'){
			var resp = eval('('+resp+')');
			if(resp.img!=$('img#banner_'+resp.pos+'_img').attr('src')){
				$('a#banner_'+resp.pos+'_url').fadeOut('fast',function(){
					$('a#banner_'+resp.pos+'_url').attr('href',resp.url);
					$('img#banner_'+resp.pos+'_img').attr('src',resp.img);
					$('a#banner_'+resp.pos+'_url').fadeIn('fast');
				});
			}
		}
	});
	return true;
}

var ib_pass = false;
var ib_right;
var ib_left;
var ib_top;

var gallery = {
	'new': function(){
		$('#center > *:not(.center_title)').remove();
		$('#center').append('<div style="width:400px;margin:5px 31px;position:relative;" id="mygalleries">'+this.inputForm(0)+'</div>');
	},
	'newPhoto': function(){
		$.post(host+'mygallery/',{action:'upload_form'},function(resp){
			if(resp!='false'){
				$('#center > *:not(.center_title)').remove();
				$('#center').append(resp);
			}
		});
	},
	'edit': function(id){
		$('#gallery_'+id+' div.info').hide().parent().append(this.inputForm(id));
	},
	'save': function(id){
		blockscreen();
		$('#gallery_'+id+' div.small_loader').show();
		$('#gallery_'+id).find('div.info').show().end().find('div.editDIV').hide();
		$.post(host+'mygallery/', {action:'manage', id:((typeof id!= 'undefined')?id:0), title:$('#gallery_'+id+'_title').val(), comment:$('#gallery_'+id+'_comment').val(), show:1}, function(res){
			if(res!='false'){ 
				$('#mygalleries').replaceWith(res); 
			} else {
				alert('Error!');
			}
			$('#gallery_'+id+' div.small_loader').hide();
			unblockscreen();
		});
	},
	'delete': function(id){
		$('#gallery_'+id+' div.small_loader').show();
		$.post(host+'mygallery/',{action:'delete',id:id},function(resp){
			if(resp=='false'){
				alert('Can\'t delete gallery!');
			} else
				$('#mygalleries').replaceWith(resp);
			$('#gallery_'+id+' div.small_loader').hide();
		});
	},
	'deleteGallery': function(id){
		$.post(host+'mygallery/',{action:'delete_gallery',id:id},function(resp){
			return resp;
		});
	},
	'delPhoto': function(id){
		$.post(host+'mygallery/',{action:'delete_photo',id:id},function(resp){
			return resp;
		});
	},
	'inputForm': function(id){
		return '<div class="editDIV" style="width:359px;margin:2px;"><div style="width:240px;clear:both;margin-top:5px;"><div style="margin: 2px; height: auto; width: 230px; clear: left;" class="textbox"><div class="tb_corner tb_lt"/><div class="topline"/><div class="tb_corner tb_rt"/><div class="lineleft divheightfix"/><div class="textbox_content"><div style="margin: 2px; width: 226px; height: auto; color: gray; font-weight: bold;"><label for="title">Title</label><input type="text" style="border: 0pt none ; margin: 0pt 0pt 0pt 3px; color: gray; background-color: transparent; width: 170px;" value="' + $('#gallery_'+id+' div.info span.title').text() + '" class="title" id="gallery_'+id+'_title" name="title" maxlength="64" /></div></div><div class="lineright divheightfix"/><div class="tb_corner tb_lb"/><div class="bottomline"/><div class="tb_corner tb_rb"/></div></div><div style="width:240px;clear:both;margin-top:5px;"><div style="margin: 2px; height: auto; width: 230px; clear: left;" class="textbox"><div class="tb_corner tb_lt"/><div class="topline"/><div class="tb_corner tb_rt"/><div class="lineleft divheightfix"/><div class="textbox_content"><div style="margin: 2px; width: 226px; height: auto; color: gray; font-weight: bold;"><label for="comment">Comment</label><input type="text" style="border: 0pt none ; margin: 0pt 0pt 0pt 3px; color: gray; background-color: transparent; width: 170px;" value="' + $('#gallery_'+id+' div.info span.comment').text() + '" class="comment" id="gallery_'+id+'_comment" name="comment" maxlength="512" /></div></div><div class="lineright divheightfix"/><div class="tb_corner tb_lb"/><div class="bottomline"/><div class="tb_corner tb_rb"/></div></div><div style="position:absolute;bottom:4px;right:5px"><a href="#save" onclick="return gallery.save(\'' + id + '\');"><img src="' + host +'img/' + lang + '/button_save.gif" alt="" /></a></div></div>';
	},
	'enableUploadify': function(id, gallery_id, comment_id) {
		var $this = $("#"+id);
		var $gallery_dropdown = $("#"+gallery_id);
		var $comment_field = $("#"+comment_id);

		

		//Create Div for queue
		var $queue = $(document.createElement("DIV"));
		$queue.attr("id", "image_uploader");
		$this.after($queue);
		$queue.css("z-index", "99999");
		
		var onUploadComplete = function(event, queueID, fileObj, response, data) {
			//var inputField = $('#' + $this.attr('id'));
			//var response = eval('(' + response + ')');
			//var filename;
			alert(response);
			//if ((typeof response['error'] == 'undefined') && response['filename']) {
				//alert($this.attr('id'));
				//filename = response['filename'];
				//alert($this.val());
				//$this.val(filename);
				//alert($this.val());

				//makeImageThumbnail();
			//}
			return true;
		}

		var onError = function(event, queueID, fileObj, errorObj) {
			alert(errorObj.info);
			return true;
		}

		var onOpen = function() {
			$("#"+id).uploadifySettings('scriptData', {HTTP_X_REQUESTED_WITH:1,'SID': sessid,'url':'gallery', 'action':'uploadPhoto', 'id':$gallery_dropdown.val(), 'comment':$comment_field.val()});
			return true;
		}
		
		$this.uploadify({
			'uploader': host+'img/uploadify.swf',
			'script': host+'mygallery/',
			'cancelImg': host+'img/delete.png',
			'width': $this.width(),
			'height': $this.height()+'',
			'css_classes': '',
			'queueID': $queue.attr('id'),
			'fileDataName':'photo',
			'scriptData': {HTTP_X_REQUESTED_WITH:1,'SID': sessid, url:'gallery', action:'uploadPhoto'},
			'wmode':'transparent',
			'fileDesc': 'Select Image',
			'fileExt': '*.gif;*.png;*.jpg',
			'method': 'POST',
			'onComplete': onUploadComplete,
			'onError': onError,
			'onSelect' : onOpen,
			'buttonText': '',
			'buttonImg': $this.attr('src'),
			'auto': true,
			'multi': true
		});		
	}

};

var jsPager = {
	loadPage: function(type,page,extra){
		if(type == 'video'){
			return refreshVideoListing(page,extra);
		} else {
			$.post(window.location.href,{method:'page',type:type,page_num:page,section:extra},function(resp){
				$('#list_container').html(resp);
				jsPager.onLoad($('#list_container'));
				$('#center .center_title .list_pages').html($('#center #list_container .list_pages').html());
				var tmp = window.location.hash;
				window.location.hash = '#top';
				window.location.hash = tmp;
			});
		}
	},
	init: function(){
		var h = window.location.hash;
		h = h.split('/');
		if(h[1] == 'page'){
			this.loadPage(h[0].substr(1),h[2],h[3]);
		}
	},
	change: function(n,o){
		if(window.console && window.console.log){
			window.console.log('new:' +n + '\n' + 'old:'+o);
		}
	},
	jumpToURL: function(id){
		var s = id.indexOf('_',id.indexOf('_')+1);
		if(s==-1)s = id.indexOf('_');
		window.location.href=host+id.substr(0,s)+'/'+id.substr(s+1)+'/';
	},
	onLoad: function(parent){
		parent.find("div.news:not(.articles)").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");})
			.click(function(){ window.location.href=host+'news/'+this.id.substr(5)+'/'; });
		parent.find("div.articles").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");})
			.click(function(){ window.location.href=host+'articles/'+this.id.substr(9)+'/'; });
		parent.find("div.materials:not(.idlink)").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");})
			.click(function(){ window.location.href=host+'materials/'+this.id.substr(10)+'/'; });
		parent.find("div.threads").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");})
			.click(function(){ window.location.href=host+'forum/'+this.id.substr(7)+'/'; });
		parent.find("div.idlink").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");})
			.click(function(){ jsPager.jumpToURL(this.id); });
		(parent || $(document.body)).find(".hovering").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");});
	}
};

 $(document).ready(function(){
	unblockscreen();

	/* login form submit link */
	$('form#login_form a.login_submit').click(function(event){ event.preventDefault(); login();});
	$('form#login_form').keypress(function(e){if(e.keyCode == 13){login();}});

	/* JQM */
	$('#alert').jqm({overlay: 0, modal: true, trigger: false});
	AlertTitle = $('div.jqmAlertTitle > h1').text();
	
	/* News */
	jsPager.onLoad($('#center'));
	
	$('div.default_table > div:not(:first-child)').hover(function(){$(this).css('background-color','rgb(216,216,216)');}, function(){$(this).css('background-color','');});
	$('div.default_table > div:even:not(:first-child)').addClass('hover');

	$('div.menulink > a').each(function(){ $(this).attr('title',$(this).text());});
	
	$('a.lang_lv,a.lang_ru,a.lang_en').fadeTo("fast",0.5);
	$('a.lang_'+lang).fadeTo("fast",1);
	
	 $(document).ajaxError(function(event, request, settings){
	   alert(request.responseText);
	 });
	jsPager.init();
});

