/*

jQuery Refons Plugin Alpha v0.1  
Slide and Resize Site Background Images

27/10/2010 By dani ( a t ) erigin.com

Released under WTFPL

About WTFPL : 
http://http://sam.zoy.org/wtfpl/COPYING
http://es.wikipedia.org/wiki/WTFPL

" becouse freedom means no restrictions

-------------------------------------------------------------------------------------------------

TODO : 

	IMPORTANT : Clean and well organize tho code

*/

(function($){
	
	function log(msg)
	{
		console.log(msg);
	}
	
	//--------------------------------------------------------------------------------
	$.fn.Refons = function(options)
	{
		
		var refons_timer = null; //el temporitzador de l'slide
		
		//---------------------------------------------------
		//-----------------------
		//opcions i variables per defecte
		var defaults = {
			transition: 1,
			slider:true,
			centrat:true,
			speed:'slow',
			delay:'5000',
			elements:null,
			n_elements:0,
			resize:'stretch', // stretch | fit | none
			concurrent_fades:true, // true: means fadein nex image without waiting complete fadeout of current visible one
			backward:false,	       // from last to first
			index:0,
			wratio:0,
			btnext:null,
			btprev:null,
			links_buttons_array : []	//array of buttons, elements must have different ID
			
		}
		//-----------------------
		var opts = $.extend(defaults,options);
		var $this = this;
		
		//-----------------------------------------------------------
		//mètodes privats
		//actualitza el ratio de la finestra
		var WRatio = function()
		{
			opts.wratio = $(window).width() / $(window).height();
		}
		
		//dóna el ratio d'un element
		var ERatio = function(qe)
		{
// 			console.log( qe.attr('src') + ' w:' + qe.width() + ' h:' + qe.height() );
			return (qe.width()/qe.height());
		}
		
		//reamida la imatge passada com a jqelement
		var Reamida = function(qe)
		{
			switch(opts.resize)
			{
				case 'none':
				default:
					console.log('No reamidem');
					break;
				case 'stretch':
					//ratio de la imatge
					var qer = ERatio(qe);
					
					//si el ratio és més gran que el de la imatge fixem l'alt sió al revés
					var nw = 0;
					var nh = 0;
					var x = 0;
					var y = 0;
					if( qer > opts.wratio)
					{
						var escala = $(window).height() / qe.height();
						nh = $(window).height();
						nw = Math.floor(qe.width() * escala);
						
						//centro
						if(opts.centrat)
						{
							var dx = nw - $(window).width();
							x -= Math.floor(dx/2);
						}
						
						
					}else{
						var escala = $(window).width() / qe.width();
						nw = $(window).width();
						nh = Math.floor(qe.height() * escala);
						
						//centro
						if(opts.centrat)
						{
							var dy = nh - $(window).height();
							y -= Math.floor(dy/2);
						}
					}
					
					qe.width(nw);
					qe.height(nh);
					qe.css({
						top: y + 'px',
						left: x + 'px'
						});
					
					break;
					
				case 'fit':
					//ratio de la imatge
					var qer = ERatio(qe);
					
					//si el ratio és més petit que el de la imatge fixem l'alt sió al revés
					var nw = 0;
					var nh = 0;
					var x = $(window).scrollLeft();
					var y = $(window).scrollTop();
					if( qer < opts.wratio)
					{
						var escala = $(window).height() / qe.height();
						nh = $(window).height();
						nw = Math.floor(qe.width() * escala);
						
						//centro
						if(opts.centrat)
						{
							var dx = $(window).width() - nw ;
							x += Math.floor(dx/2);
						}
						
						
					}else{
						var escala = $(window).width() / qe.width();
						nw = $(window).width();
						nh = Math.floor(qe.height() * escala);
						
						//centro
						if(opts.centrat)
						{
							var dy = $(window).height() - nh;
							y += Math.floor(dy/2);
						}
					}
					
					qe.width(nw);
					qe.height(nh);
					qe.css({
						top: y + 'px',
						left: x + 'px'
						});
					
					break;
			
			}
		}
		
		//-----------------------------------------
		//inicialitza
		var Init = function()
		{
			if(opts.btnext)
			{
				opts.btnext.bind('click',$this.BtSeguent);
			}
			
			if(opts.btprev)
			{
				opts.btprev.bind('click',$this.BtAnterior);
			}
			
			//----------------------------------------------ç
			//bind window events
			$(window).bind('resize.Refons',function(){
								WRatio();
								Reamida($(opts.elements[opts.index]));
							});
							
			$(window).bind('scroll.Refons',function(){
								WRatio();
								Reamida($(opts.elements[opts.index]));
							});
							
// 			$('body').bind('scroll.Refons',function(e){
// // 								WRatio();
// // 								Reamida($(opts.elements[opts.index]));
// 								var qe = $(opts.elements[opts.index]);
// 								
// 								var ysof = qe.offset().top;
// 								var xsof = qe.offset().left;
// 								
// 								var dx = xsof - parseInt(qe.css('left'));
// 								var dy = ysof - parseInt(qe.css('top'));
// 								
// 								console.log(qe.css('left') + 'x' + qe.css('top') + ' ||| ' + xsof + 'x' + ysof + ' ||| ' + dx + 'x' + dy);
// 								
// 								qe.get(0).offsetTop = qe.css('top');
// 								
// // 								qe.offset({left:parseInt(qe.css('left')),top:parseInt(qe.css('top'))});
// 								
// // 								qe.css({
// // 										top: dy + 'px',
// // 										left: dx + 'px'
// // 									});
// 							});
							
			//bind button events ( overwrites default element actions )
			var n_buttons = opts.links_buttons_array.length;
			var max_i = 0;
			if( n_buttons <= opts.elements.length)
			{
				max_i = n_buttons;
			}else{
				max_i = opts.n_elements;
			}
			
			for(var k=0; k < max_i; k++)
			{
				var obj = opts.links_buttons_array[k];
				obj.bind('click',function(e){		
										e.preventDefault();
										clearInterval(refons_timer);
										//la jota no guarda l'esta en que es troba ara, es quedarà amb l'últim valor
										// jo ja m'entenc però per aixó he de fer aixó !!!	
										var j = 0;
										var n = opts.links_buttons_array.length;
										for(var i = 0 ; i < n; i++)
										{
											if( $(this).attr('id') == opts.links_buttons_array[i].attr('id') )
											{
												j = i;
												break;
											}
										}
										$this.Canvia(j);
									});
				//show button if it's hidden
				if(obj.css('display') == 'none')
				{
					obj.fadeIn(opts.speed);
				}
			}
			if(opts.slider && opts.n_elements > 1)
			{
				Slide();
			}else{
				$this.Mostra();
			}
		}
		
		//-----------------------------------------
		this.Seguent = function()
		{
			//i'l do this way becose I think i'ts faster
			if(opts.concurent_fades)
			{
				$(opts.elements[opts.index]).fadeOut(opts.speed);
				var i = opts.index+1;
				if( i == opts.n_elements)
				{
					opts.index = 0;
				}else{
					opts.index = i;
				}
				$this.Mostra();	
	
			}else{
				$(opts.elements[opts.index]).fadeOut(opts.speed,
								function()
								{
										var i = opts.index+1;
										if( i == opts.n_elements)
										{
											opts.index = 0;
										}else{
											opts.index = i;
										}
										
										$this.Mostra();	
								});
			}
		}
		
		//
		this.Anterior = function()
		{
			if(opts.concurent_fades)
			{
				$(opts.elements[opts.index]).fadeOut(opts.speed);
				var i = opts.index-1;
				if( i < 0 )
				{
					opts.index = opts.n_elements - 1;
				}else{
					opts.index = i;
				}
				$this.Mostra();	
	
			}else{
				$(opts.elements[opts.index]).fadeOut(opts.speed,
								function()
								{
										var i = opts.index-11;
										if( i <= 0 )
										{
											opts.index = opts.n_elements-1;
										}else{
											opts.index = i;
										}
										
										$this.Mostra();	
								});
			}
		}
		
		this.Canvia = function(i)
		{
			if(opts.concurent_fades)
			{
				$(opts.elements[opts.index]).fadeOut(opts.speed);
				opts.index = i;
				$this.Mostra('.refons_img_' + i);	
	
			}else{
				$(opts.elements[opts.index]).fadeOut(opts.speed,
								function()
								{
										opts.index = i;
										$this.Mostra('.refons_img_' + i);	
								});
			}
		}
		
		//--------------------------------------------------------------
		//buttons
		this.BtSeguent = function()
		{
			clearInterval(refons_timer);
			$this.Seguent();
		}
		
		this.BtAnterior = function()
		{
			clearInterval(refons_timer);
			$this.Anterior();
		}
		
		//------------------------------------------
		//slide starts
		var Slide = function()
		{
			if(opts.backward)
			{
				opts.index = opts.n_elements - 1;
				$this.Mostra();	
				refons_timer = setInterval(function(){
						$this.Anterior()
					},opts.delay);
			}else{
				$this.Mostra();	
				refons_timer = setInterval(function(){
						$this.Seguent()
					},opts.delay);
			}
		}
		
		
		
		//-----------------------------------------------------------
		//mètodes púplics
		this.Mostra = function(quin)
		{
			if(!quin)
			{
				Reamida($(opts.elements[opts.index]));
				$(opts.elements[opts.index]).fadeIn(opts.speed);
				
			}else{
				Reamida($(quin));
				$(quin).fadeIn(opts.speed);
			}
		}
		
		//------------------------------------------------------------
		// aquí arrenca tot
		return this.each(
				function()
				{
					opts.elements = $(this).children('img');
					opts.n_elements = opts.elements.length;
					//---------------------------------------
					//calculo el ratio de la finstra i li bindo l'event
					WRatio();
					//------------------------------------------
					$.each(opts.elements,function(key,value){
								$(value).addClass('refons_img_' + key);
							});
					//-------------------------
					
					//Crap thing about caching images
					//this was when i use document ready
					//$(opts.elements[opts.n_elements - 1]).one('load',Init);
					//but for cached images i use wondow load
					//this line was a trick to leave previos line uncomented and use document load
					//$(opts.elements[opts.n_elements - 1]).load();
					Init();
				}
			);
		//------------------------
		
		
		//------------------------------
		
	};
})(jQuery);
