// fn textlimit 
jQuery.fn.textlimit = function(a) {
	
  var charDelSpeed = a.speed || 15;
	var toggleCharDel = a.speed != -1;
	var toggleTrim = true;
	
	var thelimit = a.textlimit;
	var counter_el = $(this).next();

	var that = this;
	updateCounter();
	
	function updateCounter(){
		$(counter_el).text(thelimit - that.val().length);
	};
	
	this.keypress (function(e){ if( this.val().length >= thelimit && e.charCode != '0' ) e.preventDefault() })
	.keyup (function(e){
		updateCounter();
		if( this.val().length >= thelimit && toggleTrim ){
			if(toggleCharDel){
				// first, trim the text a bit so the char trimming won't take forever
				that.val() = that.val().substr(0,thelimit+100);
				var init = setInterval
					( 
						function(){ 
							if( that.val().length <= thelimit){ init = clearInterval(init); updateCounter() }
							else{ that.val() = that.val().substring(0,that.val().length-1); jQuery(counter_el).text('trimming...  '+(thelimit - that.val().length)); };
						} ,charDelSpeed 
					);
			}
			else this.val() = that.value.substr(0,thelimit);
		}
	});
	
};

$(document).ready(function(){

	$(".counted").each(function(){ $(this).textlimit({elm: $(this), textlimit: $(this).attr("rel"), speed: 1}); });

	var $navigationBar;
	$(".navi a").click(function(){
		$parent = $(this).parent();
		if($parent.hasClass("showed")) {
			$(this).next().hide("blind",{},500)
			$parent.removeClass("showed");
			$navigationBar = null;
		} else {
			if($navigationBar != null) { $navigationBar.children().next().hide("blind",{},500); $navigationBar.removeClass("showed"); }
			$(this).next().show("blind",{},500)
			$parent.addClass("showed");
			$navigationBar = $parent;
		}
		return false;
	});
	
			

	$("map[name='regions'] area").live("click", function() {
		$("#mapLoader").css("display", "block");
		
		$regionID = $(this).attr("rel"); $regionTitle = $(this).attr("title");
		
		$("#associations").hide("blind",{},500, function() {
			$position = 0 - $regionID * 284;
			$("#map").css("background-position", $position+"px 0px"); $("#map").attr("rel", $position)
			$("#mapTitle").text($regionTitle); $("#mapTitle").attr("rel", $regionTitle);
			
			$.get("/app/helper.php?action=associations", { regionID: $regionID }, function(data) {
				$("#associations").html(data);
				$("#mapLoader").css("display", "none");
				$("#associations").show("blind",{},500)
			});
			
			$.cookie("regionID", $regionID);
		});
		return false;
	});
	
	$("map[name='regions'] area").live("mouseover", function() {
		$regionID = $(this).attr("rel"); $regionTitle = $(this).attr("title");
		$position = 0 - $regionID * 284;
		$("#map").css("background-position", $position+"px 0px");
		$("#mapTitle").text($(this).attr("title"));
	})
	
	$("map[name='regions'] area").live("mouseout", function() {
		$("#map").css("background-position", $("#map").attr("rel")+"px 0px");
		$("#mapTitle").text($("#mapTitle").attr("rel"));
	})
	
	$("#associations .assoc").live("mouseover", function(){ $(this).addClass("over"); });
	$("#associations .assoc").live("mouseout", function(){ $(this).removeClass("over"); });
	
	$("#associations .assocLink").live("click",function(){
		$("#contentbox").prepend("<div class=\"loader\"><img src=\"/img/layout/icons/loader.gif\" alt=\"\" /></div>");
		$.get("/app/helper.php?action=assocDetail", { id: $(this).attr("rel") }, function(data){
			if($("#contentbox #assoc").size() > 0) $("#contentbox #assoc").replaceWith(data);
			else $("#contentbox").prepend(data);
			$("#contentbox .loader").remove();
		});
		return false;
	});
	
	
	/* gallery */
	$("a[rel='gallery']").colorbox({
		photo: true, 
		scalePhotos: true, 
		maxHeight: "600px", 
		title: function(){
    	var url = $(this).attr('href');
    	return '<a href="'+url+'" target="photo">Zobrazit obrázek v plné velikosti</a>';
		}
	});
	$("#slideshow").colorbox({
		photo: true, 
		scalePhotos: true, 
		maxHeight: "600px", 
		rel: "gallery", 
		slideshow: true,
		title: function(){
    	var url = $(this).attr('href');
    	return '<a href="'+url+'" target="photo">Zobrazit obrázek v plné velikosti</a>';
		}
	});
	
	 
  // animated link anchors
  var anchor = new String(window.location);
  if(anchor.indexOf('#')) {
		var $target = $(window.location.hash), target = window.location.hash;
		if (target) {
			var targetOffset = $target.offset().top;
			$('html').animate({scrollTop: targetOffset}, 400, function() {
				location.hash = target;
			});
		}
	}

	$('a[href*=#]').each(function() {
		if ( location.hostname == this.hostname || !this.hostname && this.hash.replace(/#/,'') ) {
			var $target = $(this.hash), target = this.hash;
			if (target) {
				var targetOffset = $target.offset().top;
				$(this).click(function(event) {
					event.preventDefault();
					$('html').animate({scrollTop: targetOffset}, 400, function() {
						location.hash = target;
					});
				});
			}
		}
	}); 

  // reset value in search field
  $("#search input[name='q']")
  .focus(function() { if($(this).val() == 'hledej...') $(this).val(''); })
  .blur(function() { if($(this).val() == '') $(this).val('hledej...'); });

  // Pool voting animated
  $("#pool a").live("click", function(){ 
    var $link = $(this).attr("href");
    $("#pool .ctt").load("/app/helper.php?action=poolVote&string="+$link, function(){
      $("#poolResults div").each(function(){
        var txt = $(this).next().html();
    		var percentage = $(txt).next().text();
        $(this).css({width: "0%"}).animate({width: percentage}, 'slow');
      });
    });
    return false;  
  });
  
  if ($(".poolResults").length > 0 ) { 
    $(".poolResults div").each(function(){
      var txt = $(this).next().html();
  		var percentage = $(txt).next().text();
      $(this).css({width: "0%"}).animate({width: percentage}, 'slow');
    });
  }
  
  /* ratings */
  $(".rating").each(function(){
    var $this = $(this);
    var $id = $(this).children().attr("id");
    var $rating = $(this).children().html();
    if($id != "") {
      $(".rating img").live("mouseover", function(){
        var $value = parseInt($(this).attr("alt"));
        $("#"+$id+" strong").text($value);
        $("#"+$id+" img:lt("+$value+")").attr("src", "/img/layout/icons/stars/star.png");
        $("#"+$id+" img:gt("+($value-1)+")").attr("src", "/img/layout/icons/stars/empty.png");
      });
      $("img", this).live("mouseout", function(){
        $("#"+$id).html($rating);
      });
      $("img", this).live("click", function(){
        $("#"+$id).parent().append('<img src="/img/ajax_loader.gif" alt=""/>');
        $($this).load("/app/helper.php?action=ratings&rating="+$id+"&value="+$(this).attr("alt"));
        $id = "";
      });
    }
  });

	/* dialog error */				 
	$(".dialog.error").dialog({
		bgiframe: true, minHeight: 20, width: 200, modal: true, show: 'size',resizable: false,	hide: 'slide'
	});
	
	$("#msg").dialog({ 
    bigframe: true,minwidth: 100,minHeight: 100,	show: 'drop',	hide: 'drop',	resizable: false,	position: ['right', 'bottom'], 
		open: function() { window.setTimeout('$("#msg").dialog("close")', 5000) }
	});
		
	$(".regsettings").each(function() {
	  $("input[name='section']", this).val("loginSection");
	  $('<div id="setNavi" class="section-title"></div>').insertAfter("form .cleaner:eq(1)", this);
  	$("#registration .st").each(function($i){
      $next = $(this).next();
      if($i == 0) $css = ' class="selected"'; else $css = "";
      $("."+$next.attr("class")+":gt(0):not(:last)").css("display", "none");
      $("#setNavi").append('<a'+$css+' href="#" rel="'+$next.attr("id")+'">'+$(this).text()+'</a>');
      $(this).remove();
    });
    
    $("#setNavi a").click(function(){
      $("#setNavi a").attr("class", ""); $(this).attr("class", "selected");
      $("."+$next.attr("class")+":not(:last)").css("display", "none");
      $("#"+$(this).attr("rel")).css("display", "block");
      $("#registration input[name='section']").val($(this).attr("rel"));
      return false;
    });
  });
	
	if($("#registration").size() > 0) 
	  $("#registration form").Registration();
		
	$('#uploadify').uploadify({
    'uploader':'/app/files/uploadify.swf',
    'script':'/app/helper.php?action=uploadTournamentPhoto',
    'cancelImg':'/img/icons/cancel.png',
    'folder':'/tournaments/',
    'queueID':'fileQueue',
    'fileDesc':'Povolen je jen formát jpg, png ,pdf ,zip a rar',
    'fileExt':'*.jpg;*.png;*.pdf;*.zip;*.rar',
    'buttonText':'vybrat',
		'auto': true,
		'sizeLimit':4194304,
    'scriptData':{'tID': $('input[name="tournamentID"]').val() },
    'onComplete': function(event, queueID, fileObj, response, data){
      $("#docsTour").append(response);                 
    },
    'multi': false
  });
	
	$("#tournaments .delete").live("click",function(){
		$d = $(this).parent().parent();
		$.get("/app/helper.php?action=deleteTournamentPhoto", { tdID: $(this).attr("rel") }, function(data) {
			if(data == 1) $d.remove();
		});
	});
	
});


/* STRIP TAGS */
jQuery.fn.stripTags = function() {
  return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
}; 


  
