var commentsLastTimestamp
var commentModel;
var commentModelId;

// automaticky refresh komentaru
var autoRefreshComments = false;
var autoRefreshCommentsInterval;
var autoRefreshCommentsIntervalTime = 30 * 1000;

// vlozeni komentare
$("#btn-add_comment").live("click", function() {
  if ($("#comment_content").val().length > 1) {
    if (autoRefreshComments)
      clearInterval(autoRefreshCommentsInterval);
    
    $.post(
      BreezyCMS_URL + "comments/add_comment/" + commentsLastTimestamp + "/",
      $("#form-comments").serialize(),
      function (payload) {
        if (payload.state == 'ok') {
          $("#form-message.error").hide();
          
          // nastaveni vychozich hodnot
          $("#comment_content").val('');
          $("#comment_content").trigger('keyup');
          
          $.each(payload.comments, function(id) {
            if ( ! $("#comment-" + commentModel + "-" + id).length)
              $("#comments-list").prepend(payload.comments[id]);
          });
          
          commentsLastTimestamp = payload.last_timestamp;
        }
        else if (payload.state == 'error') {
          $("#form-message.error").show();
          $("#form-message.error .errors").empty();
          
          // zobrazeni chybovych hlasek
          $.each(payload.errors, function(item){
            $.each(payload.errors[item], function(key) {
              $("#form-message.error .errors").append(payload.errors[item][key]);
            });
          });
        }
      },
      'json'
    );
    
    // obnovi automaticke nacitani komentaru
    setAutoCommentsInterval();
  }
  
  return false;
});

$(document).ready(function () {
		$(".fancybox").fancybox({
  		'padding'        : 0,
  		'titlePosition'  : 'over',
      'overlayOpacity' : 1,  
      'overlayColor'   : 'transparent', 
  		'overlayShow'    : true
		});

		$(".fancybox-html").fancybox({
  		'padding'        : 0,
  		'width'          : 620,
  		'height'         : 1330,
      'autoScale'      : false,
      'overlayOpacity' : 1,  
      'overlayColor'   : 'transparent', 
      'scrolling'   	 : 'no',
  		'type'           : 'iframe'
		});
		
		$(".fancybox-signup").fancybox({
			'padding'        : 0,
			'width'          : 440,
			'height'         : 505,
		  'autoScale'      : false,
			'overlayOpacity' : 1,  
			'overlayColor'   : 'transparent',   
		  'scrolling'   	 : 'no',
			'type'           : 'iframe'
		});

		$(".fancybox-login").fancybox({
			'padding'        : 0,
			'width'          : 440,
			'height'         : 300,
		  'autoScale'      : false,
			'overlayOpacity' : 1,  
			'overlayColor'   : 'transparent',  
		  'scrolling'   	 : 'no'
		});

		$(".fancybox-pass").fancybox({
			'padding'        : 0,
			'width'          : 440,
			'height'         : 280,
		  'autoScale'      : false,
			'overlayOpacity' : 1,  
			'overlayColor'   : 'transparent',  
		  'scrolling'   	 : 'no',
      'type'           : 'iframe'
		});

		$('#gallery').isotope({
			layoutMode: 'masonry',
		  itemSelector: '.item',
			masonry : {
			   columnWidth : 155
			 }		  
		});

		// max char message
    $(".maxlength").maxlength({  
        events: [], // Array of events to be triggerd   
        maxCharacters: 320, 
        status: true,   
        statusClass: "count-chars", 
        statusText: "Počet znaků:",  
        notificationClass: "notification",   
        showAlert: false, 
        alertText: "Zadali jste příliš mnoho znaků.", 
        slider: false   
    });
    
    // zobrazeni starsich komentaru
    $("#show-more-comments").click(function(){
      $("#comments-list .more-comments .loading").show();
      
      $.post(
        $(this).attr("href"),
        function(payload) {
          if (payload.state == 'ok') {
            $.each(payload.comments, function(id) {
              // zobrazi pouze ty komentare, ktere zobrazeny nejsou
              if ( ! $("#comment-" + commentModel + "-" + id).length)
                $("#comments-list .more-comments").before(payload.comments[id]);
            });
            
            // akutalizuje link pro dalsi zobrazeni komentaru
            if (payload.show_more_link) {
              $("#show-more-comments").attr("href", payload.show_more_link);
            }
            else {
              $("#comments-list .more-comments").hide();
            }
            
            $("#comments-list .more-comments .loading").hide();
          }
        },
        'json'
      );
      
      return false;
    });
    
    if (autoRefreshComments) {
      setAutoCommentsInterval();
    }
    
    // odeslani formulare pro zaslani noveho hesla
    $("#btn-users_forgotten_password_form").click(function(){
      $.cms.submit("users_forgotten_password_form");
      
      return false;
    });
    
    // kontrola formulare pro vyhledavani
    $("#search-box").submit(function() {
      return ($("#search-box input[name='q']").val().length > 1);
    });
    
    
    var interval;
    interval = setInterval("slideSwitch()", 4000);

    // HOMEPAGE SLIDER  ---------------------------------------------------------------------------------------------------
    $("#slider .headlines li").mouseenter(function() {  
      if ($(this).hasClass('active')) {}
      else {
          $("#slider .headlines li").removeClass("active");
        	$(this).addClass("active");
          
          $("#slider .thumbs h2").attr("style", "bottom: -200px");
          $("#slider .content-item-visible").css({opacity: 0.0}).removeClass("content-item-visible");
          var ind = $("#slider .headlines li").index(this);
          $("#slider .thumbs li:eq("+ind+")").stop().animate({opacity: 1}, 1000).addClass("content-item-visible");
          $("#slider .thumbs li:eq("+ind+")").find("h2").stop().animate({bottom: 30}, 400);           
      		Cufon.replace('#slider .headlines li a', { hover: true }); 
      }
    });

		$("#slider").hover(function() {   
				clearInterval(interval);
		}, function() { 
        interval = setInterval("slideSwitch()", 4000);
    }); 
    		
		 // dropdown menu
		 $('#main-menu div.sub').hover(function(event) {
			 	$(this).parent().addClass('active');
		 }, function() { 
			 	$(this).parent().removeClass('active');
			 	Cufon.replace('a.parent span', { hover: true, hoverables: { span: true } });
		 });

		// dropdown user-box
		$('#user-box .form-login').hover(function(event) {
			 	$(this).parent().addClass('active');
		}, function() { 
			 	$(this).parent().removeClass('active');
		});

		// focus input
		$('.input, .textarea').focus(function () {
		  $(this).parent().addClass('focus');
		}).blur(function () {
		  $(this).parent().removeClass("focus");
		  }
		);

    // input placeholder
		$('input[placeholder], textarea[placeholder]').placeholder();

    // Cufon replace ---------------------------------------------------------------------------------------------------
    Cufon.now();
    Cufon.replace('#slider h2 a, #slider .thumbs li h2, .contest h3, .box h4, .box p, .partylist .date, #footer h4, #title, .title, #content h1, #content h2, #content h3', { fontFamily: 'primary', hover: true }); 
    Cufon.replace('#main-menu a span, .btn-default span, .btn-next span, .btn-prev span, .error-404 span, .error-404 p', { fontFamily: 'primary', hover: true, hoverables: { span: true} });
  
  	// Otevreni v odkazu v novem okne
  	$("a.ext").click(function(){
  		return ! window.open(this.href);
  	});

});



// prekresli texty cufonem po nacteni obsahu pres ajax
$(document).ajaxSuccess(function() {
  Cufon.refresh();
});

//slideSwitch
function slideSwitch() {
  //headlines
  var $active = $('#slider .headlines li.active');        
  if ($active.length == 0) $active = $('#slider .headlines li:last');
  var $next = $active.next().length ? $active.next() : $('#slider .headlines li:first');

	$('#slider .headlines li');
  $next.addClass('active');
  $active.removeClass('active');

  //thumb          
  var $visible = $('#slider .thumbs li.content-item-visible');        
  if ($visible.length == 0) $visible = $('#slider .thumbs li:last');        
  var $nextThumb = $visible.next().length ? $visible.next() : $('#slider .thumbs li:first');

	$('#slider .thumbs li').css({opacity: 0.0}).removeClass('content-item-visible');
  $nextThumb.addClass('content-item-visible').stop().animate({opacity: 1.0}, 1000);

	$nextThumb.find("h2").attr("style", "bottom: -200px").stop().animate({bottom: 30}, 400); 

  Cufon.refresh();
}

	// On window load. This waits until images have loaded which is essential
	$(window).load(function(){
		/*
		// Fade in images so there isn't a color "pop" document load and then on window load
		$(".thumb img").fadeIn(500);
		
		// thumb image
   	$('.thumb img').each(function(){
			var el = $(this);
			el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
				var el = $(this);
				el.parent().css({"width":this.width,"height":this.height});
				el.dequeue();
			});
			this.src = grayscale(this.src);
		});
		
		// Fade image 
		$('.thumb img').mouseover(function(){
			$(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
		})
		$('.img_grayscale').mouseout(function(){
			$(this).stop().animate({opacity:0}, 1000);
		});		
    */
	});
	
	// Grayscale w canvas method

	function grayscale(src){
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var imgObj = new Image();
		imgObj.src = src;
		canvas.width = imgObj.width;
		canvas.height = imgObj.height; 
		ctx.drawImage(imgObj, 0, 0); 
		var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
		for(var y = 0; y < imgPixels.height; y++){
			for(var x = 0; x < imgPixels.width; x++){
				var i = (y * 4) * imgPixels.width + x * 4;
				var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
				imgPixels.data[i] = avg; 
				imgPixels.data[i + 1] = avg; 
				imgPixels.data[i + 2] = avg;
			}
		}
		ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
		return canvas.toDataURL();
    }

// nastavi interval pro automaticky refresh komentaru
function setAutoCommentsInterval() {
  if (autoRefreshCommentsInterval)
    clearInterval(autoRefreshCommentsInterval);
  
  autoRefreshCommentsInterval = setInterval("getNewComments()", autoRefreshCommentsIntervalTime);
}

// vrati nove komentre od posledne zobrazeneho
function getNewComments() {
  $.post(
    BreezyCMS_URL + "comments/refresh/" + commentsLastTimestamp + "/" + commentModel + "/" + commentModelId + "/",
    function (payload) {
      if (payload.state == 'ok') {
        $.each(payload.comments, function(id) {
          if ( ! $("#comment-" + commentModel + "-" + id).length)
            $("#comments-list").prepend(payload.comments[id]);
        });
        
        commentsLastTimestamp = payload.last_timestamp;
      }
    }
  );
}

var skyscraper = "#skyscraper.sticky";
var strip = "#strip";
$(document).ready(function () {
	var top = "20";
  if ($("#leaderboard").length){ var top = "120"; }
         
	// BANNER STICKY SKYSCRAPER SCROLL			
	$(window).scroll(function () {
			var right = (($(window).width() - $("#main").width()) / '2') - '140';
			if ($(document).scrollTop() <= top) {
					$(skyscraper).css("position", "absolute");
					$(skyscraper).css("top", "0px");
					$(skyscraper).css("right", "-140px")
			} else {
          $(skyscraper).css("position", "fixed");
          $(skyscraper).css("top", "0px");
          $(skyscraper).css("right", right);    
      }

	});

	// STRIP STICKY SCROLL			 		
	$(window).scroll(function () {
			var left = (($(window).width() - $("#main").width()) / '2');	
			if ($(document).scrollTop() <= top) {
						$(strip).css("position", "absolute");
						$(strip).css("top", "0px");
						$(strip).css("left", "0px");						
      	    $(strip).stop().animate({'opacity':'1'},400);
			} else {
       	    $(strip).css("position", "fixed");
      	    $(strip).css("top", "0px");
      	    $(strip).css("left", left);	
      	    $(strip).stop().animate({'opacity':'0.5'},200);     
      }
 	  });

		$(strip).hover(
  		function () {
  			var scrollTop = $(window).scrollTop();
  			if(scrollTop >= top){
  				$(this).stop().animate({'opacity':'1'},400);
  			}
  		},
  		function () {
  			var scrollTop = $(window).scrollTop();
  			if(scrollTop >= top){
  				$(this).stop().animate({'opacity':'0.5'},200);
  			}
  		}
    );

});
