/*
 * Tvprogram
 * Author: Lukas Pesl
 * Version : 0.2 
 *  
 */   

(function($){
  
  $.fn.extend({ 
		tvprogram: function(options) {

			var defaults = {
        navigationLeft : '#tv-left-arrow',
        navigationRight : '#tv-right-arrow',
        categories : '#t2'
			};
			
			var options = $.extend(defaults, options);
			var selector = this.selector;
		
  		var $this = this;
  		var $navigationLeft = $(options.navigationLeft, this);
  		var $navigationRight = $(options.navigationRight, this);
  		var $categories = $(options.categories);
  		var $categoriesBoxes = $('input', $categories);

 			var arrows = $([]).pushStack([$navigationLeft[0], $navigationRight[0]]);
 			var tr = $('tr', this);
 			var thCount = $('th', tr[0]).length;
 			var cells = $('th, td', this);

  		var actualStep = 0;
  		var maxStep = thCount - 6; // po sloupcich
  		var maxStep = Math.ceil((thCount-1) / 5) - 1; // po strankach
  		var isBanner = null;

  		var tableTop = this.offset() ? this.offset().top : 0;
			var tableHeight = parseInt(this.height()); 

      var reoder = function() {
        var items = $('#mw-window .order-wrapper .item');
        items.each(function(){
          var number = $('.number', this);
          number.html($(this).index() + 1 + '.');
        }); 
      }

      var programListOnShow = function() {
       
         var ow = $("#mw-window .order-wrapper");
				 ow.sortable({
          stop: function(event, ui) {
           reoder();
          }
         }).disableSelection();

         var checks = $("#mw-window input");

				 if ($.cookie('tv-program-programy'))
				 {
          var checkArray = $.cookie('tv-program-programy').split(',');
          checks.each(function(){ $(this).attr('checked', false); });
          $.each(checkArray, function(key, val){
            checks.each(function(){
              var name = $(this).attr('name');
              if (name == val) 
							{
								$(this).attr('checked', 'checked');
  							 var html = '<div class="item"><div class="number">1.</div><div class="name" rel="#rel#">#name#</div></div>';
								 ow.append(html.replace(new RegExp('\\#name\\#', 'g'), $(this).val())
								               .replace(new RegExp('\\#rel\\#', 'g'), $(this).attr('name')));
							}
            });
          });
				 }

		 		checkboxHeight = 15;
				radioHeight = 15;

 	 			Custom.init($("#mw-window")[0]);
        Custom.clear($("#mw-window")[0]);

         reoder(); // az po nahrani dat

				 checks.click(function(){
						 if ($(this).attr('checked')) 
						 {
							 var html = '<div class="item"><div class="number">1.</div><div class="name" rel="#rel#">#name#</div></div>';
							 ow.append(html.replace(new RegExp('\\#name\\#', 'g'), $(this).val())
							               .replace(new RegExp('\\#rel\\#', 'g'), $(this).attr('name')));
						 } else
						 {
				        var items = $('.item', ow);
				        var check = this;
								items.each(function(){
				          var name = $('.name', this);
				          if (name.html() == $(check).val())
				          {
										$(this).remove();
										return false;
									}
				        }); 
						 }
		         reoder();
         });
	         
	      $('.programs-list #save-changes').click(function(){
	        var checkNames = '';
	        var items = $('.item', ow);
					items.each(function(){ checkNames += $('.name', this).attr('rel') + ','; });
	        checkNames = checkNames.substr(0, checkNames.length-1);
	        $.cookie('tv-program-programy', checkNames, {expires: 30});
	        location.reload(true);
	      });
	      
      }

			if (options.getOS) return programListOnShow; 

      var init = function() {
   			   $('#main, #ihned').css('overflow', 'hidden');
   			   $navigationRight.show();
   			   $this.width('auto');

           setInterval(function(){
            var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    			  var pos = top - tableTop + 308;
    			  if (pos < 308) pos = 308;
    			  if (pos > tableHeight - 308) pos = tableHeight - 308;
            arrows.clearQueue().dequeue().animate({top: pos + 'px'}, 350);
          }, 350);
      }();

      var hideShowColumn = function(index, show, last) {
        tr.each(function(){
          var cells = $($('TH, TD', this)[index]); 
          if (show)
            cells.show();
          else
            cells.hide();
          if (last) cells.addClass('last');
        });
      }

      var hideAllColumns = function() {
        cells.hide().removeClass('last');
      }

      var setStep = function(step, byClick) {

        if (step == 0) $navigationLeft.hide(); else $navigationLeft.show();
        if (step == maxStep) $navigationRight.hide(); else $navigationRight.show();

        actualStep = step;
        hideAllColumns();
        hideShowColumn(0, true);
        
        step = step * 5; // pokud to je po sloupcich, neni tu tento radek 
        for (var i=step; i<step+5; i++)
        {
          hideShowColumn(i+1, true, i==step+5-1 || i==thCount-2); 
        }
  			tableHeight = parseInt($this.height());

      };
      setStep(0);

      $categoriesBoxes.click(function(){
        var name = $(this).attr('name');
        if ($categories.find(':checked').length == 0) $(this).attr('checked', 'checked');
        
        if (name != 'all')
        {
          $categories.find('[name="all"]').attr('checked', false);
        } else
        {
          $categories.find('[name!="all"]').attr('checked', false);
        }
        if (Custom) Custom.clear();
      });
      $navigationLeft.click(function(){
        prevStep = actualStep; 
        setStep(--actualStep, true);
        return false; 
      });
      $navigationRight.click(function(){
        prevStep = actualStep; 
        setStep(++actualStep, true);
        return false; 
      });
      return this;
  	}
	});
})(jQuery);



