/**
 *
 * Spustanie
 *
 **/
jQuery(document).ready(function() {

	/**
	 *
	 * Inicializacie
	 *
	 **/
	cv_init();
	cv_autocomplete('');
	validationForms_init();
	profile_init();
	comment_init();
	message_init();
	misc_init();
	rating_init();
	report_init();
	online_users();
	new_Events();
	checkAll();
	checkNone();
	$(".filetree").treeview();
	$("#friends").tabs();
	$("#groups").tabs();
	$("#showOnlineUsers").tabs();
	$("#showOnlineCompanies").tabs();
	$("#files").tabs();
	$("#advSearch").tabs();
	$("#settings").tabs();
	$("#events").tabs();
	$("#poll").tabs();
	$("#employees").tabs();
	$("#companies").tabs();
	$("#projects").tabs();
	$("#bizplan").tabs();
	$("#jobs").tabs();
	$("#job").tabs();
	$("#modules").tabs();
	$("#feedback").tabs();
	$("#app_buy").tabs();
	$("#proInv").tabs();
	$("#invoices").tabs();
	$("#profile-tabs").tabs();
	$("#adminCompanies").tabs();
	$("#dobropis").tabs();
	$("#regProInv").tabs();
	$("#news").tabs();
	$("#event").tabs();
	$("#public-search").tabs();
	$("#promotion").tabs();
	
	$('.password').pstrength();
	$('textarea.expanding').autogrow();
	$("#accordion").accordion({ autoHeight: false,navigation: true });
	$("#accordionAddress").accordion({ autoHeight: false,navigation: true });	
	screenshotPreview();
	//divcontentloader();
	confirm();
  confirm2();
  appbuyconfirm();
	confirmKos();
	confirmDelUser();


	$("#icons a").tooltip();

  $('.styleswitch').click(function()
		{
			switchStylestyle(this.getAttribute("rel"));
			return false;
		});
		var c = $.cookie('style');
		if (c) switchStylestyle(c);

  //new
	$('input.searchinput, input.email').addClass("idleField");
	$('input.searchinput, input.email').focus(function() {
		$(this).removeClass("idleField").addClass("focusField");
		if (this.value == this.title){
			this.value = '';
		}
		if(this.value != this.title){
			this.select();
		}
	});
	$('input.searchinput, input.email').blur(function() {
		if (this.value == ''){
			$(this).removeClass("focusField").addClass("idleField");
			this.value = this.title;
		} else if (this.value == this.title){
			$(this).removeClass("focusField").addClass("idleField");
		}
		else{
		}
	});

	$('.wrap .menubox ul li.roll').hover(
	function() {
		$(this).children("ul").stop(true, true).fadeIn(300);
	},function() {
		$(this).children("ul").stop(true, true).fadeOut(300);
	});
	
	$("#content_loader").css("display", "none");
	$("#content").css("visibility", "visible");
	$("#footer").css("visibility", "visible");
});


// Validacia formularov
var validationForms_init = function() {
	$("#registrationForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#bizPlanForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#bizPlanEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#groupForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#groupEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#newTopicForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#profileUserForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#profileCompanyForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#eventsForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#eventsEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#pollForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#pollEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#jobForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#editJob").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#projectForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#projectEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#invationForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#invationCompForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#dCompProf").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#eventForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#eventEditForm").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
	$("#composeMessage").validate({success: function(label) {label.html("&nbsp;").addClass("checked");}});
};

$(function()
{
	$('#country').chainSelect('#state','index.php?ajax=selectcity',
	{
		before:function (target) //before request hide the target combobox and display the loading message
		{
			$("#loading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target) //after request show the target combobox and hide the loading message
		{
			$("#loading").css("display","none");
			//$(target).css("display","inline");
		},
      defaultValue:getQuerystring('state')
	});
	$('#state').chainSelect('#city','index.php?ajax=selectcity',
	{
		before:function (target)
		{
			$("#loading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target)
		{
			$("#loading").css("display","none");
			//$(target).css("display","inline");
		},
      defaultValue:getQuerystring('city')
	});
});

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
function chainselectCity(){
  jQuery(function($)
    {
    $('#country').change();
    $('#state').change();
    });
}

function chainselectCityEdit(){
  jQuery(function($)
    {
    $('#editcountry').change();
    $('#editstate').change();
    });
}

$(function()
{
	$('#editcountry').chainSelect('#editstate','index.php?ajax=selectcity',
	{
		before:function (target) //before request hide the target combobox and display the loading message
		{
			$("#editloading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target) //after request show the target combobox and hide the loading message
		{
			$("#editloading").css("display","none");
			$(target).css("display","inline");
		},
      defaultValue:$("#editstatevalue").val()
	});
	$('#editstate').chainSelect('#editcity','index.php?ajax=selectcity',
	{
		before:function (target)
		{
			$("#editloading").css("display","block");
			$(target).css("display","none");
		},
		after:function (target)
		{
			$("#editloading").css("display","none");
			$(target).css("display","inline");
		},
      defaultValue:$("#editcityvalue").val()
	});
});

function switchStylestyle(styleName)
	{
		$('link[@rel*=style][title]').each(function(i)
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		$.cookie('style', styleName, { expires: 365 });
	}
$(function() {
//when key is pressed in the textbox
$(".digits_only").keypress(function (e) {
  //if the letter is not digit then display error and don't type anything
  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
    //display error message
//    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
  }
});
});

$(function() {
//when key is pressed in the textbox
$(".digits_space").keypress(function (e) {
  //if the letter is not digit then display error and don't type anything
  if( e.which!=8 && e.which!=0 && e.which!=32 && (e.which<48 || e.which>57)) {
    //display error message
//    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
  }
});
});
$(function() {
	$("#feedModules").sortable({
		disabled:true,
		update: function() {
			position = $("#feedModules").sortable('serialize');
			$.ajax({
				url: "index.php?ajax=setfeedposition",
				type: "post",
				data: position
			});
		}
	});

	$('.move').mouseover(function(){$("#feedModules").sortable("option", "disabled", false)});
	$('.row').mouseover(function(){
	    $("#feedModules").sortable("option", "disabled", true);
	    $("#feedModules").attr("class", "ui-sortable");
	});

});
$(function() {
	$("#userMenu").sortable({
		update: function() {
			position = $("#userMenu").sortable('serialize');
			$.ajax({
				url: "index.php?ajax=setmenuposition",
				type: "post",
				data: position
			});
		}
	});
});
$(function() {
	$("#userModules").sortable({
	  disabled:true,
		update: function() {
			position = $("#userModules").sortable('serialize');
			$.ajax({
				url: "index.php?ajax=setmoduleposition",
				type: "post",
				data: position
			});
		}
	});

	$('.move').mouseover(function(){$("#userModules").sortable("option", "disabled", false)});
	$('.row').mouseover(function(){
	    $("#userModules").sortable("option", "disabled", true);
	    $("#userModules").attr("class", "ui-sortable");
	});
});
$(function() {
	$(".userFeed").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			.end()
		.find(".userFeed-content").hide();

	$(".roll").click(function() {
		$(this).parents(".userFeed:first").find(".userFeed-content").toggle();
	});
});

$(function() {
	$("#userModules").sortable({
	  disabled:true,
		update: function() {
			position = $("#userModules").sortable('serialize');
			$.ajax({
				url: "index.php?ajax=setmoduleposition",
				type: "post",
				data: position
			});
		}
	});

	$('.move').mouseover(function(){$("#userModules").sortable("option", "disabled", false)});
	$('.row').mouseover(function(){
	    $("#userModules").sortable("option", "disabled", true);
	    $("#userModules").attr("class", "ui-sortable");
	});

	$(".userModule").addClass("ui-widget ui-helper-clearfix ui-corner-all")
			.end()
		.find(".userModule-content");
	$(".hiddenModule").find(".userModule-content").hide();

	$(".roll").click(function() {
		$(this).parents(".userModule:first").find(".userModule-content").toggle('blind', {}, 500, function() {
			idParent = $(this).parents(".userModule:first").attr("id");
			$.ajax({
				url: "index.php?ajax=togglemodule",
				type: "post",
				data: {module: idParent}
			})
		});
	});

/*	$(".userModule-header .ui-icon-triangle-1-w").click(function() {
		$(this).toggleClass("ui-icon-triangle-1-w");
		$(this).parents(".userModule:first").find(".userModule-content").toggle('blind', {}, 500, function() {
			idParent = $(this).parents(".userModule:first").attr("id");
			$.ajax({
				url: "index.php?ajax=togglemodule",
				type: "post",
				data: {module: idParent}
			})
		});
	});
*/
	$(".um_cancel").click(function() {
		$(this).parents(".userModule:first").hide('blind', {}, 500, function() {
			idParent = $(this).attr("id");
			$.ajax({
				url: "index.php?ajax=closemodule",
				type: "post",
				data: {module: idParent}
			})
		});
	});


});

// dialog pre zaslanie ankiet
$(function() {
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: true,
			height: 430,
			width: 450,
			modal: true,
			buttons: {
				'Odoslať anketu': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#send-poll').click(function() {
			$('#dialog').dialog('open');
		});
	});

// dialog pre overovanie e-mailov
$(function() {
		$("#dialog_emailCheck").dialog({
			bgiframe: true,
			autoOpen: true,
			height: 250,
			width: 350,
			modal: true,
			buttons: {
				'Odoslať': function() {
				    document.myform.submit();
						$(this).dialog('close');
				}
			}
		});

	});

// dialog pre zaslanie pracovnych ponuk
$(function() {
		$("#dialog_job").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Odoslať správu': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#send-job').click(function() {
			$('#dialog_job').dialog('open');
		});
	});

// dialog pre zaslanie projektov
$(function() {
		$("#dialog_project").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Odoslať správu': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#send-project').click(function() {
			$('#dialog_project').dialog('open');
		});
	});

// dialog pre eventov
$(function() {
		$("#dialog_event").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Odoslať správu': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#send-event').click(function() {
			$('#dialog_event').dialog('open');
		});
	});

// dialog pre zaslanie biznis planov
$(function() {
		$("#dialog_bizplan").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Odoslať správu': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#send-bizplan').click(function() {
			$('#dialog_bizplan').dialog('open');
		});
	});

$(function() {
		$("#dialogInvite").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Pozvať do skupiny': function() {
				    document.inviteDialog.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#inivteFriends').click(function() {
			$('#dialogInvite').dialog('open');
		});
	});

$(function() {
		$("#dialogShow").dialog({
			bgiframe: true,
			autoOpen: true,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Zavrieť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#inivteFriends').click(function() {
			$('#dialogInvite').dialog('open');
		});
});
$(function() {
		$("#dialogShowAttending").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Zavrieť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#dialogShowAttendingClick').click(function() {
			$('#dialogShowAttending').dialog('open');
		});
});
$(function() {
		$("#dialogShowMaybeAttending").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			modal: true,
			buttons: {
				'Zavrieť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#dialogShowAttendingMaybeClick').click(function() {
			$('#dialogShowMaybeAttending').dialog('open');
		});
});

$(function() {
		$("#dialogFeedback").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 350,
			width: 550,
			modal: true,
			buttons: {
				'Odoslať': function() {
				    //document.feedbackDialog.submit();
				    //$('#dialogFeedbackReply').dialog('open');
						//$(this).dialog('close');
						$.ajax({
						 	type: "post",
           		url: "?ajax=feedback",
           		data: "&feedbackSubject=" + $("#dialogFeedback").find("input#feedbackSubject").val() + "&feedbackMsg=" + $("#dialogFeedback").find("textarea#feedbackMsg").val()+ "&referer=" + $("#dialogFeedback").find("input#referer").val(),
           		success: function(data) {
           		  $('#dialogFeedbackReply').dialog('open');
           		  $("#feedbackSubject").val("");
           		  $("#feedbackMsg").val("");
						    $("#dialogFeedback").dialog('close');
              }
           	});

				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#openFeedback').click(function() {
			$('#dialogFeedback').dialog('open');
		});

	});
$(function() {
		$("#dialogFeedbackReply").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 300,
			width: 500,
			modal: true,
			buttons: {
				'Zatvoriť': function() {
					$(this).dialog('close');
				}
			}
		});
	});

  	$(function() {
		$("#dialogLiReg").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 350,
			width: 550,
			modal: true,
			buttons: {
				'Registrovať': function() {
				    document.liRegDialog.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#dialogLiRegClick').click(function() {
			$('#dialogLiReg').dialog('open');
		});

	});
function openDialogLiReg(){
  
  
  	$("#dialogLiReg").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 350,
			width: 550,
			modal: true,
			buttons: {
				'Registrovať': function() {
				    document.liRegDialog.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});
		
		$('#dialogLiReg').dialog('open');
}	
$(function() {
		$("#dialogReport").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 350,
			width: 550,
			modal: true,
			buttons: {
				'Odoslať': function() {
						$.ajax({
						 	type: "post",
           		url: "?ajax=report",
           		data: "&reportSubject=" + $("#dialogReport").find("input#reportSubject").val() + "&reportMsg=" + $("#dialogReport").find("textarea#reportMsg").val()+ "&referer=" + $("#dialogFeedback").find("input#referer").val()+ "&reportReason=" + $('input:radio[name=reportReason]:checked').val()+ "&type=" + $("#dialogReport").find("input#reportType").val(),
           		success: function(data) {
           		  $("#reportSubject").val("");
           		  $("#reportkMsg").val("");
						    $("#dialogReport").dialog('close');
              }
           	});

				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#dialogReportClick').click(function() {
			$('#dialogReport').dialog('open');
		});

	});

$(function() {
		$("#dialogJobReplay").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 450,
			width: 550,
			modal: true,
			buttons: {
				'Odoslať': function() {
				    $('#dialogJobReplay2').dialog('open');
						document.jobDialog.submit();
            $('#dialogJobReplay').dialog('close');

				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#dialogJobReplayClick').click(function() {
			$('#dialogJobReplay').dialog('open');
		});
	});

$(function() {
		$("#dialogJobReplay2").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 450,
			width: 550,
			modal: true,
			buttons: {

			}
		});
	});

// dialog pre kontaktovanie autora biznis planu
$(function() {
		$("#dialog_bizplanContact").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 400,
			width: 550,
			modal: true,
			buttons: {
				'Odoslať': function() {
						document.contactform.submit();
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#dialog_bizplanContactClick').click(function() {
			$('#dialog_bizplanContact').dialog('open');
		});
	});
// dialog pre zobrazenie adries
$(function() {
		$("#dialogShowAddress").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 600,
			width: 700,
			modal: true,
			buttons: {
				'Zatvoriť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#dialogShowAddressClick').click(function() {
			$('#dialogShowAddress').dialog('open');
		});
	});

// dialog na potvrdenie akcie
var confirm = function() {
    $('a.confirmClick:not(a[href^=javascript])').click(
  function(event) {
    event.preventDefault();
    $('.confirm').dialog('option', 'href', this.href).dialog('open');
  });


		$(".confirm").dialog({
		  autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Vykonať akciu': function() {
					 var href = $(this).dialog('option', 'href');
           window.location.href = href
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});
	}

var confirm2 = function() {
    $('#confirmClick2').click(function() {
			$('#confirm2').dialog('open');
		});


		$("#confirm2").dialog({
		  autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			buttons: {
				'Vykonať akciu': function() {
					  document.confirmForm.submit();
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});
	}

$(function() {
		$("#dialogAppbuy").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 100,
			width: 300,
			modal: true
		});


		$('#appBuyButton').click(function() {
			$('#dialogAppbuy').dialog('open');
		});
	});

// dialog na potvrdenie akcie
var appbuyconfirm = function() {
    $('.appbuyConfirmClick:not(a[href^=javascript])').click(
  function(event) {
    event.preventDefault();
    $('.appbuyconfirm').dialog('open');
  });


		$(".appbuyconfirm").dialog({
		  autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:470,
			width:470,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Potvrdiť údaje': function() {
				   $('#dialogAppbuy2').dialog('open');
				   $(this).dialog('close');
				  $.ajax({
          		 	type: "post",
             		url: "?ajax=companyProfile",
             		// Posielane data
             		data: "&street=" + $("input#street").val() + "&psc=" + $("input#psc").val()+ "&city=" + $("input#city").val()+ "&country=" + $("select#country").val()+ "&ico=" + $("input#ico").val()+ "&dic=" + $("input#dic").val()+ "&dic_dph=" + $("input#dic_dph").val(),
             		success: function(data) {
          					 document.buyappform.submit();
          					 }
        		});
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});

		$("#dialogAppbuy2").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 100,
			width: 300,
			modal: true
		});
	}

$(function() {
		$("#dialogCompProf").dialog({
			bgiframe: true,
			autoOpen: true,
			height: 460,
			width: 560,
			modal: true,
			buttons: {
				'Uložiť': function() {
				    document.myform.submit();
						$(this).dialog('close');
				},
				'Zrušiť': function() {
					$(this).dialog('close');
				}
			}
		});


		$('#inivteFriends').click(function() {
			$('#dialogInvite').dialog('open');
		});
	});
// dialog o BestBrains
$(function() {
		$("#dialog_investor").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 200,
			width: 550,
			modal: true,
			buttons: {
				'Zatvoriť': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#dialog_investorClick').click(function(){
			$('#dialog_investor').dialog('open');
			return false;
		});
	});


// oznacenie vsetkych priatelov v dialogu na poslanie ankety
var checkAll =  function() { $("A[href='#select_all']").click( function() {
            $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true);
            return false;
        });
};
var checkNone =  function() { $("A[href='#select_none']").click( function() {
            $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', false);
            return false;
        });
};

// ROZLICNE
var misc_init = function() {
	// Klonovanie posledneho riadku v tabulke
		$('div.clone').appendo({subSelect:"table.form", copyHandlers: true, onAdd: cv_autocomplete_last });
};

var cv_autocomplete_last = function(){
	cv_autocomplete(":last");
}

function cv_autocomplete(param) {
	// AUTO DOPLANANIE NAZVU UNIVERZITY
	// Hladanie hodnoty
	function findValue(li) {
		if(li == null) { return alert("No match!"); }
  		if(!!li.extra) { var sValue = li.extra[0]; }
  		else { var sValue = li.selectValue; }
  		//alert(&quot;The value you selected was: &quot; + sValue);
  	}

	// Funkcia, ktora sa vykona ked vyberieme univerzitu
	function selectItem(li) { $.get("?ajax=universityRank", { name: li.selectValue } ); }

	// Format polozky v zozname
	//function formatItem(row, q) { return highlight(row[0], q); } // so zviraznenim hladaneho retazca
	function formatItem(row) { return row[0] /*+ " (id: " + row[1] + ")"*/; }

	// Funkcia na zvyraznenie hladaneho retazca vo vyslednom retazci
	function highlight(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }

	// Hladanie v zozname
	function lookupAjax(){
		var oSuggest = $(".universityName")[0].autocompleter;
		oSuggest.findValue();
		var oSuggest2 = $(".facultyName")[0].autocompleter;
		oSuggest2.findValue();
  		return false;
	}

	// Nastavenia pluginu
	//"index.php?ajax=universityName"
	
	$(".universityName"+param).autocomplete(
	"index.php?ajax=universityName",
    {
		delay: 10,
  		minChars: 1,
  		matchSubset: 2,
  		matchContains: 2,
  		cacheLength: 10,
  		maxItemsToShow: 15,
  		onItemSelect: selectItem,
  		onFindValue: findValue,
		formatItem: formatItem,
		autoFill: false
	});
	
	var curFaculty;
	$(".facultyName"+param).focus(function(){
		curFaculty = $(this);
	});
	$(".facultyName"+param).autocomplete(
	"index.php?ajax=facultyName",
	{
		delay: 10,
  		minChars: 1,
  		matchSubset: 2,
  		matchContains: 2,
  		cacheLength: 10,
  		maxItemsToShow: 15,
  		onItemSelect: selectItem,
  		onFindValue: findValue,
		formatItem: formatItem,
		extraParams: {
			university: function(){
				return curFaculty.parents('td:first').find('.universityName').val();
			}
		},
		autoFill: false
	});
	
	var curBranch;
	$(".branchName"+param).focus(function(){
		curBranch = $(this);
	});
	$(".branchName"+param).autocomplete(
	"index.php?ajax=branchName",
	{
		delay: 10,
  		minChars: 1,
  		matchSubset: 2,
  		matchContains: 2,
  		cacheLength: 10,
  		maxItemsToShow: 15,
  		onItemSelect: selectItem,
  		onFindValue: findValue,
		formatItem: formatItem,
		extraParams: {
			university: function(){
				return curBranch.parents('td:first').find('.universityName').val();
			},
			faculty: function(){
				return curBranch.parents('td:first').find('.facultyName').val();
			}
		},
		autoFill: false
	});
	
		$(".companyName"+param).autocomplete(
	"index.php?ajax=companyName",
	{
		delay: 10,
  		minChars: 1,
  		matchSubset: 2,
  		matchContains: 2,
  		cacheLength: 10,
  		maxItemsToShow: 15,
  		onItemSelect: selectItem,
  		onFindValue: findValue,
		formatItem: formatItem,
		autoFill: false
	});
	

}

// ZIVOTOPIS
var cv_init = function() {
	// Taby pre vytvorenie noveho zivotopisu
	$('#createCV').tabs();

	// Mazanie riadkov
	$(".deleteRow").click(function() {
		$tableForm = $(this).parents("table.form");
		$tableForm.find("input, textarea").val("");

		$tableForm.fadeOut(0, function() {
			$(this).html("<div class=\"info-message success\">Položka bola úspešné zmazaná</div>").fadeIn(2000, function() {
				$(this).fadeOut(2000);
			});
		});
		return false;
	});
	
	$('#miscSkillAdd').click(function(){
		$('#miscSkill1 option:selected').each(function(index) {
			var optClass = $(this).parents('optgroup:first').attr('class');
			$(this).remove().prependTo('#miscSkill2 .'+optClass);
		});
		return false;
	});
  
  
	$('#miscSkillRemove').click(function() {
		$('#miscSkill2 option:selected').each(function(index) {
			var optClass = $(this).parents('optgroup:first').attr('class');
			$(this).remove().prependTo('#miscSkill1 .'+optClass);
		});
		return false;
	});

  $('form#updateCV').submit(function() {
   $('#miscSkill2 option').each(function(i) {
    $(this).attr("selected", "selected");
   });
  });

  $('#miscSkillAdd3').click(function() {
  	$('#miscSkill3 option:selected').each(function(index) {
  		var optClass = $(this).parents('optgroup:first').attr('class');
		$(this).remove().prependTo('#miscSkill4 .'+optClass);
  	});
  	return false;
  });
  $('#miscSkillRemove3').click(function() {
  	$('#miscSkill4 option:selected').each(function(index) {
  		var optClass = $(this).parents('optgroup:first').attr('class');
  		$(this).remove().prependTo('#miscSkill3 .'+optClass);
  	});
  	return false;
  });
  $('form#editJob').submit(function() {
   $('#miscSkill4 option').each(function(i) {
    $(this).attr("selected", "selected");
   });
  });
};

// PROFIL
var profile_init = function() {
	function showCoords(c) {
		jQuery('#x').val(c.x);
		jQuery('#y').val(c.y);
		jQuery('#x2').val(c.x2);
		jQuery('#y2').val(c.y2);
		jQuery('#w').val(c.w);
		jQuery('#h').val(c.h);
	};

	// Crop-ovanie profiloveho obrazku
	jQuery('#profileImage').Jcrop({
		onSelect: showCoords,
    setSelect: [ 0, 0, jQuery('#w').val(), jQuery('#h').val() ],
    aspectRatio: 1/1,
   	minSize: [80, 80]
	});

	// Crop-ovanie obrazku spolocnosti
	jQuery('#companyImage').Jcrop({
		onSelect: showCoords,
    setSelect: [ 0, 0, jQuery('#w').val(), jQuery('#h').val() ],
   	minSize: [37, 37]
	});

	$(function(){
	  $("select#prof_country").change(function(){
	    $.getJSON("index.php",{ajax: 'getRegion', id_country: $(this).val()}, function(j){
	      var options = '';
	      if (j.length > 0)
	      	options += '<option value=""></option>';
	      for (var i = 0; i < j.length; i++) {
	        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
	      }
	      $("select#prof_region").html(options);
	    });
	  });
	});
};

// KOMENTARE
var comment_init = function() {

	// Rozbijeme si url
	$.urlParam = function(strParamName) {
	  var strReturn = "";
	  var strHref = window.location.href;
	  var bFound=false;

	  var cmpstring = strParamName + "=";
	  var cmplen = cmpstring.length;

	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        bFound=true;
	        break;
	      }

	    }
	  }
	  if (bFound==false) return null;
	  return strReturn;
	}


	// Zmazanie komentaru po odkliknuti
	$.fn.deleteComment = function(options) {
		// Po odkliknuti vykonaj dany blok prikazov
		$(this).click(function() {
			// Skryjeme prislusny komentar
    		$(this).parent().fadeOut("slow");
			// Nadefinujeme si AJAX objekt
			var ajaxDelete = {
				type: "get",
				url: "?ajax=commentDelete",
				data: "&id=" + $(this).parent().find("#commentID").val(),
				sucess: function(data) {}
			};
			// Vyvolaj AJAX objekt
			$.ajax(ajaxDelete);
		});
	}

	// Prijmeme vsetky komentare
	if ($.urlParam("page") != null) {
	$.getJSON("?ajax=commentGet&sourceTable=" + $("#leaveComment").find("input#sourceTable").val() + "&sourceID= " + $("#leaveComment").find("input#sourceID").val() + "&commentPage=" + $.urlParam('page') + "&jsoncallback=?", function(data) {
		// Ak niejaky komentar vobec existuje
		if (data != null) {
			// Prejdeme si cele pole
   		for (var x = 0; x < data.length; x++) {
   			// Vytvorime si kontajner pre kazdy jeden komentar
      		var div = $("<div>").addClass("row").appendTo("#comments");
      		// Mazanie prispevkov
      		if (data[x].name == $("#leaveComment").find("input#id").val()) {
      			// Objekt pre mazanie prispevku
      			$("<div>").addClass("delete").text("Zmazat").appendTo(div).deleteComment();
      		}

      		// Pripojime meno uzivatela
      		$("<div>").addClass("name").text(data[x].fullname).appendTo(div);
       		// Pripojime text spravy
      		$("<div>").addClass("text").text(data[x].text).appendTo(div);
      		// Pripojime si id spravy
      		$("<div>").html("<input type=\"hidden\" id=\"commentID\" name=\"commentID\" value=\"" + data[x].comment + "\" />").appendTo(div);
			}
		}
	});
}
	// Pridavanie komentarov
	$("#add").click(function() {
		// Nadefinujeme si AJAX objekt
  		var ajaxOpts = {
  		 	type: "post",
   		url: "?ajax=commentSet",
   		// Posielane data: ID pouzivatela a samotny komentar
   		data: "&tid=" + $("#leaveComment").find("input#tid").val() + "&comment=" + $("#leaveComment").find("textarea#newComment").val(),
   		success: function(data) {
      		//create a container for the new comment
      	//	var div = $("<div>").addClass("row clearfix").appendTo("#comments");
      if($("#leaveComment").find("input#type").val() == "user") {
          if($("#leaveComment").find("input#image").val() == 1){
  			     var obrazok = "<img class=\"prof_obr\" src=\"index.php?action=image&type=profile&id="+ $("#leaveComment").find("input#id_user").val() +"&w=50\" alt=\""+ $("#leaveComment").find("input#fullname").val()+"\" width=\"50\"/>";
  			   }else{
  				   var obrazok ="<img class=\"prof_obr\" src=\"file/graphic/default.gif\" width=\"50\" height=\"50\" />";
           }
       } else {
          if($("#leaveComment").find("input#image").val() == 1){
    		     var obrazok = "<img class=\"prof_obr\" src=\"index.php?action=image&type=company&id="+ $("#leaveComment").find("input#id_user").val() +"&w=50\" alt=\""+ $("#leaveComment").find("input#fullname").val()+"\" width=\"50\"/>";
    		   }else{
    			   var obrazok ="<img class=\"prof_obr\" src=\"file/graphic/default_comp.gif\" width=\"50\"/>";
           }
        }

        var sprava = $("#leaveComment").find("textarea#newComment").val();
        sprava = sprava.replace(/\n/g,"<br />");
        Stamp = new Date();
        var cas = "" + Stamp.getDate() +"."+(Stamp.getMonth() + 1)+ "."+Stamp.getFullYear() + "<br/>"+Stamp.getHours() +":"+Stamp.getMinutes()+ ":"+Stamp.getSeconds()+"";
        var kod = "<div class=\"fl\"><div class=\"left\">"+obrazok+"</div><div class=\"right\"><strong><a href=\"index.php?action=profile&subaction=show&type=users&id="+ $("#leaveComment").find("input#id_user").val() +"\">"+ $("#leaveComment").find("input#fullname").val()+"</a></strong><br />"+$("#leaveComment").find("input#company_position").val()+"<br />"+cas+"</div></div><div class=\"fr\"><div class=\"comment_bg\"><div class=\"comment\">"+sprava+"<br /></div><div class=\"comment_button\">&nbsp;&nbsp;&nbsp;</div></div></div>";
        $("<div>").addClass("row clearfix").html(""+kod+"").appendTo("#comments");

      	var theint = parseInt($("#num_of_comment").html(),10)
        theint++;
        $("#num_of_comment").html(theint);

        $("#leaveComment").find("textarea#newComment").val("");

			}
		};
		//  Uplatni nastavenia
  		$.ajax(ajaxOpts);
	});

};

// SPRAVY
var message_init = function() {
	// Taby pre vytvorenie noveho zivotopisu
	$('#message').tabs();


      $("input.SendTo").autobox({
        ajax: "index.php?ajax=messageList",
        match: function(typed) {
          this.typed = typed;
          this.pre_match = this.text;
          this.match = this.post_match = '';
          if (!this.ajax && !typed || typed.length == 0) { return true; }
          var match_at = this.text.search(new RegExp("\\b" + typed, "i"));
          if (match_at != -1) {
            this.pre_match = this.text.slice(0,match_at);
            this.match = this.text.slice(match_at,match_at + typed.length);
            this.post_match = this.text.slice(match_at + typed.length);
            return true;
          }
          return false;
        },
        insertText: function(obj) { return obj.text },
        templateText: "<li><%= pre_match %><span class='matching' ><%= match %></span><%= post_match %></li>"
      });



    $("input.SendTo")
        .bind("activate.autobox", function(e, d) { console.log(d); })
        .bind("cancel.autobox", function(e) { console.log("Cancelled"); });
};

// Hviezdickovy rating projektov
var rating_init = function() {
	$(function(){
		$('.rating-star').rating({
			required: true,
			focus: function(value, link){
				// 'this' is the hidden form element holding the current value
				// 'value' is the value selected
				// 'element' points to the link element that received the click.
				var tip = $('#rating-tip');
				tip[0].data = tip[0].data || tip.html();
				tip.html(link.title || 'value: '+value);
			},
			blur: function(value, link){
				var tip = $('#rating-tip');
				$('#hover-test').html(tip[0].data || '');
			},
			callback: function(value, link){
				// 'this' is the hidden form element holding the current value
				// 'value' is the value selected
				// 'element' points to the link element that received the click.
				//alert("The value selected was '" + value + "'\n\nWith this callback function I can automatically submit the form with this code:\nthis.form.submit();");

				// To submit the form automatically:
				this.form.submit();

				// To submit the form via ajax:
				//$(this.form).ajaxSubmit();
			}
		});
	});
};


var report_init = function() {
	$(function() {
		$("#report_done_close").click(function() {
			$("#report_done").hide("highlight",{},1500);
			return false;
		});
		$("#report_error_close").click(function() {
			$("#report_error").hide("highlight",{},3000);
			return false;
		});
		$("#report_info_close").click(function() {
			$("#report_info").hide("highlight",{},2000);
			return false;
		});
	});
	if (!($('#report_done:visible').hasClass("noautoclose")))
		setTimeout("$('#report_done:visible').hide('highlight',{},500)", 5000);
	if (!($('#report_error:visible').hasClass("noautoclose")))
		setTimeout("$('#report_error:visible').hide('highlight',{},1000)", 10000);
	if (!($('#report_info:visible').hasClass("noautoclose")))
		setTimeout("$('#report_info:visible').hide('highlight',{},500)", 5000);
};

// Zobrazenie poctu online a registrovanych pouzivatelov
var online_users = function() {
	$.get('index.php?ajax=online', function(online_data){
		online_array = online_data.split('|');
		$('#onlineCompanies').html('('+online_array[0]+')');
		$('#onlineUsers').html('('+online_array[1]+')');
		$('#regCompanies').html('('+online_array[2]+')');
		$('#regUsers').html('('+online_array[3]+')');
	});
	setTimeout("online_users()", 5000);
};
// New events
var new_Events = function() {
	$.get('index.php?ajax=newevents', function(newsData){
		news_array = newsData.split('|');
		show = false;
		htmlout = '';
		if (news_array[0] > 0) {
		  show = true;
			htmlout += '<a href="index.php?action=pm" title="Prečítať správu"><span class="msg">Prijatá nová správa ('+news_array[0]+')</span></a>';
		}
		if (news_array[1] > 0) {
		  show = true;
			htmlout += '<a href="index.php?action=friends#friends-6" title="Pozrieť požiadavku"><span class="sgs">Požiadavka o kontakt ('+news_array[1]+')</span></a>';
		}
		if (news_array[2] > 0) {
		  show = true;
			htmlout += '<a href="index.php?action=groups#groups-5" title="Pozrieť pozvánku"><span class="inv">Pridanie do skupiny ('+news_array[2]+')</span></a>';
		}
		if (show) {
			$('#newEventsInner').html(htmlout);
			$('#newEvents').css('display', 'block');
		}
	});
	setTimeout("new_Events()", 5000);
}
// file uploader
var init_uploader = function(swfPath, imagePath, backend, extensions, extDesc, filesize, currentDir, fileList) {

	/**
	 * Disables the link
	 */
	jQuery.fn.disableLink = function(fn) {
		return jQuery(this).blur().unbind('click').fadeTo("fast", 0.2, (fn ? fn : null));
	};
	//
	// Constants
	jQuery.uploader.swfURL = swfPath+'jquery.uploader.swf';
	jQuery.uploader.backendScript = backend;
	/**
	 * Removes the upload (manually) by clicking the eject button
	 */
	function uploadDelete(_link, _self) {
		var _id = _link.parent().parent().attr('id');
		//
		// Disable links to prevent user from clicking again which could screw up the interface
		jQuery('#' + _id + ' A.delete').disableLink();
		jQuery('#' + _id + ' A.start').disableLink();
		jQuery('#' + _id + ' A.cancel').disableLink();
		jQuery('#' + _id + ' A.retry').disableLink();
		//
		// Send the "remove" event to flash
		_self.remove(_id);
	}
	/**
	 * Starts the upload (manually) by clicking the play button
	 */
	function uploadStart(_link, _self) {
		_self.upload(_link.parent().parent().attr('id'), jQuery.uploader.backendScript);
	}

	/**
	 * Restores the element back to it's "not started" state.
	 */
	function uploadRestore(_elem, _self, _allowRemoveOrRetry) {
		//
		// Fix links
		jQuery('A.cancel', _elem).hide();
		if (_allowRemoveOrRetry) {
			jQuery('A.delete', _elem).fadeTo("fast", 1.0).click(function() { uploadDelete(jQuery(this), _self) });
			jQuery('A.retry', _elem).show();
		} else {
			jQuery('A.retry', _elem).show().disableLink();
		}
		//
		// Fix progressbar
		jQuery('DIV.wuICPB', _elem).hide();
		jQuery('div.wuICPBF', _elem).width(0).html(' 0% ');
		jQuery('DIV.wuICPT', _elem).hide();
		//
		// Animate the progressbar
		_elem.removeClass('active').animate({ height: 40 }, 200);
	}

	jQuery(document).ready(function() {
			//jQuery('#bbVis').attr('checked', 'checked');
			//log.toggle();
			//log.move(3);
			//
			// Step 1: Create fancy hover buttons
			jQuery('button:not(#btnBrowse)').hover(
													function() {
														$(this).css('background-position', '0px -30px');
													},
													function() {
								  						$(this).css('background-position', '0px 0px');
													}
												);
				//
			// Step 2: Add the uploader
			var oUpload = $('#uploaderOverlay').uploader({
														swfURL: jQuery.uploader.swfURL,
														buttonSkin: imagePath+'buttonSkin.png',
														maxThreads: 1,
														logging: "1"
													});
				//
			// Step 3: Overwrite the events (base events have allready been setup)
			jQuery.extend(oUpload.events, {
						/**
					 * SWF ready handler, used to bind the events the way YOU want.
					 */
					uploaderReady: function() {
							var _self = this;
							_self.setFilters([
                                   { description: extDesc, extensions: extensions }
                               ]);
							_self.setMaxFileSize(filesize);
							//
							// Upload ALL files (therefore the empty '' at the beginning)
							jQuery('#btnUpload').click(function() { _self.upload('', jQuery.uploader.backendScript); });
								//
							// Clear the entire queue (e.g. remove all files)
							jQuery('#btnClear').click(function() { _self.remove(); });
						},
						/**
					 * File added handler
					 */
					fileAdded: function(args) {
							var _id = '';
							_id = args.fileData.id;
								var sHTML = '';
							sHTML+= '<div class="wuI" id="' + _id + '">';
							sHTML+= '<div class="wuIC">';
							sHTML+= '<a href="javascript://" class="delete" title="Delete upload">&nbsp;</a> ';
							sHTML+= '<a href="javascript://" class="start" title="Start upload">&nbsp;</a> ';
							sHTML+= '<a href="javascript://" class="cancel" title="Cancel upload">&nbsp;</a> ';
							sHTML+= '<a href="javascript://" class="retry" title="Retry upload">&nbsp;</a> ';
							sHTML+= '&nbsp;' + args.fileData.name + '<br />';
							sHTML+= '<div class="wuICPB"><div class="wuICPBF"> 0% </div></div>';
							sHTML+= '<div class="wuICPT"><span class="wuICBytesDone">0 bytes</span> of <span class="wuICBytesTotal">' + this.formatSize(args.fileData.size) + '</span> <span class="wuICSpeedTime">&nbsp;</span></div>';
							sHTML+= '</div></div>';
							var _elem = jQuery(sHTML);
							jQuery('.wuQ').append(_elem);
								// Add handler
							var _self = this;
								//
							// Triggers file removal
							jQuery('A.delete', _elem).click(function() { uploadDelete(jQuery(this), _self) });
							jQuery('A.start', _elem).click(function() { uploadStart(jQuery(this), _self) });
							jQuery('A.retry', _elem).click(function() { uploadStart(jQuery(this), _self) });
							jQuery('A.cancel', _elem).click(function() { _self.cancel(_id); });
								//
							// Prevent me from calling this in a later function ...
							_elem = null;
						},
						/**
					 * File removed handler
					 */
					fileRemoved: function(args) {
							jQuery('#' + args.fileData.id).slideUp("fast", function() { jQuery(this).remove(); });
						},
						/**
					 * File upload handler,
					 * in this demo used to change the icons
					 */
					fileUploadStarted: function(args) {
							var _id = args.fileData.id;
							var _self = this;
							var _elem = jQuery('#' + _id);
								//
							// You could delete the file while uploading,
							// (since this would trigger a "cancel" event in the Flash movie which is send to JavaScript)
							// but for the sake of the demo, we don't allow it.
								//
							// Fix links
							jQuery('A.delete', _elem).disableLink();
							jQuery('A.start', _elem).hide();
							jQuery('A.retry', _elem).hide();
							jQuery('A.cancel', _elem).show();
							//
							// Animate the progressbar
							_elem.addClass('active').animate({ height: 80 }, 200);
								//
							// Show elements
							jQuery('DIV.wuICPB', _elem).show();
							jQuery('DIV.wuICPT', _elem).show();
						},
						/**
					 * File progress handler
					 * in this demo used to update the progressbar
					 * @param args.fileData
					 * @param args.fileProgress
					 * @param args.queueProgress
					 */
					fileUploadProgress: function(args) {
							var _id = args.fileData.id;
							var _self = this;
							var _elem = jQuery('#' + _id);
								jQuery('h2.wuQS').html('Uploader queue: ' + args.queueProgress.progress + '% of ' + (args.queueProgress.filesAdded - args.queueProgress.filesCompleted) + ' files');
							jQuery('div.wuICPBF', _elem).css('width', args.fileProgress.progress + '%').html('&nbsp;' + args.fileProgress.progress + '%&nbsp;');
							jQuery('span.wuICBytesDone', _elem).html(this.formatSize(args.fileProgress.bytesCompleted));
							jQuery('span.wuICSpeedTime', _elem).html('at ' + this.formatSize(args.fileProgress.bytesPerSecond) + '/sec; ' + this.formatTime(args.fileProgress.timeRemaining) + ' remain');
						},
						/**
					 * Triggered when a file is cancelled
					 */
					fileUploadCancelled: function(args) {
							var _id = args.fileData.id;
							var _self = this;
							var _elem = jQuery('#' + _id);
							uploadRestore(_elem, _self, true);
						},
						/**
					 * Triggered when a file is uploaded (or has an error)
					 */
					fileUploadCompleted: function(args) {
							var _id = args.fileData.id;
							var _self = this;
							var _elem = jQuery('#' + _id);
							uploadRestore(_elem, _self, false);
						},
						/**
					 * Triggered when a file is uploaded (or has an error)
					 */
					fileUploadError: function(args) {
							var _id = args.fileData.id;
							var _self = this;
							var _elem = jQuery('#' + _id);
							uploadRestore(_elem, _self, false);
						},
						/**
					 * Triggered when there are no files in the queue
					 */
					queueErrorEmpty: function(args) {
							alert('No files to upload. Queue is empty!');
						},
						/**
					 * Called when the entire queue is cancelled
					 */
					queueCancelled: function() {
							jQuery('h2.wuQS').html('Uploader queue');
						},
						/**
					 * Called when the entire queue is cancelled
					 */
					queueCleared: function() {
							jQuery('h2.wuQS').html('Uploader queue');
						},
						/**
					 * Called when the entire queue is uploaded/completed
					 */
					queueCompleted: function() {
							jQuery('h2.wuQS').html('Uploader queue');
							$.ajax({
								url: 'index.php?ajax=getFileList',
								data: {
									current: currentDir,
									oldList: fileList
								},
								type: "POST",
								success: function(newFileListStr) {
									 newFilesList = newFileListStr.split('|');
									 oldFilesList = fileList.split('|');
									 countOld = oldFilesList.length;
									 oldFill = 4 - (countOld % 4);
									 var i = 1;
									 var filesAdded = 0;
									 if (oldFill < 4) {
										 for (i = 1; i <= oldFill; i++) {
										 	if (newFilesList.length > 0) {
												fileStr = newFilesList.shift();
												fileArr = fileStr.split('::');
												htmlcontent = '<a href="index.php?action=files&fid='+fileArr[0]+'">';
												htmlcontent += '<img src="file/graphic/filetypes/'+fileArr[1]+'.png" /><br />';
												htmlcontent += fileArr[2];
												htmlcontent += '</a><br />';
												if (fileArr[3] != 'folder')
													htmlcontent += '('+fileArr[4]+')';
												$('#filesLast-'+i).html(htmlcontent);
												$('#filesLast-'+i).attr("class", "")
												$('#filesLast-'+i).attr("id", "");
												filesAdded++;
											}
											else {
												if (filesAdded > 0) {
													newid = i - filesAdded;
													$('#filesLast-'+i).attr("id", 'filesLast-'+newid);
												}
											}
										}
									}
									htmlcontent = '';
									filesAdded = 0;
									listLength = newFilesList.length;
									for (i = 0; i < listLength; i++) {
										if (i % 4 == 0)
											htmlcontent += '<tr>';
										htmlcontent += '<td>';
										fileStr = newFilesList.shift();
										fileArr = fileStr.split('::');
										htmlcontent += '<a href="index.php?action=files&fid='+fileArr[0]+'">';
										htmlcontent += '<img src="file/graphic/filetypes/'+fileArr[1]+'.png" /><br />';
										htmlcontent += fileArr[2];
										htmlcontent += '</a><br />';
										if (fileArr[3] != 'folder')
											htmlcontent += '('+fileArr[4]+')';
										htmlcontent += '</td>';
										if (i % 4 == 3)
											htmlcontent += '</tr>';
										filesAdded++;
									}
									insertblank = 4 - (filesAdded % 4);
									if (insertblank < 4) {
										for (i = 1; i <= insertblank; i++) {
											htmlcontent += '<td class="blank" id="filesLast-'+i+'">&nbsp;</td>';
										}
										htmlcontent += '</tr>';
									}
									$("#filesList > tbody").append(htmlcontent);
									window.location.href = 'index.php?action=files&current='+currentDir;
								}
							});
						}
				});
		});
};

var init_status = function(statusMax) {
	// Status editable box
	$(function() {
		$(".userStatus").editable("index.php?ajax=setStatus", {
			indicator : "<img src='file/css/jquery/indicator.gif' />",
			type   : "text",
			select : true,
			submit : 'Zmeniť',
			maxlength : statusMax,
			cancel : 'Zrusiť',
			cssclass : 'editable',
			name : 'newstatus'
		});
	});
};

var pagination = function(pager, page, limit, formPost) {
	formPost = formPost || null;
	$("#"+pager+"Content").html('<img src="file/graphic/indicator.gif" alt="loading..."/>');
	$.post(
		'index.php?ajax=paginationContent',
		{pager:pager,page:page,limit:limit,formPost:formPost},
		function(data){
			$.post(
				'index.php?ajax=paginationNavigation',
				{pager:pager,page:page,limit:limit,formPost:formPost},
				function(dataPager){
					$("#"+pager+"Pager").html(dataPager);
					$("#"+pager+"Content").html(data);
				}
			);
		}
	);
}

// funckia na oznacenie/odznacenie vsetkych
function changeBox(cbox) {
box = eval(cbox);
box.checked = !box.checked;
}

// funcia pri pouzivani timepickra v kalendary
function toggleAllDayEvent(chbox, container) {
	if($("#"+chbox).is(":checked")){
	  $("#"+container).hide();
	}
	else{
	  $("#"+container).show();
	}
  }

// funkcia na skryvanie datumu v zivotopise ak je aktualne zamestnanie
function hiddenText(cislo) {
    if ($('div.skryt'+cislo).is(':visible')) {
     $('div.skryt'+cislo).hide();
    } else {
     $('div.skryt'+cislo).show();
    }
  }

// kontroluje spravnost zadania datumu v tvare YYYY-MM-DD
function checkDate(date) {
  // regular expression to match required date format
  re = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;

  if(date.value != '') {
    if(regs = date.value.match(re)) {
      if(regs[3] < 1 || regs[3] > 31) {
        alert("Zadaný deň neexistuje: " + regs[3]);
        date.focus(); return false;
      }
      if(regs[2] < 1 || regs[2] > 12) {
        alert("Zadaný mesiac neexistuje: " + regs[2]);
        date.focus(); return false;
      }
      if(regs[1] < 1902 || regs[1] > 3000) {
        alert("Zle zadaný rok: " + regs[1]);
        date.focus(); return false;
      }
    } else {
      alert("Zlý format dátumu: " + date.value);
      date.focus(); return false;
    }
  } else {
    alert("Nezadali ste dátum !");
    date.focus(); return false;
  }
  return true;
}

// kontroluje srpavnost zadania casu v tvare HH:MM
function checkTime(time) {
  // regular expression to match required time format
   re = /^(\d{1,2}):(\d{2})?$/;

   if(time.value != '') {
    if(regs = time.value.match(re)) {
       if(regs[1] > 23 || regs[1] < 0) {
            alert("Zle zadaná hodina: " + regs[1]);
            time.focus(); return false;
          }
       if(regs[2] > 59 || regs[2] < 0) {
          alert("Zle zadaná minúta: " + regs[2]);
          time.focus(); return false;
        }
     } else {
      alert("Zlý format času: " + time.value);
      time.focus(); return false;
     }
  }
  return true;
}

// kontroluje ci je to cislo
function checkNumber(text) {
//var x=document.addProject.projectReward.value;
var anum=/(^\d+$)|(^\d+\.\d+$)/
if (anum.test(text)){
  return true;
}else{
  alert("Zlý format ponukanej odmeny.\nPriklad: 200.50!")
  return false
}
}

var screenshotPreview = function(){
	/* CONFIG */

		xOffset = 10;
		yOffset = 30;

		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result

	/* END CONFIG */
	$("a.screenshot").hover(function(e){
		this.t = this.title;
		this.title = "";
    if(this.rel == ""){
		  var c = (this.t != "") ? "" + this.t : "";
		  $("body").append("<center><p id='screenshot'>"+ c +"</p></center>");
		}else{
		  var c = (this.t != "") ? "<br/>" + this.t : "";
		  $("body").append("<center><p id='screenshot'><img src='"+ this.rel +"' alt='&nbsp;' />"+ c +"</p></center>");
		}

    if(this.rel == "") $("#screenshot").css("background-image","url('')");
		$("#screenshot")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#screenshot").remove();
    });

	$("a.screenshot").mousemove(function(e){
		$("#screenshot")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

var divcontentloader = function(divko, formPost) {
	formPost = formPost || null;
	$("#divContent-"+formPost+"").html('<img src="file/graphic/indicator.gif" alt="loading..."/>');
	$.post(
		'index.php?ajax=divContent',
		{divko:divko,formPost:formPost},
		function(data){
					$("#divContent-"+formPost+"").html(data);
				}
	);
}

$(function() {
	var $gallery = $('#gallery'),
		$trash = $('#trash'),
		$deleteFilesButton = $('#delete-selected-files'),
		$emptyTrashButton = $('<a id="empty-trash" class="delete-button ui-corner-all" href="javascript:;" title="Zmazať súbory v koši">Vysypať koš</a>');
		$trash.prepend($emptyTrashButton);
		
		$deleteFilesButton.css({'display': 'none'});

	if($trash.find('li').length > 0){
		$emptyTrashButton.css({'display': ''});
	}else{
		$emptyTrashButton.css({'display': 'none'});
	}
	
	
	$gallery.selectable({
		cancel: 'a.ui-icon',
		selected: function(event, ui) {
			$deleteFilesButton.fadeIn();
		},
		unselected: function(event, ui) {
			$deleteFilesButton.fadeOut();
		}
	});

	// let the trash be droppable, accepting the gallery items
	//$trash.droppable({
	//	accept: '#gallery > li',
	//	activeClass: 'ui-state-highlight',
	//	drop: function(ev, ui) {
	//		deleteImage(ui.draggable);
	//	}
	//});

	// let the gallery be droppable as well, accepting items from the trash
	//$gallery.droppable({
	//	accept: '#trash li',
	//	activeClass: 'custom-state-active',
	//	drop: function(ev, ui) {
	//		recycleImage(ui.draggable);
	//	}
	//});

			// image deletion function
	var recycle_icon = '<a href="" title="Recycle this image" class="ui-icon ui-icon-refresh">Recycle image</a>';

	function deleteImage($item) {
		
		if($item.length == 1){
		
			deleteImageEffects($item);
		
		}else if($item.length >= 2){
		
			$("#gallery").children(".ui-selected").each(function(index) {
				deleteImageEffects($(this));
			});
		
		}
	}

	function deleteImageEffects($item){
		$deleteFilesButton.fadeOut();

		$emptyTrashButton.fadeIn();

		$item.fadeOut(function() {
			//var $list = $('ul',$trash).length ? $('ul',$trash) : $('<ul class="gallery ui-helper-reset"/>').appendTo($trash);
			var $list = $('#trash-gallery').appendTo($trash);

			$item.find('a.ui-icon-trash').remove();
			$item.find('.file-size').hide();
			$item.append(recycle_icon).appendTo($list).fadeIn(function() {
				$item.animate({ width: '48px' }).find('img').animate({ 'width': '48px', 'height': '48px' });
			});
		});
	}

			// image recycle function
	var trash_icon = '<a href="" title="Delete this image" class="ui-icon ui-icon-trash">Delete image</a>';
	function recycleImage($item) {
		if($('ul', $trash).length == 0){
			$emptyTrashButton.fadeOut();
		}
		$item.fadeOut(function() {
			$item.find('a.ui-icon-refresh').remove();
			$item.find('.file-size').show();
			$item.css({'width':'100px'})
				.append(trash_icon)
				.find('img')
				.css({'width': '100px', 'height': '100px'})
				.end()
				.appendTo($gallery)
				.fadeIn();
		});
	}

	// image preview function, demonstrating the ui.dialog used as a modal window
	function goTo($link) {
		var src = $link.attr('href');

		window.location.href=""+src+"";
	}

	// resolve the icons behavior with event delegation
	$('ul.gallery > li').click(function(ev) {
		var $item = $(this);
		var $target = $(ev.target);

		if ($target.is('a.ui-icon-trash')) {
			deleteImage($item);
			trashImage($item, true);
		} else if ($target.is('a.ui-icon-info')) {
			goTo($target);
		} else if ($target.is('a.ui-icon-arrowreturnthick-1-s')) {
			goTo($target);
		} else if ($target.is('a.ui-icon-refresh')) {
			recycleImage($item);
			trashImage($item, false); 
		}

		return false;
	});

	$deleteFilesButton.live('click', function(){
		var $selected = $("#gallery").children(".ui-selected");
		
		deleteImage($selected);
		trashImage($selected, true);

	});
	
	function trashImage($selected, throwToTrash){
		if(throwToTrash){
			$selected.wrapAll('<form id="trash-form-throw" />');
			queryString = $('#trash-form-throw').serialize();
			$selected.parent('#trash-form-throw').removeAttr('id');
		}else{
			$selected.wrapAll('<form id="trash-form-recycle" />');
			queryString = $('#trash-form-recycle').serialize();
			$selected.parent('#trash-form-recycle').removeAttr('id');
		}
		
		
		if(throwToTrash == true)
			queryString += '&action=throwToTrash';
		else
			queryString += '&action=recycleFromTrash';
			
		$.post(
			'index.php?ajax=fileTrash',
			 queryString,
			function(data){
				if(data.length > 0)
					alert(data.error);
			},
			"json"
		);
	}

});

var confirmKos = function() {
$(".confirmKos").dialog({
		  autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Vykonať akciu': function() {
				$('#kos').submit();
				},
				Zrušiť: function() {
					$(this).dialog('close');
				}
			}
		});

$('#empty-trash').live('click', function(){
		$('.confirmKos').dialog('open');
});
}

var confirmDelUser = function() {
$(".confirmDelUser").dialog({
		  autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Vykonať akciu': function() {
          document.deleteUser.submit();
				},
				Zrušiť: function() {
					$(this).dialog('close');
				}
			}
		});

$('#delUser').click(function(){
		$('.confirmDelUser').dialog('open');
});
}


// funckie na doplnanie vyhladavania
function lookup(inputString, num, redirect) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions'+num+'').hide();
    } else {
        var inputType = document.getElementById('tablelimit'+num+'').value;
        $.post("index.php?ajax=topSearch", {string: ""+inputString+"",type: ""+inputType+"",num: ""+num+"",redirect: ""+redirect+""}, function(data){
            if(data.length >0) {
                $('#suggestions'+num+'').show();
                $('#autoSuggestionsList'+num+'').html(data);
            } else {
                $('#suggestions'+num+'').hide();
            }
        });
    }
} // lookup

function fill(thisValue, num) {
   $('#inputString'+num+'').val(thisValue);
   $('#suggestions'+num+'').hide();
}

function hidesugges(num){
    $('#suggestions'+num+'').hide();
}


//koniec funkcie na vyhladavanie
function fillFaculty(element, thisValue) {
	$(element).parents('td:first').find('.facultyName').val(thisValue);
	$(element).parents('td:first').find('.facultySuggestions').hide();
}
function fillBranch(element, thisValue) {
	$(element).parents('td:first').find('.branchName').val(thisValue);
	$(element).parents('td:first').find('.branchSuggestions').hide();
}

// funckia na zväcsovanie fontu
function resizeFont(size) {
      document.body.style.fontSize = ""+size+"em";
      $.cookie('font_size', ''+$.cookie('font_size')+'',{ expires: -31 });
      $.cookie('font_size', ''+size+'',{ expires: 31 });
}

function setFontSize() {
      var ulozeny = $.cookie('font_size');
      if (ulozeny == null) {
        $.cookie('font_size', '0.7',{ expires: 31 });
        ulozeny = 0.7;
      }else{
        if (ulozeny != 0.7) {$('body').css('font-size', ulozeny+'em');}
      }
}


function printJob() {
   $( "#print_job").print();
}

function terms(lang){
  if(lang == "sk")
    window.open('page/terms_sk.html','novinky','width=600,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
  else
    window.open('page/terms_en.html','novinky','width=600,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
}

function terms2(lang){
  if(lang == "sk")
    window.open('page/obchodne_podmienky_sk.html','novinky','width=600,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
  else
    window.open('page/obchodne_podmienky_en.html','novinky','width=600,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
}

function sendStats(type,id,what){
  $.ajax({
   	type: "post",
  	url: "?ajax=sendStats",
  	data: "&type=" + type + "&id=" +id+ "&what=" + what,
  	success: function(data) {
    }
  });
}

function getSelectboxSkills(){
$('[name=ITSkill[]]').each(function() {
    $('#ITSkillNew option[value="'+$(this).val()+'"]').remove();
  });
}

function addSelectboxSkills(id){
  $('#ITSkillNew').append('<option value="'+id+'">'+$('#ITSkill-'+id).val()+'</option>');
}

function saveItSkillValues(){
	if($("#ITSkillNew").val() > 0 && $("#ITLevelNew").val() > 0){
		$('#definedItSkillsContainer').append('<tr id="itSkillsRow-'+$("#ITSkillNew").val()+'">' +
		'<td>' + 
		$("#ITSkillNew option:selected").text()+
		'<input type="hidden" name="ITSkill[]" value="'+$("#ITSkillNew").val()+'" />'+
		'<input type="hidden" name="ITSkill-'+$("#ITSkillNew").val()+'" id="ITSkill-'+$("#ITSkillNew").val()+'" value="'+$("#ITSkillNew option:selected").text()+'" />'+
		'<input type="hidden" name="ITLevel[]" value="'+$("#ITLevelNew").val()+'" />'+
		'</td>'+
		'<td>'+
		$("#ITLevelNew option:selected").text()+
		'</td>'+
		'<td><a href="#" class="button" onclick="removeItSkill('+$("#ITSkillNew").val()+');return false;">' +
		'<img src="file/graphic/icons/cancel_icon.png" alt="delete" /> Zmazať'+
		'</td></tr>');
		getSelectboxSkills();
		$('#ITSkillNew').val(0);
		$('#ITLevelNew').val(0);
	}
}

function removeItSkill(id){
  addSelectboxSkills(id);
  $('#itSkillsRow-'+id).remove();
  $('#ITSkillNew').val(0);
  $('#ITLevelNew').val(0);
}

function getSelectboxSkillsL(){
$('[name=langSkill[]]').each(function() {
    $('#LANGSkillNew option[value="'+$(this).val()+'"]').remove();
  });
}

function addSelectboxSkillsL(id){
  $('#LANGSkillNew').append('<option value="'+id+'">'+$('#LANGSkill-'+id).val()+'</option>');
}

function saveLangSkillValues()
{
	if($("#LANGSkillNew").val() > 0 && $("#LANGLevelNew").val() > 0){
		$('#definedLangSkillsContainer').append('<tr id="langSkillsRow-'+$("#LANGSkillNew").val()+'">' +
		'<td>' + 
		$("#LANGSkillNew option:selected").text() + '</td>' +
		'<input type="hidden" name="langSkill[]" value="'+$("#LANGSkillNew").val()+'" />'+
		'<input type="hidden" name="LANGSkill-'+$("#LANGSkillNew").val()+'" id="LANGSkill-'+$("#LANGSkillNew").val()+'" value="'+$("#LANGSkillNew option:selected").text()+'" />'+
		'<input type="hidden" name="langLevel[]" value="'+$("#LANGLevelNew").val()+'" />'+
		'<td>' + $("#LANGLevelNew option:selected").text() + '</td>' +
		'<td><a href="#" class="button" onclick="removeLangSkill('+$("#LANGSkillNew").val()+');return false;">'+
		'<img src="file/graphic/icons/cancel_icon.png" alt="delete" /> Zmazať'+'</td></tr>');
		getSelectboxSkillsL();
		$('#LANGSkillNew').val(0);
		$('#LANGLevelNew').val(0);
	}
}

function removeLangSkill(id){
  addSelectboxSkillsL(id);
  $('#langSkillsRow-'+id).remove();
  $('#LANGSkillNew').val(0);
  $('#LANGLevelNew').val(0);
}


function getSelectboxSkills2(){
$('[name=newITSkill[]]').each(function() {
    $('#newITSkillNew option[value="'+$(this).val()+'"]').remove();
  });
}

function addSelectboxSkills2(id){
  $('#newITSkillNew').append('<option value="'+id+'">'+$('#newITSkill-'+id).val()+'</option>');
}

function saveItSkillValues2(){
  if($("#newITSkillNew").val() > 0 && $("#newITLevelNew").val() > 0){
    $('#definedItSkillsContainer2').append('<div class="row" id="newitSkillsRow-'+$("#newITSkillNew").val()+'">'+
	'<input type="hidden" name="newITSkill[]" value="'+$("#newITSkillNew").val()+'" />'+
	'<input type="hidden" name="newITSkill-'+$("#newITSkillNew").val()+'" id="newITSkill-'+$("#newITSkillNew").val()+'" value="'+$("#newITSkillNew option:selected").text()+'" />'+
	'<input type="hidden" name="newITLevel[]" value="'+$("#newITLevelNew").val()+'" />'+
	'<div class="left">'+
	  $("#newITSkillNew option:selected").text()+
	'</div>'+
	'<div class="middle">'+
	  $("#newITLevelNew option:selected").text()+
	'</div>'+
	'<div class="navi" onclick="removeItSkill2('+$("#newITSkillNew").val()+');">'+
	  '<img src="file/graphic/icons/cancel_icon.png" alt="delete" /> Zmazať'+
	'</div></div>');
    getSelectboxSkills2();
    $('#newITSkillNew').val(0);
    $('#newITLevelNew').val(0);
  }
}

function removeItSkill2(id){
  addSelectboxSkills2(id);
  $('#newitSkillsRow-'+id).remove();
  $('#newITSkillNew').val(0);
  $('#newITLevelNew').val(0);
}

function getSelectboxSkillsL2(){
$('[name=newlangSkill[]]').each(function() {
    $('#newLANGSkillNew option[value="'+$(this).val()+'"]').remove();
  });
}

function addSelectboxSkillsL2(id){
  $('#newLANGSkillNew').append('<option value="'+id+'">'+$('#newLANGSkill-'+id).val()+'</option>');
}

function saveLangSkillValues2(){
  if($("#newLANGSkillNew").val() > 0 && $("#newLANGLevelNew").val() > 0){
    $('#definedLangSkillsContainer2').append('<div class="row" id="newlangSkillsRow-'+$("#newLANGSkillNew").val()+'">'+
	'<input type="hidden" name="newlangSkill[]" value="'+$("#newLANGSkillNew").val()+'" />'+
	'<input type="hidden" name="newLANGSkill-'+$("#newLANGSkillNew").val()+'" id="newLANGSkill-'+$("#newLANGSkillNew").val()+'" value="'+$("#newLANGSkillNew option:selected").text()+'" />'+
	'<input type="hidden" name="newlangLevel[]" value="'+$("#newLANGLevelNew").val()+'" />'+
	'<div class="left">'+
	  $("#newLANGSkillNew option:selected").text()+
	'</div>'+
	'<div class="middle">'+
	  $("#newLANGLevelNew option:selected").text()+
	'</div>'+
	'<div class="navi" onclick="removeLangSkill2('+$("#newLANGSkillNew").val()+');">'+
	  '<img src="file/graphic/icons/cancel_icon.png" alt="delete" /> Zmazať'+
	'</div></div>');
    getSelectboxSkillsL2();
    $('#newLANGSkillNew').val(0);
    $('#newLANGLevelNew').val(0);
  }
}

function removeLangSkill2(id){
  addSelectboxSkillsL2(id);
  $('#newlangSkillsRow-'+id).remove();
  $('#newLANGSkillNew').val(0);
  $('#newLANGLevelNew').val(0);
}

/*
 * odstranenie zleho zobrazenia dropdown menu v IE7 (menu bolo prekryte tabmi)
 * podla http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/
 */
$(function() {
	var zIndexNumber = 1000;
	$('ul').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
});

$(function() {
$(".tabsH").css("zIndex", 949);
$(".tabsH").css("display", "block");
});
/*
 * koniec vynimky pre opera a IE7
 */

function disableButton(button){
  $('#'+button).disabled=true;
}

function del_country(){
  $('#delcountry').val(1);
}


//Autoscroll po nacitani stranky
window.onload = function() {
        //$('html, body').animate({scrollTop:0}, 'fast');
        window.scrollTo(0,0);
}


$(function(){
	$('#showCV').click(function() {
			var id = $('#iduser').val();
			var url = "index.php?action=cv";
       $.ajax({
       	type: "post",
      	url: "?ajax=showCV",
      	data: "&id=" +id,
      	success: function(data) {
      	 window.open(url, 'zivotopis', 'resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=1')
        }
      });
      return false;
		});

});

function selectTab(name, num){
  var $tabs = $('#'+name).tabs();
  $tabs.tabs('select', num);
}

function addItemToAppBill(){
	if($("#applicationSelect").val() > 0 && 
		($("#timeSelect").val() > 0 || $("#amountSelect").val() > 0) 
		// && ($("#priceSelect").val() != "0 €" && $("#priceSelect").val() != "0  €")
    ) {
		
			
			var cDate = new Date();
			var timestamp = cDate.getTime();
			
			$('tr:last', '#appBillContainer').after(
				'<tr id="billRow-'+timestamp+'"><td>'+
				'<input type="hidden" name="appname[]" value="'+$("#applicationSelect option:selected").text()+'" />'+
				'<input type="hidden" name="applications[]" value="'+$("#applicationSelect").val()+'" />'+
				'<input type="hidden" name="time[]" value="'+$("#timeSelect").val()+'" />'+
				'<input type="hidden" name="amount[]" value="'+$("#amountSelect").val()+'" />'+
				'<input type="hidden" name="price[]" value="'+$("#priceSelect").val()+'" />'+

				$("#applicationSelect option:selected").text() +
				'</td>'+
				'<td>'+
				$("#amountSelect option:selected").text()+
				'</td>'+
				'<td>'+
				$("#timeSelect option:selected").text()+
				'</td>'+
				'<td><input type="text" value="'+$("#priceSelect").val()+'" name="price" readonly="readonly" /></td>'+
				'</div>'+
				'<td>'+
				'<a href="#" class="button" onclick="removeItemBill('+timestamp+');return false;"><img src="file/graphic/icons/cancel_icon.png" alt="delete" /> &nbsp;Zmazať</a>'+
				'</td></tr>'
			);
			
			countPrice();

			$('#applicationSelect').val(0);
			$('#timeSelect').empty();
			$('#amountSelect').empty();
			$('#priceSelect').val("0.00 €");
	} else{
		alert("Neexistuje takáto kombinácia.");
	}
	return false;
}

function removeItemBill(id){
  $('#billRow-'+id).remove();
  $('#applicationSelect').val(0);
  $('#timeSelect').val(0);
  $('#amountSelect').val(0);
  countPrice();
}

function countPrice(){
  var itemBox = document.getElementById('buyappform');
  total = 0.00;
  items = "";
  for (i = 0; i < parseInt(itemBox.elements.length); i++)
  {
      if(itemBox.elements[i].name == "price"){
          var hodnota = parseFloat(itemBox.elements[i].value);
          var total = total + hodnota;
          var totaltxt = total.toFixed(2)+" €";
          $("#totalSum").empty();
          $("#totalSum").val(totaltxt);
          $("#totalSum2").empty();
          $("#totalSum2").val(totaltxt);
          var totalDPH = ((total*1.19).toFixed(2))+" €";
          $("#totalSumDPH").empty();
          $("#totalSumDPH").val(totalDPH);
          $("#totalSumDPH2").empty();
          $("#totalSumDPH2").val(totalDPH);
      }
      if(itemBox.elements[i].name == "appname[]"){
        items = items+" "+itemBox.elements[i].value+",";
      }
  }
  $("#totalApps").empty();
  $("#totalApps").append(items);
  return false;
}

$(function()
{
	$('#applicationSelect').chainSelect('#timeSelect','index.php?ajax=appDuration',
	{
		before:function (target) //before request hide the target combobox and display the loading message
		{ },
		after:function (target) //after request show the target combobox and hide the loading message
		{ }
	});
	$('#applicationSelect').chainSelect('#amountSelect','index.php?ajax=appAmount',
	{
		before:function (target)
		{	},
		after:function (target)
		{ }
	});
});

function appCountPrice(){
    $.ajax({
     	type: "post",
    	url: "?ajax=appCountPrice",
    	data: "&app=" + $("#applicationSelect").val() + "&duration=" + $("#timeSelect").val() + "&amount=" + $("#amountSelect").val(),
    	success: function(data) {
        $('#priceSelect').val(data+" €");
      }
    });

}

function likeIt(id){
  $.ajax({
		 	type: "post",
   		url: "?ajax=likeit",
   		data: "&id=" + id,
   		success: function(data) {
   		  $('#status_like_'+id).html("<a onclick=\"dontLikeIt("+id+");\" ><span class=\"link dont_like_it\">Nepáči sa mi</span></a>");
   		  refreshStatus(id);
      }
   	});
}
function dontLikeIt(id){
  $.ajax({
		 	type: "post",
   		url: "?ajax=dontlikeit",
   		data: "&id=" + id,
   		success: function(data) {
   		  $('#status_like_'+id).html("<a onclick=\"likeIt("+id+");\" ><span class=\"link like_it\">Páči sa mi</span></a>");
   		  refreshStatus(id);
      }
   	});
}
function whoLikeIt(id){
  var htmlc="";
  htmlc = $('#status_text_'+id).text();
  $.ajax({
		 	type: "post",
   		url: "?ajax=wholikeit",
   		data: "&id=" + id,
   		success: function(resp) {
   		  htmlc = htmlc+"<br /><br />"+resp;
   		  $('#whoLikeContent').html(htmlc);
      }
   	});
    
  $('#whoLikeDialog').dialog('open');
  return false;
}
// dialog pre zobrazenie komu sa paci status
$(function() {
		$("#whoLikeDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 450,
			modal: true,
			buttons: {
				'Zatvoriť': function() {
					$(this).dialog('close');
				}
			}
		});
	});

function submitComment(id){
   var text = $('#comment_'+id).val();
   if(text != ""){
     $.ajax({
  		 	type: "post",
     		url: "?ajax=addcomment",
     		data: "&id=" + id +"&text=" + text,
     		success: function(data) {
     		  $('#comment_'+id).val("");
     		  hiddenText(id);
     		  refreshStatus(id);
        }
     	});
  }
}
function submitComment2(id){
   var text = $('#comment2_'+id).val();
   if(text != ""){
     $.ajax({
  		 	type: "post",
     		url: "?ajax=addcomment",
     		data: "&id=" + id +"&text=" + text,
     		success: function(data) {
     		  $('#comment_'+id).val("");
     		  $('#showCommentsDialog').dialog('close');
     		  refreshStatus(id);
        }
     	});
  }
}

function showComments(id){
var htmlc="";
  htmlc = $('#status_text_'+id).text();
  $.ajax({
		 	type: "post",
   		url: "?ajax=showcomments",
   		data: "&id=" + id,
   		success: function(resp) {
   		  htmlc = htmlc+"<br /><br />"+resp;
   		  $('#showCommentsContent').html(htmlc);
      }
   	});
    
  $('#showCommentsDialog').dialog('open');
  return false;
}
// dialog pre zobrazenie komu sa paci status
$(function() {
		$("#showCommentsDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 570,
			modal: true,
			buttons: {
				'Zatvoriť': function() {
					$(this).dialog('close');
				}
			}
		});
	});

  function delComment(id){
    $.ajax({
		 	type: "post",
   		url: "?ajax=delcomment",
   		data: "&id=" + id,
   		success: function(resp) {
   		  $('#comm_'+id).hide();
      }
   	});
   	refreshStatus(id);
  }
  
  function refreshStatus(id){
    $.ajax({
		 	type: "post",
   		url: "?ajax=refreshstatus",
   		data: "&id=" + id,
   		success: function(resp) {
   		  $('#status_info_'+id).html(resp);
      }
   	});
  }
