$(document).ready(function() {
/* Logo animation */
if ($.browser.msie && $.browser.version < 9) { }else{
  function animateLogo(){
    $('a.logo').animate({'opacity': 'toggle'}, 'slow', function(){
    $(this).animate({'opacity': 'toggle'}, 'slow');
    setTimeout(animateLogo,8000);
    });
  }
  setTimeout(animateLogo,3000);
}

/* Banner-rotator in the main page */
  $('#mycarousel').jcarousel({
    scroll: 2,
    animation: 'slow'
  });
  if ($.browser.msie && $.browser.version < 9) { }else{
    $('.banner-rotator').css({'opacity': '0', 'visibility': 'visible'}).animate({'opacity': '1'}, 'slow');
  }



posterPreview();

starRatingSystem();


/* Schedule-menubacklight slider */
  var minPos = 0;
  var maxPos = 840;
  var current = $('.schedule .current');
  var position = current.position();
  var backlight = $('.schedule-backlight');
  if (position != null) {
  var left = position.left + 8 - (backlight.width() - current.width())/2;
  if (left < minPos) { left = minPos };
  if (left > maxPos) { left = maxPos };
  backlight.stop(1,0).animate({'left': left}, 'normal');
  $(".schedule a").hover(
    function () {
      var position = $(this).position();
      var backlight = $('.schedule-backlight');
      var left = position.left + 8 - (backlight.width() - $(this).width())/2;
      if (left < minPos) { left = minPos };
      if (left > maxPos) { left = maxPos };
      backlight.stop(1,0).animate({'left': left}, 'slow');
    },
    function () {
      var current = $('.schedule .current');
      var position = current.position();
      var backlight = $('.schedule-backlight');
      var left = position.left + 8 - (backlight.width() - current.width())/2;
      if (left < minPos) { left = minPos };
      if (left > maxPos) { left = maxPos };
      backlight.stop(1,0).delay('0').animate({'left': left}, 'normal');
    }
  );
  }

/* Movie previews */
  $('.icon-play').click( function(e){
    e.preventDefault();
    if ($(this).is($(this).not('.pressed'))){
      $(this).addClass('pressed');
      var id = $(this).attr('href');
      var videoSrc = ''+$(this).attr('name');
      var video = '<div class="video-js-box">'
                 +'<video class="video-js" width="470" height="320" preload="none" autoplay controls>'
                 +'<source src="'+videoSrc+'.mp4" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />'
                 +'<object id="flash_fallback_1" class="vjs-flash-fallback" width="470" height="320" type="application/x-shockwave-flash" data="/swf/flowplayer-3.2.7.swf">'
                 +'<param name="movie" value="/swf/flowplayer-3.2.7.swf" />'
                 +'<param name="allowfullscreen" value="true" />'
                 +'<param name="flashvars" value=\'config={"playlist":[{"url": "'+videoSrc+'.flv","autoPlay":true,"autoBuffering":false}]}\' />'
                 +'</object>'
                 +'</video>'
                 +'<p class="vjs-no-video">'
                 +''
                 +'</p>'
                 +'</div>';
      $(this).parent().find('a, img').stop(0,0).animate({'width': '100px', 'height': '140px', 'opacity': '0'}, 'normal')
             .end().parent().find('.vote-result').stop(0,0).animate({'opacity': '0'}, function(){ $(this).css({'display': 'none'});} )
             .end().parent().find('article.film-poster').stop(0,0).animate({'width': '100px', 'height': '140px'}, 'normal');
      var filmDescript = $(this).parent().parent().parent().find('.content h1, .content p');
      filmDescript.stop(0,0).animate({'opacity': '0.01'}, 'fast');
      $('#'+id).append(video).find('video').VideoJS();
      $('#'+id).stop(0,0).animate({'right': '0px'}, 'slow');
      var closeTag = '<p style="text-align: left; width: 100%;"><span style="color: #FFC600; display: none;">&larr;&nbsp;</span><a href="#" id="close-'+id+'" class="close-preview">Вернуться к описанию</a></p>';
      $('#'+id).append(closeTag).parent().find('.close-preview').parent().css({'margin-top': '0'}).find('#close-'+id+', span').delay(500).fadeIn('slow');
      //$(this).parent().append(closeTag).find('#close-'+id).delay(500).fadeIn('slow');
    }
    else
    {
      $(this).removeClass('pressed');
      var id = $(this).attr('href');
      $('#close-'+id).parent().fadeOut('normal', 'swing', function(){
        var filmDescript = $(this).parent().parent().parent().parent().find('.content h1, .content p');
        filmDescript.animate({'opacity': '1'});
        $(this).remove();
      });
      $('#'+id).stop(0,0).animate({'right': '-500'}, 'normal', 'swing', function(){ $(this).find('*').css({'display': 'none'}).remove(); });
      $(this).parent().animate({'width': '170px', 'height': '238px'}, 'normal').find('img').stop(0,0).animate({'width': '170px', 'height': '238px', 'opacity': '1'}, 'normal')
                .end().find('.icon-play').stop(0,0).animate({'width': '170px', 'height': '238px', 'opacity': '1'}, 'normal', function(){
                  $(this).parent().parent().find('.vote-result').delay(500).css({'display': 'block'}).animate({'opacity': '1'});
                });
    }
  });
  // Trigger for closing
  $('.close-preview').live('click', function(e){
    e.preventDefault();
    $(this).parent().parent().parent().parent().parent().find('a.icon-play').trigger('click');
    //$(this).parent().parent().find('a.icon-play').trigger('click');
  });


InitializeMovieSessionList();




// show-time schedule table script
$('.bg-poloski td:odd').addClass('add-bg-lightest');
$('.show-time').each(function(i){
      var block = jQuery(this);
      var hour = parseInt(block.attr("hour"));
      var minute = parseInt(block.attr("minute"));
      var startPos = 900; // offset from begin of day 9:00 9*100
//       var time = hour*100 + Math.round((minute > 30 ? minute*1.69 : minute)) - startPos; // 1.69 magic koef for norm display block
      var time = hour*100 + minute - startPos; // 1.69 magic koef for norm display block
      var W = block.parent().width(); // count of real pixel in width
      var w = 1600; // count of virtual pixel in width
      var koef = W/w; // count of real pixels in one virtual
      var left = Math.round(koef * time) - 3;
      block.css({'top': '50%'}).animate({'left': left, 'margin-top': '-17'}, function(){ nowTimeWidth(W,w,startPos); });
});

$('.show-time').hover(function(){
    var nowTime = $('.now-time').width();
    var left = $(this).css('left');
    left = parseFloat(left);
    if (left < nowTime) {
      $(this).css({'cursor': 'default'});
      return false;
    }else{
      $(this).find('p').css({'box-shadow': '0 0 5px 1px #888', 'cursor': 'pointer'});
      //$(this).stop(1,1).animate({'left': '+=5'}, 'fast' , 'swing');
    }
  },
  function(){
    var nowTime = $('.now-time').width();
    var left = $(this).css('left');
    left = parseFloat(left);
    if (left < nowTime) {
      $(this).css({'cursor': 'default'});
      return false;
    }else{
      $(this).find('p').css({'box-shadow': '0 0 5px 1px #444', 'cursor': 'default'});
      //$(this).stop(1,1).animate({'left': '-=5'}, 'fast', 'swing');
    }
});

var showTooltip = 1;

jQuery('a.show-qtip').each(function() {
  jQuery(this).qtip({
      content:  {
                  text: jQuery('#'+jQuery(this).attr('data-qtipID'))
                }
    , position: {
                  target: false
                , adjust: {
                            mouse: false
                          , screen: true
                          , resize: true
                          , scroll:true
                          }
                , corner: {
                            target: 'topMiddle'
                          , tooltip: 'bottomMiddle'
                          }
                }
    , tip: true
    , style:  {
                width: 310
              , padding: 0
              , margin: 0
              , name: 'blue'
              }
    , show: {
              when: 'mouseenter'
            , solo: true
            }
    , hide: {
              when: 'mouseout'
            , fixed: true
            }
    , api:  {
              beforeShow: function(){
                if ( !showTooltip ){
                  return false;
                }
                else {
                  return true;
                }
              }
            }
  });
});


countHeight();


$('.movie-preview-mini-icon').live('click', function(e){
  e.preventDefault();
  if ($(this).is($(this).not('.pressed'))){
    $('.movie-preview-mini-icon').removeClass('pressed');
    $(this).addClass('pressed');
    var videoSrc = $(this).attr('href');
    var width = '768';
    var height = '432';
    showTrailer(videoSrc, width, height);
  }
});


/* Input stilization */
$('input[type="file"]').live('onchange', function () {
  var str = this.value;
  $(this).parent().find('.file-name').val(str);
})
.change();
$('.delete-file-button').live('click', function(e){
  e.preventDefault();
  $(this).parent().find('.file_fake').val('');
  $(this).parent().find('.file-name').val('');
  if ($('.file-form .one-file-input').length > 1){
    $(this).parent().remove();
  }
});

$('.add-file-button').live('click', function(e){
  e.preventDefault();
  $(this).parent().find('input[type="file"]').trigger('click');
});

$('.add-more-file').click(function(e){
  e.preventDefault();
  var InputName = $('.file-form input[type="file"]').attr('name');
  var fi = $('input[type="file"]').length + 1;
  $('.file-form .one-file-input:last')
    .after(
    '<div class="one-file-input">'+
    '<div class="attach">'+
    '<input id="file-input'+fi+'" class="file_fake" type="text" readonly="readonly" />'+
    '<span class="file" title="Выбрать файл">'+
    '<input type="file" name="'+InputName+'" class="file_select" onchange="document.getElementById(\'file-input'+fi+'\').value = this.value" value="">'+
    '<input type="button" class="add-file-button" value="Выбрать файл" title="Выбрать файл" />'+
    '</span>'+
    '</div>'+
    '<a href="#" class="delete-file-button">Удалить</a>'+
    '</div>');
});












});


function InitializeMovieSessionList(){
  /* Open/Close movie session list's */
  $('.films-description .sessions-list').slideUp('fast');

  $('.all-sessions').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('name');
    $('#'+id+'-session').slideToggle('fast', 'swing', function() {});
  });
};


function nowTimeWidth(W,w,startPos){
  var nowTime = $('.now-time').eq(0).attr('id') - startPos;
  nowTime = W*nowTime/w;
  nowTime = parseFloat(nowTime);
  nowTime = nowTime.toFixed(0);
  $('.now-time').animate({'width': nowTime}, 'fast', 'swing');
}



function countHeight(){
$('.raspisanie-table tbody tr').each(function(i){
  $(this).find('.autoHeight').height($(this).height());
});
}

function posterPreview(){
/* Poster-preview in the #poster-preview block */
var totWidth=0;
var widths = new Array();
var totHeight=0;
var heights = new Array();
var maxW = 920;
var maxH = 600;

$('#slides img').each(function(i){
  totWidth = $(this).width();
  if (totWidth>maxW) { totWidth = maxW; }
  widths[i] = totWidth;

  totHeight = $(this).height();
  if (totHeight>maxH) { totHeight = maxH; }
  heights[i] = totHeight;

  if(!$(this).width()){
    //alert("Please, check in width for all your images!");
    return false;
  }
  if(!$(this).height()){
    //alert("Please, check in height for all your images!");
    return false;
  }
});

$('#menu ul li a').bind('click', function(e){
if ($(this).parent().hasClass('act')){} else {

    $('li.menuItem').removeClass('act').addClass('inact');
    $(this).parent().addClass('act');

    var pos = $(this).parent().prevAll('.menuItem').length;

    var imgW = $('#gallery img').eq(pos).width();
    var imgH = $('#gallery img').eq(pos).height();
    var k = 1;
    var n = 1;
    if (imgW>maxW){ var k = imgW/maxW; }
    if (imgH>maxH){ var n = imgH/maxH; }
    if ( n>k ) { k = n; }
    imgW = imgW/k;
    imgH = imgH/k;
    $('#gallery img').stop(0,0).animate({'opacity': 0}, 450, 'linear', function(){
      $('#gallery').stop(0,0).animate({width: imgW, height: imgH},450, 'easeInOutExpo', function(){
        $('#gallery img').eq(pos).css({width: imgW, height: imgH}).animate({'opacity': 1}, 450, 'linear');
      });
    });
}
  e.preventDefault();
});

$('#menu ul li a:first').trigger('click');
$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');
var arrows = $('#gallery .arrow-prev, #gallery .arrow-next');
if ($.browser.msie && $.browser.version < 9) { }else{ arrows.fadeOut(2000); }
$("#gallery").hover(
  function () { if ($.browser.msie && $.browser.version < 9) { }else{ arrows.stop(1,1).fadeIn('normal'); } },
  function () { if ($.browser.msie && $.browser.version < 9) { }else{ arrows.stop(1,1).fadeOut('normal'); } }
);

arrows.click(function(e){
  var num = $('#menu ul li.act').index();
  if (num == $('#menu ul li'.length)) num = $('#menu ul li'.length)-1;
  if ($(this).hasClass('arrow-prev')){ if (num == 0) { var x = 0; }else{ var x = -1; } } else { var x = 1; }
  $('#menu ul li a').eq(num+x).trigger('click');
  e.preventDefault();
});
}

function starRatingSystem(){
$('form.vote-result').each(function(){
var x = $(this).find("input[name='sred']").val();
if (x){
x = parseFloat(x);
x = x.toFixed(0);
if ( x>0 ) {
  $(this).find("input.test").eq(x-1).attr('checked', 'checked');
}
}
});

/* Star rating system */

$('input.test').parent().find('input[type="submit"]').hide();
$('input.test').rating({
  split: 0,
  starWidth: 20,
  cancel: 'Очистить',
  cancelValue: 'clicked',
  callback: function(value, link){
    // $(this).rating('disable');
    var movie = $("input[name='movie']",this.form).val();
    var action = $("input[name='action']",this.form).val();
    var loaderIcon = '<img id="ajax-loader-'+movie+'" src="/img/ajax-loader.gif" width="16" height="11" style="display: block; position: absolute; top: -16px; right: -5px;">';
    $('.movie-result-'+movie).css({'position': 'relative'}).append(loaderIcon);
    $.post("/?action="+action, { movie: movie, action: action, mark: value }, function(data) {
      var result = $(data).find("#people-mark").html();
      $('#people-mark.movie-result-'+movie,this.form).html(result);
      countHeight();
      // alert(data);
    })
    .complete(function() { /*alert("complete");*/ });
    ;
  }
});
}

function showTrailer(videoSrc, width, height){
  if (videoSrc == ''){
    
  }
  var trailer = 
            '<div class="video-js-box">'
           +'<video class="video-js" width="'+width+'" height="'+height+'" preload="none" autoplay controls>'
           +'<source src="'+videoSrc+'.mp4" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />'
           +'<object id="flash_fallback_1" class="vjs-flash-fallback" width="'+width+'" height="'+height+'" type="application/x-shockwave-flash" data="/swf/flowplayer-3.2.7.swf">'
           +'<param name="movie" value="/swf/flowplayer-3.2.7.swf" />'
           +'<param name="allowfullscreen" value="true" />'
           +'<param name="flashvars" value=\'config={"playlist":[{"url": "'+videoSrc+'.flv","autoPlay":true,"autoBuffering":false}]}\' />'
           +'</object>'
           +'</video>'
           +'<p class="vjs-no-video">'
           +'</p>'
           +'</div>';
    $('#trailer-preview').html(trailer).find('video').VideoJS();
}






















