var calendarUrl = "/cinema/calendar";
var bookingUrl = "/cinema/booking/calendar";
jQuery(function($){


  // fix ie background cache bug
  if ($.browser.msie)
   { document.execCommand("BackgroundImageCache", false, true); }

  // hide noscript
  $("#noscript").hide();

  // poster animation
  var poster = $("#poster");
  if (poster.length)
  {
    var i, j, n, m;
    var posterBox = poster.find("div.poster");
    var posterBig = poster.find("div.poster-big");
    var posterBigCurrent = 0;
    var posterBigSize = posterBig.size();
    var posterBigIn = false;
    var posterBigHover = false;
    var posterVisible = 4;
  
    var posterGroup = new Array();
    var posterFreez = 7500;
    for(i = 0, n = Math.ceil(posterBox.length / posterVisible); i < n; i++)
    {
      posterGroup[i] = posterBox.slice(i * posterVisible, (i + 1) * posterVisible);
    }
    posterBox.bind("mouseover", function() { $(this).data("hover", true); });
    posterBox.bind("mouseout", function() { $(this).data("hover", false); });
    posterBox = null;
  
    var posterCol = new Array();
    for(i = 0, n = posterGroup.length; i < n; i++)
    {
      for(j = 0, m = posterGroup[i].length; j < m; j++)
      {
        posterCol[j] = (posterCol[j] ? posterCol[j] : new Array());
        posterCol[j][i] = posterGroup[i][j];
      }
    }
  
    var posterPosition = new Array();
    for(i = 0, n = posterGroup[0].length; i < n; i++)
    {
      posterPosition[i] = {"left":posterGroup[0][i].offsetLeft, "top":posterGroup[0][i].offsetTop};
    }
    for(i = 0, n = posterGroup.length; i < n; i++)
    {
      for(j = 0, m = posterGroup[i].length; j < m; j++)
      {
        $(posterGroup[i][j]).css({"position":"absolute", "z-index": (i == 0 ? 3 : 2), "left":posterPosition[j].left, "top":posterPosition[j].top});
      }
    }
    posterGroup = null;
    posterPosition = null;

    posterBig.each(function(i){
      if(i == posterBigCurrent)
       $(this).hide();
    });

    posterBig.bind("mouseover", function() { $(this).data("hover", true); });
    posterBig.bind("mouseout", function() { $(this).data("hover", false); });
  
    var posterMutex = 0;
    var posterCurrent = new Array();
    function posterShow()
    {
      if (! posterMutex)
      {
        var i, n, prev, next;
        if (posterBigIn)
        {
          if (posterBigCurrent >= posterBigSize)
            { posterBigCurrent = 0; }

          for(i = 0, n = posterBig.length; i < n; i++)
          {
            if(i != posterBigCurrent)
            {
              posterMutex++;
              $(posterBig[i]).hide(500, function() { posterMutex--; });
            }
          }
          posterMutex++;
          $(posterBig[posterBigCurrent]).fadeIn(500, function() { posterMutex--; });

          posterBigCurrent++;
        }
        else
        {
          posterBig.fadeOut(500);
          for(i = 0, n = posterCol.length; i < n; i++)
          {
            if (posterCol[i].length >= 2)
            {
              if (! posterCurrent[i] || posterCurrent[i] >= posterCol[i].length)
               { posterCurrent[i] = 0; }
         
              prev = posterCurrent[i];
              next = ((posterCurrent[i] + 1) == posterCol[i].length ? 0 : posterCurrent[i] + 1);
         
              prev = $(posterCol[i][ prev ]);
              next = $(posterCol[i][ next ]);
         
              if(prev && !prev.data("hover"))
              {
                posterMutex++;
                prev.fadeOut((i + 1) * 250, function() { posterMutex--; } );
              }
         
              if(next && !next.data("hover"))
              {
                posterMutex++;
                next.fadeIn((i + 3) * 250, function() { posterMutex--; } );
              }
         
              posterCurrent[i]++;
            }
          }
        }
        if (posterBigSize > 0)
        {
          posterBigIn = !posterBigIn;
        }
      }
    }
    setInterval(posterShow, posterFreez);
  }

  // ticker animation
  var tickerBox = $("div#ticker");
  var tickerItems = tickerBox.find("ul li");
  if(tickerItems.length > 0)
  {
    var tickerCurrent = 0;
    var tickerMutex = 0;
    var tickerHover = false;
    var tickerFreez = 3000;
    var tickerSize = tickerItems.size();
    tickerItems.css("position", "absolute").hide();
    $(tickerItems[tickerCurrent]).show();
    tickerBox.hover(function() { tickerHover = true; }, function() { tickerHover = false; });
    function tickerShow()
    {
      if (!tickerMutex && !tickerHover)
      {
        // hide
        var curr = tickerItems[tickerCurrent % tickerSize];
        if (curr)
        {
          tickerMutex++;
          $(curr).animate({width:"hide",opacity:"hide"}, "slow", function() { tickerMutex--; });
        }
        // next
        tickerCurrent++;
        // show
        var next = tickerItems[tickerCurrent % tickerSize];
        if (next);
        {
          tickerMutex++;
          $(next).animate({width:"show",opacity:"show"}, "slow", function() { tickerMutex--; });
        }
      }
    }
    setInterval(tickerShow, tickerFreez);
  }

  // hide calendar button
  $("#calendar").find(".button").hide();

  // ajax calendar
  $("#calendar-date").bind("change", function(){
    var el = $(this);
//    if (el && el.attr("selectedIndex"))
    {
      var cur = el.attr("options")[ el.attr("selectedIndex") ].value;
      var url = calendarUrl;
      if (el.attr("tag") && el.attr("tag") == "booking") url = bookingUrl;
      url += "?date=" + cur;
      var data = {};

      $.ajax({
       "url": url,
       "dataType": "html",
       "type": "GET",
       "cache": false,
       "beforeSend" : function(){
         var loader = $("#calendar-ajax");
         var days = $("#calendar-days")
         loader.css("width", days.attr("offsetWidth"));
         loader.css("height", days.attr("offsetHeight"));
         loader.show();
         days.hide();
       },
       "success": function(data){
         var node = $(data)[0];
         var days = $("#calendar-days")[0];
         days.parentNode.replaceChild(node, days);
         $("#calendar-ajax").hide();
         $("#calendar-days").show();
       },
       "error":function(){
         $("#calendar-ajax").hide();
         $("#calendar-days").show();
         alert("Server AJAX error");
       }
      });
    }
  });

  // timeline animation
  var timelineBox = $("#timeline");
  var timelineTable = timelineBox.find("table.timeline");
  var timelineFull = timelineTable.hasClass("full");
  timelineTable.find("tr:gt(0)").each(function(){
    var el = $(this);
    if (el.find("a").length > 0)
    {
      el.bind("mouseover", function() { $(this).addClass("light"); } );
      el.bind("mouseout", function() { $(this).removeClass("light"); } );
      el.bind("click", function() { $(this).find("a").get(0).click(); } );
    }
  });

  // swap node
  function swapBox(i, j) 
  {
    var p = j.parentNode, s = j.nextSibling;
    if (s == i) 
    {
      p.insertBefore(i, j);
    }
    else if (j == i.nextSibling) 
    {
      p.insertBefore(j, i);
    }
    else
    {
      i.parentNode.replaceChild(j, i);
      p.insertBefore(i, s);
    }
  }

  // sort compare callback
  function timelineCmp(a, b, td)
  {
    // integer
    if(td == 3 || td == 0)
    {
      a = parseInt(a);
      b = parseInt(b);
    }
    else
    {
      a = String(a).toLowerCase().replace(/<\/?.*?>/g, "");
      b = String(b).toLowerCase().replace(/<\/?.*?>/g, "");
    }
    // string
    return a > b;
  }

  // sort timeline by td
  function timelineSort(td)
  {
    var i, j, a, b, table = timelineTable[0];
    for(i = table.rows.length - 1; i >= 0; i--)
    {
      for(j = 1; j <= (i - 1); j++)
      {
        a = table.rows[j];
        b = table.rows[j + 1];
        if (td == 0)
        {
          var sa = $(a).data("sort");
          var sb = $(b).data("sort");
          if (timelineCmp(sa, sb, td))
          {
            swapBox(a, b);
          }
        }
        else if(timelineCmp(a.cells[td].innerHTML, b.cells[td].innerHTML, td))
        {
          swapBox(a, b);
        }
      }
    }
  }

  // timeline sort buttons
  var timelineNow = $("#timeline-now");
  var timelineHall = $("#timeline-hall");
  var timelineMovie = $("#timeline-movie");
  var timelinePrice = $("#timeline-price");
//  var timelineExt = (timelineTable.find("tr:eq(1) td").size() > 6);
  timelineTable.find("tr:gt(0)").each(function(i){ $(this).data("sort", (i + 1)); });

  timelineNow.bind("click", function(){
    timelineNow.addClass("active");
    timelineHall.removeClass("active");
    timelineMovie.removeClass("active");
    timelinePrice.removeClass("active");
    timelineSort(0);
    return false;
  });
  timelineMovie.bind("click", function(){
    timelineMovie.addClass("active");
    timelineHall.removeClass("active");
    timelineNow.removeClass("active");
    timelinePrice.removeClass("active");
    timelineSort(1);
    return false;
  });
  timelineHall.bind("click", function(){
    timelineHall.addClass("active");
    timelineMovie.removeClass("active");
    timelineNow.removeClass("active");
    timelinePrice.removeClass("active");
    timelineSort(2);
    return false;
  });
  timelinePrice.bind("click", function(){
    timelinePrice.addClass("active");
    timelineMovie.removeClass("active");
    timelineNow.removeClass("active");
    timelineHall.removeClass("active");
    timelineSort(3);
    return false;
  });

  // gamezone
  var gameslimit = 9;
  var gamezone = $("#moregamezone");
  if (gamezone.length > 0)
  {
    var games = $("div.game:gt(" + (gameslimit - 1)+ ")");
    games.hide();
    gamezone.bind("click", function() {
      games.each(function(i) { $(this).show(100 + (25 * i)); }); 
      return true; 
   });
  };

  // fix ie click bug
  if ($.browser.msie)
  {
    $("div.poster span").bind("click", function(){ this.parentNode.click(); }); 
    $("div.poster-big span").bind("click", function(){ this.parentNode.click(); }); 
  }

  // logo hover
  var logor = $("div.logo a.r");
  logor.bind("mouseover", function(){ $(this.parentNode).addClass("logoa");});
  logor.bind("mouseout", function(){ $(this.parentNode).removeClass("logoa");});
  logor = null;

  // film hover
  var filmr = $("div.film a");
  filmr.bind("mouseover", function(){ $(this.parentNode).addClass("filma");});
  filmr.bind("mouseout", function(){ $(this.parentNode).removeClass("filma");});
  filmr = null;

  // input hover
  var input = $("div.content input[class!=button]");
  input.bind("focus", function(){ $(this).addClass("focus");});
  input.bind("blur", function(){ $(this).removeClass("focus");});
  input = null;

  // first input auto-focus
  $("div.content input:eq(0)").focus();

  // vote
  $("form#vote a.result").bind("click", function () {
    var el = $(this);
    var url = el.attr("href");
  
    $.ajax({
      "url": url,
      "dataType": "html",
      "type": "GET",
      "cache": false,
      "success": function(data) {
        var html = new String(data);
        var index = html.indexOf("<div");
        html = html.substring(index, data.length - 1);
        index = html.indexOf("<a");
        html = html.substring(0, index);
        e = $("form#vote");
        e.after(html + "</div>");
        e.remove();
      },
      "error":function() {
        alert("Server AJAX error");
      }
  });
  return false;
  });
  
  $("form#vote").bind("submit", function () {
    var el = $(this);
    var url = el.attr("action");
    var post = el.serializeArray();
  
    $.ajax({
      "url": url,
      "dataType": "html",
      "data": post,
      "type": "POST",
      "cache": false,
      "success": function(data) {
        var html = new String(data);
        var index = html.indexOf("<div");
        html = html.substring(index, data.length - 1);
        index = html.indexOf("<a");
        html = html.substring(0, index);
        e = $("form#vote");
        e.after(html);
        e.remove();
      },
      "error":function() {
        alert("Server AJAX error");
      }
  });
  return false;
  });

});