/*
 * THIS IS FREE SCRIPT BUT LEAVE THIS COMMENT IF
 * YOU WANT USE THIS CODE ON YOUR SITE
 * 
 * Made by Wilq32, wilq32@gmail.com, Wroclaw, Poland, 01.2009
 * Adaptation author for Mootools : Cédric Pellevillain, contact@piksite.com, Paris, France, 02.2009 
 * 
 */
/*
Description:

This is an final product of a Wilq32.PhotoEffect Snippet. Actually you can
 use this simple and tiny script to get effect of rotated images directly 
 from client side (for ex. user generated content), and animate them using
 own functions. 


Notices:

Include script after including main Mootools.
If you want to get this work in Internet Explorer you will need to 
include ExCanvas also.

Usage:

$(imgElement).rotate(angleValue)
$(imgElement).rotate(parameters)
$(imgElement).rotateAnimation(parameters)
$(imgElement).rotateAnimation(parameters)

Parameters:

    ({angle:angleValue,
     [animateAngle:animateAngleValue],
     [maxAngle:maxAngleValue],
     [minAngle:minAngleValue],
     [callback:callbackFunction],
     [bind:[{event: function},{event:function} ] })
$(imgElement).rotateAnimation

Where:

- angleValue - clockwise rotation given in degrees,
- [animateAngleValue] - optional parameter, animate rotating into this value,
- [maxAngleValue] - optional parameter, maximum angle possible for animation,
- [minAngleValue] - optional parameter, minimum angle possible for animation,
- [callbackFunction] - optional function to run after animation is done
- [bind: [ {event: function}...] -optional parameter, list of events binded
  to newly created rotateable object

Examples:

    document.addEvent('domready', function () {
			$('image').rotate(-25);			
		});

    document.addEvent('domready', function () {
			$('image2').rotate({angle:5});	
		});

    document.addEvent('domready', function () {
      var rot = $('image3').rotate({maxAngle:180, minAngle:-180,
    			bind:
    				[
    					{"mouseover":function(){rot.rotateAnimation(180);}},
    					{"mouseout":function(){rot.rotateAnimation(-180);}}
    				]
    	});
		});
*/

var termine=false;
//var listaImgs=['imagen1','imagen2','imagen3','imagen4'];

var indiceImg=0;

Element.implement({

ImageRotate:function(parameters) {	
	if (!this.Wilq32) this.Wilq32 = {}
	if (this.Wilq32.PhotoEffect) {
		return;
	}
	this.Wilq32.PhotoEffect = new Wilq32.PhotoEffect(this,parameters);
	
},

rotate:function(parameters) {  

	if ($type(parameters) == false) return;
	
	if ($type(parameters) == 'number') parameters = {angle:parameters};
	if (!this.Wilq32) {this.ImageRotate(parameters);//primer giro
	}
	else { this.Wilq32.PhotoEffect._rotate(parameters.angle);//nunca entra
	}
	return this;
},

rotateAnimation:function(parameters) {
	if ($type(parameters) == false) return;
	if ($type(parameters) == 'number') parameters = {angle:parameters};
	if (!this.Wilq32) this.ImageRotate(parameters);
	else {
		this.Wilq32.PhotoEffect._parameters.animateAngle = parameters.angle;
		this.Wilq32.PhotoEffect._parameters.callback = parameters.callback || function(){};		
		this.Wilq32.PhotoEffect._animateStart();
	}
	return this;
}

});

Wilq32 = {};

Wilq32.PhotoEffect = function(img,parameters) {
			this._IEfix = img;			      
			this._parameters = parameters;
			if (!parameters) this._parameters = {};
			this._angle=0;
			if (!parameters.angle) this._parameters.angle = 0;
			this._temp = new Element('span');
			//var image = img.src;
			
			/*------------------------------------*/
			
			//var image =  "../../images/rotate/"+listaImgs[indiceImg]+".png";
			//var image =  "images/rotate/"+listaImgs[indiceImg]+".png";
			var image =  listaImgs[indiceImg];
			/*--------------------------------------*/
			
			
			
			img.getParent().insertBefore(this._temp,img);//insercion del span 
			this._img = new Image();
			this._img.src = image;
			this._img._ref = this;
			//document.write('photo effect');
			
			//la imagen de fondo va a ser la siguiente imagen a la actual
			this._img2 = new Image();
			//this._img2.src = "../../images/rotate/"+listaImgs[indiceImg+1]+".png";
			//this._img2.src = "images/rotate/"+listaImgs[indiceImg+1]+".png";
			
			if(indiceImg == listaImgs.length){
				this._img2.src = listaImgs[0];
			}else{
				this._img2.src = listaImgs[indiceImg+1];
			}	
			
			
			$(this._img).addEvent('load', function() {
				this._ref._Loader.call(this._ref);
			});
			this._Loader();	
}

Wilq32.PhotoEffect.prototype._Loader = function () {
	this._IEfix.parentNode.removeChild(this._IEfix);
	var width = this._img.width;
	var height = this._img.height;
	
	this._img._widthMax = this._img._heightMax = Math.sqrt((height)*(height) + (width) * (width));

	this._canvas = new Element('canvas');
	this._canvas._ref = this;
	this._canvas.height = width;
	this._canvas.width = height;

	this._canvas.setProperty('width',width);

	this._canvas.inject(this._temp);
	if (Browser.Engine.trident) {	
		// ExCanvas to make it work in IE
		this._canvas.id = "Wilq32.PhotoTemp";
		G_vmlCanvasManager.initElement(this._canvas);
		this._canvas = $('Wilq32.PhotoTemp');
		this._canvas.id = "";							
		this._canvas._ref = this;
	}
	var self = this;
	this._parameters.animateAngle = 0;
	if (this._parameters.bind) {
		for (var a in this._parameters.bind) if (this._parameters.bind.hasOwnProperty(a)) 
		for (var b in this._parameters.bind[a]) if (this._parameters.bind[a].hasOwnProperty(b)) 
		this._canvas.addEvent(b,this._parameters.bind[a][b]);//agrega evento
	}
	this._cnv = this._canvas.getContext('2d');
	this._rotate(this._parameters.angle);
}

Wilq32.PhotoEffect.prototype._animateStart = function() {	
	if (this._timer) clearTimeout(this._timer);	
	this._animate();
}

Wilq32.PhotoEffect.prototype._animate = function() {	
  var temp = this._angle;
	if ($type(this._parameters.animateAngle) != false) this._angle -= (this._angle - this._parameters.animateAngle) * 0.1;
	if ($type(this._parameters.minAngle) != false) if (this._angle < this._parameters.minAngle) this._angle = this._parameters.minAngle;
	if ($type(this._parameters.maxAngle) != false) if (this._angle > this._parameters.maxAngle) this._angle = this._parameters.maxAngle; 

	if (Math.round(this._angle * 100 - temp * 100) == 0 && this._timer) {
		clearTimeout(this._timer);
		
		angle=0;
		document.getElementById("imagenes").innerHTML="";
		
		/*---------------------------------------
				Llamada a la siguiente imagen
		-----------------------------------------*/
		var myimg = new Image;
		//myimg.src = "../../images/rotate/"+ listaImgs[++indiceImg]+".png";
		//myimg.src = "images/rotate/"+ listaImgs[++indiceImg]+".png";
		
		myimg.src = listaImgs[indiceImg++];
		//alert(myimg.src);
		if(indiceImg==listaImgs.length-1){
			//alert('ultimo');
			indiceImg = 0; //resetea el indice
			document.getElementById('imagenes').style.padding='15px 0 0  0';
			document.getElementById('imagenes').innerHTML = "<img src='"+ listaImgs[0]+"'>";
		}else{
			var divImgs =document.getElementById("imagenes");
			divImgs.appendChild(myimg);
			var rot = $(myimg).rotate({maxAngle:180, minAngle:-180});
			rot.rotateAnimation(deg);		
			
			/*----------------------------------------------------------*/
			// function con el clic
			/*----------------------------------------------------------*/
			/*var rot = $(myimg).rotate({maxAngle:180, minAngle:-180,
  			bind:
  				[
  					{"click":function(){rot.rotateAnimation(180);}},
  					//{"mouseleave":function(){rot.rotateAnimation(-180);}}
  				] 
			}); */
			
			/*----------------------------------------------------------*/
		}
		
			
		/*--------------------------------------------------
		   fin un click
		---------------------------------------------------
		*/
		//alert('angle'+this._parameters.animateAngle);
			
		/*--------------------------------------------------*/
		if (this._parameters.callback) 
			this._parameters.callback();
	}	else {
		this._rotate(this._angle);
		var self = this;
		
		
		
		this._timer = setTimeout(function()	{
			self._animate.call(self);
		}, 25);
	}
}

Wilq32.PhotoEffect.prototype._rotate = function(angle) {
	if (!this._img.width) return;
	if ($type(angle) != 'number') return;
	angle =( angle%360)* Math.PI / 180;
	var width = this._img.width;
	var height = this._img.height;
	var widthAdd = this._img._widthMax - width;
	var heightAdd = this._img._heightMax - height;
	// clear canvas	
	this._canvas.width = width + widthAdd;
	this._canvas.height = height + heightAdd;

	//this._cnv.scale(0.8,0.8); // SCALE - if needed ;)
	
	// REMEMBER: all drawings are read from backwards.. so first function is translate, then rotate, then translate, translate..
	this._cnv.save();
	/*this._cnv.translate(widthAdd/2,heightAdd/2); // at least center image on screen
	this._cnv.translate(width/2,height/2);		  // we move image back to its orginal 
	*/
	//alert(angle);
	//if(this._parameters.angle <=-3.14){
	if(angle ==-3.1407452981751547){
		termine=true;
		
		//document.getElementById('log').innerHTML+="<br><br>"+angle;
		//return true;
		//this._cnv.drawImage(this._img, 0, 0); //imagen de fondo
		
	}else{
		this._cnv.drawImage(this._img2, 0, 15); //imagen de fondo			
		//termine=false;
	}
	
	this._cnv.translate(57,35);
	
	//this._cnv.save();
	this._cnv.rotate(angle);					  // rotate image
	//this._cnv.translate(-width/2,-height/2);	  // move image to its center, so we can rotate around its center
	//this._cnv.drawImage(this._img, 0, 0);		  // First - we draw image
		
	this._cnv.drawImage(this._img, -56, -20);
	
	
	//this._cnv.translate(57,28); //agregado poner
	
	/*
	if(indiceImg > 0){	
		this._cnv.translate(0,0);
		this._cnv.translate(57,20);
		this._cnv.rotate(-3);
		var imgPrim = new Image;
		imgPrim.src = "../../images/rotate/"+listaImgs[indiceImg-1]+".png";
		
		this._cnv.drawImage(imgPrim,-57, -20); //imagen primera
		this._cnv.restore();
		//alert('');		
	}	*/
	
	
	this._cnv.restore();
	
}

