/*
 * Daniel Pennypackers Query based javascript banner
 * www.danielpennypacker.com
 *
 * Copyright (c) 2009 Daniel Pennypackers
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: 2009-06-01
 */


Pennypacker = {} 
Pennypacker.RotatingBanner = function(elementId, options) {
  this.init(elementId, options );
  var autoNext = function(){this.next_image()}
}

$.extend(Pennypacker.RotatingBanner.prototype, {
	ext: '.png',
	fadeSpeed: 500,
	changeFrequency: 2000,
	
	init: function(elementId, options) {
     //initialization
		this.container = $(elementId);
		if (!options) {   
			var options = []   
		}	

		//set the image file extension if you want, default .png		
	 	if (options['ext']) {	this.ext = options['ext']; 	}

		//speed at which an image fades in or out.
		if (options['fadeSpeed']) {	this.fadeSpeed = options['fadeSpeed']; }

		//set the frequency that the image changes
		if (options['changeFrequency']) { this.changeFrequency = options['changeFrequency']; }
				
		if (options['js_load_images']) {
			//To make this more modular, you can laod the images using JS, but you'll need to pass in 
			//additional paramaters. It's off by default.
			this.path = options['imagePath'];
			this.imageCount = options['imageCount'] ;
			this.load_images();						
		} else {
			this.imageCount = this.container.find('img').size();
		}		
		//
	 	this.show_image();	
   	},
	
   	load_images: function() {
		var max = this.imageCount
 		for( i=1;  i<= max; i++) {
			this.container.append('<img src="'+ this.path + '/' + i + this.ext +'">');
		}	
		
	},
	
	show_image:function(nthChild) {
		var firstTime = false
		if (!nthChild) {
			var nthChild = Math.floor(Math.random() * this.imageCount) + 1;
			this.selectedIndex = nthChild;
			firstTime = true
		}	
		
		this.container.find(' img.visibleBannerElement')
			.fadeOut(this.fadeSpeed, function(){$(this).removeClass('visibleBannerElement')} ) ;
		if (firstTime) {
			this.container.find(' img:nth-child(' + nthChild + ')').addClass('visibleBannerElement');
		} else {
			this.container.find(' img:nth-child(' + nthChild + ')')
				.fadeIn(this.fadeSpeed, function(){$(this).addClass('visibleBannerElement')} ) ;	
		}		
	},
	
	next_image:function(){
		
		if ( (this.selectedIndex + 1) > this.imageCount) {
			this.selectedIndex = 1;
		} else {
			this.selectedIndex = this.selectedIndex + 1
		}	
			
		this.show_image(this.selectedIndex);
	},
	
	start_auto_play:function(changeFrequency) {		
		 if (changeFrequency) {
			this.changeFrequency = changeFrequency;
		 }	
		
		 var _self = this
		 this.autoPlayer = setInterval(function(){ _self.next_image(); }, this.changeFrequency );		
	},	
	
	stop_auto_play:function() {	
		clearInterval(this.autoPlayer);
	}
});
