/* KONSTANTY */

var RETCODE_ERROR = "RETCODE_ERROR";
var BAD_LOGIN = 'Používateľské meno neexistuje.';
var WRONG_PARAM = "WRONG_PARAM";
var NOT_RESPONSE = "NOT_RESPONSE";
var REGISTRATION_ERROR = "REGISTRATION_ERROR";
var REGISTRATION_OK = "REGISTRATION_OK";
var REGISTRATION_SEND = "REGISTRATION_SEND";
var DEFAULT_SEARCH = "nick";
var ADD_COMMENT = '';
var BTN_SEND = 'odoslať';
var TITLE = document.title;

var scriptUrl = 'http://sk.facebookvice.com/';
var loadingImage = scriptUrl+'img/loading2.gif';
var updateStatus = false;
var playSound = true;
var lastGroup = 0;
/* # KONSTANTY */

/* DCOUMENT READY */
$(document).ready(function(){
	$("input[name='registerUsername']").val("");
	$("input[name='registerPassword']").val("");
	$("input[name='confirmTerms']").attr("checked","");
	$('ul#animated').animatedinnerfade({
		speed: 2500,
		type: 'random',
		containerheight: '325px',
		containerwidth: '489px',
		animationSpeed: 100,
		animationtype: 'fade',
		bgFrame: 'none',
		controlBox: 'none',
		displayTitle: 'none',
		timeout: 5000
	});
	$('ul#animated_pub').animatedinnerfade({
		speed: 2500,
		type: 'random',
		containerheight: '142px',
		containerwidth: '374px',
		animationSpeed: 100,
		animationtype: 'fade',
		bgFrame: 'none',
		controlBox: 'none',
		displayTitle: 'none',
		timeout: 5000
	});
	/* MUTE */
	$("#soundMute").click(function(){
		if(playSound) {
			$("#soundMute").html('<img src="'+scriptUrl+'img/sound_off.png" />');
			playSound = false;
		} else {
			$("#soundMute").html('<img src="'+scriptUrl+'img/sound_on.png" />');
			playSound = true;
		}
	});
	/* SUBMIT LOGIN */
	$('#form_button').click(function(){
		username = $('#form_username').val();
		password = $('#form_password').val();
		if(username.length == 0 || password.length == 0) { showAlert(BAD_LOGIN,2); return; }
		getData(scriptUrl+"index.php/login/verify","POST","username="+username+"&password="+password, "html", "checkLogin");
	});
	$("#searchUsername").click(function(){
		user = $("#searchUsername").val();
		if(user == DEFAULT_SEARCH) {
			$("#searchUsername").val("");
		}
	});
	$("#right_form").submit(function(){
		user = $("#searchUsername").val();
		if(user == DEFAULT_SEARCH) { return; }
		LoadContent("app/post","search_out","Hledat","action=search&username="+user);
	});
	$(".buttons div").click(function(){
		btn = $(this).attr("id");
		$("#"+btn+" .count").remove()
	});

	$(".foot .buttons div").mousemove(function(e){
		$("#rel").remove();
		if($("#rel").not(":visible")){
		    $(".foot").before('<div id="rel" class="rel"></div>');
		    var PosX	= e.pageX;
			var title = $(this).attr("rel");
		    $("#rel").html(
		      '<div class="t"></div>'+
			  '<div class="m fs11 center">'+title+'</div>'+
			  '<div class="b"></div>'
		);
		    $("#rel").css({left : PosX});
			$("#rel").fadeIn(250);
		}
	});
	$(".foot .buttons div").mouseout(function(){
		$("#rel").remove();
	});

	$(".foot .buttons div").click(function(){
		var id = $(this).attr("id");
		$("#"+id+" .footerCounter").fadeOut(400,function(){
			$(this).remove();
		});
	});

	$(window).scroll(function(){
		if($(window).scrollTop() > 42){
		    $("#rightBlokDiv").css("position", "fixed");
		    $("#rightBlokDiv").css("top", "0");
		}
		if($(window).scrollTop() <= 42){
		    $("#rightBlokDiv").css("position", "relative");
		    $("#rightBlokDiv").css("top", $("#header").offset);
		}
	});



	/* FRIENDS */
	$("#searchUsername").val(DEFAULT_SEARCH);
	getLoading("#newMess .content");
	getLoading("#onlineFriends .content");
	getLoading(".box .mid #rightBox");

	// ESC => POPUP CLOSE
	$(document).keyup(function(e){ if(e.which == 27) { popupClose(); } });
});

function admin_search(user) {
	LoadContent("app/post","search_out","Hledat","action=search&username="+user);

}

function galleryPwd(id) {
	id = "#"+id;
	if ($(id).val() == 3) {
		$("#gallery_password").removeAttr("disabled");
	} else {
		$("#gallery_password").attr("disabled","disabled");
	}
}

function leave_group(id_group,change_btn) {
	$("#home_group_"+id_group).fadeOut(400,function(){
		$(this).remove();
	});
	postQuery = "action=leave_group&id_group="+id_group;
	getData(scriptUrl+"index.php/app/post","POST", postQuery, "html", "");
	if(change_btn==true) {
		fun_change_btn(id_group,"leave");
	}
}

function delete_proposal(id_user) {
	$("#home_proposal_"+id_user).fadeOut(400,function(){
		$(this).remove();
		postQuery = "action=delete_home_proposal&id_user="+id_user;
		getData(scriptUrl+"index.php/user/post","POST", postQuery, "html", "appendDataFadeIn", "#proposal_home");
	});
}

function change_offer(action,id_user) {
	postQuery = "action="+action+"&id_user="+id_user;
	getData(scriptUrl+"index.php/user/post","POST", postQuery, "html", "change_offer_callback", action);
}

function change_offer_callback(ret, to) {
	LoadTabContent('app/get/users/'+to,to,'.cont');
}

function fun_change_btn(id_group,action) {
	if(action == "enter") {
		$(".group_control_btn_"+id_group).html('<div class="b_svestka buttonDiv" id="'+id_group+'" onclick="leave_group('+id_group+',true)" lang="Pinkout">Zrušiť členstvo</div>');
	} else {
		$(".group_control_btn_"+id_group).html('<div class="b_svestka buttonDiv" id="'+id_group+'" onclick="enter_group('+id_group+',true)" lang="Pinkout">Stať sa členom</div>');
	}
}

function enter_group(id_group,change_btn) {
	postQuery = "action=enter_group&id_group="+id_group;
	getData(scriptUrl+"index.php/app/post","POST", postQuery, "html", "");
	if(change_btn==true) {
		fun_change_btn(id_group,"enter");
	}
}

function set_action(id,val) {
	$("#"+id).val(val);
}

function slidetogg(id) {
	$("#"+id).slideToggle("fast");
}

function hide_def_val(id,val) {
	if($("#"+id).val() == val) { $("#"+id).val(""); }
}

function show_def_val(id,val) {
	if($("#"+id).val() == "") { $("#"+id).val(val); }
}

function changeStatus(img) {
	st = $(img).attr("rel");
	id = $(img).attr("id");
	if(st == "a") { stat = ""; } else { stat = "a"; }
	$(img).attr("rel",stat);
	$(img).html('<img src="'+scriptUrl+'img/i_m_'+id+st+'.png" />');
	updateStatus = true;
}

function changeGroupStatus(img,id_group) {
	st = $(img).attr("rel");
	id = $(img).attr("id");
	if(st == "a") { stat = ""; } else { stat = "a"; }
	$(img).attr("rel",stat);
	$(img).html('<img src="'+scriptUrl+'img/b_g_'+id+st+'.png" />');
	postQuery = "action=groupstatus&id_group="+id_group+"&status=";
	if($("#home_group_"+id_group+" #comment").attr("rel") == "") { postQuery+= "1;"; } else { postQuery+= "0;"; }
	if($("#home_group_"+id_group+" #email").attr("rel") == "") { postQuery+= "1;"; } else { postQuery+= "0;"; }
	if($("#home_group_"+id_group+" #wall").attr("rel") == "") { postQuery+= "1;"; } else { postQuery+= "0;"; }
	postQuery = postQuery.substr(0,postQuery.length-1);
	getData(scriptUrl+"index.php/app/post","POST", postQuery, "html", "");
}

function StartLoading() {
	MsgsCsv();
	var d = new Date();
	getData(scriptUrl+"index.php/app/get/leftfavs","GET", "", "html", "showData","#onlineFriends .content");
	getData(scriptUrl+"index.php/app/get/right/"+d.getMilliseconds(),"GET", "", "html", "showData",".box .mid #rightBox");
	LoadContent("app/get/tabs_home","home","Home");
}

/* SLIDESHOW NEWS */
function mainNews(){
	var news = $("#scroller p:eq(0)").html();
	$("#scroller p:eq(0)").hide(500,function(){
		$(this).remove();
		$("#scroller p:last").after('<p class="fLeft left">'+news+'</p>');
	});
}

function MsgsCsv() {
	var d = new Date();
	getData(scriptUrl+"index.php/app/get/leftmsgs/"+d.getMilliseconds(),"GET", "", "html", "incomeMsgsCsv");
}

function incomeMsgsCsv(IncomingData) {
	html = "";
	is_msg = false;
	insert = $("#newMess .content ul").size();
	if(insert == 0) { html += "<ul>"; }

	data_arr = IncomingData.split(';');
	data_count = data_arr.length;
	for(i=0;i<=data_count-2;i++) {
		data_item = data_arr[i].split(':');
		id=data_item[0];
		name=data_item[1];
		sts=data_item[2];
		msgs_count=data_item[3];
		exist = $("#leftmsgs_"+id+"").size();
		if(exist == 1) {
			exist_count = parseInt($("#leftmsgs_"+id+" .counter span").html());
			if(exist_count < msgs_count) {
				is_msg = true;
				$("#leftmsgs_"+id+" .counter span").html(msgs_count);
			}
		} else {
			is_msg = true;
			switch(sts) {
				case "0": cl = "offline"; break;;
				case "1": cl = "online"; break;;
				case "2": cl = "away"; break;;
			}
			if(i%2 == 0) { cl+=" box_suda"; } else { cl+=" box_licha"; }
			html += '<li id="leftmsgs_'+id+'" onclick="popup(\'app/get/msgs_window/'+id+'\', 600,'+id+');" class="'+cl+'"><span class="fLeft name">'+name+'</span><span class="counter">(<span>'+msgs_count+'</span>)</span><div class="clear"></div></li>';
		}
	}
	if(insert == 0) {
		html += "</ul>";
		$("#newMess .content").html(html);
	} else {
		$("#newMess .content ul").append(html);
	}
	pocet = 0;
	for(i=0;i<=$("#newMess .content ul li").size()-1;i++) {
		pocet += parseInt($("#newMess .content ul li:eq("+i+") .counter span").html());
	}
	//$("#newMess #mess_count").html($("#newMess .content ul li").size());
	$("#newMess #mess_count").html(pocet);
	if(pocet > 0) {
		document.title = "( "+pocet+" ) "+TITLE;
	} else {
		document.title = TITLE;
	}
	$("#onlineFriends #friend_counter").html($("#onlineFriends .content ul li").size());
	if(is_msg && playSound) {
		getData(scriptUrl+"index.php/sound/get","GET", "", "html", "showData", "#msgs_sound");
	}
}

function test_sound() {
	soundType = $("#msg_sound_combo option:selected").val();
	getData(scriptUrl+"index.php/sound/get_test_sound/"+soundType,"GET", "", "html", "showData", "#msgs_sound");
}

function FooterCsv() {
	var d = new Date();
	getData(scriptUrl+"index.php/app/get/footer/"+d.getMilliseconds(),"GET", "", "html", "incomeFooterCsv");
}

function incomeFooterCsv(IncomingData) {
	data_arr = IncomingData.split(';');
	data_count = data_arr.length;
	for(i=0;i<=data_count-2;i++) {
		data_item = data_arr[i].split(':');
		id=data_item[0];
		val=data_item[1];

		counter_size = $("#footer_"+id+" .count").size();
		if(counter_size == 0) {
			$("#footer_"+id).prepend('<span class="count block">0</span>');
		}
		counter_html = $("#footer_"+id+" .count").html();
		counter_html = eval(parseInt(counter_html)+parseInt(val));
		$("#footer_"+id+" .count").html(counter_html);
	}
}

function rightBlok() {
	/* update statusu */
	if(updateStatus) {
		img = $(".currentStatus").size();
		postQuery = "action=status&status=";
		for(i=1;i<=img;i++) {
			if($(".curStatus #"+i).attr("rel") == "") { st = 1; } else { st = 0; }
			postQuery+= st;
		}
		getData(scriptUrl+"index.php/app/post","POST", postQuery, "html", "");
		updateStatus = false;
	}

	if(false) {
		counter_size = $(".buttons #footer_msgs .count").size();
		if(counter_size == 0) {
			$(".buttons div").prepend('<span class="count block">0</span>');
		}
		counter_html = $(".buttons div .count").html();
		counter_html = eval(parseInt(counter_html)+parseInt(1));
		$(".buttons div .count").html(counter_html);
	} else {
		getData(scriptUrl+"index.php/app/get/leftfavs","GET", "", "html", "showData","#onlineFriends .content");
		MsgsCsv();
		FooterCsv();
	}

	if($("#rightBox .rightI[class*='hidden']").size() > 0) {
		box_item = $("#rightBox .rightI[class*='hidden']").html();
		$("#rightBox .rightI[class*='hidden']:eq(0)").remove();
		$("#rightBox").prepend('<div class="rightI hidden">'+box_item+'</div>');
		$("#rightBox .rightI[class*='hidden']:eq(0)").fadeIn(400,function() {
			$(this).removeClass("hidden");
			$(this).addClass("active");
			if($("#rightBox .rightI[class*='active']").size() > 4) {
				$("#rightBox .rightI[class*='active']:last").fadeOut(400,function() {
					$(this).remove();
				});
			}
		});
		
	} else {
		getData(scriptUrl+"index.php/app/get/right","GET", "", "html", "prependData",".box .mid #rightBox");
	}
}

/* SPOUSTENI */ 
	/* SLIDESHOW USERS */
	window.setInterval("loginNews()",10000);
	window.setInterval("mainNews()",6000);
	window.setInterval("rightBlok()",5000);
	/* SLIDESHOW NEWS */
	window.setInterval("loginPhotos()",5000);
/* # SPOUSTENI */

/* ================================= LOGIN PAGE ================================== */
/* VYHODNOCENI LOGINU */
function checkLogin(data) {
	if(data == "true") {
		document.location = scriptUrl+"index.php/app/get/home";
	} else {
		showAlert(BAD_LOGIN,2);
	}
}
/* SLIDESHOW NEWS */
function loginNews(){
	var news = $(".news div:eq(0)").html();
	$(".news div:eq(0)").hide(1000,function(){
		$(this).remove();
		$(".news div:last").after('<div>'+news+'</div>');
	});
}
/* SLIDESHOW USERS */
function loginPhotos(){
	var image = $(".slider .fLeft:eq(0)").attr("rel");
	var nick = $(".slider .fLeft:eq(0) a").attr("rel");
	if($(".slider .fLeft").length > 5){
		$(".slider .fLeft:eq(0)").hide(1000,function(){
			$(this).remove();
			$(".slider .fLeft:last").after('<div class="fLeft" rel="'+image+'" style="background-image:url(\''+image+'\');"><a href="'+scriptUrl+''+nick+'" rel="'+nick+'"></a></div>');
		});
	}
}
/* SUBMIT REGISTRACE */



/* asi pujde pryc */
function SubmitRegistration(){
	url = scriptUrl+"/index.php/user/register";
	User = $("input[name='registerUsername']").val();
	Pass = $("input[name='registerPassword']").val();
	PassCon = $("input[name='registerPassword_confirm']").val();
	Email = $("input[name='registerEmail']").val();
	DOB_day = $("select[name='register_date_of_birth_day'] option:selected").val();
	DOB_month = $("select[name='register_date_of_birth_month'] option:selected").val();
	DOB_year = $("select[name='register_date_of_birth_year'] option:selected").val();
	Terms = $("input[name='confirmTerms']").attr("checked");	
	if(User.length == 0 || Pass.length == 0 || Pass != PassCon || Email.length != 0 || !Terms) {
		showAlert(WRONG_PARAM,1);
		return;
	}
	var postData = "User="+User+"&Pass="+Pass+"&PassCon="+PassCon+"&Email="+Email+"&dob_day="+DOB_day+"&dob_month="+DOB_month+"&dob_year="+DOB_year+"&Terms="+Terms;
	showAlert('<p class="m20l">'+REGISTRATION_SEND+'<br /><br /><img src="'+loadingImage+'" border="0" /></p>',true);
	ret = getData(scriptUrl+"index.php/login/register","POST", postData, "html", "checkRegister");
	if(!ret) {
		showAlert(NOT_RESPONSE,1);
	}
}
/* SUBMIT REGISTRACE => VYHODNOCENI */
function checkRegister(data) {
	if(data == "true") {
		$(":text,:password").val("");
		$("select option").removeAttr("selected");
		$(":checkbox").removeAttr("checked");
		showAlert(REGISTRATION_OK,1);
	} else {
		showAlert(REGISTRATION_ERROR,1);
	}	
}
/* ================================= END LOGIN PAGE =============================== */

function send_comment(id,action,to,func_to,send_to,id_user) {
	send_post(id,action,to,func_to,send_to);
	comment_area = $('#comment_'+id_user).val();
	$('#profilecomment_'+id_user).html(comment_area);
	addComment('#p_ca_'+id_user,'user/post','profile_comment',id_user);
	return false;
}

function send_post_home(id,action,to,func_to,send_to) {
	if($("#home_mail").val() == "email") { return false; }
	send_post(id,action,to,func_to,send_to);
	message = "Email bude odoslaný vašemu kamarátovi";
	showAlert(message,2);
	return false;
}

function send_post_alert(id,action,to,func_to,send_to,id_wall,defval,message) {
	if($("#"+id_wall).val() == "" || $("#"+id_wall).val() == defval) {
		showAlert(message,2);
		return false;
	}
	send_post(id,action,to,func_to,send_to);
	return false;
}

function send_post_support(id,action,to,func_to,send_to) {
	if($("#support_textarea").val() == "") { return false; }
	send_post(id,action,to,func_to,send_to);
	message = "Váš dotaz bol odoslaný";
	$("#support_textarea").val("");
	showAlert(message,2);
	return false;
}

function send_post_remove(id,action,to,func_to,send_to,rem) {
	send_post(id,action,to,func_to,send_to);
	$("#"+rem).fadeOut(400,function(){
		$(this).remove();
	});
	return false;
}

function send_post_loading(id,action,to,func_to,send_to) {
	send_post(id,action,to,func_to,send_to);
	$(to).html('<div class="loadingM"></div>');
	return false;
}

/* Obecna funkce pro poslani postu */
function send_post(id,action,to,func_to,send_to) {
	if(send_to == "") { send_to = "app/post"; }
	if(func_to == "") { func_to = "showData"; }
	var postquery = $("#"+id).serialize();
	if(postquery.length > 0) {postquery+="&"; }
	postquery+="action="+action;
	getData(scriptUrl+"index.php/"+send_to,"POST", postquery, "html", func_to,to);
	return false;
}

function showData2(IncomeData,to) {
	alert(IncomeData);
}

/* ==================================== APPS PAGE ================================= */

function hideContent(content,img) {
	$(content).slideToggle("fast",function(){
		if($(img+" img").attr("rel") != "close") {
			$(img).html('<img src="http://sk.facebookvice.com/img/i_box_close.png" rel="close" alt="hide" />');
			$(content).removeClass("noHeight");
		} else {
			$(img).html('<img src="http://sk.facebookvice.com/img/i_box_open.png" rel="open" alt="hide" />');
			$(content).addClass("noHeight");
		}
	});
}
function application_menu() {
	$("#applications").slideToggle("fast");
}
function application_close() {
	$("#applications").fadeOut("fast");
}

function getLoading(url) {
	$(url).html('<div class="loading"></div>');
}
function LoadContent(url,element,title,postData) {
	application_close();
	$("html").scrollTop(0);
	popupClose();
	if(!postData) { postData = ""; }
	var tabs = $("#mainTabs ul li").length;
	$("#mainTabs ul li").removeClass("active");
	if($("#mainTabs ul li[rel='"+element+"']").size() > 0){
		$("#mainTabs ul li[rel='"+element+"']").addClass("active");
		if(postData.length > 0) {
			LoadContentBox(url,element,postData);
		}
	} else {
		if(tabs > 4){
			$("#mainTabs ul li:eq(0)").remove();
		}
		if(title.length > 10){
			liTitle = title.substr(0,10)+'&hellip;';
		} else {
			liTitle = title;
		}
		$("#mainTabs ul").append('<li class="head active" rel="'+element+'" title="'+title+'"><a href="#" onclick="LoadContentBox(\''+url+'\',\''+element+'\',\'\');">'+liTitle+'</a> <img src="http://sk.facebookvice.com/img/i_close_win.png" border="0" onclick="CloseTab(\''+element+'\')" /></li>');
        LoadContentBox(url,element,postData);
    }
}

function LoadContentBox(url, element, postData) {
	isActive = $("#mainTabs ul li[rel='"+element+"'][class^='head active']").length;
	if(isActive == 1) {
        if($(".main .content .contentBox[rel='"+element+"']").length == 0 || postData.length > 0) {
            $(".main .content .contentBox").hide();
			$(".main .content .contentBox[rel='"+element+"']").show();
            LoadContentBoxData(url,element,postData);
        }
        return;
	}
	$("#mainTabs ul li").removeClass("active");
	$("#mainTabs ul li[rel='"+element+"']").addClass("active");
	$(".main .content .contentBox").hide();
	if($(".main .content .contentBox[rel='"+element+"']").size() > 0) {
        $(".main .content .contentBox[rel='"+element+"']").show();
    } else {
        LoadContentBoxData(url,element,postData);
    }
}

function LoadContentBoxData(url,element,postData) {
	if(postData.lenght == 0) { postData = ""; }
	if($(".main .content .contentBox[rel='"+element+"']").size() == 0) {
		$(".main .content").append('<div class="contentBox" rel="'+element+'"><div class="loadingM"></div></div>');
	}
	to = ".main .content .contentBox[rel='"+element+"']";
	getData(scriptUrl+"index.php/"+url,"POST", postData, "html", "showData", to);
	return;
}

function LoadTabContent(url,rel,element,postData) {
	$("html").scrollTop(0);
	mainTabRel = $("#mainTabs ul li[class^='head active']").attr("rel");
	element = ".main .content .contentBox[rel='"+mainTabRel+"'] "+element;
	$(".main .content .contentBox[rel='"+mainTabRel+"'] .submenu li").removeClass("active");
	$(".main .content .contentBox[rel='"+mainTabRel+"'] .submenu li[rel='"+rel+"']").addClass("active");
	$(element).html('<div class="loadingM"></div>');
	getData(scriptUrl+"index.php/"+url,"POST", postData, "html", "showData", element);
}

function CloseTab(element){
	isActive = $("#mainTabs ul li[rel='"+element+"'][class^='head active']").length;
	if(isActive == 1) {
		$("#mainTabs ul li").removeClass("active");
	}
	$("#mainTabs ul li[rel='"+element+"']").remove();
	$(".content div[rel='"+element+"']").remove();
	if(isActive == 1) {
		var tabCount = $("#mainTabs ul li").size();
		var lastTabElement = $("#mainTabs ul li:eq("+(tabCount-1)+")").attr("rel");
		$("#mainTabs ul li[rel='"+lastTabElement+"']").addClass("active");
		$(".main .content .contentBox[rel='"+lastTabElement+"']").show();
	}
}


/* ================================= END APPS PAGE ================================ */

/* ============================== SPOLECNE FUNKCE ================================= */

/* GLOBALNI FUNKCE PRO KOMUNIKACI */
function getData(script_url,action,data,dataType,onSuccess,endObject) {
	if(script_url == "") {return false; }
	timeout = 30000;
	$.ajax({
		url: script_url,
		type: action,
		data: data,
		timeout: timeout,
		dataType: dataType,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			return false;
		},
		success: function (RetData) {
			if(onSuccess == "") { return true; }
			eval(onSuccess+"(RetData,endObject);");
			return true;
		}
	});
}

function appendDataFadeIn(IncomeData,to) {
	$(to).append(IncomeData);
	$(to+" div:last-child").fadeIn(400);
	//alert($(to+" div:eq(0)").html());
}

function prependData(IncomeData,to) {
	$(to).prepend(IncomeData);
}

function alertDataGallery(IncomeData,to) {
	popupClose();
	if(IncomeData == "ERROR") {
		showAlert("Chybné heslo",2);
	} else {
		$(to).html(IncomeData);
	}
}

function alertDataLogin(IncomeData,to) {
	popupClose();
	if(IncomeData == "login") {
		document.location = scriptUrl+"index.php/app/get/home";
	} else {
		showAlert(IncomeData,2);
	}
}

function alertData(IncomeData,to) {
	$("html").scrollTop(0);
	showAlert(IncomeData,2);
}


function prependStatus(IncomeData,to) {
	$(to).prepend('<div id="status" class="hidden">'+IncomeData+'</div>');
	$("#status").fadeIn('slow', function(){
		setTimeout("removeStatus()",6000);
	});
}

function removeStatus() {
	$("#status").fadeOut("slow", function(){
		$(this).remove();
	});
}

function showData(IncomeData,to) {
	if(to == "search_out") {
		var tabs = $("#mainTabs ul li").length;
		$("#mainTabs ul li").removeClass("active");
		if($("#mainTabs ul li[rel='"+to+"']").size() > 0){
			$("#mainTabs ul li[rel='"+to+"']").addClass("active");
			$(".main .content .contentBox").hide();
			$(".main .content .contentBox[rel='"+to+"']").show();
			to = ".main .content .contentBox[rel='"+to+"']";
		} else {
			if(tabs > 4){
				$("#mainTabs ul li:eq(0)").remove();
			}
			title = "Výsledek hledání";
			if(title.length > 10){
				liTitle = title.substr(0,10)+'&hellip;';
			} else {
				liTitle = title;
			}
			
			$("#mainTabs ul").append('<li class="head active" rel="'+to+'" title="'+title+'"><a href="#" onclick="LoadContentBox(\'\',\''+to+'\',\'\');">'+liTitle+'</a> <img src="http://sk.facebookvice.com/img/i_close_win.png" border="0" onclick="CloseTab(\''+to+'\')" /></li>');
			LoadContentBox("app/get/next_result",to,"");
			to = ".main .content .contentBox[rel='"+to+"']";
			return;
		}
	}
	$(to).html(IncomeData);
}

function report_spam(id_user) {
	if(confirm("Naozaj chcete nahlásiť spam?")) {
		postquery="action=report_spam&id_user="+id_user;
		getData(scriptUrl+"index.php/app/post","POST", postquery, "html", "","");
	} 
}

/* CONFIRM */
function showConfirm(postQuery,fncCallback,eleCallback,callServer,showText){
	application_close();
    var icon = "pup_i_1.png";
    if($("#confirm").length > 0){ $("#confirm").remove(); }
	if($("#alert").length > 0){ $("#alert").remove(); }
    var confirmHtml = '<div id="confirm">'+
        '<div id="confirmContent">'+
        '<div id="confirmContentLeft"><img src="'+scriptUrl+'img/'+icon+'" border="0" alt="alert" /></div>'+
        '<div id="confirmContentRight">'+showText+'</div>'+
        '<div id="confirmBottom"><div id="confirmBottomArea">'+
		'<div id="confirmBtn" onclick="send_post_confirm(\''+postQuery+'\',\''+fncCallback+'\',\''+eleCallback+'\',\''+callServer+'\');" class="b_sedy buttonDiv">Ok</div>'+
        '<div id="confirmBtn" onclick="closeConfirm();" class="b_sedy buttonDiv">Zavrieť</div><div class="clear"></div>'+
        '</div><div class="clear"></div></div>'+
        '</div>'+
        '</div>';
    $("div:first").before(confirmHtml);
    $("#confirm").fadeIn(300);
}

function closeConfirm(){
    $("#confirm").fadeOut(300,function(){
        $(this).remove();
    });
}

function send_post_confirm(postQuery,fncCallback,eleCallback,callServer) {
	closeConfirm();
	getData(scriptUrl+"index.php/"+callServer,"POST", postQuery, "html", fncCallback,eleCallback);
}


/* ALERT */
function showAlert(message,type){
	popupClose();
	application_close();
    switch(type){
        case 1: var icon = "pup_i_1.png"; break;
        case 2: var icon = "pup_i_2.png"; break;
        case 3: var icon = "pup_i_3.png"; break;
        default: var icon = "pup_i_1.png"; break;
    }
    if($("#alert").length > 0){ $("#alert").remove(); }
    var alertHtml = '<div id="alert">'+
        '<div id="alertContent">'+
        '<div id="alertContentLeft"><img src="'+scriptUrl+'img/'+icon+'" border="0" alt="alert" /></div>'+
        '<div id="alertContentRight">'+message+'</div>'+
        '<div id="alertBottom">'+
        '<div id="closeAlertButton" onclick="closeAlert();" class="b_sedy">OK</div>'+
        '</div>'+
        '</div>'+
        '</div>';
    $("div:first").before(alertHtml);
    $("#alert").fadeIn(300);
}
/* ZRUSENI ALERT */
function closeAlert(){
    $("#alert").fadeOut(300,function(){
        $(this).remove();
    });
}

function popup(url,width,id_user){
	if(id_user) {
		$("#leftmsgs_"+id_user+"").fadeOut(300,function(){
			$(this).remove();
		});
	}
	application_close();
	$("html").scrollTop(0);
	$("#pup").remove();
    $("#lightbox").fadeOut(500,function(){
	  $(this).remove();
    });
    if(!width){
	  width = 600;
    }
    var popupHtml	= '<div id="pup"></div>';
    
	$("body").prepend(popupHtml);
	var d = new Date();
	getData(scriptUrl+"index.php/"+url+"/"+d.getMilliseconds(),"GET", "", "html", "pup_html");

	$("#pup").css({
		"margin-left" : "-"+eval((width/2)+15)+"px",
		"width" : width+"px"
	});
	if($("#game").length > 0){
		$("#game").css({
			"visibility" : "hidden"
		});
	}
}

function pup_html(incomeData) {
	$("#pup").html(incomeData);
	
}

function popupClose(){
    $("#pup").remove();
    if($("#game").length > 0){
	  $("#game").css({
		"visibility" : "inherit"
	  });
    }
}

function getpopup(id) {
	$("#window_msg .msg_loading").remove();
	$("#window_msg").prepend('<div class="loading msg_loading"></div>');
	$('#window_msg').scrollTop(0);
	/* messageText=&id_user=1&action=send_msg */
	send_post(id,"send_msg","send_msg","ins_msg","");
	if(!$("#is_pupclose").attr("checked")) {
		popupClose();
	}
	$("#window_msg_area").val("");
}

function insert_smile(smile) {

var textarea = document.getElementById("window_msg_area");
if (typeof textarea.selectionStart != 'undefined') {
		var start    = textarea.selectionStart;
		var end      = textarea.selectionEnd;
		var text_stred = smile;
		textarea.focus();
		textarea.value = textarea.value.substr(0,start) + text_stred + textarea.value.substr(end);
		textarea.selectionStart = start + text_stred.length;
		textarea.selectionEnd   = start + text_stred.length;
	} else if (typeof document.selection != 'undefined') {		// www IE ; jestlize document.selection existuje, pak...
		var text_stred = smile;
		textarea.focus();
		var oznaceni   = document.selection.createRange();
		oznaceni.text  = text_stred;
		oznaceni.select();
	} else {
		text_stred      = smile;
		textarea.focus();
		textarea.value += text_stred;
	}
}

function ins_msg(html) {
	$("#window_msg .msg_loading").remove();
	$("#window_msg").prepend(html);
}

function check_it(id) {
	if($(id).attr("checked")) {
		$(id).attr("checked",false);
	} else {
		$(id).attr("checked",true);
	}
}

function addComment(element,url,action,id_user) {
	if($("#form_comment_"+id_user+"[class*='hidden']").size() == 1 || $("#form_comment_"+id_user+"[class*='active']").size() == 0) {
		comm_area = $("#profilecomment_"+id_user).html();
		var html = '<form id="form_comment_'+id_user+'" class="hidden active" action="#" method="post" onsubmit="return send_comment(\'form_comment_'+id_user+'\',\''+action+'\',\'\',\'ins_msg\',\''+url+'\','+id_user+');">';
		html += '<input type="hidden" name="id" value="'+id_user+'">';
		html += '<div class="comment">';
		html += '<textarea rows="1" name="comment" id="comment_'+id_user+'">'+comm_area+'</textarea>';
		html += '<input type="submit" class="fRight b_svestka" value="'+BTN_SEND+'">';
		html += '<div class="clear"></div>';
		html += '</div></from>';
		$(element).html(html);
		$("#form_comment_"+id_user).show(400,function(){
			$(this).removeClass("hidden");
		});
	} else {
		$("#form_comment_"+id_user).hide(400,function(){
			$(this).addClass("hidden");
		});
	}
}

/* ANIMACE JQUERY LIBRARY */
(function($) {
$.fn.animatedinnerfade = function(options) {
	  var mytimer;
	  var pauseActivated=false;
	  this.each(function(){
		var settings = {
		    animationtype: 'fade',
		    speed: 'normal',
		    timeout: 15000,
		    type: 'sequence',
		    containerheight: '300px',
		    containerwidth: '600px',
		    runningclass: 'innerfade',
		    animationSpeed: 15000,
		    bgFrame: 'none',
		    controlButtonsPath: 'img',
		    controlBox: 'none',
		    controlBoxClass: 'none',
		    displayTitle: 'none',
		    titleClass: 'innerfade-title'
		};
		$(this).css('margin', '0 0 0 0').css('padding', '0 0 0 0').find('img').css('border', 'none');
		if(options)
		    $.extend(settings, options);

		var elements = $(this).children();

		if (elements.length > 1) {

		    $(this).css('position', 'relative').css('overflow', 'hidden').css('height', settings.containerheight).css('width', settings.containerwidth);

		    $(this).addClass(settings.runningclass);

		    for ( var i = 0; i < elements.length; i++ ) {
			  $(elements[i]).css('position', 'absolute').css('top', 0).css('left', 0).css('z-index', String(elements.length-i));
			  $(elements[i]).hide();
		    };
		    $(elements[0]).css('top', 0);
		    $(elements[0]).css('left', 0);

		    $.animatedinnerfade.move_photo(elements[0], settings);

		    if ( settings.type == 'sequence' ) {
			  mytimer = setTimeout(function(){
				$.animatedinnerfade.next(elements, settings, 1, 0, mytimer, pauseActivated);
			  }, settings.timeout);

		    }
		    else {
			  var nextrandom;
			  do {
				nextrandom = Math.floor ( Math.random ( ) * ( elements.length ) );
			  } while ( nextrandom == 0 )
			  mytimer = setTimeout((function(){
				$.animatedinnerfade.next(elements, settings, nextrandom, 0, mytimer, pauseActivated);
			  }), settings.timeout);

		    }
		    $(elements[0]).show();
		}

	  });
};
$.animatedinnerfade = function() {}
$.animatedinnerfade.next = function (elements, settings, current, last, mytimer, pauseActivated) {
	  var vwidth =  - (parseInt($(elements[current]).find("img").attr("width"))-parseInt(settings.containerwidth));
	  if ((parseInt($(elements[current]).css('left')) == 0) || (parseInt($(elements[current]).css('left')) == vwidth))
	  {
		clearTimeout(mytimer);
		var vwidth =  - (parseInt($(elements[current]).find("img").attr("width"))-parseInt(settings.containerwidth));
		var next, prev;
		if (current == (elements.length - 1))
		    next = 0;
		else
		    next = current+1;
		if (current == 0)
		    prev = elements.length - 1;
		else
		    prev = current - 1;
		for ( var i = 0; i < elements.length; i++ ) {
		    if ((i != last) && (i != current))
		    {
			  $(elements[i]).css('z-index', '1');
			  $(elements[i]).css('top', 0).css('left', 0);
			  $(elements[i]).hide();
		    }
		}
		$(elements[last]).css('z-index', '190');
		$(elements[current]).css('z-index', '195');
		if (settings.bgFrame != 'none')
		    $(this).find(".bg-frame a").attr("href", $(elements[current]).find("a:first").attr("href"));

		$(elements[current]).css('top', 0).css('left', 0);
		if ( settings.animationtype == 'slide' ) {
		    $(elements[last]).slideUp(settings.speed, $(elements[current]).slideDown(settings.speed));
		} else if ( settings.animationtype == 'fade' ) {
		    $(elements[last]).fadeOut(settings.speed);
		    $(elements[current]).fadeIn(settings.speed);
		} else {
		    alert('animationtype must either be \'slide\' or \'fade\'');
		};
		$.animatedinnerfade.move_photo(elements[current], settings);
		if ( settings.type == 'sequence' ) {
		    mytimer = setTimeout((function(){
			  $.animatedinnerfade.next(elements, settings, next, current, mytimer, pauseActivated);
		    }), settings.timeout);
		}
		else
		{
		    var nextrandom;
		    do {
			  nextrandom = Math.floor ( Math.random ( ) * ( elements.length ) );
		    } while ( nextrandom == current )
		    mytimer = setTimeout((function(){
			  $.animatedinnerfade.next(elements, settings, nextrandom, current, mytimer, pauseActivated);
		    }), settings.timeout);
		}
	  }
};
$.animatedinnerfade.move_photo = function (element, settings) {
	  if (settings.animationSpeed > 0)
	  {
		var vheight =  - (parseInt($(element).find("img").attr("height"))-parseInt(settings.containerheight));
		var vwidth =  - (parseInt($(element).find("img").attr("width"))-parseInt(settings.containerwidth));
		if (vheight > 0) vheight = 0;
		if (vwidth > 0) vwidth = 0;
		$(element).show().css('left', 0).css('top', 0).animate({
		    top: vheight,
		    left: parseInt(vwidth/2)
		    }, parseInt(settings.animationSpeed/2)).animate({
		    top: 0,
		    left: vwidth
		}, parseInt(settings.animationSpeed/2));
	  }
};

})(jQuery);


// Pri volani UPLOADU
// Nutne vratit true, na submit formulare
function startCallback(id) {
	//$("#"+id).fadeOut(300,function(){});
	$("#"+id+" ").parents("div:eq(0)").prepend('<div class="loading"></div>');
	//$("#div_"+id).html('<div class="loading"></div>');
	return true;
}

// Pri navratu UPLOADU
function completeCallback(ret) {
	id_gallery = $("#new_photo_gallery option:selected").val();
	LoadTabContent('user/get/gallery_detail/'+id_gallery,'gallery_detail','.cont');
	//alert(ret);
	//$("#"+id+"_div").html('OK');
}

AIM = {
	frame : function(c) {
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
		return n;
	},
	form : function(f, name) {
		f.setAttribute('target', name);
	},
	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart(f.id);
		} else {
			return true;
		}
	},
	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}
}

/* Upload fotky pro skupiny */

// Pri navratu UPLOADU
function completeGroupCallback(ret) {
 	id_gallery = $("#new_group_photo_gallery option:selected").val();
 	id_group = $("#id_groups").val();
 	LoadTabContent('app/get/group/admin/'+id_group+'/'+id_gallery,'group_admin','.cont');
	//alert(ret);
	//$("#"+id+"_div").html('OK');
}
