(function($){
  
  $.fn.sageTicker = function(options){
    var o = $.extend($.fn.sageTicker.def, options||{});
    var _feed = 'wtf';
    var _timer;
    var _liveItem;
    var _tickerIndex = o.startItem-1||0;
    var _this;
    var _navigation;
    
    $.ajax({
      url:o.feed,
      type:"GET",
      dataType:"xml",
      async:false,
      success:function(xml) {
        //called when successful
        _feed = $(xml);
      },  
      error:function(resp) {
        //called when there is an error
        _feed = {};
      }
    });
    
    if(typeof _feed == 'object' && _feed.length > 0){
      this.each(function(){
        _this = $(this);
        var ticker = _this.wrap($('<div class="sage_news"></div>').css({
          position:'relative',
          overflow:'hidden',
          height:_this.height(),
          'z-index':10000
        }));
        
        //normailze background options as an object
        if(typeof o.background == 'string'){
        	o.background = {'background-color':o.background};
        }
        
        
        
        o.background = $.extend(o.background||{}, {
    		'position':'absolute',
    		height:_this.height(),
    		width:_this.width()
    	});
        
        $('<div class="sage_news-background"></div>').css(o.background).prependTo(ticker.parent());
        
        if(typeof o.title == 'string'){
        	$('<div class="sage_news-title">'+o.title+'</div>').css({
        		padding:'0 15px',
        		position:'absolute',
        		height:_this.height(),
        		'line-height':_this.height()+'px',
        		'vertical-align':'middle',
        		'font-weight':'bold'
        	}).appendTo(_this);
        }
        
        if(o.navigation == true){
         
          var _navigation = $('<div class="sage_news-navigation"></div>').css({
            height:35, 
            width:85,
            'padding-right':15,
            position:'absolute',
            right:0,
            top:0,
            'line-height':'35px',
            'text-align':'center',
            'font-size':'11px',
            'z-index':1000
          });
          
          
          var prev = $('<a class="sage_news-button-next" href="#">&lt;</a>').css({
            'margin-right':10,
            'font-weight':'bold',
            'text-decoration':'none',
            'vertical-align':'baseline'
            }).click(function(){
            tick(_tickerIndex-1, o.repeat);
            clearInterval(_timer);
            setTimeout(function(){
              _timer = setInterval(function(){tick(_tickerIndex+1, o.repeat||false); clearTimeout();}, o.speed||5000);
            }, o.speed||5000);
          }).appendTo(_navigation);
          
          var counter = $('&nbsp;<span class="sage_news-current-item">'+(_tickerIndex+1)+'</span> / <span class="sage_news-total-items">'+$('item', _feed).length+'</span>&nbsp;').appendTo(_navigation);
          
          var next = $('<a class="sage_news-button-next" href="#">&gt;</a>').css({
            'margin-left':10,
            'font-weight':'bold',
            'text-decoration':'none'
            }).click(function(){
            tick(_tickerIndex+1, o.repeat);
            clearInterval(_timer);
            setTimeout(function(){
              _timer = setInterval(function(){tick(_tickerIndex+1, o.repeat||false); clearTimeout();}, o.speed||5000);
            }, o.speed||5000);
          }).appendTo(_navigation);
          
          
          $('<div></div>').css({
            opacity:0.9, 
            height:'100%', 
            width:'100%', 
            position:'absolute', 
            top:0, 
            left:0,
            background:'#fff',
            'z-index':-1
          }).appendTo(_navigation);

          ticker.append(_navigation);
        }
        
        tick(0);
        _timer = setInterval(function(){tick(_tickerIndex+1, o.repeat||false);}, o.speed||5000);
        
      });
    }
    
    return this;
   
    
    function tick(targetIndex, repeat){
      var xmlItems = $('item', _feed);
      
      var $itemSizePosition = function(){
    	  var values = {
    		'width':_this.width()-15,
    		'left':15
    	  };
    	  
    	  var title = $('.sage_news-title', _this);
    	  if(title.length > 0){
    		  values.width = _this.width() - title.outerWidth();
    		  values.left = title.outerWidth();
    	  }
    	  
    	  return values;
      };
      
      var $animate = function(e){
    	  e.appendTo(_this).animate({
	          left:$itemSizePosition().left,
	          opacity:1
	      }, 2500, 'swing');
      }
      
      if(targetIndex >= xmlItems .length){
    	  targetIndex = 0;
      } else if(targetIndex < 0){
    	  targetIndex = xmlItems.length-1;
      }
    	
      var xmlItem = $('item', _feed).get(targetIndex);
      var link = $('<a></a>').attr({
          target:$('window', xmlItem).text(),
          href:$('link', xmlItem).text()
        }).text($('text', xmlItem).text()).css({
          'line-height':_this.outerHeight()+'px',
          position:'relative',
          'z-index':1000
        });
      
      var curDomItem = $('.sage_news-item', _this);
      var nxtDomItem = $('<div class="sage_news-item"></div>').css({
          position:'absolute', 
          left:_this.outerWidth()+1,
          height:_this.height(),
          width:$itemSizePosition().width, 
          'z-index':999,
          'overflow':'hidden'
        }).append(link);
      
      
      
      if(curDomItem.length > 0){
    	  curDomItem.fadeOut('slow', function(){
    		  $(this).remove();
    		  $animate(nxtDomItem);
    	  });
      } else {
    	  $animate(nxtDomItem);
      }

      //$('.sage_news-current-item', _navigation).text(targetIndex+1); 
      //_tickerIndex++;
      _tickerIndex = targetIndex;
/*
      if(_tickerIndex >= $('item', _feed).length){
        _tickerIndex = 0;
      } else if(_tickerIndex = 0){
    	  _tickerIndex = $('item', _feed).length-1;
      }*/
    };
    
 
  };
  
  $.fn.sageTicker.def = {
    feed:'/assets/news.xml',
    item:{'element':'<span></span>', css:{}},
    title:'News:',
    startItem:1,
    repeat:true,
    speed:6000,
    navigation:false
  };
  
})(jQuery);
