/***********************************************************
Scriptname: 	banner_fade.js
Dependencies: 	jquery.1.5.0
Version: 		1.0 live
Description:	Banner with fading action

Copyright: 		Webavance B.V. 2011
Legal: 			Any use of this script without Webavance B.V.
				express written consent is prohibited
************************************************************/

(function($){

	$.fn.banner_fade = function(c) {
		if (!c) c = {};
		var elm = $(this);
		var imgs = new Array();
		var tmr;
		var goslide=null;
		
		c = $.extend({
			playtime: 3,
			activetime: 7,
			fade: 1000,
			btnwidth: 0,
			align: 'center'
		}, c);
		
		var menu = $('<ul/>').appendTo(elm);
		
		elm.find('img').each(function(i,img) {
			imgs.push({
				src: $(img).attr('src'),
				href: $(img).attr('href')
			});
			$('<li/>').appendTo(menu);
		});
		elm.find('img').remove();
		
		switch(c.align) {
			case 'left':	menu.css({left:'10px'}); break;
			case 'center': 	menu.css({left: ((elm.width()/2)-((c.btnwidth*imgs.length)/2)) + 'px'}); break;
			case 'right': 	menu.css({right:'10px'}); break;
		}
		
		menu.find('li:eq(0)').addClass('active');
		menu.find('li').bind('click', function(e){
			if (tmr) clearTimeout(tmr);
			e.cancelBubble = false;
			
			goslide = $(this).prevAll().length;
			
			menu.find('li').removeClass('active');
			menu.find('li:eq(' + goslide + ')').addClass('active');
			
			pane.css({ backgroundImage: "url('" + imgs[goslide].src + "')",opacity: 1 }).attr({ rel: imgs[goslide].href });
			setTimeout(function(){ _rotate_banner(goslide); }, c.activetime*1000);
		});
		
		var pane = $('<div/>')
			.bind('click', function(e){ window.location.href = $(e.currentTarget).attr('rel'); })
			.css({ width: elm.width(), height: elm.height() })
			.appendTo(elm);
		
		_rotate_banner(0);
		
		function _rotate_banner(i) {
			if (tmr) clearTimeout(tmr);
			
			var next = (i+1<imgs.length) ? i+1 : 0 ;
			
			pane.css({ backgroundImage: "url('" + imgs[i].src + "')",opacity: 1 }).attr({ rel: imgs[i].href });
			elm.css({ backgroundImage: "url('" + imgs[next].src + "')" });
			
			tmr = setTimeout(function(){
				menu.find('li').removeClass('active');
				menu.find('li:eq(' + next + ')').addClass('active');
				
				pane.animate({
					opacity: 0
				}, c.fade, 'linear', function(){
					_rotate_banner(next);
				});
			}, c.playtime*1000);
		}
	}
	
})($);
