$(function(){
  var eventsWidth = 0;

  var $events = $('div.video-box');
  $events.children('.video-item').each(function(){eventsWidth += $(this).width() + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));})
  $events.width(eventsWidth);

  var maxOffset = eventsWidth - $('#container').width() + 30;

  $(window).bind('resize',function(){
    maxOffset = eventsWidth - $('#container').width() + 30;
  });

  $.getJSON('/'+SF_CULTURE+'/filter',function(data){
    onloadFilters(data.current_filter);
  });

  $('.exhibition-past a').incrPlaceClicks();
  $('#page-roller .page-fwd a, #page-roller .page-back a').applyCalendar();
});


$.widget('ui.dateroller',{


  _init: function() {

    this.prevIndex = 0;
    
    var self = this, o = this.options;
    var step = 100 / (this.options.poster.length * 2 - 1);

    $(this.options.box).css({left: 0});
    
    if (this.options.poster) {
      var today = new Date();
      var current_date = new Date();
      var today_date = today.getDate();
      var today_month = today.getMonth();
      var today_year = today.getYear() + 1900;
      var url,
          anchor,
          anchor_clickme;

      var table = '<table style="table-layout: fixed"><tr>';
      table += '<td colspan="' + (this.options.poster.length * 2 - 1) + '" class="scrollbar-col"><div class="scrollbar"><div class="line"></div></div></td></tr><tr>';
      for (var i = 1; i <= this.options.poster.length; i++) {               
        current_date.setFullYear(o.year, o.month - 1, i);
        var current_day = (current_date.getDay());

        url = '/'+SF_CULTURE+'/afisha/'+ (current_date.getYear() + 1900) +'/'+ (current_date.getMonth() + 1) +'/'+ current_date.getDate();
        anchor = '<a href="'+ url +'">'+ i +'</a>';
        anchor_clickme = '<a class="clickme" href="'+ url +'">'+ i +'</a>';

        table += '<td style="width: ' + step + '%">';

        if (i == today_date && today_month == o.month - 1 && today_year == o.year) {
          table += '<span class="current">';
          if (this.options.poster[i - 1] == 0) table += i;
          else table += anchor;

        } else {
          if (current_day == 6 || current_day == 0) {
            table += '<span class="weekend">';
            if (this.options.poster[i - 1] == 0) table += i;

            else if (this.options.poster[i - 1] == -1) table += anchor_clickme;
            else table += anchor;

          } else {
            table += '<span>';
            if (this.options.poster[i - 1] == 0) table += i;

            else if (this.options.poster[i - 1] == -1) table += anchor_clickme;
            else table += anchor;

          }
        }

        table += '</span></td>';
        if (i != this.options.poster.length) {
          if (this.options.poster[i - 1] > 6) table += '<td style="width: ' + step + '%"><span>&nbsp;</span></td>';
          else table += '<td style="width: ' + step + '%">&nbsp;</td>';
        }
      }
      table += '</tr></table>';

      this.element.html(table);

      this._setPaddings();
     
     
      $(window).bind('resize',function(){
        self._setPaddings();
      });      
      
      var $trs = this.element.find('tr');
      $trs.eq(0).find('div.line').slider({
        min: 1,
        max: o.poster.length * 2 - 1,
        step: 0.01,

        slide: function(event, ui) {
          var int_coord, offset;
          //console.log(this.prevIndex,ui.value);
          if (this.prevIndex <= ui.value) {
            int_coord = Math.floor(ui.value);
            offset = ui.value - this.prevIndex;
          }
          else {
            int_coord = Math.ceil(ui.value)
            offset = this.prevIndex - ui.value;
          }

          //console.log(offset, $(o.box).queue('fx').length)

          //Если бегунок двигается медленнее чем заданная скорость, надо перелистывать.          
          if (offset <= o.speed) {
            if (int_coord % 2) {
              
              if (o.poster[(int_coord + 1) / 2 - 1] > 0) {
                $(o.box).stop(/*true, true*/);
                $(o.box).animate({
                  left: parseInt($(o.box).css('left'))
                        - $('#d' + ((int_coord + 1) / 2)).offset().left
                        + o.offset + 'px'
                }, o.animatespeed);

              }
            } else {

              if (o.poster[(int_coord) / 2 - 1] > 6) {

                var $all_items = $(o.box).children();
                var day_item_num = $('#d' + ((int_coord) / 2)).prevAll().length + 6;
                $(o.box).stop(/*true, true*/);
                $(o.box).animate({
                    left: parseInt($(o.box).css('left'))
                          - $all_items.eq(day_item_num).offset().left
                          + o.offset + 'px'
                  }, o.animatespeed);

              }
            }
          }
          this.prevIndex = ui.value;          
        },

        stop: function(event, ui) {
          
          var int_value = Math.round(ui.value);
          var point;

          if (int_value % 2) {
            //попали в начало дня где есть события            
            point = (int_value + 1) / 2;
          } else if (o.poster[int_value / 2 - 1] > 6) {
                   //вторая половина дня с больше чем 6ю выставками                   
                   point = (int_value - 1) / 2;
                 } else if (int_value == Math.floor(ui.value)) {
                          //между днями ближе к большему                          
                          point = (Math.round(ui.value + 0.5) + 1) / 2;
                        } else {
                          //между днями ближе к меньшему                          
                          point = (Math.floor(ui.value) + 1) / 2;
                        }         
          var direction = 1;
          var i = 1;
          var j = 1;

          var $all_items;
          var day_item_num;

          if (Math.round(point) != point) {
            //если в этот день больше 6 выставок и мы на середине дня
            point += 0.5;
            $all_items = $(o.box).children();
            day_item_num = $('#d' + point).prevAll().length + 6;

            $(o.box).animate({
                left: parseInt($(o.box).css('left'))
                      - $all_items.eq(day_item_num).offset().left
                      + o.offset + 'px'
              }, o.animatespeed);

            $(this).slider('value',point * 2);

          } else {

            if ($('#d'+point).length > 0) {
              //если в этот день открываются выставки и мы на начале дня
              $(o.box).animate({
                left: parseInt($(o.box).css('left'))
                      - $('#d'+point).offset().left
                      + o.offset + 'px'
              }, o.animatespeed);

              $(this).slider('value',point * 2 - 1);

            } else {
              //если в этот день выставки не открываются
              
              if ((point - 1) * 2 == Math.floor(ui.value)) {
                direction = -1;
              }

              //находим ближайший день с выставками
              while ( $('#d' + (point + direction)).length == 0
                      && (point + direction) > 0
                      && (point + direction) <= o.poster.length) {

                if (j % 2) {
                  direction = - direction;
                } else {
                  direction = - (i * direction / Math.abs(direction));
                  i++;
                }
                j++;

              }

              if (!(o.poster[point - 2] <= 6 || (o.poster[point - 2] > 6 && direction > 0))) {
                //если нашли день и в котором больше 6 выставок или пришли к нему справа, то ставим на половину дня
                $all_items = $(o.box).children();
                day_item_num = $('#d' + (point - 1)).prevAll().length + 6;

                $(this).slider('value',(point + direction) * 2);
                $(o.box).animate({
                  left: parseInt($(o.box).css('left'))
                        - $all_items.eq(day_item_num).offset().left
                        + o.offset + 'px'
                }, o.animatespeed);
              } else {
                //на начало дня
                $(this).slider('value',(point + direction) * 2 - 1);
                $(o.box).animate({
                  left: parseInt($(o.box).css('left'))
                        - $('#d' + (point + direction)).offset().left
                        + o.offset + 'px'
                }, o.animatespeed);
              }             
            }
          }
        },

        start: function(event, ui){
          
        }
      });
    }
  },

  _setPaddings: function() {
    var $trs = this.element.find('tr');
    var padLeft = $trs.eq(1).children('td').eq(0).width()/2;
    var padRight = $trs.eq(1).children('td').eq(this.options.poster.length-1).width()/2;
    $trs.eq(0).children('td').css('padding-left',padLeft);
    $trs.eq(0).children('td').css('padding-right',padRight);
  },

  _scrollToDate: function(date) {

  }
});

$.extend($.ui.dateroller, {
  version: '1.0',
  defaults: {
    box: 'div.video-box',
    offset: 29,
    animatespeed: 200,
    speed: 0.5
  }
});


$.fn.applyCalendar = function() {
  $(this).bind('click',function() {
    var link = this.href;
    link = link.substring(link.indexOf('?'), link.length);
    reloadEvents(link);
    return false;
  });
}


