(function($){
  
  $.fn.goodTicker = function(options){
    var o = $.extend($.fn.goodTicker.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="good-ui_ticker"></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};
        }
        
        // if we are in msie we need to remove opacity from the options
        if($.browser.msie && typeof o.background.opacity != 'undefined'){
    		delete o.background.opacity;
    	}
        
        o.background = $.extend(o.background||{}, {
    		'position': 'absolute',
    		height: _this.height(),
    		width: _this.width()
    	});
        
        $('<div class="good-ui_ticker-background"></div>').css(o.background).prependTo(ticker.parent());
        
        if(typeof o.title == 'string'){
        	$('<div class="good-ui_ticker-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="good-ui_ticker-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="good-ui_ticker-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="good-ui_ticker-current-item">'+(_tickerIndex+1)+'</span> / <span class="good-ui_ticker-total-items">'+$('item', _feed).length+'</span>&nbsp;').appendTo(_navigation);
          
          var next = $('<a class="good-ui_ticker-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 = $('.good-ui_ticker-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 = $('.good-ui_ticker-item', _this);
      var nxtDomItem = $('<div class="good-ui_ticker-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);
      }

      //$('.good-ui_ticker-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.goodTicker.def = {
    feed: '/text/news.xml',
    item: {'element': '<span></span>', css: {}},
    title: 'Good Press Releases:',
    startItem: 1,
    repeat: true,
    background: '#ffffff',
    speed: 10000,
    navigation: false
  };
  
})(jQuery);