// wrap in a function to be executed imediately pass in $ namespace
(function($) {
  Rotator = function(root, options) {
	
	this.public = {
	  root: $(root),
	  options: options,
	  items: [],
	  lastItem: -1
	};
	
	this.init();
  };
  Rotator.prototype = {
	init : function() {
	  var self = this;	
	  
	  $.ajax({
		url: self.public.options.url, 
		cache: self.public.options.cache,
		dataType: self.public.options.dataType,
		success: function(data, status) {
		  $('nodes > node', data).each(
			function(i) {
	 	 	  self.public.root.html('');				
				
			  switch (self.public.options.dataType) {	
			    case 'xml': {
				  self.public.items.push(
					{ 
					  id: $.trim($('id', this).text()),
					  heading: $.trim($('heading', this).text()),
					  text: $.trim($('text', this).text()),
					  image: $.trim($('image', this).text())
					}
				  );
				  break;
				}
				case 'json': {
				  self.public.items = data;
				  break;
				}
			  }
			}
		  );
		  self.loadItem();
		}
	  });
	},
	startItemLoad : function () {
	  var self = this;
	  setTimeout(function () { self.loadItem.call(self) }, self.public.options.delay * 1000);
	},
	loadItem : function () {
	  var self = this;
	  var node = self.getItem();
	  var id = 'rotator_' + node.id;
	  
	  self.format(node, id);
	  self.show(node, id);
	  self.startItemLoad();
	},
	format: function(node, id) {
	  var self = this;
	  var html = '';
	  
	  html += '<div id="' + id + '">';
	  html += node.heading.length ? node.heading : '';
	  html += node.image.length ? '<img src="' + node.image + '" />' : '';
	  html += node.text.length ? node.text : '';
	  html += '</div>';
	  
	  self.public.root.html(html);	  	
	},
	show: function(node, id) {
	  var self = this;
	  
	  $('#' + id).hide().fadeIn(self.public.options.speed);		
	},
	getItem : function () {
	  var self = this;
	  var l = self.public.items.length;
	  var j = 0;
	  
	  switch (self.public.options.sequence) {
		case 'random': {
		  
		  j = parseInt(Math.random() * l);
		  
		  while (self.public.lastItem == j && l > 1) {
			j = parseInt(Math.random() * l);
		  }

		  self.public.lastItem = j;			
		  return self.public.items[j];
		}
		case 'sequential': {
		  j = self.public.lastItem + 1 >= l || l == 1 ? 0 : self.public.lastItem + 1;			

		  self.public.lastItem = j;			
		  return self.public.items[j];
		}
	  }
	}
  };
	
  // methods to add to the jQuery namespace
  var methods = {
	Rotator : function(options) {

	  options = $.extend({
	    url: '',
		cache: false,	
		dataType: 'xml',
		speed: 'slow',
		delay: 3,
		sequence: 'sequential'
	  }, options || {});
		  
	  return this.each(function(i) {
		new Rotator(this, options);								
	  });
	}	
  };

  // add new private methods
  $.each(methods, function(i) {
	$.fn[i] = this;
  });
// pass jquery object in when executing
})(jQuery);
