// -----------------------------------------------------------------------------------
// SliderImage
// -----------------------------------------------------------------------------------
// Objeto: SliderImage
// Comentario: Archivo Principal.
// Programado por Ivan Mattoni (Dic-2008)
// Version 1.0
// -----------------------------------------------------------------------------------

var SliderImage={
	init: {
		root: '', //Mandatory
		id: '',  //Mandatory
		
		frame: {
			images: [], //Mandatory
			links: [],
			path_images: '' //Mandatory
		},
		
		icon_width: 32,
		icon_height: 32		
	},
	
	configure: {
		automatic: true,
		duration_transition: 5,
		opacity_button: false
	},
		
	_images: [],
	_index: 0,
	_tempID: false,
	_error: 1,
	_page: 0,
	_countpage: 0,
	_indexImage: 0,
	objects: {},
	onload: Function(),
	
	start: function(status){
		if( !status ){
			// Verify Variables
			if( !this.verify_variables() ) return;
	
			// 	Verify Existence Images
			SliderImage.Ajax.XMLHttp = SliderImage.Ajax.create_instance_ajax();
			if( SliderImage.Ajax.XMLHttp ){
				SliderImage.Ajax.XMLHttp.onreadystatechange = function(){SliderImage.Ajax.changing_state_ajax();}
				SliderImage.Ajax.XMLHttp.open("POST", this.init.root+"/verifyimages.php", true);
				
				url = "pathimages="+this.init.frame.path_images+"&";
				url+= "images=";
				for( i in this.init.frame.images ){
					url+=this.init.frame.images[i]+"::";
				}
				url=url.substr(0,url.length-2);			
				SliderImage.Ajax.XMLHttp.send(url);
			}

		}else{
			if( this._error==1 ){
				alert("EL componente SliderImage no podra ser ejecutado porque existen errores.");
				return;
			}
			
			// Set style Main DIV
			div = this.$(this.init.id);
			div.style.position = "relative";
			div.style.overflow = "hidden";
			this.disabled_selection(div);


			var headID = document.getElementsByTagName("head")[0];
			if( !headID ) return;
			
			// Open CSS
			var cssNode = document.createElement('link');
				cssNode.type = 'text/css';
				cssNode.rel = 'stylesheet';
				cssNode.href = this.init.root+"/sliderimage.css";
				cssNode.title = "cssSliderImage";
				headID.appendChild(cssNode);
				this.objects.sheet = cssNode;
	
			// Button Left
			var frameLeft = document.createElement("DIV");
				frameLeft.className = "sliderimage_frameLeft";
				frameLeft.style.position = "absolute";
				frameLeft.style.width = (this.init.icon_width+5)+"px";
				frameLeft.style.height = parseInt(div.style.height)+"px";
				frameLeft.style.left = "0px";
				frameLeft.style.top = "0px";
				
			var imgButtonLeft = document.createElement("DIV");
				imgButtonLeft.className = "sliderimage_buttonLeft";
				imgButtonLeft.style.position = "absolute";
				imgButtonLeft.style.background = "url("+this.init.root+"/images/leftarrow.png) no-repeat";
				imgButtonLeft.style.width = this.init.icon_width+"px";
				imgButtonLeft.style.height = this.init.icon_height+"px";
				imgButtonLeft.style.left = ((parseInt(frameLeft.style.width)/2) - (this.init.icon_width/2))+"px";
				imgButtonLeft.style.top = ((parseInt(frameLeft.style.height)/2) - (this.init.icon_height/2))+"px";				
				if( this.configure.opacity_button ){
					imgButtonLeft.onmouseover = Function("javascript:SliderImage.set_opacity(this, 5)");
					imgButtonLeft.onmouseout = Function("javascript:SliderImage.set_opacity(this, 10)");
				}
				imgButtonLeft.onclick = Function("javascript:SliderImage.move_frame_back()");
				frameLeft.appendChild(imgButtonLeft);
				this.objects.frameLeft = frameLeft;
				this.objects.imgButtonLeft = imgButtonLeft;
	
	
			// Button Right
			var frameRight = document.createElement("DIV");
				frameRight.className = "sliderimage_frameRight";
				frameRight.style.position = "absolute";
				frameRight.style.width = (this.init.icon_width+5)+"px";
				frameRight.style.height = parseInt(div.style.height)+"px";
				frameRight.style.left = (parseInt(div.style.width)-parseInt(frameRight.style.width))+"px";
				frameRight.style.top = "0px";

			var imgButtonRight = document.createElement("DIV");
				imgButtonRight.className = "sliderimage_buttonRight";
				imgButtonRight.style.position = "absolute";
				imgButtonRight.style.background = "url("+this.init.root+"/images/rightarrow.png) no-repeat";
				imgButtonRight.style.width = this.init.icon_width+"px";
				imgButtonRight.style.height = this.init.icon_height+"px";
				imgButtonRight.style.left = ((parseInt(frameRight.style.width)/2) - (this.init.icon_width/2))+"px";
				imgButtonRight.style.top = ((parseInt(frameRight.style.height)/2) - (this.init.icon_height/2))+"px";
				if( this.configure.opacity_button ){
					imgButtonRight.onmouseover = Function("javascript:SliderImage.set_opacity(this, 5)");
					imgButtonRight.onmouseout = Function("javascript:SliderImage.set_opacity(this, 10)");
				}
				imgButtonRight.onclick = Function("javascript:SliderImage.move_frame_next()");
				frameRight.appendChild(imgButtonRight);
				this.objects.frameRight = frameRight;
				this.objects.imgButtonRight = imgButtonRight;


			// Slide Container
			var slide = document.createElement("DIV");
				slide.className = "sliderimage_slide";
				slide.style.position = "absolute";
				slide.style.left = parseInt(frameLeft.style.width)+"px";
				slide.style.top = "0px";
				slide.style.width = (parseInt(div.style.width)-parseInt(frameLeft.style.width)-parseInt(frameRight.style.width))+"px";
				slide.style.height = parseInt(div.style.height)+"px";
				slide.style.overflow = "hidden";
				this.objects.slide = slide;

			// Div Progress
			var divProgress = document.createElement("DIV");
				divProgress.style.position = "absolute";
				divProgress.style.width = "150px";
				divProgress.style.height = "80px";
				divProgress.style.left = (parseInt(slide.style.width)/2-(parseInt(divProgress.style.width)/2))+"px";
				divProgress.style.top = (parseInt(slide.style.height)/2-(parseInt(divProgress.style.height)/2))+"px";
				divProgress.style.overflow = "hidden";
//				divProgress.style.backgroundColor = "#cccccc";
				divProgress.style.zIndex = "20";
				divProgress.innerHTML = '<table width="100%"><tr><td align="center"><img src="'+this.init.root+'/images/progress.gif" /></td></tr><tr><td align="center"><span style="font-family:Arial;font-size:12px;"><b>Loading</b></span></td></tr></table>';	
				this.objects.divProgress = divProgress;	
				
			slide.appendChild(divProgress);
			
			// Append Buttons and Slide
			div.appendChild(frameLeft);
			div.appendChild(frameRight);
			div.appendChild(slide);
			
			SliderImage.upload_images();
		}
		
	},
	
	create_frames: function(){
		var slide = this.objects.slide;
		// Frame1
/*		width = parseInt(slide.style.width)/2;
		height = parseInt(slide.style.height)-60;*/

		// Estas son las medidas de los div
		width = 210;
		height = 180;
		// ***********************************
		
		var frame1 = document.createElement("DIV");
			frame1.style.position = "absolute";
			frame1.style.left = (width*-1)+"px";
			//frame1.style.top = (parseInt(slide.style.height)/2-(height/2)) + "px";
			frame1.style.top = "0px";
			frame1.style.width = width+"px";
			frame1.style.height = height+"px";
			frame1.style.zIndex = 2;
			MoveFrames.frame1.object = frame1;	
			slide.appendChild(frame1); // Append Frame	

		// Frame2
		width = parseInt(slide.style.width)/2-20;
		height = parseInt(slide.style.height)-120;
		var frame2 = document.createElement("DIV");
			frame2.style.position = "absolute";
			frame2.style.left = (width*-1)+"px";
			//frame2.style.top = (parseInt(slide.style.height)/2 - (height/2)) + "px";
			frame2.style.top = "45px";
			frame2.style.width = width+"px";
			frame2.style.height = height+"px";
			frame2.style.zIndex = 1;
			MoveFrames.frame2.object = frame2;	
			frame2.appendChild(this.get_shadow()); // Append Shadow
			slide.appendChild(frame2); // Append Frame
	
		// Frame3
		width = parseInt(slide.style.width)/2-20;
		height = parseInt(slide.style.height)-120;
		var frame3 = document.createElement("DIV");
			frame3.style.position = "absolute";
			frame3.style.left = (width*-1)+"px";
			//frame3.style.top = (parseInt(slide.style.height)/2 - (height/2)) + "px";
			frame3.style.top = "45px";
			frame3.style.width = width+"px";
			frame3.style.height = height+"px";
			frame3.style.zIndex = 0;
			MoveFrames.frame3.object = frame3;	
			frame3.appendChild(this.get_shadow()); // Append Shadow
			slide.appendChild(frame3); // Append Frame	
	},
	
	remove_images_frame: function(){
		for( var n=1; n<=3; n++ ){
			eval("frame=MoveFrames.frame"+n+".object;");
			
			frame = frame.getElementsByTagName("*");

			for(var i=frame.length-1; i>=0; i--){
				node = frame[i];				
				if( node!=null && (node.nodeName=="IMG" || node.nodeName=="CANVAS") ){
					p = node.parentNode;
					p.removeChild(node);
				}
			}
			
		}
	},

	move_frame_next: function(){
		if( MoveFrames.working ) return;	
		if( this._page < this._countpage ){
			MoveFrames.exit_right();
		}else{
			//if( this.configure.automatic ){
				this._page=0;
				this._indexImage=0;
				MoveFrames.exit_right();
			//}
		}
	},

	move_frame_back: function(){
		if( MoveFrames.working ) return;		
		if( this._page>1 ){
			this._indexImage-=6;
			MoveFrames.exit_left();
		}else{
			this._page=this._countpage+1;
			this._indexImage=(this._countpage-1)*3;
			MoveFrames.exit_left();	
		}
	},
	
	move_image: function(direction){		
		if( (direction=="next" && this._page < this._countpage) || (direction=="back" && this._page>1) ){
			this._page = (direction=='next') ? this._page+1 : this._page-1;

			this.remove_images_frame();
			
			for(var n=1; n<=3; n++)
			{
				this._indexImage++;
				index = this._indexImage-1;
					
				eval("frame = MoveFrames.frame"+n+".object");
				width  = parseInt(frame.style.width);
				height = parseInt(frame.style.height);
												
				this._images[index].style.width  = width+"px";
				this._images[index].style.height = height+"px";
				
				val1 = (!document.all) ? 0.2 : 0.45;
				val2 = (!document.all) ? 4 : 7;
				
				this.addReflection(this._images[index], frame, val1, val2);

				frame.appendChild(this._images[index]); // Add Image
								
				// Add Link
				if( index <= this.init.frame.links.length-1 ){
					link = this.init.frame.links[index];
					if( link!="" ){
						frame.style.cursor="pointer";
						frame.onclick = Function("SliderImage.OpenWindow('"+link+"')");
					}
				}								
			}
			
		}		
	},

	upload_images: function(){
		if( this._index <= this.init.frame.images.length-1 ){
			this._images[this._index] = new Image();
			this._images[this._index].src = this.init.frame.path_images+"/"+this.init.frame.images[this._index];
			this._tempID = setInterval("SliderImage.verify_complete_images()", 1);
		}else{
			this.start_slide();
		}
	},
	
	start_slide: function(){
		this.objects.divProgress.style.display="none";
		
		this.create_frames();
		this._countpage = this._images.length / 3;
		
		MoveFrames.go_left();
		if( this.configure.automatic ){
			t = (parseInt(this.configure.duration_transition) > 0 ) ? this.configure.duration_transition : 5;
			this._tempID = setInterval("SliderImage.move_frame_next()", t*1000);
		}
		
		this.onload();
	},
	
	verify_complete_images: function(){
		if( this._images[this._index].complete ){
			this._index++;
			clearInterval(this._tempID);
			this.upload_images();
		}		
	},

	verify_variables: function(){
		if( this.init.root=="" ){
			alert("La propiedad init.root es obligatoria.");
			return;
		}
		if( this.init.id=="" ){
			alert("La propiedad init.id es obligatoria.");
			return;
		}
		if( !this.$(this.init.id) ){
			alert("El objeto DIV no existe o el nombre del id esta mal escrito.");
			return;
		}
		if( this.init.frame.path_images=="" ){
			alert("La propiedad init.frame.path_images es obligatoria.");
			return;				
		}
		if( this.init.frame.images.length==0 ){
			alert("Debe ingresar como mínimo 3 imágenes.");
			return;				
		}
		if( this.init.frame.images.length%3 > 0 ){
			var i=0;
			var n=this.init.frame.images.length;
			do{
				i++;
				n++;
			}while( (n%3)>0 )
			
			if( i==1 ) msg="Falta una imágen para el funcionamiento del componente SliderImage.";	
			else       msg="Faltan dos imágenes para el funcionamiento del componente SliderImage.";
			
			alert(msg);
			return;
		}
		
		this._error=0;
		return true;
	},

	get_shadow: function(){
		var shadow = document.createElement("DIV");
			shadow.style.position = "absolute";
			shadow.style.left = "0px";
			shadow.style.top = "0px";
			shadow.style.width = "100%";
			shadow.style.height = "100%";
			shadow.style.backgroundColor = "black";
			this.set_opacity(shadow, 3);
		return shadow;		
	},

	Ajax: {	
		XMLHttp: false,
		create_instance_ajax: function(){
			this.XMLHttp=false;
			
			if( window.XMLHttpRequest ){
				return new XMLHttpRequest();
			}
			else if( window.ActiveXObject ){
				var versiones = ["Msxml2.XMLHTTP.7.0","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
				
				for(var i=0;i<versiones.length;i++){
					try {
						XMLHttp = new ActiveXObject(versiones[i]);
						if( XMLHttp ){
							return XMLHttp;
							break;
						}
					} catch(e){}
				}
			}
		},
	
		changing_state_ajax: function(id){
			if( SliderImage.Ajax.XMLHttp.readyState==1 ){
				try{
					SliderImage.Ajax.XMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				}
				catch(e){}
			}
					
			if( SliderImage.Ajax.XMLHttp.readyState==4 ){	
				if( SliderImage.Ajax.XMLHttp.status==200 ){
					resp=SliderImage.Ajax.XMLHttp.responseText;

					if( resp=="ok" ){
						SliderImage._error=0;
						SliderImage.start("allright");
						
					}else{
						alert("Las siguientes imágenes no han sido encontradas:\nCarpeta origen: "+SliderImage.init.frame.path_images+"\nArchivo(s):\n"+resp);
						return;
					}			
				}
				else{
					alert("Error al recibir respuesta "+SliderImage.Ajax.XMLHttp.statusText);
					return;
				}
			}
		}
	},

	addReflection: function(image, frame, height, opacity){
		var widthImage = parseInt(image.style.width);
		var heightImage = parseInt(image.style.height);
		var reflectionHeight = Math.floor(heightImage * height);
		var reflectionWidth = widthImage;
		
		if( document.all && !window.opera ){
			var reflection = document.createElement('img');
			reflection.style.position  ="absolute";
			reflection.style.top = heightImage+"px";
			reflection.style.left = "0px";
			reflection.style.height = heightImage+'px';
			reflection.style.width = widthImage+'px';
			reflection.height = heightImage;
			reflection.width = widthImage;
			reflection.src = image.src;


//			reflection.style.marginBottom = "-"+(heightImage - reflectionHeight)+'px';
			reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(height*45)+')';
			
			
			frame.appendChild(reflection);
		
		}else{		
			var canvas = document.createElement('canvas');
			if( canvas.getContext ){
				var context = canvas.getContext("2d");
				
				canvas.style.position = "absolute";
				canvas.style.top = heightImage+"px";
				canvas.style.left = "0px";
				canvas.style.height = reflectionHeight+"px";
				canvas.style.width = widthImage+'px';
				canvas.height = reflectionHeight;
				canvas.width = widthImage;
				
				frame.appendChild(canvas)				
						
				context.save();
				
				context.translate(0, heightImage-1);
				context.scale(1,-1);
				
				context.drawImage(image, 0, 0, reflectionWidth, heightImage);
	
				context.restore();
				
				context.globalCompositeOperation = "destination-out";
				var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
				
				opacity = opacity*0.1;
				
				gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gradient.addColorStop(0, "rgba(255, 255, 255, "+(1-opacity)+")");
	
				context.fillStyle = gradient;
				if (navigator.appVersion.indexOf('WebKit') != -1) {
					context.fill();
				} else {
					context.fillRect(0, 0, reflectionWidth, reflectionHeight*2);
				}
			}
		}
	},
	
	
	// Generic Functions
	$: function(id){
		return document.getElementById(id);	
	},

	disabled_selection: function(div){
		if( document.all ){
			div.onselectstart=new Function ("return false");
		}else{
			if( window.sidebar ) { 
			   div.onmousedown = function() {return false}
			   div.onclick = function() {return true}
			} 
		}				
	},
	
	set_opacity: function(o, val) {
		if( document.all ) {  //For IE
			val = parseInt(val)*10;
			try {
				o.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
			} catch (e) { 
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				o.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
			}
		} else {
			val = parseInt(val)*0.1;
			o.style.opacity = val;
			o.style.MozOpacity = val;  //This is for older Mozilla Browsers
		}
	},
	
	OpenWindow: function(link){
		width=screen.availWidth;
		height=screen.availHeight;
		
		if( link.indexOf("http://")==-1 ) link = "http://"+link;
		
		window.open(link,'', 'scrollbars=yes,width='+width+',height='+height+',left=0px,top=0px,resizable=1');
	}
		
}