var chatInterval = 5000;

$(function(){

  $(".fancybox").fancybox({
    centerOnScroll: true,
    transitionIn: 'elastic',
    transitionOut: 'elastic',
    titlePosition: 'inside'
  });
  
  $(".form small").css("display","none");
  $(".form input, .form textarea").focus(function() {
    $(this).parents("p").find("small").fadeIn();
  });
  $(".form input, .form textarea").blur(function() {
    $(this).parents("p").find("small").fadeOut();
  });

  $(".video-link").each(function(){
    var href = $(this).attr("href" );
    $(this).attr("href", htdocs + "apps/player.php?link=" + $(this).attr("href" ));
  });

  $(".video-link").fancybox({
    centerOnScroll: true,
    type: "iframe",
    width: 620,
    height: 382,
    autoDimensions: false
  });

// LIDE
  $('.lide .bio').css('display', 'none');
  $('.lide .more').click(function(){
    $(this).parents('.lide').find('.bio').slideToggle();
    return false;
  });

// CHAT
  $('.chat-form-add .submit-line input:first').click(function(){
    $('#mess').removeClass('warn');
    var mess = $('#mess').val();
    if(mess == '') {
      $('#mess').addClass('warn');
      return false;
    }
    else {
      var url = htdocs + 'apps/chat-add.php?mess=' + mess;
  		$.ajax({
  			'url':url,
  			'type':'get',
  			'dataType':'json',
  			'success':function(data,textStatus) {
          giveChat(data,textStatus);
        	$('#mess').attr('value','').focus();
        }
      });
      return false;
    }
  });
  
});

function refreshChat() {
  var url = htdocs + 'apps/chat-add.php';
	$.ajax({
		'url':url,
		'dataType':'json',
		'success':function(data,textStatus) {
      giveChat(data,textStatus);
      setTimeout('refreshChat()', chatInterval);
    }
  });
}


function giveChat(data, textStatus){
	if(textStatus != 'success'){
		alert('Stala se chyba na straně serveru.');
		return false;
	}
  $('.chat-item').addClass('to_del');

  var klasa = ( ($('.chat-item:last').hasClass('even')) ? 'even' : 'odd' );
  
	$.each(data,function(i,item){
	  if($('.chat-item[rel=item'+item.id+']').length > 0) {
      $('.chat-item[rel=item'+item.id+']').removeClass('to_del');
    }
    else {
  		var code = '<div style="display:none;" class="chat-item" rel="item' + item.id + '"><em>' + item.time + '</em> <strong>' + item.user + ':</strong>' + item.mess + '</div>';
  		klasa = klasa == 'odd' ? 'even' : 'odd';
  		$('#chat-stream').append(code);
  		$('.chat-item:last').addClass(klasa).slideDown('slow');
  	}
  });
  $('.to_del').slideUp(function(){ $(this).remove(); });
	return false;
}
