/**
 *
 *
 *
 *
 *
 *
 * Effects: [http://jquery.malsup.com/cycle/]
**/
(function($) {

	var opts = new Array; //Options
	var idTime = 0; //ID Timer
	var wH = 0; //Window height
	var wW = 0; //Window width
	var img = new Array; //Images
	var zindex = -9999; //Z index
	var delay = 5000; //Delay timer
	var timeEffect = 1000; //Time effect
	var bgcolor = 'transparent'; //Background color
	var transition = 'fade'; //Transition type
	var wrapper; //Wrapper object
	
	
	$.fn.jqBackground = $.fn.jqbackground = function(options){
		
		init = function(el){
			opts = $.extend({}, $.fn.jqBackground.defaults, options);
			
			//DEFAULT PARAMETERS
			params = opts;
			if (typeof params.delay != 'undefined') { delay=parseInt(params.delay); }
			if (typeof params.timeEffect != 'undefined') { timeEffect=parseInt(params.timeEffect); }
			if (typeof params.zindex != 'undefined') { zindex=parseInt(params.zindex); }
			if (typeof params.bgcolor != 'undefined') { bgcolor=params.bgcolor; }
			if (typeof params.transition != 'undefined') { transition=params.transition; }
			
			//TRANSITIONS PARAMETERS
			$.jqbExec(transition,'setParams',params);
			
			//SET WRAPPER OBJECT
			wrapper=el;
			
			//CONFIGURE BODY/WINDOW
			$('body').css('overflow','hidden');
			
			//SET JQB CLASSES (LOADING)
			$(wrapper).addClass('jqb-wrapper')
				.addClass('jqb-loading')
				.css('z-index',zindex)
				.css('background-color',bgcolor);
			
			//INITIALIZE IMAGES
			$.jqbExec(transition,'initImages');
			
			//INITIALIZE TRANSITIONS
			$.jqbExec(transition,'initTransition');
			
			//RESIZE EVENT
			$.jqbExec(transition,'resizeBackground');
			$(window).resize(function(){
				$.jqbExec(transition,'resizeBackground');
			});
			
			//START
			if (img.length>0) {
				$.jqbNextBackground();
				idTime=setInterval('$.jqbNextBackground()', delay);
			}
		};
		
		$.jqbExec = function(t,f,v) {
			var evalFunc='$.jqbTransitions.'+t+'.'+f+'(v)';
			eval(evalFunc);
		};
		/*$.jqbGetParam = function(t,p) {
			var result=null;
			eval('result=$.jqbTransitions.'+t+'.params.'+p);
			return result;
		}*/
		
		$.jqbTransitions = {
			standard : {
				params : {},
				setParams : function(params) {},
				initImages : function() {
					$.each($('#'+wrapper.id+' img'), function(i,item){
						img[i] = {
							src:$(item).attr('src'),
							width:$(item).width(),
							height:$(item).height()
						};
						$(item).remove();
						
						var bimg = new Image();
						$(bimg).load(function(){
							$(this).css('display','none');
							$(wrapper).removeClass('jqb-loading').append(this);
							$(this).css('z-index',zindex)
								.addClass('jqb-item');
							$.jqbTransitions.standard.scaleBackground();
						}).error(function(){
							$(item).remove();
						}).attr('src', img[i].src);
					});
				},
				initTransition : function () {},
				resizeBackground : function () {
					wH=$(window).height();
					wW=$(window).width();
					$(wrapper).width(wW);
					$(wrapper).height(wH);
				},
				scaleBackground : function () {
					$('#'+wrapper.id+' img').each(function(){
						var bufferW=$(this).width();
						var bufferH=$(this).height();
						var difW=wW - bufferW;
						var difH=wH - bufferH;
						var ratioB=bufferH / bufferW;
						var ratioW=wH / wW;
						if (ratioB > ratioW) {
							bufferH=wW * bufferH /bufferW;
							bufferW=wW;
						}
						else {
							bufferW=bufferW * wH / bufferH;
							bufferH=wH;
						}
						$(this).css('width', bufferW+'px');
						$(this).css('height', bufferH+'px');
					});
				},
				nextBackground : function() {}
			},
			fade : {
				params : {},
				setParams : function(params) {},
				initImages : function () { $.jqbTransitions.standard.initImages(); },
				initTransition : function () {},
				resizeBackground : function () { $.jqbTransitions.standard.resizeBackground(); $.jqbTransitions.fade.scaleBackground(); },
				scaleBackground : function () { $.jqbTransitions.standard.scaleBackground(); },
				nextBackground : function() {
					var $list=$('#'+wrapper.id+' img.jqb-item');
					var total=$list.length;
					if (total>0) {
						var unactive=false;
						var active=false;
						var n=0;
						$list.each(function(){
							if (!unactive) {
								var isActive=$(this).hasClass('jqb-active');
								if (isActive) {
									unactive=true;
									$(this).removeClass('jqb-active').fadeOut(timeEffect);
								}
							}
							else {
								active=true;
								$(this).addClass('jqb-active').fadeIn(timeEffect);
								return false;
							}
							n++;
						});
						if ((unactive && !active) || (!unactive && !active)) {
							$list.each(function(){
								active=true;
								$(this).addClass('jqb-active').fadeIn(timeEffect);
								return false;
							});
						}
					}
				}
			},
			squares : {
				params : {
					spw : 7, //Horizontal squares
					sph : 5, //Vertical squares
					direction : 'random', //Direction transition
					sDelay : 50, //Squares delay
					order : new Array, //Ordres
					squarePos : 0, //Square position
					appInterval : 0 //ID App Interval
				},
				setParams : function(params) {
					if (typeof params.spw != 'undefined') { $.jqbTransitions.squares.params.spw=params.spw; }
					if (typeof params.sph != 'undefined') { $.jqbTransitions.squares.params.sph=params.sph; }
					if (typeof params.direction != 'undefined') { $.jqbTransitions.squares.params.direction=params.direction; }
					if (typeof params.sDelay != 'undefined') { $.jqbTransitions.squares.params.sDelay=params.sDelay; }
				},
				initImages : function (el) { $.jqbTransitions.standard.initImages(); },
				initTransition : function () {
					$('#'+wrapper.id+' img').each(function(){
						$.jqbTransitions.fade.scaleBackground(this);
					});
					spw=$.jqbTransitions.squares.params.spw;
					sph=$.jqbTransitions.squares.params.sph;
					tWidth = sWidth = parseInt(wW/spw);
					tHeight = sHeight = parseInt(wH/sph);
					counter = sLeft = sTop = 0;
					tgapx = gapx = wW - spw*sWidth;
					tgapy = gapy = wH - sph*sHeight;
					for (i=1;i <= sph;i++) {
						gapx = tgapx;
						if (gapy > 0) { gapy--; sHeight = tHeight+1; }
						else { sHeight = tHeight; }
						for (j=1; j <= spw; j++) {
							if (gapx > 0) { gapx--; sWidth = tWidth+1; }
							else { sWidth = tWidth; }
							$.jqbTransitions.squares.params.order[counter] = i+''+j;
							counter++;
							$('#'+wrapper.id).append(
								"<div class='jqb-square' id='jqb-"+i+j+"' style='width:"+sWidth+"px; height:"+sHeight+"px; float: left; position: absolute;left: "+sLeft+"px;top: "+sTop+"px;z-index:"+zindex+";'>"+
									+"<img src='' style='' border='0' />"
								+"</div>"
							);
							sLeft += sWidth;
						}
						sTop += sHeight;
						sLeft = 0;	
					}
				},
				resizeBackground : function () {
					$.jqbTransitions.standard.resizeBackground();
					$.jqbTransitions.squares.scaleBackground();
					spw=$.jqbTransitions.squares.params.spw;
					sph=$.jqbTransitions.squares.params.sph;
					tWidth = sWidth = parseInt(wW/spw);
					tHeight = sHeight = parseInt(wH/sph);
					counter = sLeft = sTop = 0;
					tgapx = gapx = wW - spw*sWidth;
					tgapy = gapy = wH - sph*sHeight;
					for (i=1;i <= sph;i++) {
						gapx = tgapx;
						if (gapy > 0) { gapy--; sHeight = tHeight+1; }
						else { sHeight = tHeight; }
						for (j=1; j <= spw; j++) {
							if (gapx > 0) { gapx--; sWidth = tWidth+1; }
							else { sWidth = tWidth; }
							$.jqbTransitions.squares.params.order[counter] = i+''+j;
							counter++;
							$('#jqb-'+i+j).width(sWidth).height(sHeight).css('left',sLeft+'px').css('top',sTop+'px').css('z-index',zindex);
							sLeft += sWidth;
						}
						sTop += sHeight;
						sLeft = 0;	
					}
				},
				scaleBackground : function () { $.jqbTransitions.standard.scaleBackground(); },
				nextBackground : function() {
					var $list=$('#'+wrapper.id+' img.jqb-item');
					var total=$list.length;
					if (total>0) {
						var unactive=false;
						var active=false;
						var n=0;
						$list.each(function(){
							if (!unactive) {
								var isActive=$(this).hasClass('jqb-active');
								if (isActive) {
									unactive=true;
									$(this).removeClass('jqb-active').fadeOut(0);
								}
							}
							else {
								active=true;
								$(this).addClass('jqb-active').fadeIn(0);
								return false;
							}
							n++;
						});
						if ((unactive && !active) || (!unactive && !active)) {
							$list.each(function(){
								active=true;
								$(this).addClass('jqb-active').fadeIn(0);
								return false;
							});
						}
					}
				}
			}
		};
		
		$.jqbNextBackground = function() {
			$.jqbExec(transition,'nextBackground');
		}
		
		$.effectBackground = function(el) {
			if(direction == 'random'){
				counter = 0;
				for(i=1;i <= sph;i++){
					for(j=1; j <= spw; j++){	
						order[counter] = i+''+j;
						counter++;
					}
				}	
				$.randomSquaresBackground(order);
			}
		}
		
		$.randomSquaresBackground = function(arr) {	
			var i = arr.length;
			if ( i == 0 ) return false;
			while ( --i ) {
				var j = Math.floor( Math.random() * ( i + 1 ) );
				var tempi = arr[i];
				var tempj = arr[j];
				arr[i] = tempj;
				arr[j] = tempi;
			}
		}
		
		$.appereanceSquaresBackground = function(el,sid){
			if (squarePos == spw*sph) {
				clearInterval(appInterval);
				return;
			}
			$('#cs-'+sid+' img').attr('src',el.src);
			$('#cs-'+sid).css({ opacity: 1 });
			$('#cs-'+sid).animate({ opacity: 0 }, 300);
			squarePos++;
		};
		
		$.unactiveBackground = function(el) {
			switch (transition) {
				case 'squares':
					$.effectBackground(el);
					squarePos = 0;
					appInterval = setInterval(function() { $.appereanceSquaresBackground(el,order[squarePos])  },sDelay);
				break;
				case 'fade':
				default:
					$(el).attr('active','false')
						.fadeOut(timeEffect);
				break;
			}
		}
		
		$.activeBackground = function(el) {
			switch (transition) {
				case 'squares':
					$(el).attr('active','true')
						.fadeIn(timeEffect);
				break;
				case 'fade':
				default:
					$(el).attr('active','true')
						.fadeIn(timeEffect);
				break;
			}
		}
		
		this.each (
			function(){ init(this); }
		);
	};
	
	// default values
	$.fn.jqBackground.defaults = {
		delay: 5000,
		timeEffect: 1000,
		zindex: -9999,
		bgcolor: 'transparent',
		transition: 'fade'
	};

})(jQuery);
