/**
*   Плагин jquery.kiwi_viewer.js
*   
*   @author Isaev Roman
*   @modufy_date 19.02.10
*   @version 1.0 beta
*   
*/

(function($) { 

  function getRandomInt(min, max)
  {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }

	// constructor
	function Kiwi_viewer(self, ops) 
  {          
      var kw_window = self.find('ul:first')
        .addClass('kw_window');
      var kw_window_width = kw_window.width();  
      var kw_window_height = kw_window.height();
      var kw_items = kw_window.find('li')
        .hide();
      var curr_item_index = null; // индекс текущего элемента
      
      /*var timer = 0;
      var timer_iteration = 0;*/
      
      self.append('<div class="clock"> </div>');
      var clock_timer = 0;
      var clock_iteration = 11;
                     
  		// methods
  		$.extend(this, {
  			
    			getItems: function() {
            return self.find('ul li');	
    			},
    			
    			getOptions: function() {
            return ops;	
    			},
    			
    			clickOnItem: function(func) {
            self.find('ul li').click(func);
          }
  			
  		});
  		
      // выбор первого видимого элемента  		
  		self.select_start_item = function()
  		{          
          switch (ops.start_item) {
             case 'first':
                self.preload_item(0);
                break
             case 'last':
                self.preload_item(kw_items.length-1);
                break
             case 'center':
                self.preload_item( Math.floor( (kw_items.length - 1)/2) );
                break
             case 'random':
                self.preload_item( getRandomInt(0, kw_items.length-1) );
                break
             default:
                self.preload_item(0);
                break
          }
      }
      
      self.preload_item = function(index)
      {
          if ( (index != curr_item_index) && (index < kw_items.length) )
          {
              var item = kw_items.eq(index); 
              switch (ops.content_type) {
                  case 'image':
                    alert('no options!');
                    /*if ( item.data('is_load') ) { 
                        self.onLoadItem(item, index);
                    } else {
                        self.preload_image(item, index);
                    }*/
                    break
                  default: // content
                    self.onLoadItem(item, index);
                    break
              } 
          }                     	             
      }
        		
  		self.preload_image = function(item, index)
  		{ 
  		    alert('preload_image');
  		    /*
          clearInterval(timer);
          self.addClock();
          timer_iteration = 0;
          timer = setInterval(function()
          {
      		    timer_iteration++;
              if ( load_item.data('is_load') ) 
              { 
                  clearInterval(timer);
                  self.removeClock();
                  self.onLoadItem();
              }
              if (timer_iteration > 30){
                  clearInterval(timer);
                  self.removeClock();
                  alert('Error: timeout load image.');
                  self.onLoadItem();  
              }
          }, 1000); 
  		    */
  		}
  		
  		self.onLoadItem = function(load_item, load_index)
  		{  
          if (curr_item_index === null){
              load_item.show();
          } else {          
              var cur_item = kw_items.eq(curr_item_index);
              switch (ops.effect) 
              {
                 case 'fade':
                    load_item.css({ opacity: 0 }).show();
                    cur_item.animate({ opacity: 0 }, ops.animate_time, function(){
                        $(this).hide();
                    });
                    load_item.animate({ opacity: 1 }, ops.animate_time);
                    break
                    
                 case 'slide-hor':
                    var load_width = load_item.width();
                    var cur_width = cur_item.width();
                    if (curr_item_index < load_index){
                        // next
                        load_item
                          .css({ zIndex: 0 })
                          .show();
                        cur_item
                          .css({ zIndex: 1 })
                          .animate({ width: 0 }, ops.animate_time, function(){
                              $(this).hide().css({ width: cur_width + 'px' });
                          });                       
                    } else {
                        // prev
                        cur_item.css({ zIndex: 0 });
                        load_item
                          .css({ zIndex: 1, width: 0 })
                          .show()
                          .animate({ width: load_width + 'px' }, ops.animate_time, function(){
                              cur_item.hide();    
                          }); 
                    }                     
                    break
                    
                 case 'slide-vert':
                    var load_height = load_item.height();
                    var cur_height = cur_item.height();
                    if (curr_item_index < load_index){
                        // next
                        load_item
                          .css({ zIndex: 0 })
                          .show();
                        cur_item
                          .css({ zIndex: 1 })
                          .animate({ height: 0 }, ops.animate_time, function(){
                              $(this).hide().css({ height: cur_height + 'px' });
                          });                       
                    } else {
                        // prev
                        cur_item.css({ zIndex: 0 });
                        load_item
                          .css({ zIndex: 1, height: 0 })
                          .show()
                          .animate({ height: load_height + 'px' }, ops.animate_time, function(){
                              cur_item.hide();    
                          }); 
                    }                     
                    break

                 case 'scroll-hor':
                    var load_width = load_item.width();
                    var cur_width = cur_item.width();
                    var load_val = '';
                    var cur_val = '';
                    if (curr_item_index < load_index){
                        // next
                        load_val = load_width + 'px';
                        cur_val = '-' + load_width + 'px';                        
                    } else {
                        // prev
                        load_val = '-' + load_width + 'px';
                        cur_val = load_width + 'px'; 
                    }                    
                    load_item.css({ left: load_val }).show();                    
                    cur_item.animate({ left: cur_val }, ops.animate_time, function(){
                        $(this).hide().css({ left: '0' });
                    });
                    load_item.animate({ left: '0px' }, ops.animate_time);                             
                    break
                                        
                 case 'scroll-vert':
                    var load_height = load_item.height();
                    var cur_height = cur_item.height();
                    var load_val = '';
                    var cur_val = '';
                    if (curr_item_index < load_index){
                        // next
                        load_val = load_height + 'px';
                        cur_val = '-' + load_height + 'px';                        
                    } else {
                        // prev
                        load_val = '-' + load_height + 'px';
                        cur_val = load_height + 'px'; 
                    }                    
                    load_item.css({ top: load_val }).show();                    
                    cur_item.animate({ top: cur_val }, ops.animate_time, function(){
                        $(this).hide().css({ top: '0' });
                    });
                    load_item.animate({ top: '0px' }, ops.animate_time);                             
                    break
                    
                 default: // 'none'
                    cur_item.hide();
                    load_item.show();
                    break
                  
              }
              cur_item.removeClass('current');
          }
          
          load_item.addClass('current');               
          curr_item_index = load_index;          
          
          /*var w = load_item.width();
          var h = load_item.height();
          //alert(self.html() + " w: " + w + " h: " + h);
          
          var item_l = Math.floor((kw_window_width - w)/2);
          var item_t = Math.floor((kw_window_height - h)/2);
          
          load_item.css({
            left: item_l + 'px',
            top: item_t + 'px'
          });*/
      }
      
  		self.addClock = function()
  		{ 
  		    self.find('div.clock').show();
  		    clearInterval(clock_timer);
  		    clock_timer = setInterval(function()
          {
              var val = clock_iteration*40;
              self.find('div.clock').css('background-position','0 '+ val + 'px');   
              if (clock_iteration > 0){
                  clock_iteration--;
              } else {
                  clock_iteration = 11;
              }                
          }, 100);
  		}
  		
  		self.removeClock = function()
  		{ 
  		    clearInterval(clock_timer);
          self.find('div.clock').hide();
  		}
            
      // обработчики событий кнопок
      
      // next
      self.find(ops.btn_next).click(function()
      {
          if(curr_item_index < kw_items.length - 1)
          {
              self.preload_item(curr_item_index + 1);
              self.state_buttons();          
          } else if (ops.circle){
              self.preload_item(0);
          } 
          return false;     
      });
      
      // prev
      self.find(ops.btn_prev).click(function()
      {
          if(curr_item_index > 0)
          {
              self.preload_item(curr_item_index - 1); 
              self.state_buttons();          
          } else if (ops.circle){
              self.preload_item(kw_items.length - 1);
          }
          return false;     
      });
      
      // end обработчики событий кнопок
      
      // Определяет скрывать кнопки "НАЗАД" и "ВПЕРЕД" или нет
      self.state_buttons = function()
      {
          if (!ops.circle)
          {
              // next
              if(curr_item_index >= kw_items.length - 1)
              {
                  self.find(ops.btn_next).addClass('disabled');
              } else {
                  var btn = self.find(ops.btn_next);
                  if ( btn.hasClass("disabled") ){              
                    btn.removeClass('disabled');
                  }
              }  
              
              // prev
              if(curr_item_index <= 0)
              {
                  self.find(ops.btn_prev).addClass('disabled');
              } else {
                  var btn = self.find(ops.btn_prev);
                  if ( btn.hasClass("disabled") ){              
                    btn.removeClass('disabled');
                  }
              }
          } 
      }
      
      if (kw_items.length > 0){
          self.select_start_item();
          self.state_buttons();
      }
          		
	}

  // jQuery plugin implementation
  $.fn.kiwi_viewer = function(ops)
  {  
  		var el = this.eq(0).data('kiwi_viewer');
  		if (el) { return el; }
      
      // default settings
      var ops = $.extend({
          btn_next: 'a.btn_next', //селектор для выбора кнопки движения вперед
          btn_prev: 'a.btn_prev', //селектор для выбора кнопки движения назад
          start_item: 'first', // first / center / last / random
          content_type: 'content', // content / image
          //window_size: 'auto', // auto / css
          effect: 'none', // none / fade / slide-vert / slide-hor / scroll-vert / scroll-hor
          animate_time: 500, // время анимации
          circle: false // цикличиское движение по кругу 
      },ops);
          
  		this.each(function() {			
  			el = new Kiwi_viewer($(this), ops);
  			$(this).data('kiwi_viewer', el);	
  		});
  		
  		return this;    
  };

})(jQuery);



