var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline = 0;

(function(jQuery){jQuery.fn.extend({elastic:function(){var mimics=['paddingTop','paddingRight','paddingBottom','paddingLeft','fontSize','lineHeight','fontFamily','width','fontWeight'];return this.each(function(){if(this.type!='textarea'){return false}var $textarea=jQuery(this),$twin=jQuery('<div />').css({'position':'absolute','display':'none','word-wrap':'break-word'}),lineHeight=parseInt($textarea.css('line-height'),10)||parseInt($textarea.css('font-size'),'10'),minheight=parseInt($textarea.css('height'),10)||lineHeight*3,maxheight=parseInt($textarea.css('max-height'),10)||Number.MAX_VALUE,goalheight=0,i=0;if(maxheight<0){maxheight=Number.MAX_VALUE}$twin.appendTo($textarea.parent());var i=mimics.length;while(i--){$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()))}function setHeightAndOverflow(height,overflow){curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow})}}function update(){var textareaContent=$textarea.val().replace(/&/g,'&amp;').replace(/  /g,'&nbsp;').replace(/<|>/g,'&gt;').replace(/\n/g,'<br />');var twinContent=$twin.html();if(textareaContent+'&nbsp;'!=twinContent){$twin.html(textareaContent+'&nbsp;');if(Math.abs($twin.height()+lineHeight-$textarea.height())>3){var goalheight=$twin.height()+lineHeight;if(goalheight>=maxheight){setHeightAndOverflow(maxheight,'auto')}else if(goalheight<=minheight){setHeightAndOverflow(minheight,'hidden')}else{setHeightAndOverflow(goalheight,'hidden')}}}}$textarea.css({'overflow':'hidden'});$textarea.keyup(function(){update()});$textarea.live('input paste',function(e){setTimeout(update,250)});update()})}})})(jQuery);

jQuery.extend({
	gup: function(param){
		var param = param.replace(/[[]/,"[").replace(/[]]/,"]"); 
		var regexS = "[?&]"+param+"=([^&#]*)";  
		var regex = new RegExp(regexS);  
		var results = regex.exec(window.location.href);  
		if(results) { 
			return results[1];
		}
	},
	gpn: function(){
		var params = new Array( );
		var regex = /[?&]([^=]+)=/g;
		while((results=regex.exec(window.location.href)) != null)
			params.push(results[1]);
		return params;	
	},
	gpnv: function(){
		var oString = new Array();
		var values = new Array();
		values = $.gpn();
		for (var i=0;i < values.length;i++){
			oString[i] = new Array(i);
			oString[i,i] = [values[i],$.gup(values[i])];
		}
		return oString;
	}
});

jQuery.fn.textlimit=function(counter_el, thelimit, speed) {
	var charDelSpeed = speed || 15;
	var toggleCharDel = speed != -1;
	var toggleTrim = true;
	
	var that = this[0];
	updateCounter();
	
	function updateCounter(){
		jQuery(counter_el).text(thelimit - that.value.length);
	};
	
	this.keypress (function(e){ if( this.value.length >= thelimit && e.charCode != '0' ) e.preventDefault() })
	.keyup (function(e){
		updateCounter();
		if( this.value.length >= thelimit && toggleTrim ){
			if(toggleCharDel){
				// first, trim the text a bit so the char trimming won't take forever
				that.value = that.value.substr(0,thelimit+100);
				var init = setInterval
					( 
						function(){ 
							if( that.value.length <= thelimit){ init = clearInterval(init); updateCounter() }
							else{ that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text(' skracujem...  '+(thelimit - that.value.length)); };
						} ,charDelSpeed 
					);
			}
			else this.value = that.value.substr(0,thelimit);
		}
	});
	
};

$().ready(function() {

	$.yggid = $.gup("yggid");
	$.defaultSearchValue = $('#searchInput').attr('value');

	if (($.browser.msie) && (jQuery.browser.version=='6.0')) {
		$('#header h1, #header ul li, #header ul li img, .box ul li, #search, #g02, #forecast img').pngfix();
		$('div#content div#contentInner div.box div.inner ul li a').css({'zoom' : '1'});
	}

	$("div#news, div#communique, div#pezincan").carousel( { direction: "vertical", dispItems: 6 });
	$("div#events").carousel2( { direction: "vertical", dispItems: 4});
	$("div#exhibitions").carousel2( { direction: "vertical", dispItems: 6});

	headline_count = $("ul#headlines li").size();
	$("ul#headlines li:eq("+current_headline+")").css('top', '0px');
	if (headline_count>1) {
		headline_interval = setInterval(headline_rotate,5000);
		$('ul#headlines').hover(function() {
			clearInterval(headline_interval);
		}, function() {
			headline_interval = setInterval(headline_rotate,5000);
		});
	}

	weather_count = $("ul#weather li").size();
	$("ul#weather li").each(function (i) {
		var li = jQuery(this);
		if (($.yggid == "1") || ($.yggid == undefined)) {
			setTimeout(function() {
				li.animate({top: 0},"slow");
			}, i*400);
		} else {
			li.css('top', '0');
		}
	});

	$('#searchInput').focus(function() { if ($(this).attr('value')==$.defaultSearchValue) $(this).attr('value', ''); });
	$('#searchInput').blur(function() { if ($(this).attr('value')=='') $(this).attr('value', $.defaultSearchValue); });
	
	$('#searchForm').submit(function() {
    var searched = $('#searchInput').val();
    if (searched != "Vyhľadávanie") {
      if (searched.length > 2) {
        return true;
      } else {
        alert('Zadajte aspoň 3 znaky.');
        $('#searchInput').focus();
        return false;
      }
    } else {
      alert('Zadajte hľadaný výraz.');
      $('#searchInput').focus();
      return false;
    }
  });

	$("ul[id^='votepoll-']").each(function() {
		var v_id = this.id.replace("votepoll-","");
		jQuery(this).find("a.vote").click(function(){vote(v_id, $(this).text())});
		animateResults(v_id);
	});

	if ($.yggid == "10") {
		gmap();
	}
	
	//$("a.photo").click(function(){return hs.expand(this)})
	
	// TEST
	if( $('#wrapperSite').height() > 1500) {
		$('#contentInner').append('<div class="up"><a href="#" class="right" title="Posunúť stranu hore">Na začiatok</a></div>');
	}

	$('textarea.limited').each(
		function initArea(inx) {
			$(this).elastic();
			$(this).after('<div id="counter_'+$(this).attr('id')+'" class="counter">Ostáva <span>'+$(this).attr('maxlength')+'</span> znakov</div>');
			$(this).textlimit('#counter_'+$(this).attr('id')+' span', $(this).attr('maxlength'));
		}
	);

	$('form.add.post').submit(function() {
		p_name = $('#f_name').val();
		p_text = $('#f_text').val();
		p_pass = $('#f_pass').val();
		if (p_name.length == 0) {
			alert("Zadajte vaše meno.");
			$('#f_name').focus();
			return false;
		} else if (p_name.length < 3) {
			alert("Meno musí mať aspoň 3 znaky.");
			$('#f_name').focus();
			return false;
		} else if (p_text.length == 0) {
			alert("Zadajte váš komentár.");
			$('#f_text').focus();
			return false;
		} else if (p_text.length > $('#f_text').attr('maxlength')) {
			alert("Prekročili ste maximálny počet znakov komentára!");
			$('#f_text').focus();
			return false;
		} else if (p_pass.length == 0) {
			alert("Zadajte kontrolný kód z obrázka.");
			$('#f_pass').focus();
			return false;
		} else {
			return true;
		}
	});

	$('div.post small a').click(function(){remedialAction($(this).attr('href'))});
	$('div.hint a').click(function(){
		thesrc = $("#capcha").attr("src");
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		$("#capcha").attr("src", thesrc+"?"+Math.round(Math.random()*100000));
	});

	// Change font size
	var nResizes = 0;
	function bigger(){
		nResizes = nResizes + 1;
		$("div.h").css({fontSize: parseFloat($("div.h").css("font-size"), 10) * 1.2});
		if (nResizes == 3) {
			$("li.fontsize").css('background-image', 'url(i/magnifier-minus.png)');
		}
	}

	$("li.fontsize a").toggle(function(){
		this.x_originalSize = $("div.h").css('font-size');
		bigger();
	}, bigger, bigger, function(){
		nResizes = 0;
		$("li.fontsize").css('background-image', 'url(i/magnifier-plus.png)');
		$("div.h").css({fontSize : this.x_originalSize});
	});

});

function remedialAction(o) {
	n = o.substring(2);
	$.ajax({type:"POST", url:"scripts/ax/ax.remedial.php", data:"q="+n, success: function(res){$("a[href='#p"+n+"']").unbind('click').text('Ďakujeme');}});
}

function headline_rotate() {
	current_headline = (old_headline + 1) % headline_count;
	$("ul#headlines li:eq(" + old_headline + ")").animate({top: -32},"slow", function() {
		$(this).css('top', '32px');
	});
	$("ul#headlines li:eq(" + current_headline + ")").animate({top: 0},"slow");
	old_headline = current_headline;
}

function vote(id, ch) {
	$.ajax({type:"POST", url:"scripts/ax/ax.votepoll.php", data:"q="+id+"&a="+ch, success: function(msg){
	  alert(msg);
		if (msg!="") {
			loadResults(id);
			$('h3.votepoll').prepend('<div id="thanks"></div>');
			setTimeout(function() {
				$('div#thanks').animate({opacity:0},600);
			}, 5000);
		}
	} });
}

function loadResults(id) {
	var v = "votepoll-"+id;
	$.ajax({type:"GET", url:"scripts/ax/ax.votepoll.php?r="+id, dataType:"json", success:
		function(data){
      x=0;
			$.each(data.score, function(i,item){
				$("ul#"+v+" li a").unbind('click').attr('class', 'disabled');
				$("ul#"+v+" li:eq("+x+")").append('<div class="ranking"><div class="bar" style="width:0%"></div><span>'+item+'&#37;</span></div>');
				x++;
			});
			if (data.total!="") {
				$("ul#"+v).after('<p class="total">Hlasovalo '+data.total+' návštevníkov.</p>');
			}
			animateResults(id);
		}
	});
}

function animateResults(id) {
	var v = "votepoll-"+id;
	$('#'+v+' li').each(function() {
		percentage = $(this).find("span:first").text();
		$(this).find("a.vote").click(function() {null}); 
		$(this).find("div.ranking").css({opacity:0}).animate({opacity:1});
		$(this).find("div.ranking div.bar").css({width:"0%"}).animate({width: percentage}, 'slow');
	});
}

function reloadCaptcha (c) {
	$('#'+c).attr('src', 'scripts/ax/ax.captcha.php?'+Math.random());
}

function tryLink () {
	window.location = $('#urlInput').attr('value');
	return false;
}

function submitBadLink (lnk) {
	$.url = document.URL;
	$.lnk = $(lnk).attr('href');
	$.ajax({type:'POST', url:'scripts/ax/badlink.php', data:{ url:$.url },
		success:function(res){
			if (res==1) alert('InformĂˇcia o chybe bola odoslanĂˇ sprĂˇvcovy strĂˇnky. ÄŽakujeme'); else window.location=$.lnk;
		}
	});
	return false;
}

function gmap() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(48.286981, 17.271084), 13);
		map.setUIToDefault();
	}
}