/*
 * 	 imBannerRotater - a JQuery Plugin
 * 	 @author Les Green
 * 	 Copyright (C) 2009 Intriguing Minds, Inc.
 *   
 *   Version 1.0 - 3 July 2010
 *   1. Added interval option to have images fade in and out simultaneously when in 'rotate' mode
 *   2. Urls can be supplied for every mode, not just random
 *   3. Added title attribute to image data_map (image_title)
 *   4. Added Banner Carousel
 *   5. Added Global url_target. Default: '_blank'
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */
 
;(function($) {
	$.fn.extend({
        imBannerRotater: function(options) { 
        	opts = $.extend({}, $.bannerRotater.defaults, options);
			return this.each(function() {
				new $.bannerRotater(this, opts);
			});
        }
    });	

$.bannerRotater = function(obj, opts) {
	var $this = $(obj);
	var imgCnt = 0;
	var ttlImg = 0;
	var nLeft = 0;
	var ttlWidth = 0;
	var aImages = [];
	if (opts.image_url) {
		var d = getDataString();
		doAjax('GET', opts.image_url, d, '', doCreate);
	} else {
		doCreate(opts.images);
	}
	
	function getDataString() {
		var str = '';
		$.each(opts.data, function(i, itm) {
			str += itm.name + "=" + itm.value + "&";							
		});
		//remove last "&"
		str = str.substr(0, (str.length-1));
		return str;
	};
		
	function doAjax(t, u, d, fnBefore, fnSuccess) {
		var dt = (opts.return_type == 'json') ? 'json' : 'text';
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: dt,
			beforeSend: fnBefore, //function(){$("#loading").show("fast");}, //show loading just when link is clicked
			//complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
			success: fnSuccess,
			error: showError
	 	}); //close $.ajax(
	};
	
	function showError(XMLHttpRequest, textStatus, errorThrown) {
		console.log(textStatus);
	};
	
	function doCreate(data) {
		//var tbl, tr;
		var img, pic, tgt, sel, url, desc, li;
		if (opts.return_type == 'list') {
			var daAR = data.split(',');
		} else {
			var daAR = new Array();
			$.each(data, function(i, itm) {
				//if (opts.mode == 'random') {
					if (opts.data_map.url_name) {
						desc = (opts.data_map.image_title) ? itm[opts.data_map.image_title] : itm[opts.data_map.image_name];
						tgt = (opts.data_map.url_target) ? itm[opts.data_map.url_target] : opts.url_target;
						daAR[i] = new Array(itm[opts.data_map.image_name], itm[opts.data_map.url_name], desc, tgt);
					} else {
						daAR[i] = itm[opts.data_map.image_name];
					}	
				//} else {
				//	daAR[i] = itm[opts.data_map.image_name];
				//}	
			});
		}
		if (opts.mode == 'random') {
			img = new Image();
			if (opts.data_map.url_name) {
				sel = daAR[Math.floor(Math.random()*daAR.length)];
				pic = opts.base_path + sel[0];
				url = sel[1];
				desc = sel[2];
				tgt = sel[3];
				$this.append($('<a></a>').attr({'href': url, 'target': tgt}).append($(img).attr({ src: pic, title: desc})));
			} else {
				pic = opts.base_path + daAR[Math.floor(Math.random()*daAR.length)];
				$this.append($(img).attr({ src: pic, title: pic}));
			}	
		} else if (opts.mode == 'rotate') {
			ttlImg = daAR.length;
			for (var i = 0; i < ttlImg; i++) {
				if (opts.data_map.url_name) {
					img = new Image();
					sel = daAR[i];
					pic = opts.base_path + sel[0];
					url = sel[1];
					desc = sel[2];
					tgt = sel[3];
					var a = $('<a></a>').attr({'href': url, 'target': tgt, 'id':'imBanner'+i}).css({'display': 'none', 'position': 'relative', 'zIndex': 1000 - (ttlImg + i)}).append($(img).attr({ src: pic, title: desc})).appendTo($this);
					aImages[i] = $(a).width();
					
				} else {
					img = new Image();
					pic = opts.base_path + daAR[i];
					$this.append($(img).attr({
						src: pic,
						title: daAR[i],
						'id': 'imBanner' + i
					}).css({'display': 'none', 'position': 'relative', 'zIndex': 1000 - (ttlImg + i)}));
					aImages[i] = $(img).width();
				}	
			}
			if (opts.interval) {
				setFadeInterval();	
			} else {
				imgFadeIn();
			}
		} else if (opts.mode == 'carousel') {
			var ul = $('<ul></ul>').appendTo($this);
			ttlImg = daAR.length;
			for (var i = 0; i < ttlImg; i++) {
				if (opts.data_map.url_name) {
					img = new Image();
					sel = daAR[i];
					pic = opts.base_path + sel[0];
					url = sel[1];
					desc = sel[2];
					tgt = sel[3];
					li = $('<li></li>').attr('id','imBanner'+i).append($('<a></a>').attr({'href': url, 'target': tgt}).append($(img).attr({ src: pic, title: desc}))).appendTo($(ul));
					aImages[i] = $(li).width() + parseInt($(li).css('marginLeft'));
				} else {
					img = new Image();
					pic = opts.base_path + daAR[i];
					$('<li></li>').attr('id','imBanner'+i).append($(img).attr({ src: pic, title: daAR[i]})).appendTo($(ul));
				}
			}
			/*var li = $('ul li', $this);
			li = $(li)[0];
			var mL = parseInt($(li).css('marginLeft'));
			var w = parseInt($(li).width());
			ttlWidth = w + mL;
			nLeft = ttlWidth;*/
			nLeft = aImages[0];
			setCarouselInterval();
		}
	};
	
	function setFadeInterval() {
		intervalFadeIn();
		setInterval(intervalFadeOut, opts.interval);
	};
	
	function intervalFadeIn() {
		$("#imBanner"+imgCnt).fadeIn(opts.speed, function(){
			$("#imBanner"+imgCnt).css('left', '0px');
		});
	};
	
	function intervalFadeOut() {
		$("#imBanner"+imgCnt).fadeOut(opts.speed);
		if (imgCnt == ttlImg - 1) {
			$("#imBanner"+imgCnt).css('left', -aImages[imgCnt]);
			imgCnt = 0;
		} else {
			imgCnt++;
		}
		//imgCnt = (imgCnt == ttlImg - 1) ? 0 : imgCnt + 1;
		if (imgCnt == 0) {
			$("#imBanner0").css('left', 0);
		}
		else {
			$("#imBanner" + imgCnt).css('left', -aImages[imgCnt]);
		}
		intervalFadeIn();
	};
	
	function imgFadeIn() {
		$("#imBanner"+imgCnt).fadeIn(opts.speed, function(){
			imgFadeOut();
		});
	};
	
	function imgFadeOut() {
		$("#imBanner"+imgCnt).fadeOut(opts.speed, function(){
			imgCnt = (imgCnt == ttlImg - 1) ? 0 : imgCnt + 1;
			imgFadeIn();
		});
	};
	
	function setCarouselInterval() {
		setInterval(imgCarousel, opts.interval);
	};
	
	function imgCarousel() {
		$('ul', $this).animate({left: -nLeft+'px'}, opts.speed, function() {
			var lPos = $('ul li:last', $this).offset();
			var thisPos = $this.offset();
			if ((lPos.left + $('ul li:last', $this).width()) < (thisPos.left + $this.width())) {
				imgCnt = 0;
				nLeft = 0;
			} else {
				imgCnt++;
				nLeft += aImages[imgCnt-1];
			}
		});
	};
};

$.bannerRotater.defaults = {
	mode: 'random',//rotate, carousel
	interval: '',//5000
	image_url: '',
	data: '',
	images: '',//can be used instead of image_url. contains comma delimited list of images
	return_type: 'list', //list, json
	base_path: '',
	url_target: '_blank',
	data_map: '', //{image_name: '', image_title: '', url_name: '', url_target: '_blank'}
	speed: 1500
};
})(jQuery);		   

