

// textlimit function

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('trimming...  '+(thelimit - that.value.length)); };
						} ,charDelSpeed 
					);
			}
			else this.value = that.value.substr(0,thelimit);
		}
	});
	
};

/*jQuery.fn.news = function() {
	
	var $newsIndex = 0;
	var $newsTimer;
	
	changeNews();
	
	function changeNews() {
		if($newsIndex > 5) $newsIndex = 0;
		$newsI = $("#newsList .list:eq("+$newsIndex+")");
		
		$height = ($newsI.position().top + $newsI.outerHeight());
		if($height > 300) $scroll = $height - 300; else $height = 0; 
		$("#newsIndex #newsList")[0].scrollTo($height - 300);
		
		$.get("/app/helper.php", { action: 'loadNews', newsID: $newsI.attr("id").substr(3)}, function(data){
			$("#newsContent .news").html(data);
			$("#newsIndex #newsList .list").attr("class", "list");
			$newsI.attr("class", "list active");
		});
		
		$newsIndex += 1;
		$newsTimer = setTimeout( function() { changeNews(); }, 15000);
	}

	this.mouseover(function(){ $newsTimer = clearTimeout($newsTimer); });
	this.mouseout(function(){ $newsTimer = setTimeout( function() { changeNews(); }, 3000); });
	
}*/

jQuery.fn.news = function() {

	$total = $('#newsContent img').length;
	$nextSlide = ($('#newsContent').data('nivo:vars').currentSlide)+1;

	if($nextSlide > 14) $nextSlide = 0;
	$newsI = $("#newsList .list:eq("+$nextSlide+")");
		
	$height = ($newsI.position().top + $newsI.outerHeight());
	if($height > 300) $scroll = $height - 300; else $height = 0; 
	$("#newsIndex #newsList")[0].scrollTo($height - 300);
	
	$("#newsIndex #newsList .list").attr("class", "list");
	$newsI.attr("class", "list active");
	
}


$(window).load(function(){  
  if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
    $('#header').supersleight();
    $('#nav-search #search form').supersleight({imgs: false, backgrounds: true, apply_positioning: true});    
    $('#content .icon').supersleight();
    $('#media').supersleight();
    $('#videoprew .prewiev a.r3-2').supersleight({imgs: false, backgrounds: true});
    $('#partners').supersleight();     
    $('#copyright').supersleight();  
  } 
 
	 $("#msg").dialog({ 
    bigframe: true,minwidth: 100,minHeight: 100,	show: 'drop',	hide: 'drop',	resizable: false,	position: ['center', 'center'],
		open: function() { window.setTimeout('$("#msg").dialog("close")', 7000) }
	});	  
   
});


$(document).ready(function(){
 
  // timing news
 
  /*$("#newsList .list").click(function() {
		$news = $(this);
    $.get("/app/helper.php", { action: 'loadNews', newsID: $news.attr("id").substr(3)}, function(data){
    	$("#newsContent .news").html(data);
			$("#newsIndex #newsList .list").attr("class", "list");
			$news.attr("class", "list active");
    });
  });*/
	
	$("#top .seasons").mouseover(function(){ $(this).addClass("showed"); });
	$("#top .seasons").mouseout(function(){ $(this).removeClass("showed"); });
	
	if($("#newsIndex #newsList").size() > 0) {
		$("#newsIndex #newsList").jScrollPane({showArrows:true, animateTo:true, animateInterval:0, animateStep:3 });
		//$("#newsIndex").news();
		$("#newsContent").nivoSlider({
        effect:'boxRain', // Specify sets like: 'fold,fade,sliceDown'
        slices: 15, // For slice animations
        boxCols: 10, // For box animations
        boxRows: 6, // For box animations
        animSpeed:500, // Slide transition speed
        pauseTime:10000, // How long each slide will show
        directionNav:true, // Next & Prev navigation
        directionNavHide:true, // Only show on hover
        controlNav:true, // 1,2,3... navigation
        controlNavThumbs:false, // Use thumbnails for Control Nav
        controlNavThumbsFromRel:false, // Use image rel for thumbs
        keyboardNav:false, // Use left & right arrows
        pauseOnHover:true, // Stop animation while hovering
        prevText: '', // Prev directionNav text
        nextText: '', // Next directionNav text
        beforeChange: function(){ $("#newsIndex #newsList").news(); }, // Triggers before a slide transition
    });
	}
	
 
  // 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;
					});
				});
			}
		}
	}); 
	
  if($("#categoryHash").size() > 0) {
		$target = $("#kategorie-"+$("#categoryHash").val());
		if ($target) {
			var targetOffset = $target.offset().top;
			$('html').animate({scrollTop: targetOffset}, 400);
		}
	}
	
	//$("#newsticker").newsticker();

  // 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/icons/stars/star.png");
        $("#"+$id+" img:gt("+($value-1)+")").attr("src", "/img/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 = "";
      });
    }
  });
	
	$("#trades").jScrollPane({showArrows:true, animateTo:true, animateInterval:0, animateStep:3 });

	/* dialog error */				 
	$(".dialog.error").dialog({
		bigframe: true, minHeight: 20, width: 200, modal: true, show: 'size',resizable: false,	hide: 'slide'
	});
		
	/* input tip messages */
	$(".help").oxtip({float: "left", width: 200, opacity: 0.9, a: "mouseover", d: "mouseout"});
	$(".tip").oxtip({float: "bottom", width: 270, maxWidth: 270, a: "focus", d: "blur"});
	
	$(".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();
		
	// adding tip to tipleague
	$(".tip .tt a").click(function(){
																 
		$("#tipLeague .loading").show();
		
		$a = $(this); $parent = $a.parent().parent();
		$type = $a.attr("rel");
		$matchID = $parent.attr("id").substr(3);
		//$matchID = $parent.attr("rel");
		$value = $a.text();
		
		$.get("/app/helper.php", { action: 'addTicketTip', matchID: $matchID, type: $type, value: $value });
		
		if($("#tipLeague").size() == 0) {
			
			$.get("/app/helper.php", { action: 'loadTicket' }, function(data){
				$("#tipBox").html(data);
				$("a", $parent).removeClass("selected");
				$a.addClass("selected");
			});
			
		} else {
					
			$.get("/app/helper.php", { action: 'loadTicketTips' }, function(data){
				$("#tipLeague #tips").html(data);
				$("a", $parent).removeClass("selected");
				$a.addClass("selected");
				tipleague_checkLane();
				$("#tipLeague .loading").hide();
			});
			
		}
		
		return false;
		
	});
	
	$("#tipBox #tipLeague #tips .tipDelete").live("click", function() {
		$("#tipLeague .loading").show();
		$tr = $(this).parent().parent();
		$val = $(this).attr("alt");
		//$val = $(this).attr("rel");
		$.get("/app/helper.php", { action: 'removeTicketTip', matchID: $val }, function(data) {
			if(data == 0) {
				$tr.fadeOut(500, function() { $tr.remove(); tipleague_checkLane(); });
				$(".tip[id='tip"+$val+"'] a").removeClass("selected");
				//$(".tip[rel='"+$val+"'] a").removeClass("selected");
				if($("#tipBox #tipLeague #tips tr").size() < 2) 
					$("#tipLeague").fadeOut(500, function(){ $("#tipLeague").remove(); });
				$("#tipLeague .loading").hide();
			} else alert("Nepodařilo se smazat tip.");
		});
	});
	
	$("#tipLeague .sum input").live("change", function() { 
		if(parseFloat($(this).val()) < 10 || isNaN($(this).val()) || $(this).val() == "") $(this).val(10);
		if(parseFloat($(this).val()) > 10000) $(this).val(10000);
		tipleague_checkAmount(); 
	});
	if($("#tipLeague .sum").size() > 0) { tipleague_checkAmount(); }
	
	$("#tipLeague .buttons a").live("click", function() {
		$type = $(this).attr("rel");
		$.get("/app/helper.php", { action: 'postTicket', type: $type, bet: $("#tipLeague .sum input").val() }, function(data) {
			if(data.length < 3) {
				$(".tip a").removeClass("selected");
				$("#tipLeague").fadeOut(500, function(){ $("#tipLeague").remove(); });
			} else showAlert(data);
		});
		return false;
	});
	
	
	$("#player .teamDetail .more, #player .teamDetail .morePunish").mouseover(function(){ $(this).addClass("over"); });
	$("#player .teamDetail .more, #player .teamDetail .morePunish").mouseout(function(){ $(this).removeClass("over"); });
	$("#player .teamDetail .more").click(function(){
		$this = $(this);
		$state = $this.attr("abbr");
		//hide the opposite group
     $this.prev('.morePunish').removeClass("selected").attr("abbr", 'state0');
     $this.parent().next('.matches').next('.punish').hide();
		//---
		$matches = $this.parent().next();
		
		if($state == 'state0') {
			$this.addClass("selected");
			$this.attr("abbr", 'state1');
			//$matches.fadeIn(500);     - not work in IE8 :-(
			$matches.show();
		} else {
			$this.removeClass("selected");
			$this.attr("abbr", 'state0');
			//$matches.fadeOut(500); - not work in IE8 :-(
			$matches.hide();
		}
		
	});	
	$("#player .teamDetail .morePunish").click(function(){
		$this = $(this);
		$state = $this.attr("abbr");
		//hide the opposite group
     $this.next('.more').removeClass("selected").attr("abbr", 'state0');
     $this.parent().next('.matches').hide();
		//---
		$matches = $this.parent().next().next();

		if($state == 'state0') {
			$this.addClass("selected");
			$this.attr("abbr", 'state1');
			//$matches.fadeIn(500);     - not work in IE8 :-(
			$matches.show();
		} else {
			$this.removeClass("selected");
			$this.attr("abbr", 'state0');
			//$matches.fadeOut(500); - not work in IE8 :-(
			$matches.hide();
		}

	});
	
	
	
	$("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>';
		}
	});
	
	$("a.videoFile").click(function(){ 
		$linkToMovie = $(this).attr("href");
		$('#videoPlayer object param[name="initParams"]').attr("value", "m="+$linkToMovie);
		$.colorbox({
			minWidth:"720px", minHeight:"576px",
			inline:true, href:"#player" ,current:"", scrolling: false,
			title: $(this).attr("title")
		});
		return false;
	});	
	
	$('#match .referee').click(function() {
		if($(this).css("z-index") == 100) {
			$(this).css("z-index", "1");
			$(".about", this).hide('slow');
		} else {
			$(this).css("z-index", "100");
			$(".about", this).show('slow');
		}
	});
	
	$('#match .players .ground .player').click(function() {
	  $('.home, .away').css('z-index', '1');
		$('#match .players .ground .player .about').hide('slow');
		if($(this).css("z-index") == 100) {
			$("#match .players .ground .player").css("z-index", "1");
			$(".about", this).hide('slow');
			$(this).closest('.home, .away').css('z-index', '1');
		} else {
			$(this).css("z-index", "100");
      $(this).closest('.home, .away').css('z-index', '110');
			$(".about", this).show('slow');
		}
	});
	
	$('#goalsAndCardsOn').click(function() {
		$(this).fadeOut('slow');
		$("#match .goalsAndCards").fadeIn('slow');
		return false;
	});
	
	$('#goalsAndCardsOff').click(function() {
		$('#goalsAndCardsOn').fadeIn('slow');
		$("#match .goalsAndCards").fadeOut('slow');
		return false;
	});
	
	/*$('#attachmentAdd').uploadify({
		'uploader':'/app/files/uploadify.swf',
		'script':'/app/admin.helper.php?action=uploadFile',
		'cancelImg':'/img/icons/cancel.png',
		'folder':'/documents/temp/',
		'queueID':'uploadQueue',
		'buttonText':'vybrat soubory',
		'fileExt':'*.jpg;*.gif;*.png;*.ai;*.pdf;*.doc;*.docx',
		'sizeLimit': 5242880,
		'onComplete': function(event, queueID, fileObj, response, data){
			
		},
		'multi': true,
		'auto': true
	});*/
	
  $("#splLogos a").each(function() {
  }).hover(function() {
  
    $(this).children('img').stop().animate({ height: 45,
                             width: 45,
                             left: 0,     //odecet = (nova sirka - stara sirka) / 2
                             top: 0}, 300);
  }, function() {
    $(this).children('img').stop().animate({ height: 35,
                             width: 35,
                             left: 5,
                             top: 5}, 300);
  });


  $('.headerSwitcher a').click(function(){
      $('.headerSwitcher a').removeClass('selected');
      $btn = $(this);
      $btn.addClass('selected');
      $('.switcherTab').removeClass('active');
      $('#'+$btn.attr('rel')).addClass('active');
      return false;
  });
});


function tipleague_checkLane() {
	var $lane = 1;
	
	$("#tips .lane").each(function() {
		$val = parseFloat($(this).text());
		$lane = $lane * $val;
	});
				
	$lane = Math.round($lane*100)/100;
	$("#tipLeague .totalLane strong").text($lane);
	if($("#tipLeague .sum").size() > 0) {
		$price = $lane * parseFloat($("#tipLeague .sum input").val());
		tipleague_checkAmount();
	}
}

function tipleague_checkAmount() {
	$price = Math.round(parseFloat($("#tipLeague .totalLane strong").text()) * parseFloat($("#tipLeague .sum input").val())*100)/100;
	$("#tipLeague .winning strong").text($price);	
}



showAlert = function(message) {
	var alertDiv = "<div id='alert'><h2><img src=\"/img/icons/small/error.png\"> Chyba</h2><p>"+message+"</p></div>";
	$("body").append(alertDiv);//left side
	$.colorbox({inline:true,href:"#alert",onClosed: function(){	$("#alert").remove();	}});
}



/* oxtip */
jQuery.fn.oxtip = function(e) {

	this.bind(e.a, function(){
		var de = document.documentElement;
		var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var clickElementy = getAbsoluteTop(this.id); //set y position	
    var clickElementx = getAbsoluteLeft(this.id); //set x position
   
		if(e.float == "left") clickElementx -= ((this.offsetWidth*1) + e.width); else clickElementx += ((this.offsetWidth*1) + 15);
		if(e.float == "bottom") clickElementx -= $(this).innerWidth() + 15; clickElementy += $(this).innerHeight() + 5;
    		
		var div = "<div id='tip'>";
		if(this.title != false) div += "<div class='title'>"+this.title+"</div>";
		div += "<div id='tipText'><img src=\"/img/animations/tip-loader.gif\" alt=\"nahrávám...\" /></div></div>";
		$("body").append(div);//left side
		$('#tipText').load("/app/scripts/tip.php?tip="+this.name);
		$('#tip').css({'left': clickElementx+'px', 'top': clickElementy+'px', 'width': e.width+'px', 'max-width': e.maxWidth+'px', '-moz-opacity': e.opacity, 'filter': 'filter: alpha(opacity='+(e.opacity*100)+')'});  			
    $('#tip').show(500);
	});
	this.bind(e.d,function(){
		$('#tip').remove();
	})
}

function getAbsoluteLeft(objectId) {
/*
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
	*/
  pos = $('#'+objectId).offset();
  return Math.floor(pos.left);	
}

function getAbsoluteTop(objectId) {
/*
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
	*/
  pos = $('#'+objectId).offset();
  return Math.floor(pos.top);		
}



/* STRIP TAGS */
jQuery.fn.stripTags = function() {
  return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
}; 

