$(function(){
  var Scroller = function(opts){
    var obj      = this;
    var defaults = {};  
    defaults.autoInit         = true;    
    defaults.selectorId       = 'scroller-';
    defaults.disabledNavClass = 'disabled';
  defaults.effectTime       = 500;
  defaults.fixBoxesHeight   = false;
    defaults.transitionMethod = function(itemToHide, itemToShow, cb){
      itemToHide.fadeOut(obj.opts.effectTime, function(){
    itemToShow.fadeIn(obj.opts.effectTime, cb);
    });
    };
    
    // merge options with defaults
    obj.opts = $.extend({}, defaults, opts);  

    if(obj.opts.selectorId == null) return false;
    
    obj.items = $("." + obj.opts.selectorId + "fragment");
    obj.navPrev = $("." + obj.opts.selectorId + "prev");
    obj.navNext = $("." + obj.opts.selectorId + "next");
    
    obj.inTransact = false;
    
    obj.init = function(){     
      obj.navPrev.addClass(obj.opts.disabledNavClass);
      obj.navPrev.attr("href", "javascript:void(0)");
      obj.navNext.attr("href", "javascript:void(0)");        
      
      if(obj.items.length > 1){
        obj.navPrev.attr("rel", -1);
        obj.navNext.attr("rel", 1);
        
        obj.items.each(function(i, el){ 
          if(i == 0) $(el).addClass(obj.opts.selectorId + "current");
      
          if(i != 0){
      //console.log(obj.opts.selectorId + " " + i);
      $(el).hide();    
      }  
          $(el).addClass(obj.opts.selectorId + "fragment-" + i);
        });      
        
        obj.navPrev.click(obj.showItem);
        obj.navNext.click(obj.showItem);        
      }else{
        obj.navNext.addClass(obj.opts.disabledNavClass);  
      }
    /*
      // add navigation
      if(this.opts.news.length > 1){
        var navigation = $(document.createElement('div'));
        navigation.attr('class', this.opts.wrapper + '_navigation');
        
        // previous link
        var prev = $(document.createElement('a'));
        prev.attr('class', this.opts.nav_prev_link_class);
        prev.attr('href', 'javascript:void(0)');
        prev.html(this.opts.nav_prev_link_html);
        prev.click(function(){
          obj.show_prev();
        });
        navigation.append(prev);
        
        var status = $(document.createElement('a'));
        status.attr('id', this.opts.status_link_id);
        status.attr('href', 'javascript:void(0)');
        status.html(this.opts.status_html_on);
        status.click(function(){
          obj.toggle_reproduction();
        });
        navigation.append(status);        
        
        // next link
        var next = $(document.createElement('a'));    
        next.attr('class', this.opts.nav_next_link_class);
        next.attr('href', 'javascript:void(0)');
        next.html(this.opts.nav_next_link_html);
        next.click(function(){
          obj.show_next();
        });
        navigation.append(next);
        
        // append controls to navigation
        $('#' + obj.opts.wrapper).append(navigation);
        
        if(this.opts.auto_start){
          this.start_reproduction();
        }
      }  
*/  
    if(obj.opts.fixBoxesHeight){
      $(window).load(function(){
        var maxHeight = 0;
        obj.items.each(function(){
          var boxHeight = $(this).outerHeight();
          if(boxHeight > maxHeight) maxHeight = boxHeight;        
        });
        
        obj.items.each(function(){
          $(this).height(maxHeight);
        });   
        
        obj.navPrev.fadeIn(200);
        obj.navNext.fadeIn(200);            
      });
    }
    };
    
    obj.showItem = function(event){
      if(obj.inTransact) return;
      
      var trigger = $(event.target);
      var index   = parseInt(trigger.attr('rel'));
            
      if(index > -1 && obj.items.length > index){       
        var item = $("." + obj.opts.selectorId + "fragment-" + index);
       
        if(item.length > 0){
          obj.inTransact = true;
          
          var currentClass = obj.opts.selectorId + "current"; 
                          
          obj.opts.transitionMethod($("." + currentClass), item, function(){
            $("." + currentClass).removeClass(currentClass);  
            item.addClass(currentClass);  

            obj.inTransact = false;
          });

          var prevIndex, nextIndex;
          if(index == 0){
            obj.navPrev.addClass(obj.opts.disabledNavClass);
            obj.navNext.removeClass(obj.opts.disabledNavClass);            
            prevIndex = -1;
            nextIndex = index + 1;
          }else{
            obj.navPrev.removeClass(obj.opts.disabledNavClass);                  
            if(index == obj.items.length - 1){
              obj.navNext.addClass(obj.opts.disabledNavClass);         
              nextIndex = -1;                
            }else{
              obj.navNext.removeClass(obj.opts.disabledNavClass);                 
              nextIndex = index + 1;
            }
            prevIndex = index -1;  
          }
    
          obj.navPrev.attr("rel", prevIndex);
          obj.navNext.attr("rel", nextIndex);    
        }
      }
    };
    
    /*
    this.show = function(index){
      // too much clicks
      if(obj.in_transact){
        return false;
      }else{
        obj.in_transact = true;
      }
      
      // hide old index
      var next = $('.' + 'js_' + obj.opts.source_id + '_item_' + index);
      
      if(!next.length) return false;
      
      var current = $('.' + 'js_' + obj.opts.source_id + '_item_' + obj.shown_index);
      current.fadeOut(obj.opts.effect_time, function(){
        current.hide();
        next.fadeIn(obj.opts.effect_time);  
        // end of transaction
        obj.in_transact = false;        
      });
      
      obj.shown_index = index;
      
      return true;
    }
    
    this.show_prev = function(){
      var index = obj.shown_index <= 0? obj.opts.news.length - 1: obj.shown_index - 1;
      
      obj.show(index);
    }    
    
    this.show_next = function(){
      var index = obj.shown_index < (obj.opts.news.length - 1)? obj.shown_index + 1: 0;
      
      obj.show(index);
    }    
    
    this.show_random = function(){
      var index = Math.floor(obj.opts.news.length*Math.random());

      // if index is currently shown, show another element
      if(index == obj.shown_index){
        obj.show_random();
        return;
      }else{
        obj.show(index);
      }
    }
    
    this.start_reproduction = function(){  
    
      switch(obj.opts.behave_as){
        case 'left': function timed_update(){ obj.show_prev(); } break;
        case 'right': function timed_update(){ obj.show_next(); } break;
        case 'random': function timed_update(){ obj.show_random(); } break;
      }
      
      obj.interval_id = setInterval(timed_update, this.opts.interval);  
      obj.status      = true;
    }
    
    this.stop_reproduction = function(){
      if(typeof obj.interval_id != 'undefined'){
        clearInterval(obj.interval_id);
        obj.status  = false;        
      }
    }
    
    this.toggle_reproduction = function(){
      if(obj.status){
        obj.stop_reproduction();
        $('#' + obj.opts.status_link_id).html(obj.opts.status_html_off);
      }else{
        obj.start_reproduction();
        $('#' + obj.opts.status_link_id).html(obj.opts.status_html_on);
      }
    }  

    // build from newstool
    if(typeof this.opts.source_id == 'string' && $('#' + this.opts.source_id).length > 0 && this.opts.news.length == 0){
    
      $('#' + opts.source_id).children().each(function(){
        var title = $(this).children('.newsTool_newsLink');
        var description = $(this).children('.newsTool_newsIntroduction');
        var pubdate = $(this).children('.js_pubdate');      
        
        if(!title.length || !description.length){
          return false;
        }
        
        var title = $($(this).children('.newsTool_newsLink').get(0));
        var description = $($(this).children('.newsTool_newsIntroduction').get(0));
        var pubdate = $($(this).children('.newsTool_newsPubDate').get(0));  
        var link = undefined;
        
        // gets url from selected anchor
        if(title.get(0).tagName == 'A'){
          link = title.attr('href');
        }

        obj.opts.news.push({ title: title.html(), description: description.html(), pubdate: undefined, link: link});
        
        // adds a reference class to the element
        $(this).addClass('js_' + obj.opts.source_id + '_item_' + (obj.opts.news.length - 1));  

        $(this).hide();
        
        return true;
      });
      
      obj.show(Math.floor(obj.opts.news.length*Math.random()));
    }    
    */
    
    if(obj.opts.autoInit) obj.init();
  }
  
  // extends jquery
  $.extend({
    scroller: function(opts){
      var _Scroller = new Scroller(opts);
    }
  });
});
