/** implemetaciones extras**/
new Asset.css('css/estilos_carrito.css');
new Asset.css('css/mooventana.css');
new Asset.css("css/formcheck.css");
var CargandoAjax= new Element('div',{
		id:'AjaxCargando',
		styles:{
			top:'250px',
			backgroundColor:'white',
			left :'250px',
			padding:'10px',
			border:'3px solid #FF8FBB',
			width:'80px',
			height:'15px',
			fontSize:'12px',
			color:'#FF8FBB',
			position:'relative',
			zIndex:500
		},
		html:'<b>Cargando...</b>'
	});

Element.implement({ 
    show: function() { 
      this.setStyle('display',''); 

    }, 
    hide: function() { 
      this.setStyle('display','none'); 
    },
	fadeTo: function(value){
		var elt = this; 
		 elt = new Fx.Tween(elt, {
			 duration : 500,
			 transition : Fx.Transitions.Quad.easeIn
		 }); 
		elt.start('opacity', value);
	}

}); 

Element.implement({
	Imprimir: function() {
		var strName = 'printer-' + (new Date()).getTime(),
		styles = $$('link[type=text/css]').clone(),
		title = document.title,
		that = this,
		iframe = new IFrame({
			name: strName,
			styles: {
				width: 1,
				height: 1,
				position: 'absolute',
				left: -9999
			},
			events: {
				load: function() {
					var doc = this.contentDocument || window.frames[strName].document;
					doc.title = title;
					$(doc.body).adopt(styles, that.clone());
					this.contentWindow.focus(); // IE requires us to focus before printing, or the parent prints.
					this.contentWindow.print();
				}
			}
		}).inject($(document.body));
		iframe.dispose.delay(15000); // Destroy the iframe in 15s so that it doesn't hang around.
	}
});


/****/

var Petnico= new Class({
	Implements:Options,
	options:{},
	ZOOM:"",
	tipOlvido:"",
	initialize:function(page){
		this.pagina=page
	},
	PNG:function(){
		if(Browser.Engine.trident4){
		 for(var i=0; i<document.images.length; i++)
			   {
				  var img = document.images[i]
				  var imgName = img.src.toUpperCase()
				  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
				  {
					 var imgID = (img.id) ? "id='" + img.id + "' " : ""
					 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
					 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
					 var imgStyle = "display:inline-block;" + img.style.cssText 
					 if (img.align == "left") imgStyle = "float:left;" + imgStyle
					 if (img.align == "right") imgStyle = "float:right;" + imgStyle
					 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
					 var strNewHTML = "<span " + imgID + imgClass + imgTitle
					 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
					 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
					 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
					 img.outerHTML = strNewHTML
					 i = i-1
				  }
			   }
		}
	},
	cargaCatalogo:function(tipo){
		if(tipo=="caballeros"){
			this.verCatalogoCaballeros();
		}else{
			this.verCatalogoDamas()
		}
	},
	cargarImagenes:function(tipo){
		new Request({
			url:"sec/imagenes.php?tipo="+tipo,
			evalScripts:true
		}).send();
	},
	cargarImagenesPagina:function(id){
		new Request({
			url:"sec/imagenes.php?page=si&id="+id,
			evalScripts:true
		}).send();
	},	
	verCatalogoCaballeros:function(){
		var m=0;
		if($('productos')){
			$('productos').set("tween",{
				onComplete:function(){
					m++;
					if(m==1){
						new Request.JSON({
							url:'galeria.php?tipo=caballeros',
							evalScripts:true,
							onSuccess:function(e){
								$('productos').set("html",e.imagenes).fade("in");
								$('paginacion_productos').set("html",e.paginas).fade("in");
								this.cargarImagenes("caballeros");
							}.bind(this)
						}).send();
					}
				}.bind(this)
			}).tween("opacity",[1,0]);
		}
	},		
	verCatalogoDamas:function(){
		var m=0;
		if($('productos')){
			$('productos').set("tween",{
				onComplete:function(){
					m++;
					if(m==1){
						new Request.JSON({
							url:'galeria.php?tipo=damas',
							evalScripts:true,
							evalResponse:true,
							onSuccess:function(e){
								$('productos').set("html",e.imagenes).fade("in");
								$('paginacion_productos').set("html",e.paginas).fade("in");
								this.cargarImagenes("damas");
							}.bind(this)
						}).send();
					}
				}.bind(this)
			}).tween("opacity",[1,0]);
		}
	},	
	verCaballeros:function(url){
		var m=0;
		$('productos').set("tween",{
				onComplete:function(){
					m++;
					if(m==1){
						new Request.JSON({
							url:url,
							onSuccess:function(e){
								$('productos').set("html",e.imagenes).fade("in");
								$('paginacion_productos').set("html",e.paginas).fade("in");
							}
						}).send();
					}
				}
		}).tween("opacity",[1,0]);
	},
	verDetalle:function(id,img,chica,zoom_chica,imggrande,tipo){
		this.cargarImagenesPagina(id);
	if($('detalles_de_producto')){
		var m=0;
		var i=0;
		$('detalles_de_producto')
			.set({
				"load":{
					onSuccess:function(){
						$('detalles_de_producto').tween("opacity",[0,1]);
					}
				},
				"tween":{
					duration:800,
					onComplete:function(){
						m++;
						if(m==1){
							$('detalles_de_producto').load("detalles.php?i="+id);
						}
					}
				}
			}).tween("opacity",[1,0]);
			
		$('foto_producto')
				.set("tween",{
					duration:800,
					onComplete:function(){
						i++;
						if(i==1){
							setTimeout(function(){
									$('foto_producto').getElement("img")
									.set({"src":"images/productos/"+imggrande});
									$('foto_producto').tween("opacity",[0,1]);
									$('zommerImg').set({"href":"images/productos/"+img});
									 jQuery('.cloud-zoom').CloudZoom();
									//this.ZOOM.generate();
							}.bind(this),2000)
							
							//.reflect({height:0.1,opacity:0.3})
							
							
						}
						
					}.bind(this)
		}).tween("opacity",[1,0]);
	
		$y=0;
		
		$('vista2_product')
		.set("tween",{
			duration:800,
			onComplete:function(){
				$y++;
				if($y==1){
					
				setTimeout(function(){
					$('vista2_product').fade("in");
					$('vista2_product').getElement("img").destroy();
				},2000);
						
						
						var nuevachica= new Element("img",{
							"src":"images/productos/"+chica,
							"border":0,
							"width":96,
							"height":133,
							"events" :{
								"click":function(){
									this.verZoomChica(zoom_chica,tipo);	
								}.bind(this)
							}
						});
						$('vista2_product').getElement("a").adopt(nuevachica);
				}
				
				
			}.bind(this)
		}).tween("opacity",[1,0]);
	}
	},
	verZoomChica:function(imagen,imggrande){
		var img= $('foto_producto').getElement("img")
		img.fade("out");
		setTimeout(function(){
			img.set({"src":"images/productos/"+imggrande});
			$('zommerImg').set({"href":"images/productos/"+imagen});
			img.fade("in");
			 jQuery('.cloud-zoom').CloudZoom();
			
		}.bind(this),800);
		$('vista2_product').getElement("img").
		removeEvent("click");
	},
	creaMenu:function(){
		if($('product_catalog')){
			new MenuEtnico({
				ancho:191,
				alto:100,
				separacion:0,
				fondo:"",
				estiloMenu:"menu_over",
				principal:'product_catalog',
				html:'<div style="float:left"><a href="catalog.php?t=damas">'+
						'<img border="0" onmouseover="this.src=\'images/img_ladies2.jpg\'" onmouseout="this.src=\'images/img_ladies.jpg\'" src="images/img_ladies.jpg" />'+
					 '</a></div>'+
					'<div style="float:right"><a href="catalog.php?t=caballeros">'+
					'<img border="0" onmouseover="this.src=\'images/img_men2.jpg\'" onmouseout="this.src=\'images/img_men.jpg\'" src="images/img_men.jpg"/>'+
					'</a></div>'
			});
			
			$('imgaShop')
			.addEvent("click",function(){
				window.location.href="catalog.php?t=damas";return false;
			});
			
		}
	},
	menuLogin:function(){
		
		if($('iniciasesion')){
			
			new MenuLogin({
				principal:"iniciasesion",
				evento:"click",
				imagenFondo:"images/bloq_login.png",
				ancho:317,
				alto:182,
				transicion:"back:out",
				duracion:1,
				html:'<div id="cont_login">'+
					  '<form autocomplete="off" name="form_login" id="form_login" action="petnico.php?controlador=sesion&accion=iniciaSesion" method="post">'+
						'<table width="100%" height="138" border="0">'+
						  '<tr>'+
							'<td width="32%"><span class="txt_j">Email :</span></td>'+
							'<td width="68%"><span id="sprytextfield1">'+
							  '<label>'+
								'<input class="validate[\'required\',\'email\'] text-input txt_input"  type="text" name="txtusuario" id="txtusuario" />'+
							  '</label>'+
							'<span class="textfieldRequiredMsg">*</span></span></td>'+
						  '</tr>'+
						  '<tr>'+
							'<td><span class="txt_j">Password :</span></td>'+
							'<td><span id="sprytextfield2">'+
							  '<label>'+
								'<input class="validate[\'required\'] text-input txt_input" type="password" name="txtpass" id="txtpass" />'+
							  '</label>'+
							'<span class="textfieldRequiredMsg">*</span></span></td>'+
						  '</tr>'+
						  '<tr>'+
							'<td>&nbsp;</td>'+
							'<td valign="middle"><label>'+
							  '<input align="absmiddle" type="image" src="images/b_send_login.jpg" name="send" id="send" value="Enviar" />'+
							  '<img align="absmiddle" id="carga_login" style="padding-left:8px;padding-right:5px;visibility:hidden" src="images/cargar_ajax.gif"/>'+
							  '<span id="respuestaLogin"></span>'+
							'</label></td>'+
						  '</tr>'+
						  '<tr>'+
							'<td>&nbsp;</td>'+
							'<td class="txt_index_a"><span id="ayuda_email" style="width:120px">Forgot your password?</span></td>'+
						  '</tr>'+
						  '<tr>'+
							'<td>&nbsp;</td>'+
							'<td class="txt_index_d">If you\'re a new user <a href="register.php" class="txt_index_a">register here</a>.</td>'+
						  '</tr>'+
						'</table>'+
					 '</form>'+
					  '</div>'
			});
			
			new FormCheck('form_login',{
				display : {
					errorsLocation : 0,	indicateErrors : 2,	showErrors : 1,	addClassErrorToField : 1,scrollToFirst:false
				},
				submitByAjax:true,
				onAjaxRequest:function(){
					$('carga_login').fade("in");
				},
				onAjaxSuccess:function(e){
					$('carga_login').fade("out");
					if(e==1){
						if(carrito.Totalproductos==0){
							document.location.href="catalog.php?t=damas";
							return false;
						}else{
							document.location.href="shoppingcart_1.php";
							return false;	
						}
					}else{
						$('respuestaLogin').set("html","Data Incorrect").fade("in");
					}
					
				},
				 onAjaxFailure:function(){
				  alert("errorr");
				}
			});
				
			
			
			this.tipOlvido=new Tooltips({
						div:"ayuda_email",
						ancho:385,
						alto:185,
						posicion:"centroArriba",
						bntCerrar:'<div style="font-family:verdana;font-size:12px;color:#7D4D25;padding-top:8px;padding-right:15px"><strong>X</strong></div>',
						fondo:"images/tooltip.png",
						html:'<div style="padding:20px;padding-top:0px;">'+
							 '<form autocomplete="off" id="form_recuerda" action="remember.php" method="post">'+
								 '<span class="mgs_ok">Just enter the e-mail address you used for registration, and we will send your login information to that address immediately.</span><br>'+
								 '<input style="width:270px" class="validate[\'required\',\'email\'] text-input txt_input" type="text" id="email_recordar" name="email_recordar">&nbsp;'+
								 '<input class="btn" type="submit" value="Send"><br>'+
								 '<img id="carga_recordar" style="padding-left:8px;visibility:hidden" src="images/cargar_ajax.gif"/>'+
								 '<div id="msg_recordar" class="mgs_ok"></div>'+
							 '</form>'+
							 '</div>',
						evento:"click",
						estiloInterior:"txt_l"
			});
			
			new FormCheck('form_recuerda',{
				display : {
					errorsLocation : 0,
					indicateErrors : 2,
					showErrors : 1,
					addClassErrorToField : 1,
					scrollToFirst:false
				},
				submitByAjax:true,
				onAjaxRequest:function(){
					$('carga_recordar').fade("in");
				},
				onAjaxSuccess:function(e){
					$('carga_recordar').fade("out");
					if(e=="god"){
						$('msg_recordar')
						.set("html","<b><span style='color:red'>Thanks your message has been sent successfully.</span></b>");
						$('form_recuerda').reset();
						setTimeout(function(){
							$('moo_tip__ayuda_email').fade("out");
							$('msg_recordar').set("html","");
						},2000)
					}else{
						$('msg_recordar')
						.set("html","<b><span style='color:red'>Sorry, but you are not registered on our website.</span></b>");
					}
					
					
				},
				 onAjaxFailure:function(){
				  alert("errorr");
				}
			});
		
		
			$('moo_tip__ayuda_email').addEvent("click",function(e){
				e.stopPropagation();
			}.bind(this))
			
			$$(document.body).addEvent("click",function(){
				if($('moo_tip__ayuda_email')){
					if($('moo_tip__ayuda_email').getStyle("visibility")=="visible"){
						$('moo_tip__ayuda_email').fade("out");
					}
				}
			});	
			
		
		}
	},
	creaZoom:function(){
		if($('foto_producto')){		
			/*this.ZOOM =new AZoom("aZoom",{
					capaZoom:"bloq_zoom",
					mas:"zoom_mas",
					menos:"zoom_menos",
					anchoImagen:287,
					altoImagen:423,
					limita:"si"
			});
			*/
			this.ZOOM = new ImageZoom();
			
			$('foto_producto').addEvents({
				"mouseenter":function(){
					$('zoomer_region').fadeTo(0.5);
				},
				"mouseleave":function(){
					$('zoomer_region').fadeTo(0);
				}
			});
		
		}
	},
	discount:function(){
		 new Ventana({
			titulo:"",
			url: "register_discount.php",
			modal:true,
			fondo:"",
			alto:476,
			ancho:622,
			borde:0,
			separacion:0,
			btnCerrar:"cerrar_form_factory"
		}).render();
	},
	procesos:function(){
		if($('n_processes')){
			//el shadowbox
			Shadowbox.init({
				overlayColor : '#996600',
				overlayOpacity:	0.3,
				counterType:'skip'
			});
			$$('#n_processes img')
			.addEvents({
				"mouseenter":function(){
					this.tween("opacity",[1,0.6]);
					setTimeout(function(){
						this.tween("opacity",[0.6,1]);				
					}.bind(this),500)
				}
			}).setStyle("cursor","pointer")
			.each(function(k){
				new Asset.image(k.getParent().get("href"));
			})				
			
		}
	},
	activaRegistrar:function(){
		if($('form_envio_registro')){
			$('formu_register').getElements('input[type=text]').addClass("txt_input_registro");
				$('form_envio_registro').set("send",{
					onSuccess:function(e){
						if(e==1){
							$('msg_registro_ajax')
							.set("html","<br><span class='txt_index_c' style='color:red'><b>Thanks for signing up, please check your inbox to see access your data to the web.</b></span>")
							.fade("in");
							
							new Request({
								url:"petnico.php?controlador=sesion&accion=iniciaSesion",
								onSuccess:function(){
									
								if($('total_items').get("html")=="0"){
										document.location.href="catalog.php?t=damas";
										return false;
									}else{
										document.location.href="shoppingcart_1.php";
										return false;	
									}
									
								}
							}).send("txtusuario="+$('email').get("value")+"&txtpass="+$('repeat_password').get("value"));
							
						}else{
							$('msg_registro_ajax')
							.set("html","<br><span class='txt_index_c' style='color:red'><b>The email entered already exists, please enter a different email.</b></span>")
							.fade("in");
						}
					}
				})
				.addEvent("submit",function(ev){
					ev.preventDefault();
					var ret = Spry.Widget.Form.validate($('form_envio_registro'));
					if(ret){
						this.send();
					}
					
				});
		}
	},
	GaleriaOurStore:function(){
		if($('caja_our_store')){
			Shadowbox.init({
				overlayColor : '#996600',
				overlayOpacity:	0.3,
				continuous:true,
				counterType:'skip'
			});
		}	
	},
	responsabilidadSocial:function(){
		if($('galeria_proy1')){
			Shadowbox.init({
				overlayColor : '#996600',
				overlayOpacity:	0.3,
				continuous:true,
				counterType:'skip'
			});
		}	
	},
	enviaContacto:function(){
		if($('form_envio_contact')){
			new Contador({a:"mensaje",maximo:400,mensajeEn:"contador_contacto"});
			$('form_envio_contact')
			.set("send",{
				onSuccess:function(){
					$('form_envio_contact').reset();
					new Ventana({
							titulo:"",
							url: "thankyou_contactus.php",
							modal:true,
							fondo:"",
							alto:174,
							ancho:478,
							borde:0,
							separacion:0,
							btnCerrar:"cerrar_5"
					}).render();
				setTimeout(function(){
					window.location.href='index.php';
					return false;
				},3000)
				}
			})
			.addEvent("submit",function(e){
				e.preventDefault();
				var ret = Spry.Widget.Form.validate($('form_envio_contact'));
					if(ret){
						this.send();
					}
			});
			
		}
		
	},
	formularioIndustrial:function(){
			new Ventana({
				titulo:"",
				url: "pop_up_industrial.php",
				modal:true,
				fondo:"",
				alto:446,
				ancho:461,
				borde:0,
				separacion:0,
				btnCerrar:"closed6"
			}).render();

	},
	verDetalleCompra:function(i){
		new Ventana({
				titulo:"",
				url: "_detallePedido.php?id="+i,
				modal:true,
				fondo:"",
				alto:750,
				ancho:705,
				borde:0,
				separacion:0,
				btnCerrar:"cerrar_detalle"
		}).render();
	},
	carruselVisitas	:function(){
		
		if($('carrusel_visitas')){
			$('carrusel_visitas').getElements("img").setStyle("border","1px solid white");
			new ACarrusel("carrusel_visitas",{
					avanze:2,
					ver:5,
					duracion:1,
					/*anchoItem:56,
					altoItem:56,
					*/
					transicion:"sine:out",
					anterior:"flecha_before",
					siguiente:"flecha_next"
				});
		}
	},
		
	recordarPass:function(){
		var RP= new Ventana({
					titulo:"Ethnic Peru.com  -  Recordar Contrase&ntilde;a",
					modal:true,
					ancho:461,
					alto:180,
					url:"recordar.php"
				});
		RP.render();
	},
	Enviamail:function(i){
		$('msgrecordar').removeClass("estado_ok");
		$('msgrecordar').removeClass("estado_mal");
		$('msgrecordar').removeClass("estado_cargando");
		$('msgrecordar').addClass("estado_cargando").set("html","Enviando y comprobando...").show();
		var rcAjax= new Request({
			url:"petnico.php?controlador=sesion&accion=validarEmail",
			data:{email_recordar:i},
			onSuccess:function(e){
				if(e=="ok"){
					$('msgrecordar').removeClass("estado_cargando");
					$('msgrecordar').addClass("estado_ok").set("html","Se acaba de enviar tu contrase&ntilde;a a el email indicado").show();
				}else{
					$('msgrecordar').removeClass("estado_cargando");
					$('msgrecordar').addClass("estado_mal").set("html","Error al parecer tu email no se encuentra registrado").show();
				}
			}.bind(this)
		});
		rcAjax.send();
	},
	msgSesion:function(){
		$menu= new Element('div',{
					id:'capa___sessionn',
					styles:{
						height:'150px',
						width :'250px',
						backgroundColor:'white',
						zIndex:1500,
						top:'145px',
						left:'570px',
						position:'absolute',
						border:'3px solid #957B63',
						padding:'5px'
					},
					html:'<div align="right"><span style="cursor:pointer" class="txt_f" onclick="$(\'capa___sessionn\').destroy()">Close</span></div>'+
							'<div><span class="txt_f">For you can buy please Log In</span></div>'+
							'<div id="cont____sesion"></div>'
			   });
		
		$('base').grab($menu);
		$('cont____sesion').load("sistema/aplicacion/vistas/sesion/form_sesion.php");
	},
	
	modalSesion:function(){
		var sesion= new Ventana({
			titulo :"",
			url:'pop_register.php',
			modal:true,
			alto:230,
			ancho: 627,
			borde:0,
			separacion:0,
			btnCerrar:"cerrar_registr4o_nuevo"
		});
		sesion.render();
	}
	
	
});

var Carrito= new Class({
	Totalproductos:0,
	initialize:function(page){
		this.seccion=page
	},
	total:function(){
		window.addEvent("domready",function(){
			if($('total_items')){
			var agregaAjax = new Request.JSON({
						url:"petnico.php?controlador=carrito&accion=totalItems",
						onComplete:function(e){
									$('total_items').set("text",e.cantidad);
									this.Totalproductos=e.cantidad;
									$('precio_total_carrito').set("text",e.total_carrito);							
						}.bind(this)
			}).get();

		}
		});
		
	},
	agregar:function(iditem){
		var nombre=$('nombre_'+iditem).get('text');
		var talla=$('talla_'+iditem).get('value');
		var precio=$('precio_'+iditem).get('text');
		var cantidad=$('cantidad_'+iditem).get('value');
		var color=$('color_'+iditem).get('value');
		var imagen=$('imagen_'+iditem).get('value');
		
		
		
		/*
		
		var capa_carrito = new Element('div',{
			id:'div__carrito',
			styles:{
				//padding:'10px',
				height:'180px',
				width:'220px',
				position:'relative',
				zIndex:500,
				left:'0px',
				top:'25px',
				border : '0px solid #F18AB2'
			},
			html:'<div style="position:absolute;width:196px;height:200px;">'+
					'<div style="position:absolute;left:19px;top:33px;width:158px;height:80px;z-index:1;">'+
					'<table width="100%" border="0">'+
						'<tr>'+
							'<td rowspan="2">'+
								'<img src="'+imagen+'" width="63" height="92" alt="" id="img_carrito" />'+
							'</td>'+
							'<td class="txt_n"><span id="nombre_carrito">'+nombre+'</span><br /></td>'+
						'</tr>'+
						'<tr>'+
							'<td align="right"><span id="precio_carrito" class="txt_o">$'+precio+'</span></td>'+
						'</tr>'+
					'</table>'+
					'</div>'+
					'<img src="images/caja_product_added.png" width="196" height="154" alt="Product Added" />'+
				  '</div>'
		});
		
			if(!$('div__carrito')){
				capa_carrito.setStyle("left",165);
				$('sub_menu').grab(capa_carrito);
			}else{
				$('img_carrito').set("src",imagen);
				$('precio_carrito').set("html","$"+precio);
				$('nombre_carrito').set("html",nombre);
			}
		
			var scrollcarrito = new Fx.Scroll(window, {
				wait: false,
				duration: 1200,
				offset: {'x': -200, 'y': -50},
				transition:  Fx.Transitions.Sine.easeInOut
			});
			scrollcarrito.toElement('sub_menu');
			var capa_desliza = new Fx.Slide('div__carrito',{wait:false,duration:1000}).hide();
				capa_desliza.slideIn();
			var capa_oculta	= new Fx.Slide('div__carrito',{
										   wait:false,
										   transition: Fx.Transitions.Back.easeInOut,
										   duration:1000,
										   onComplete:function(){
												//$('div__carrito').destroy();		
												
										   } 
							});
			
			setTimeout(function(){
							capa_oculta.slideOut();
			},3000);
		
		
		
			*/
		
		
		
			var agregaAjax = new Request.JSON({
					url:"petnico.php?controlador=carrito&accion=agregar",
					data :{
						id_producto:iditem+'_'+talla+'_'+color,
						iditem:	iditem,
						cantidad:cantidad,
						nombre_producto:nombre,
						precio:precio,
						color:color,
						talla:talla
					},
					onSuccess:function(e){
						$('total_items').set("text",e.cantidad);
						$('precio_total_carrito').set("text",e.total_carrito);
						tamanio=$('total_items').getStyle("font-size");
						window.location.href="shoppingcart_1.php";
						return false;
					}
			});
			agregaAjax.send();
			
	},
	ver:function(){
		if($('n_de_product')){
			$('n_de_product').load("petnico.php?controlador=carrito&accion=ver");
		}
	},
	actualiza:function(iditem){
		var actualizaAjax= new Request({
			url:"petnico.php?controlador=carrito&accion=actualizarItem&i="+iditem+"&c="+$('cantidad_'+iditem).get("value"),
			onSuccess:function(e){
				this.ver();
			}.bind(this)
		});
		actualizaAjax.send();
	},
	setDestino:function(idestino){
		$('msg_shipping').set("html","Calculating Shipping...");
		var destinoAjax= new Request({
			url:"petnico.php?controlador=carrito&accion=registraDestino&d="+idestino,
			onSuccess:function(){
				$('msg_shipping').set("html","");
				this.ver();
			}.bind(this)
		});
		destinoAjax.send();
	},
	eliminar:function(iditem){
		new Request({
			url:"petnico.php?controlador=carrito&accion=eliminarItem&i="+iditem,
			onSuccess:function(e){
				$('fila_'+iditem).destroy()
				this.ver();
				this.total();
			}.bind(this)
		}).send();
		
	},
	iniciarSesion:function(){
		var $ventana = new Ventana({
			id:"ventana_1",
			titulo:'Inicie sesi&oacute;n para poder realizar su pedido',
			modal:true,
			ancho:400,
			fondoModal:"#331D0F",
			url:"isesion.php"
		});
			$ventana.render();
		
	},
	errorSesion:function(){
		var $verror = new Ventana({
			id:"ventana_error__",
			titulo:'Inicio de sesi&oacute;n - Error de datos',
			modal:true,
			alto:250,
			html:"<img src='images/hk.gif'/><br>Datos incorrectos usuario y/o contrase&ntilde;a"
		});
			$verror.render();
	},
	datosEnvio:function(){
		if($('form_shopping2')){
			$('form_shopping2').load("petnico.php?controlador=carrito&accion=getDatos");
		}
	},
	grabarCompra:function(){
		var formAjax= new Request({
				url:"petnico.php?controlador=carrito&accion=grabarCarrito",
				evalScripts :true,
				evalResponse :true,
				onSuccess:function(e){
					window.location.href='shoppingcart_3.php';
					//this.cerrar();
					//this.agradecer();
				}.bind(this),
				data : $('form_evio_datos').toQueryString()
			});
			formAjax.send();
	},
	fVirtual:function(){
		if($('contenido_fvirtual')){
			var formAjax= new Request({
				url:"petnico.php?controlador=carrito&accion=grabarCarrito",
				onSuccess:function(e){
					alert("listo");
				}
				//data : $('form_evio_datos').toQueryString()
			});
//			formAjax.send();
			
		}
	},
	verFactura:function(){
		if($('capa_boleta')){
			$('capa_boleta').load("petnico.php?controlador=carrito&accion=verFactura");
		}
	},
	imprimir:function(){
		var cimpresion=$('imprimir_compra').get("html");
		var impresionFrame= new IFrame({
			src :'imp.html',
			styles:{
				height:50,
				width:100
			}
		}).inject(document.body);
		impresionFrame.contentWindow.document.body.innerHTML = "aasdasdasdsad";
		impresionFrame.contentWindow.document.body.set('html',"sdasdasdasdsadsaddasd");
	},
	cerrar:function(){
		var cierraAjax= new Request({
			url:"petnico.php?controlador=carrito&accion=cerrarCarrito",
			data : {ema:$('imprimir_compra').get("html")},
			onSuccess:function(e){
				this.total();
			}.bind(this)
		});	
		cierraAjax.send();
	},
	agradecer:function(){
		new Ventana({
			titulo:"",
			url: "thankyou_shopping.php",
			modal:true,
			fondo:"",
			alto:174,
			ancho:478,
			borde:0,
			separacion:0,
			btnCerrar:"cerrar_5"
		}).render();
		setTimeout(function(){
			window.location.href='index.php';
			return false;
		},8000);
		
	
	},
	enviarEmailAmigo:function(form){
		var enviaAmigoAjax= new Request({
			url:"petnico.php?controlador=carrito&accion=enviaraAmigo",
			data : $(form).toQueryString(),
			onSuccess:function(e){
				return true;
			},
			onFailure:function(){
				return false;
			}
		});
		enviaAmigoAjax.send();
	},
	cerrarSesion:function(){
		var csesion= new Request({
			url:"petnico.php?controlador=sesion&accion=cerrar",
			evalScripts:true,
			onSuccess:function(e){
				window.location.href="index.php";
				
			}
		});
		csesion.send();

	}
	
});


var Ventana= new Class({
	Implements: Options,
	options :{
		modal:false,
		ancho:350,
		titulo:'Ventana',
		alto: 350,
		id : "VentanaMoo",
		fondo : "",
		fondoModal:"#996600",
		opacidad:0.25,
		html:"Contenido ventana moo",
		url:"",
		arrastra:false,
		juntoA:"",
		separacion:10,
		borde:1,
		btnCerrar:"",
		imagenFondo:"",
		colorfondoCabecera:"",
		colorBorde:"",
		textoCerrar:"",
		anchoPrivado:35,
		htmlCerrar:"",
		estiloCabecera:""
		
	},
	initialize:function(options){
		
		this.setOptions(options);
		av=window.getWidth()/2;
		alv=window.getHeight()/2;
		ad=this.options.ancho/2;
		ald=this.options.alto/2;
		ventana=new Element("div",{
				id:this.options.id,
					styles:{
						backgroundColor : this.options.fondo,
						padding:this.options.separacion + 'px',
						height:this.options.alto + 'px',
						width:this.options.ancho + 'px',
						position:'absolute',
						border:this.options.borde+'px solid #CCC',
						left:parseInt(av)-parseInt(ad),
						top:parseInt(alv)-parseInt(ald),
						zIndex:1200						
					}
					
		});
		
		if(!$(this.options.juntoA)){
			ventana.set('html','<div id="header__moo" class="cabecera__moo" style="padding:10px;height:15px" >'+
								 '<div style="width:85%;float:left;">'+this.options.titulo+'</div>'+
								 '<div align="right" id="cierra_v_moo" style="float:left;width:15%;cursor:pointer;" title="Close"></div>'+
								 '</div>'+
								 '<div style="border-top:0px solid #CCC;padding:35px;height:'+parseInt(this.options.alto-25)+
								 'px;overflow:auto;vertical-align:middle" align="center" id="conte__moo" class="cuerpo__moo">'+
								 '</div>');
			
		}else{
			ventana.set('html','<div style="border-top:0px solid #CCC;height:'+parseInt(this.options.alto)+
								'px;overflow:auto;vertical-align:middle" align="center" id="conte__moo" class="cuerpo__moo">'+
								'</div>');
		}
	
	},
	render:function(){		
		if(!this.options.modal){
				$$('select').setStyle("visibility","hidden");
				$$('body').grab(ventana);
				
			if(!$(this.options.juntoA)){	
				$('cierra_v_moo').addEvent('click',this.cerrar.bind(this));
			}

				if(this.options.url==""){
					$('conte__moo').set('html',this.options.html);	
				}else{
					$('conte__moo').load(this.options.url);	
				}
				
		}else{
			var modal= new Element('div',{
				id:"VentanaMooModal",
				styles:{
					backgroundColor : this.options.fondoModal,
					opacity:this.options.opacidad,
					height:window.getScrollHeight(),
					width:'100%',
					zIndex:1009,
					position:'absolute',
					top:'0px',
					left:'0px'
				}
			});
			$$('select').setStyle("visibility","hidden");
			$$('body').grab(modal);
			modal.setOpacity(this.options.opacidad);
			//modal.tween("opacity",[1,this.options.opacidad]);
			$$('body').grab(ventana);
			
			if(this.options.separacion==0){
				$('conte__moo').setStyle("padding","0px");
			}
			
			if(this.options.htmlCerrar!=""){
				$('cierra_v_moo').set("html",this.options.htmlCerrar);
			}
			if(this.options.colorBorde!=""){
				ventana.setStyles({"border-color":this.options.colorBorde});
			}
			if(this.options.estiloCabecera!=""){
				$('header__moo').addClass(this.options.estiloCabecera);
			}
			if(this.options.imagenFondo!=""){
					$('conte__moo').setStyle("background-image","url("+this.options.imagenFondo+")");
					$('conte__moo').setStyle("background-repeat","repeat-x");
			}
			
			this.posicionar();
			if(this.options.url==""){
				$('conte__moo').set('html',this.options.html);	
			}else{
					try{
						$('conte__moo').set('load',{
							'evalResponse':true,
							'onSuccess':function(){
								if($(this.options.btnCerrar) && this.options.url){
									$(this.options.btnCerrar).addEvent('click',this.cerrar.bind(this)).setStyle("cursor","pointer").set("title","close");
								}else{
									$('cierra_v_moo').addEvent('click',this.cerrar.bind(this));
								}
							}.bind(this)
						});
					
					}catch(err){
							txt="There was an error on this page.\n\n";
							txt+="Error description: " + err.description + "\n\n";
							txt+="Click OK to continue.\n\n";
							alert(txt);
					}
						
				$('conte__moo').load(this.options.url);	
			}
		}
		
		if(this.options.arrastra=="si"){
			if($('header__moo')){
				$('header__moo').setStyle("cursor","move");
				$(ventana).makeDraggable({handle :'header__moo'/*,container:document.body*/});
			}
			
		}
		
		window.addEvents({
		'keydown':function(e){
				if(e.key == 'esc' ){
					if($('conte__moo')){
						this.cerrar();
					}
				}
			}.bind(this),
			'resize':function(){
				if($('conte__moo')){
					//this.posicionar();
				}
				
			}.bind(this)
		});
		
		
	},
	cerrar:function(){
			//window.removeEvent('keypress',function(e){});
			$('VentanaMooModal').set("tween",{
										duration:500,
										onComplete:function(){
											$('VentanaMooModal').destroy();
										}
								});
			if($(this.options.id)){
				$(this.options.id).destroy();
			}
			$('VentanaMooModal').tween("opacity",[this.options.opacidad,0])
			
			$$('select').setStyle("visibility","visible");
	},
	posicionar:function(){
		var scrollventana = new Fx.Scroll(window, {
				wait: false,
				duration: 800,
				transition:  Fx.Transitions.Sine.easeInOut
		});
		if($(this.options.juntoA)){
				var pos=$(this.options.juntoA).getCoordinates();
				scrollventana.toElement($(this.options.juntoA).getParent());
				try{
					ventana.set('morph', {
									duration: 800, 
									transition: 'quad:out',
									onComplete:function(){
										//$('VentanaMooModal').setStyles({"width","100","height":"100"})
									}
								})
								
							.setStyle("left",pos.left - (this.options.ancho / 2).toInt());
							ventana.morph({
								opacity : [0.5,1]
								//top: pos.top -  (this.options.alto).toInt() - 30
							});
				}catch(err){
					  txt="There was an error on this page.\n\n";
					  txt+="Error description: " + err.description + "\n\n";
					  txt+="Click OK to continue.\n\n";
					  alert(txt);
				}	
				
							
		}else{
				var pos=window.getHeight();
				var posAncho=window.getWidth();
				defaz=(pos-this.options.alto) / 2;
				sizes = window.getSize();
				scrollito = window.getScroll();
				
				
				ventana.setStyles({
					//top:0 + defaz.toInt()  
					'top': (scrollito.y + (sizes.y - this.options.alto) / 2).toInt()
				})
				try{
					ventana.set('morph', {
									duration: 500, 
									transition: 'sine:out',
									onComplete:function(){
										//scrollventana.toElement($('conte__moo'));
									//	$('VentanaMooModal').setStyles({"width","100%","height":"100%"})
									}
								})								
							.morph({
									opacity:[0.5,1]
								//"top":pos  + (this.options.alto / 2  ).toInt() ,
								//"left":posAncho / 2 - (this.options.ancho / 2).toInt()
							});
					$('cierra_v_moo').addEvent('click',this.cerrar.bind(this));
					
							
				}catch(err){
					  txt="There was an error on this page.\n\n";
					  txt+="Error description: " + err.description + "\n\n";
					  txt+="Click OK to continue.\n\n";
					  alert(txt);
				}	
				
		}
	}
});


var Tooltips=new Class({
	Implements: Options,				   
	options:{
		objeto:"moo__tip",
		clase:"mootips",
		ancho: 250,
		alto: 150,
		fondo:"",
		html:"",
		div:"moo",
		posicion:"arriba",
		estiloInterior:"",
		evento:"over",
		bntCerrar:"",
		colorFondo:"",
		borde:"",
		forzarCierre:true,
		aliner:""
		
	},
	initialize:function(options){
		this.setOptions(options);
		if(this.options.evento=="over"){
			this.bntCerrar="";
		}
		 moo___tip = new Element("div",{
			id:'moo_tip__'+this.options.div,
			styles:{
				backgroundImage : 'url('+this.options.fondo+')',
				backgroundRepeat: 'no-repeat',
				border : '0px solid blue',
				width : this.options.ancho,
				height :this.options.alto,
				position:'absolute',
				visibility:'hidden',
				padding:'0px',
				zIndex:1500,
				top:0
			},
			html:'<div align="right" style="padding-right:10px;margin-top:2px"  id="cierraTip__'+this.options.div+'">'+this.options.bntCerrar+'</div><div style="padding:5px">'+
						'<span class="'+this.options.estiloInterior+'">'+this.options.html+'</span></div>'
		});
		 if(this.options.fondo!=""){
		//	 $('moo_tip__').setStyle("border","0");
		 }
		 
		 if(this.options.colorFondo!=""){
			moo___tip.setStyle("background-color",this.options.colorFondo);
		 }
		 
		 if(this.options.borde!=""){
			moo___tip.setStyle("border",this.options.borde);
		 }
		 this.iniciar();
		 window
		 .addEvent("resize",function(){
			if($('moo_tip__'+this.options.div).getStyle("visibility")=="visible"){
				this.mostrar() 
			}
			
		 }.bind(this))
	},
	iniciar:function(){
		$$('body').grab(moo___tip);
		$(this.options.div)
		.addEvents({
			"mouseenter":function(){
				if(this.options.evento=="over"){
					this.mostrar();
				}
				
				
			}.bind(this),
			"mouseleave":function(){
				if(this.options.evento=="over" || this.options.forzarCierre==false ){
					this.cerrar();
				}
			}.bind(this),
			"click":function(){
				if(this.options.evento=="click"){
					this.mostrar();
				}
			}.bind(this)
		}).setStyle('cursor','pointer');

		$('cierraTip__'+this.options.div)
		.addEvent("click",function(){
				this.cerrar();
		}.bind(this)).setStyle("cursor","pointer");
		
	},
	mostrar:function(){
		$('moo_tip__'+this.options.div).setStyles({
			"width":this.options.ancho,
			"height":this.options.alto
		});
		pos=$(this.options.div).getCoordinates();
		if(this.options.alinear!=""){
			switch(this.options.alinear){
				case "izquierda":
					miizquierdaarriba=(pos.left).toInt();
					miizquierdaabajo=(pos.left).toInt();
				break;
				default: 
					miizquierdaarriba=(pos.left).toInt()-(this.options.ancho/2);
					miizquierdaabajo=(pos.left).toInt() - ((this.options.ancho - pos.width) / 2).toInt();
			}

		}
		switch(this.options.posicion){
			case "arriba":
				$('moo_tip__'+this.options.div)
				.setStyles({'left':miizquierdaarriba,'top':(pos.top)-this.options.alto - 10 })
				.morph({
					'top' :[$('moo_tip__'+this.options.div).getStyle("top") ,(pos.top).toInt() - this.options.alto ]
				});	
			break;
			
			case "abajo":
				$('moo_tip__'+this.options.div)
				.setStyles({
					'left':miizquierdaabajo,
					'top':pos.top,
					'visibility':'hidden'
				}).morph({
					'top' :[(pos.top).toInt() + pos.height + 10,(pos.top).toInt() + pos.height]
				});
			
			case "centroArriba":
				$('moo_tip__'+this.options.div)
				.setStyle('left',miizquierdaarriba + $(this.options.div).getStyle("width").toInt()/2  ).morph({
					'top' :[(pos.top - this.options.alto)-20 ,(pos.top).toInt() - this.options.alto ]
				});
			break;			
		}
		$('moo_tip__'+this.options.div).fade("in");
	},
	cerrar:function(){
		$('moo_tip__'+this.options.div).fade("out");
	}
});




var user = new Petnico();
var carrito= new Carrito();


var Productos= new Class({
	Implements: Options,				   
	options:{
		tipo:"productos"
	},
	initialize:function(options){
		this.setOptions(options);
	},
	cargarGaleria:function(){
		$tipo=this.tipo;
		var jsonProductos= new Request.JSON({
			url:"petnico.php?controlador=productos&accion=listarGaleria",
			onComplete:function(e){
				$n=0;
				$('detalles_de_producto').load("detalles.php?i="+e.id_uno);
				$$('#foto_producto img').set("src","images/productos/"+e.imagen_grande).reflect({height:1/8});			
				$each(e,function(value){
					$each(value,function(v,k){
						$n++;
						$('prod_'+$n).set("html","<a href='javascript:;' id='"+v.id
										  		   +"' ><img border='0' src=\"images/dama/"+
										  			v.imagen_chica
													+"\" class=\"border\" width=\"96\" height=\"133\" alt=\"\" /></a>");
						new Asset.image('images/productos/'+v.imagen_grande);
						$(v.id).addEvent("click",
								function(e){
									new Fx.Morph('detalles_de_producto',{
											duration : 500,
											property: 'left',
											transition: Fx.Transitions.Sine.easeOut,
											onComplete:function(){
												$('detalles_de_producto').load("detalles.php?i="+v.id);
												new Fx.Tween('detalles_de_producto',{
															 property: 'opacity',
															 duration : 500}).start(0,1);
											}
									}).start({
										'opacity': [1,0], 
									    'left': [50, 42]
									});
									
									new Fx.Tween('foto_producto',{
											duration : 500,
											property: 'opacity',
											onComplete:function(){
												$$('#foto_producto img').set("src","images/productos/"+v.imagen_grande).reflect({height:1/8});			
												new Fx.Tween('foto_producto',{
															 property: 'opacity',
															 duration : 500}).start(0,1);
											}
									}).start(1,0);
								}.bind(this))
					})
				});
					
				
				
			}.bind(this)
		}).post({tipo:"catalogo"});
		
	}.bind(this),
	
	verDetalle:function(i){

	}
});




/**menu Class perutenico**/

var MenuEtnico= new Class({
	Implements: Options,				   
	options:{
		principal:"",
		ancho:300,
		alto:250,
		links:{},
		estiloMenu:"",
		//fondo:"#7c4d25",
		fondo:"",
		evento:"over",
		imagenFondo:"",
		transicion:"linear",
		duracion:500,
		html:"",
		separacion:5
	},
	Menu:"",
	initialize:function(options){
		this.setOptions(options);
		var mimenu= new Element('div',{
			id:'mi___menuu____'+this.options.principal,
			styles:{
				backgroundColor:this.options.fondo,
				border:'0px solid black',
				padding:this.options.separacion,
				position:'relative',
				zIndex:900,
				height:0,
				width:0,
				visibility:'hidden',
				top:"10px"
			}
		});
		
		$(this.options.principal).setStyle("cursor","pointer");
		//$(this.options.principal).setStyle("overflow","hidden");
		alto_item=((this.options.alto-10).toInt()/this.options.links.length).toInt();
		var coor=$(this.options.principal).getCoordinates();
		mimenu.setStyles({
			'top':'0px', //solo para etnico
			'left':-(this.options.ancho - $(this.options.principal).getStyle("width").toInt() - 6),
			'height': this.options.alto +'px', 
			'width': (this.options.ancho-6)+'px'
		});
		$(this.options.principal).getParent().setStyle("zIndex",1000);
		$(this.options.principal).grab(mimenu)
		this.Menu=mimenu;
	
		if(this.options.imagenFondo!=""){
			this.Menu.setStyles({
				backgroundColor:"",
				backgroundImage : 'url('+this.options.imagenFondo+')',
				backgroundRepeat:"no-repeat"
			});
		}
		if(this.options.evento=="over"){
			$(this.options.principal).addEvents({
				"mouseenter":function(){
					this.mostrar();
					
				}.bind(this),
				"mouseleave":function(){
					this.ocultar()
				}.bind(this)
					
			});
			}else if (this.options.evento=="click"){
				$(this.options.principal).addEvents({
						"click":function(e){
							this.mostrar();	
							e.stopPropagation();
						}.bind(this)
				});
				$$(document.body)
					.addEvent("click",function(){
						this.ocultar();
					}.bind(this));
			}
		
	},
	mostrar:function(){
		if(this.options.html==""){
			var mlinks=this.options.links;
							for(var men in mlinks){
								var sp= new Element("a",{
									'class' : this.options.estiloMenu,
									html:men +"<br>",
									href:mlinks[men],
									styles:{
										display:"block"
									}
								});
								
								this.Menu.grab(sp);
							}
		}else{
			this.Menu.set("html",this.options.html);
		}
		tam=$(this.options.principal).getStyle("width");
		$(this.options.principal).setStyles({"overflow":"visible","width":tam});
		this.Menu.tween("opacity",[0,1]);
	},
	ocultar:function(){
		if(this.Menu.isVisible()){
			this.Menu.fade("in");
			this.Menu.fade("out");
			this.Menu.set("html","");
		}
	}
});


var MenuLogin = new Class({
	Extends: MenuEtnico,
	initialize:function(options){
		this.parent(options);
		this.Menu.setStyles({
			"width":this.options.ancho,
			"height":this.options.alto,
			"left":-(this.options.ancho/2 - (this.Menu.getParent().getStyle("width").toInt()/2)),
			"zIndex":"5000",
			"cursor":"default",
			"top":"0px"
		});
		this.Menu.getParent().setStyle("zIndex",1000);
		this.Menu.set("html",this.options.html);
	},
	mostrar:function(){
		if($(this.options.principal).hasClass("seleccionado")){
			$(this.options.principal).removeClass("seleccionado");
			this.ocultar();
			return false;
		}else{
			$(this.options.principal).addClass("seleccionado")
			this.Menu.setStyles({"zIndex":1000})
			.set("morph",{
				transition:this.options.transicion,
				duration:this.options.duracion * 1000,
				onComplete:function(){
					
				}.bind(this)
			})	
			.morph({
					opacity:1
					//height: [0,this.options.alto]				
			});
			
			this.Menu.addEvent("click",function(e){ e.stopPropagation();} );
			return false;
		}
	},
	ocultar:function(){
		if(this.Menu.getStyle("visibility")=="visible"){
			$(this.options.principal).removeClass("seleccionado");
				this.Menu
				.set("morph",{
					onComplete:function(){
						
					}.bind(this)
				})
				.morph({
					//height: [this.options.alto,0] ,
					opacity:0
				});
			//this.Menu.set("html","");
		
		}	
		
		
	}
});



/***class Zoom**/
var AZoom = new Class({
	Implements:Options,
	options:{
		capaZoom:"",
		barraZoom:"",
		mas:"",
		menos:"",
		anchoImagen:"",
		altoImagen:"",
		limita:""
	},
	imagen:"",
	clon:"",
	Zoomactual:"",
	slider:"",
	moverconRueda:"",
	imagenZoom:"",
	contenedor:"",
	tamanoInicial:"",
	initialize:function(imagen,options){
		this.setOptions(options);
		this.imagen=$(imagen);
		this.imagen.getParent().setStyle("overflow","hidden");
		this.imagenZoom = new Asset.image(this.imagen.get("rel"));
		this.tamanoInicial=this.imagen.getCoordinates();
		this.imagen.setStyles({"top":0,"left":0,"cursor":"move"});
		if(this.options.limita!=""){
			this.contenedor= new Element("div",{
			}).injectBefore(this.imagen).adopt(this.imagen);
			anchoLimite=this.imagen.getParent().getStyle("width");
			altoLimite=this.imagen.getParent().getStyle("height");
			this.contenedor.setStyles({
					"width": anchoLimite,
					"height": altoLimite,
					"top": 0,
					"left":0
			});
			this.imagen.makeDraggable({
				wait:true,
				container:this.contenedor
			});
		}else{
				this.imagen.makeDraggable({wait:true});
		}
		
		
		el=$(this.options.capaZoom);
		this.slider = new Slider(el, el.getElement('div'), {
			   steps: 20,	
			   range: [0,100],
			   wheel: true,
			   onChange: function(value){
				   todoActual= this.imagen.getCoordinates();
				   if(value!=0){
					   this.contenedor.set("align","center");
						this.imagen.set("morph",{duration:100})
						.setStyles({
							'left':'-'+((value*1))+'px',
							'top':'-'+((value)*2)+'px',
							'width':(((value*5.1)+this.options.anchoImagen)),
							'height':((((value*(6.2)))+this.options.altoImagen))
						});
						this.contenedor
						.setStyles({
							'margin-left':-(todoActual.width-this.tamanoInicial.width),
							'margin-top':-(todoActual.height-this.tamanoInicial.height),
							'width':(2*todoActual.width-this.tamanoInicial.width),
							'height':(2*todoActual.height-this.tamanoInicial.height)
						});	
					this.Zoomactual=value;
					}else if(value==0 || value==5 ) {
						
						this.imagen
						.setStyles({
							'margin-left':'0px',
							'margin-top':'0px',
							'width':this.anchoImagen,
							'height':this.altoImagen,
							'left':0,
							'top':0
						});
					
						this.contenedor
						.setStyles({
							'margin-left':'0px',
							'margin-top':'0px',
							'width':this.imagen.getStyle("width"),
							'height':this.imagen.getStyle("height"),
							'left':0,
							'top':0
						});
						this.Zoomactual=value;
					}
				   
				   
			   }.bind(this)

		}).set(0);
		
		$(this.options.mas)
		.addEvent("click",function(){
			this.aumentarZoom();
		}.bind(this)).setStyle("cursor","pointer");
		$(this.options.menos)
		.addEvent("click",function(){
				this.disminuirZoom();
		}.bind(this)).setStyle("cursor","pointer");
		
		if(this.options.moverconRueda!=""){
			this.imagen
			.addEvent("mousewheel",function(e){
				var e = new Event(e).stop();
				if ( e.wheel > 0  ) {
					this.Zoomactual=this.Zoomactual+5
					this.slider.set(this.Zoomactual);
				}else{
					this.Zoomactual=this.Zoomactual-5
					this.slider.set(this.Zoomactual);
				}
			}.bind(this));
		}
		
	},
	aumentarZoom:function(){
		this.Zoomactual=this.Zoomactual+5
		this.slider.set(this.Zoomactual);
	},
	disminuirZoom:function(){
		this.Zoomactual=this.Zoomactual-5
		this.slider.set(this.Zoomactual);
	},
	resetearZoom:function(){
		/*this.imagen
		.setStyles({
			'margin-left':'0px',
			'margin-top':'0px',
			'width':this.options.anchoImagen,
			'height':this.options.altoImagen,
			'left':0,
			'top':0
		});
		this.slider.set(0);
		*/
		this.ZOOM.generate()
	}
});


/*
	Class: FormCheck
		Performs different tests on forms and indicates errors.
		
	Usage:
		Works with these types of fields :
		- input (text, radio, checkbox)
		- textarea
		- select
		
		You just need to add a specific class to each fields you want to check. 
		For example, if you add the class
			(code)
			validate['required','length[4, -1]','differs[email]','digit']
			(end code)
		the value's field must be set (required) with a minimum length of four chars (4, -1), 
		must differs of the input named email (differs[email]), and must be digit. 
		
		You can perform check during the datas entry or on the submit action, shows errors as tips or in a div before or after the field, 
		show errors one by one or all together, show a list of all errors at the top of the form, localize error messages, add new regex check, ...
		
		The layout is design only with css. Now I added a hack to use transparent png with IE6, so you can use png images in formcheck.css (works only for theme, so the file must be named formcheck.css). It can also works with multiple forms on a single html page.
		The class supports now internationalization. To use it, simply specify a new <script> element in your html head, like this : <script type="text/javascript" src="formcheck/lang/fr.js"></script>.

		If you add the class
			(code)
			validate['submit']
			(end code)
		to an element like an anchor (or anything else), this element will act as a submit button.
		
		N.B. : you must load the language script before the formcheck and this method overpass the old way. You can create new languages following existing ones. You can otherwise still specifiy the alerts' strings when you initialize the Class, with options.
		If you don't use a language script, the alert will be displayed in english.
	
	Test type:
		You can perform various test on fields by adding them to the validate class. Be careful to *not use space chars*. Here is the list of them.
			
		required 					- The field becomes required. This is a regex, you can change it with class options.
		alpha 						- The value is restricted to alphabetic chars. This is a regex, you can change it with class options.
		alphanum 					- The value is restricted to alphanumeric characters only. This is a regex, you can change it with class options.
		nodigit 					- The field doesn't accept digit chars. This is a regex, you can change it with class options.
		digit 						- The value is restricted to digit (no floating point number) chars, you can pass two arguments (f.e. digit[21,65]) to limit the number between them. Use -1 as second argument to not set a maximum.
		number 						- The value is restricted to number, including floating point number. This is a regex, you can change it with class options.
		email 						- The value is restricted to valid email. This is a regex, you can change it with class options.
		image						- The value is restricted to images (jpg, jpeg, png, gif, bmp). This is a regex, you can change it with class options.
		phone 						- The value is restricted to phone chars. This is a regex, you can change it with class options.
		phone_inter					- The value is restricted to international phone number. This is a regex, you can change it with class options.
		url: 						- The value is restricted to url. This is a regex, you can change it with class options.
		confirm 					- The value has to be the same as the one passed in argument. f.e. confirm[password].
		differs 					- The value has to be diferent as the one passed in argument. f.e. differs[user].
		length 						- The value length is restricted by argument (f.e. length[6,10]). Use -1 as second argument to not set a maximum.
		words						- The words number is limited by arguments. f.e. words[1,13]. Use -1 as second argument to don't have a max limit.
		target						- It's not really a validation test, but it allows you to attach the error message to an other element, usefull if the input you validate is hidden. You must specifiy target id, f.e. target:myDiv.
		
		You can also use a custom function to check a field. For example, if you have a field with class
			(code)
			validate['required','%customCheck']
			(end code)
		the function customCheck(el) will be called to validate the field. '%customcheck' works with other validate(s) together, and '~customcheck' works if the element pass the other validate(s). 
		Here is an example of what customCheck could look : 
			(code)
			function customCheck(el){
				if (!el.value.test(/^[A-Z]/)) {
					el.errors.push("Username should begin with an uppercase letter"); 
					return false;
				} else {
					return true;
				}
			}
			(end code)
		
		It is now possible to register new fields after a new FormCheck call by using <FormCheck::register> (see <FormCheck::dispose> too). You need first to add the validate class to the element you want to register ( $('myInput').addClass("validate['required']") ).
		
	Parameters:
		When you initialize the class with addEvent, you can set some options. If you want to modify regex, you must do it in a hash, like for display or alert. You can also add new regex check method by adding the regex and an alert with the same name.
		
		Required:
			
			form_id - The id of the formular. This is required.
			
		Optional:
		
			submit					- If you turn this option to false, the FormCheck will only perform a validation, without submitting the form, even on success. You can use validateSuccess event to execute some code.
			
			submitByAjax 			- you can set this to true if you want to submit your form with ajax. You should use provided events to handle the ajax request (see below). By default it is false.
			ajaxResponseDiv 		- id of element to inject ajax response into (can also use onAjaxSuccess). By default it is false.
			ajaxEvalScripts 		- use evalScripts in the Request response. Can be true or false, by default it is false.
			onAjaxRequest 			- Function to fire when the Request event starts.
			onAjaxSuccess 			- Function to fire when the Request receives .  Args: response [the request response] - see Mootools docs for Request.onSuccess.
			onAjaxFailure 			- Function to fire if the Request fails.
			
			onSubmit				- Function to fire when form is submited (so before validation)
			onValidateSuccess 		- Function to fire when validation pass (you should prevent form submission with option submit:false to use this)
			onValidateFailure		- Function to fire when validation fails
			
			tipsClass 				- The class to apply to tipboxes' errors. By default it is 'fc-tbx'.
			errorClass 				- The class to apply to alertbox (not tips). By default it is 'fc-error'.
			fieldErrorClass 		- The class to apply to fields with errors, except for radios. You should also turn on  options.addClassErrorToField. By default it is 'fc-field-error'
			
			trimValue				- If set to true, strip whitespace (or other characters) from the beginning and end of values. By default it is false.
			validateDisabled		- If set to true, disabled input will be validated too, otherwise not.

		Display:
			This is a hash of display settings. in here you can modify.
			
			showErrors 				- 0 : onSubmit, 1 : onSubmit & onBlur, by default it is 0.
			titlesInsteadNames		- 0 : When you do a check using differs or confirm, it takes the field name for the alert. If it's set to 1, it will use the title instead of the name.
			errorsLocation 			- 1 : tips, 2 : before, 3 : after, by default it is 1.
			indicateErrors 			- 0 : none, 1 : one by one, 2 : all, by default it is 1.
			indicateErrorsInit		- 0 : determine if the form must be checked on initialize. Could be usefull to force the user to update fields that don't validate.
			keepFocusOnError 		- 0 : normal behaviour, 1 : the current field keep the focus as it remain errors. By default it is 0.
			checkValueIfEmpty 		- 0 : When you leave a field and you have set the showErrors option to 1, the value is tested only if a value has been set. 1 : The value is tested  in any case.  By default it is 1.
			addClassErrorToField 	- 0 : no class is added to the field, 1 : the options.fieldErrorClass is added to the field with an error (except for radio). By default it is 0.
			removeClassErrorOnTipClosure - 0 : Error class is kept when the tip is closed, 1 : Error class is removed when the tip is closed

			fixPngForIe 			- 0 : do nothing, 1 : fix png alpha for IE6 in formcheck.css. By default it is 1.
			replaceTipsEffect 		- 0 : No effect on tips replace when we resize the broswer, 1: tween transition on browser resize;
			closeTipsButton 		- 0 : the close button of the tipbox is hidden, 1 : the close button of the tipbox is visible. By default it is 1.
			flashTips 				- 0 : normal behaviour, 1 : the tipbox "flash" (disappear and reappear) if errors remain when the form is submitted. By default it is 0.
			tipsPosition 			- 'right' : the tips box is placed on the right part of the field, 'left' to place it on the left part. By default it is 'right'.
			tipsOffsetX 			- Horizontal position of the tips box (margin-left), , by default it is 100 (px).
			tipsOffsetY				- Vertical position of the tips box (margin-bottom), , by default it is -10 (px).
			
			listErrorsAtTop 		- List all errors at the top of the form, , by default it is false.
			scrollToFirst 			- Smooth scroll the page to first error and focus on it, by default it is true.
			fadeDuration 			- Transition duration (in ms), by default it is 300.
		
		Alerts:
			This is a hash of alerts settings. in here you can modify strings to localize or wathever else. %0 and %1 represent the argument.
			
			required 				- "This field is required."
			alpha 					- "This field accepts alphabetic characters only."
			alphanum 				- "This field accepts alphanumeric characters only."
			nodigit 				- "No digits are accepted."
			digit 					- "Please enter a valid integer."
			digitmin 				- "The number must be at least %0"
			digitltd 				- "The value must be between %0 and %1"
			number 					- "Please enter a valid number."
			email 					- "Please enter a valid email: <br /><span>E.g. yourname@domain.com</span>"
			phone 					- "Please enter a valid phone."
			phone_inter 			- "Please enter a valid international phone number."
			url 					- "Please enter a valid url: <br /><span>E.g. http://www.domain.com</span>"
			image					- "This field should only contain image types"
			confirm 				- "This field is different from %0"
			differs 				- "This value must be different of %0"
			length_str 				- "The length is incorrect, it must be between %0 and %1"
			length_fix 				- "The length is incorrect, it must be exactly %0 characters"
			lengthmax 				- "The length is incorrect, it must be at max %0"
			lengthmin 				- "The length is incorrect, it must be at least %0"
			words_min				- "This field must concain at least %0 words, now it has %1 words"
			words_range				- "This field must contain between %0 and %1 words, now it has %2 words"
			words_max				- "This field must contain at max %0 words, now it has %1 words",
			checkbox 				- "Please check the box"
			radios 					- "Please select a radio"
			select 					- "Please choose a value"
		
	Example:
		You can initialize a formcheck (no scroll, custom classes and alert) by adding for example this in your html head this code :
		
		(code)
		<script type="text/javascript">
			window.addEvent('domready', function() {
				var myCheck = new FormCheck('form_id', {
					tipsClass : 'tips_box',
					display : {
						scrollToFirst : false
					},
					alerts : {
						required : 'This field is ablolutely required! Please enter a value'
					}
				})
			});
		</script>
		(end code)
	
	About:
		formcheck.js v.1.5 for mootools v1.2 - 09 / 2009
		
		by Mootools.Floor (http://mootools.floor.ch) MIT-style license
		
		Created by Luca Pillonel, 
		Last modified by Luca Pillonel
		
	Credits:
		This class was inspired by fValidator by Fabio Zendhi Nagao (http://zend.lojcomm.com.br)
		
		Thanks to all contributors from groups.google.com/group/moofloor (and others as well!) providing ideas, fixes and motivation!
*/

var FormCheck = new Class({
	
	Implements: [Options, Events],

	options : {
		
		tipsClass : 'fc-tbx',				//tips error class
		errorClass : 'fc-error',			//div error class
		fieldErrorClass : 'fc-field-error',	//error class for elements
		
		submit : true,						//false : just validate the form and do nothing else. Use onValidateSuccess event to execute some code
		
		trimValue : false,					//trim (remove whitespaces before and after) the value
		validateDisabled : false,			//skip validation on disabled input if set to false.
		
		submitByAjax : false,				//false : standard submit way, true : submit by ajax
		ajaxResponseDiv : false,			//element to inject ajax response into (can also use onAjaxSuccess) [cronix] 
		ajaxEvalScripts : false,			//use evalScripts in the Request response [cronix] 
		onAjaxRequest : $empty,				//Function to fire when the Request event starts 
		onAjaxSuccess : $empty,				//Function to fire when the Request receives .  Args: response [the request response] - see Mootools docs for Request.onSuccess 
		onAjaxFailure : $empty,				//Function to fire if the Request fails
		
		onSubmit		  : $empty,			//Function to fire when user submit the form
		onValidateSuccess : $empty,			//Function to fire when validation pass
		onValidateFailure : $empty,			//Function to fire when validation fails

		display : {
			showErrors : 0,
			titlesInsteadNames : 0,
			errorsLocation : 1,
			indicateErrors : 1,
			indicateErrorsInit : 0,
			keepFocusOnError : 0,
			checkValueIfEmpty : 1,
			addClassErrorToField : 0,
			removeClassErrorOnTipClosure : 0,
			fixPngForIe : 1,
			replaceTipsEffect : 1,
			flashTips : 0,
			closeTipsButton : 1,
			tipsPosition : "right",
			tipsOffsetX : -45,
			tipsOffsetY : 0,
			listErrorsAtTop : false,
			scrollToFirst : true,
			fadeDuration : 300
		},
		
		alerts : {
			required : "Este campo es obligatorio.",
			alpha : "Este campo solo acepta letras.",
			alphanum : "Este campo s&oacute;lo acepta letras y n&uacute;meros.",
			nodigit : "No se aceptan d&iacute;gitos.",
			digit : "Por favor solo ingrese numero enteros.",
			digitltd : "Este valor debe estar entre %0 y %1",
			number : "Por favor ingrese un n&uacute;mero v&aacute;lido.",
			email : "Por favor ingrese un email v&aacute;lido.",
			image : 'Este campo s&olo acepta im&aacute;genes', 
			phone : "Por favor ingrese un numero de tel&eacute;fono v&acute;lido.",
			phone_inter : "Por favor ingrese un numero internacional de tel&eacute;fono v&acute;lido.",
			url : "Por favor ingrese una correcta URL.",
			
			confirm : "Este campo es diferente de  %0",
			differs : "Este campo debe ser diferente de  %0",
			length_str : "El tama&ntilde;o es incorrecto, debe ser contener entre %0 y %1",
			length_fix : "El tama&ntilde;o es incorrecto, debe contener exactamente %0 caracteres",
			lengthmax : "El tama&ntilde;o es incorrecto, debe ser como m&aacute;ximo %0",
			lengthmin : "El tama&ntilde;o es incorrecto, debe ser mayor a %0",
			words_min : "Este campo debe estar entre %0 palabras, actualmente: %1 palabras",
			words_range : "Eset campo debe contener %0-%1 palabras, actualmente: %2 palabras",
			words_max : "Este campo debe contener como m&aacute;ximo %0 palabras, actualmente: %1 palabras",
			checkbox : "Por favor revise el check",
			radios : "Por favor seleccione una opci&oacute;n",
			select : "Por favor seleccione un valor"
		},
		
		regexp : {
			required : /[^.*]/,
			alpha : /^[a-z ._-]+$/i,
			alphanum : /^[a-z0-9 ._-]+$/i,
			digit : /^[-+]?[0-9]+$/,
			nodigit : /^[^0-9]+$/,
			number : /^[-+]?\d*\.?\d+$/,
			email : /^([a-zA-Z0-9_\.\-\+%])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
			image : /.(jpg|jpeg|png|gif|bmp)$/i,
			phone : /^[\d\s ().-]+$/, // alternate regex : /^[\d\s ().-]+$/,/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
			phone_inter : /^\+{0,1}[0-9 \(\)\.\-]+$/,
			url : /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i
		}
	},
	
	/*
	Constructor: initialize
		Constructor
	
		Add event on formular and perform some stuff, you now, like settings, ...
	*/
	initialize : function(form, options) {
		if (this.form = $(form)) {
			this.form.isValid = true;
			this.regex = ['length'];
			this.setOptions(options);
			
			//internalization
			if (typeof(formcheckLanguage) != 'undefined') this.options.alerts = $merge(this.options.alerts, formcheckLanguage);
			
			this.validations = [];
			this.alreadyIndicated = false;
			this.firstError = false;
			
			var regex = new Hash(this.options.regexp);
			regex.each(function(el, key) {
				this.regex.push(key);
			}, this);

			this.form.getElements("*[class*=validate]").each(function(el) {
				if (el.get('tag') == 'select' || el.get('tag') == 'input' || el.get('tag') == 'textarea') this.register(el);
			}, this);
			
			this.form.addEvents({
				"submit": this.onSubmit.bind(this)
			});
			
			if(this.options.display.fixPngForIe) this.fixIeStuffs();
			document.addEvent('mousewheel', function(){
				this.isScrolling = false;
			}.bind(this));
		}
	},
	register : function(el, position) {
		el.validation = [];
		el.getProperty("class").split(' ').each(function(classX) {
			if(classX.match(/^validate(\[.+\])$/)) {
				var valid = true;
				//we check if group is already registered
				if (el.type == "radio") {
					this.validations.each(function(valider){
						if (valider.name == el.name) valid = false;
					}, this)
				}
				var validators = eval(classX.match(/^validate(\[.+\])$/)[1]);
				for(var i = 0; i < validators.length; i++) {
					el.validation.push(validators[i]);
					if (validators[i].match(/^confirm\[/)) {
						var field = eval(validators[i].match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i, "'$1'"));
						if (this.form[field].validation.contains('required')){
							el.validation.push('required');
						}							
					}
					if(validators[i].match(/^target:.+/)) {
						el.target = validators[i].match(/^target:(.+)/)[1];
					}
				}
				//new push way
				if (position && position <= this.validations.length) {
					var newValidations = [];
					this.validations.each(function(valider, i){
						if (position == i+1 && valid) {
							newValidations.push(el);
							this.addListener(el);
						}
						newValidations.push(valider);
					}, this);
					this.validations = newValidations;
				} else {
					if (valid) {
						this.validations.push(el);
						this.addListener(el);
					}
				}
			}
		}, this);
	},
	dispose : function(element) {
		this.validations.erase(element);
	},
	addListener : function(el) {
		el.errors = [];
		
		if (this.options.display.indicateErrorsInit) {
			this.validations.each(function(el) {
				if(!this.manageError(el,'submit')) this.form.isValid = false;
			}, this);
			return true;
		} 
	
		if (el.validation[0] == 'submit') {
			el.addEvent('click', function(e){
				if (this.onSubmit(e)) this.form.submit();
			}.bind(this));
			return true;
		}

		if (this.isChildType(el) == false) el.addEvent('blur', function() {
			(function(){
				if(!this.fxRunning && (el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value))
				this.manageError(el, 'blur')
			}.bind(this)).delay(100);
		}.bind(this))
		//We manage errors on radio
		else if (this.isChildType(el) == true) {
			//We get all radio from the same group and add a blur option
			var nlButtonGroup = this.form.getElements('input[name="'+ el.getProperty("name") +'"]');
			nlButtonGroup.each(function(radio){
				radio.addEvent('blur', function(){
					(function(){
						if((el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value)) this.manageError(el, 'click');
					}.bind(this)).delay(100);
				}.bind(this))
			},this);
		}
	},
	validate : function(el) {
		el.errors = [];
		el.isOk = true;
		
		//skip validation and trim if specified
		if (!this.options.validateDisabled && el.get('disabled')) return true;
		if (this.options.trimValue && el.value) el.value = el.value.trim();
		
		el.validation.each(function(rule) {
			if(this.isChildType(el)) {
				if (this.validateGroup(el) == false) {
					el.isOk = false;
				}
			} else {
				var ruleArgs = [];
				
				if(rule.match(/target:.+/)) return;
				
				if(rule.match(/^.+\[/)) {
					var ruleMethod = rule.split('[')[0];
					ruleArgs = eval(rule.match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i, "'$1'"));
				} else var ruleMethod = rule;
				
				if (this.regex.contains(ruleMethod) && el.get('tag') != "select") {
					if (this.validateRegex(el, ruleMethod, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'confirm') {
					if (this.validateConfirm(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'differs') {
					if (this.validateDiffers(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'words') {
					if (this.validateWords(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (el.get('tag') == "select" || (el.type == "checkbox" && ruleMethod == 'required')) {
					if (this.simpleValidate(el) == false) {
						el.isOk = false;
					}
				}
				if(rule.match(/%[A-Z0-9\._-]+$/i) || (el.isOk && rule.match(/~[A-Z0-9\._-]+$/i))) {
					if(eval(rule.slice(1)+'(el)') == false) {
						el.isOk = false;
					}
				}
			}
		}, this);
		
		if (el.isOk) return true;
		else return false;
	},
	simpleValidate : function(el) {
		if (el.get('tag') == 'select' && el.selectedIndex <= 0) {
			el.errors.push(this.options.alerts.select);
			return false;
		} else if (el.type == "checkbox" && el.checked == false) {
			el.errors.push(this.options.alerts.checkbox);
			return false;
		}
		return true;
	},
	validateRegex : function(el, ruleMethod, ruleArgs) {
		var msg = "";
		if (ruleArgs[1] && ruleMethod == 'length') {
			if (ruleArgs[1] == -1) {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +",}$");
				msg = this.options.alerts.lengthmin.replace("%0",ruleArgs[0]);
			} else if(ruleArgs[0] == ruleArgs[1]) {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +"}$");
				msg = this.options.alerts.length_fix.replace("%0",ruleArgs[0]);
			} else {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +","+ ruleArgs[1] +"}$");
				msg = this.options.alerts.length_str.replace("%0",ruleArgs[0]).replace("%1",ruleArgs[1]);
			}
		} else if (ruleArgs[0] && ruleMethod == 'length') {
			this.options.regexp.length = new RegExp("^.{0,"+ ruleArgs[0] +"}$");
			msg = this.options.alerts.lengthmax.replace("%0",ruleArgs[0]);
		} else {
			msg = this.options.alerts[ruleMethod];
		}
		if (ruleArgs[1] && ruleMethod == 'digit') {
			var regres = true;
			if (!this.options.regexp.digit.test(el.value)) {
				el.errors.push(this.options.alerts[ruleMethod]);
				regres = false;
			}
			if (ruleArgs[1] == -1) {
				var valueres = ( el.value.toInt() >= ruleArgs[0].toInt() ); 
				msg = this.options.alerts.digitmin.replace("%0",ruleArgs[0]);
			} else {
				var valueres = ( el.value.toInt() >= ruleArgs[0].toInt() && el.value.toInt() <= ruleArgs[1].toInt() );
				msg = this.options.alerts.digitltd.replace("%0",ruleArgs[0]).replace("%1",ruleArgs[1]);
			}
			if (regres == false || valueres == false) {
				el.errors.push(msg);
				return false;
			}
		} else if (this.options.regexp[ruleMethod].test(el.value) == false)  {
			el.errors.push(msg);
			return false;
		}
		return true;
	},

	/*
	Function: validateConfirm
		Private method
		
		Perform confirm validations
	*/
	validateConfirm: function(el,ruleArgs) {
		
		var confirm = ruleArgs[0];
		if(el.value != this.form[confirm].value){
			if (this.options.display.titlesInsteadNames)
				var msg = this.options.alerts.confirm.replace("%0",this.form[confirm].getProperty('title'));
			else
				var msg = this.options.alerts.confirm.replace("%0",confirm);
			el.errors.push(msg);
			return false;
		}
		return true;
	},
	
	/*
	Function: validateDiffers
		Private method
		
		Perform differs validations
	*/
	validateDiffers: function(el,ruleArgs) {
		var differs = ruleArgs[0];
		if(el.value == this.form[differs].value){
			if (this.options.display.titlesInsteadNames)
				var msg = this.options.alerts.differs.replace("%0",this.form[differs].getProperty('title'));
			else
				var msg = this.options.alerts.differs.replace("%0",differs);
			el.errors.push(msg);
			return false;
		}
		return true;
	},
	
	/*
	Function: validateWords
		Private method
		
		Perform word count validation
	*/
	validateWords: function(el,ruleArgs) {
		var min = ruleArgs[0];
		var max = ruleArgs[1];
		
		var words = el.value.replace(/[ \t\v\n\r\f\p]/m, ' ').replace(/[,.;:]/g, ' ').clean().split(' ');
		
		if(max == -1) {
			if(words.length < min) {
				el.errors.push(this.options.alerts.words_min.replace("%0", min).replace("%1", words.length));
				return false;
			}
		} else {
			if(min > 0)	{
				if(words.length < min || words.length > max) {
					el.errors.push(this.options.alerts.words_range.replace("%0", min).replace("%1", max).replace("%2", words.length));
					return false;
				}
			} else {
				if(words.length > max) {
					el.errors.push(this.options.alerts.words_max.replace("%0", max).replace("%1", words.length));
					return false;
				}
			}
		}
		return true;
	},


	/*
	Function: isFormValid
		public method
		
		Determine if the form is valid
		
		Return true or false
	*/
    isFormValid: function() {
		this.form.isValid = true;
		this.validations.each(function(el) {
			var validation = this.manageError(el,'testonly');
			if(!validation) this.form.isValid = false;
		}, this);
		return this.form.isValid;
	},
	
	/*
	Function: isChildType
		Private method
		
		Determine if the field is a group of radio or not.
	*/
	isChildType: function(el) {
		return ($defined(el.type) && el.type == 'radio') ? true : false;
	},
	
	/*
	Function: validateGroup
		Private method
		
		Perform radios validations
	*/
	validateGroup : function(el) {
		el.errors = [];
		var nlButtonGroup = this.form[el.getProperty("name")];
		el.group = nlButtonGroup;
		var cbCheckeds = false;
		
		for(var i = 0; i < nlButtonGroup.length; i++) {
			if(nlButtonGroup[i].checked) {
				cbCheckeds = true;
			}
		}
		if(cbCheckeds == false) {
			el.errors.push(this.options.alerts.radios);
			return false;
		} else {
			return true;	
		}
	},
	
	/*
	Function: listErrorsAtTop
		Private method
		
		Display errors
	*/
	listErrorsAtTop : function(obj) {
		if(!this.form.element) {
			 this.form.element = new Element('div', {'id' : 'errorlist', 'class' : this.options.errorClass}).injectTop(this.form);
		}
		if ($type(obj) == 'collection') {
			new Element('p').set('html',"<span>" + obj[0].name + " : </span>" + obj[0].errors[0]).injectInside(this.form.element);
		} else {
			if ((obj.validation.contains('required') && obj.errors.length > 0) || (obj.errors.length > 0 && obj.value && obj.validation.contains('required') == false)) {
				obj.errors.each(function(error) {
					new Element('p').set('html',"<span>" + obj.name + " : </span>" + error).injectInside(this.form.element);
				}, this);
			}
		}
		window.fireEvent('resize');
	},
	
	/*
	Function: manageError
		Private method
		
		Manage display of errors boxes
	*/
	manageError : function(el, method) {
		var isValid = this.validate(el);
		if (method == 'testonly') return isValid;
		if ((!isValid && el.validation.flatten()[0].contains('confirm[')) || (!isValid && el.validation.contains('required')) || (!el.validation.contains('required') && el.value && !isValid)) {
			if(this.options.display.listErrorsAtTop == true && method == 'submit')
				this.listErrorsAtTop(el);
			if (this.options.display.indicateErrors == 2 ||this.alreadyIndicated == false || el.name == this.alreadyIndicated.name)
			{
				if(!this.firstError) this.firstError = el;
				
				this.alreadyIndicated = el;
				
				if (this.options.display.keepFocusOnError && el.name == this.firstError.name) (function(){el.focus()}).delay(20);
				this.addError(el);
				return false;
			}
		} else if ((isValid || (!el.validation.contains('required') && !el.value))) {
			this.removeError(el);
			return true;
		}
		return true;
	},
	
	/*
	Function: addError
		Private method
		
		Add error message
	*/
	addError : function(obj) {
		//determine position
		var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
		
		if(!obj.element && this.options.display.indicateErrors != 0) {
			if (this.options.display.errorsLocation == 1) {
				var pos = (this.options.display.tipsPosition == 'left') ? coord.left : coord.right;
				var options = {
					'opacity' : 0,
					'position' : 'absolute',
					'float' : 'left',
					'left' : pos + this.options.display.tipsOffsetX,
					'z-Index' : 900
				}
				obj.element = new Element('div', {'class' : this.options.tipsClass, 'styles' : options}).injectInside(document.body);
				this.addPositionEvent(obj);
			} else if (this.options.display.errorsLocation == 2){
				obj.element = new Element('div', {'class' : this.options.errorClass, 'styles' : {'opacity' : 0}}).injectBefore(obj);
			} else if (this.options.display.errorsLocation == 3){
				obj.element = new Element('div', {'class' : this.options.errorClass, 'styles' : {'opacity' : 0}});
				if ($type(obj.group) == 'object' || $type(obj.group) == 'collection')
					obj.element.injectAfter(obj.group[obj.group.length-1]);
				else
					obj.element.injectAfter(obj);
			}
		}					
		if (obj.element && obj.element != true) {
			obj.element.empty();
			if (this.options.display.errorsLocation == 1) {
				var errors = [];
				obj.errors.each(function(error) {
					errors.push(new Element('p').set('html', error));
				});
				var tips = this.makeTips(errors).injectInside(obj.element);
				if(this.options.display.closeTipsButton) {
					tips.getElements('a.close').addEvent('mouseup', function(){
						this.removeError(obj, 'tip');
					}.bind(this));
				}
				obj.element.setStyle('top', coord.top - tips.getCoordinates().height + this.options.display.tipsOffsetY);
			} else {
				obj.errors.each(function(error) {
					new Element('p').set('html',error).injectInside(obj.element);
				});
			}
			
			if (!this.options.display.fadeDuration || Browser.Engine.trident && Browser.Engine.version == 5 && this.options.display.errorsLocation < 2) {
				obj.element.setStyle('opacity', 1);
			} else {
				obj.fx = new Fx.Tween(obj.element, {
					'duration' : this.options.display.fadeDuration,
					'ignore' : true,
					'onStart' : function(){
						this.fxRunning = true;
					}.bind(this),
					'onComplete' : function() {
						this.fxRunning = false;
						if (obj.element && obj.element.getStyle('opacity').toInt() == 0) {
							obj.element.destroy();
							obj.element = false;
						}
					}.bind(this)
				})
				if(obj.element.getStyle('opacity').toInt() != 1) obj.fx.start('opacity', 1);
			}
		}
		if (this.options.display.addClassErrorToField && this.isChildType(obj) == false){
			obj.addClass(this.options.fieldErrorClass);
			obj.element = obj.element || true;
		}
			
	},
	
	/*
	Function: addPositionEvent
		
		Update tips position after a browser resize
	*/
	addPositionEvent : function(obj) {
		if(this.options.display.replaceTipsEffect) {
			obj.event = function(){
				var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
				new Fx.Morph(obj.element, {
					'duration' : this.options.display.fadeDuration
				}).start({ 
					'left':[obj.element.getStyle('left'), coord.right + this.options.display.tipsOffsetX],
					'top':[obj.element.getStyle('top'), coord.top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY]
				});
			}.bind(this);
			
		} else {
			obj.event = function(){
				var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
				obj.element.setStyles({ 
					'left':coord.right + this.options.display.tipsOffsetX,
					'top':coord.top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY
				});
			}.bind(this)
		}
		window.addEvent('resize', obj.event);
	},
	
	/*
	Function: removeError
		Private method
		
		Remove the error display
	*/
	removeError : function(obj, method) {
		if ((this.options.display.addClassErrorToField && !this.isChildType(obj) && this.options.display.removeClassErrorOnTipClosure) || (this.options.display.addClassErrorToField && !this.isChildType(obj) && !this.options.display.removeClassErrorOnTipClosure && method != 'tip'))
			obj.removeClass(this.options.fieldErrorClass);

		if (!obj.element) return;
		this.alreadyIndicated = false;
		obj.errors = [];
		obj.isOK = true;
		window.removeEvent('resize', obj.event);
		if (this.options.display.errorsLocation >= 2 && obj.element) {
			new Fx.Tween(obj.element, {
				'duration': this.options.display.fadeDuration
			}).start('height', 0);
		}
		if (!this.options.display.fadeDuration || Browser.Engine.trident && Browser.Engine.version == 5 && this.options.display.errorsLocation == 1 && obj.element) {
			this.fxRunning = true;
			obj.element.destroy();
			obj.element = false;
			(function(){this.fxRunning = false}.bind(this)).delay(200);
		} else if (obj.element && obj.element != true) {
			obj.fx.start('opacity', 0);
		}
	},
	
	/*
	Function: focusOnError
		Private method
		
		Create set the focus to the first field with an error if needed
	*/
	focusOnError : function (obj) {
		if (this.options.display.scrollToFirst && !this.alreadyFocused && !this.isScrolling) {
			if (!this.options.display.indicateErrors || !this.options.display.errorsLocation) {
				var dest = obj.getCoordinates().top-30;
			} else if (this.alreadyIndicated.element) {
				switch (this.options.display.errorsLocation){
					case 1 : 
						var dest = obj.element.getCoordinates().top;
						break;
					case 2 :
						var dest = obj.element.getCoordinates().top-30;
						break;
					case 3 :
						var dest = obj.getCoordinates().top-30;
						break;
				}
				this.isScrolling = true;
			}
			if (window.getScroll.y != dest) {
				new Fx.Scroll(window, { duration:"long",
					onComplete : function() {
						this.isScrolling = false;
						if (obj.getProperty('type') != 'hidden') obj.focus();
					}.bind(this)
				}).start(0,dest);
			} else {
				this.isScrolling = false;
				obj.focus();
			}
			this.alreadyFocused = true;
		}
	},
	
	/*
	Function: fixIeStuffs
		Private method
		
		Fix png for IE6
	*/
	fixIeStuffs : function () {
		if (Browser.Engine.trident4) {
			//We fix png stuffs
			var rpng = new RegExp('url\\(([\.a-zA-Z0-9_/:-]+\.png)\\)');
			var search = new RegExp('(.+)formcheck\.css');
			for (var i = 0; i < document.styleSheets.length; i++){
				if (document.styleSheets[i].href.match(/formcheck\.css$/)) {
					var root = document.styleSheets[i].href.replace(search, '$1');
					var count = document.styleSheets[i].rules.length;
					for (var j = 0; j < count; j++){
						var cssstyle = document.styleSheets[i].rules[j].style;
						var bgimage = root + cssstyle.backgroundImage.replace(rpng, '$1');
						if (bgimage && bgimage.match(/\.png/i)){
							var scale = (cssstyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
							cssstyle.filter =  'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src=\'' + bgimage + '\', sizingMethod=\''+ scale +'\')';
							cssstyle.backgroundImage = "none";
						}
					}
				}
			}
		}
	},
	
	/*
	Function: makeTips
		Private method
		
		Create tips boxes
	*/
	makeTips : function(txt) {
		var table = new Element('table');
			table.cellPadding ='0';
			table.cellSpacing ='0';
			table.border ='0';
			
			var tbody = new Element('tbody').injectInside(table);
				var tr1 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'tl'}).injectInside(tr1);
					new Element('td', {'class' : 't'}).injectInside(tr1);
					new Element('td', {'class' : 'tr'}).injectInside(tr1);
				var tr2 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'l'}).injectInside(tr2);
					var cont = new Element('td', {'class' : 'c'}).injectInside(tr2);
						var errors = new Element('div', {'class' : 'err'}).injectInside(cont);
						txt.each(function(error) {
							error.injectInside(errors);
						});
						if (this.options.display.closeTipsButton) new Element('a',{'class' : 'close'}).injectInside(cont);
					new Element('td', {'class' : 'r'}).injectInside(tr2);
				var tr3 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'bl'}).injectInside(tr3);
					new Element('td', {'class' : 'b'}).injectInside(tr3);
					new Element('td', {'class' : 'br'}).injectInside(tr3);			
		return table;
	},
	
	/*
	Function: reinitialize
		Reinitialize form before submit check. You can use this also to remove all tips from a form, passing the argument "forced" ( formcheck.reinitialize('forced'); )
	*/
	reinitialize: function(forced) {
		this.validations.each(function(el) {
			if (el.element) {
				el.errors = [];
				el.isOK = true;
				if(this.options.display.flashTips == 1 || forced == 'forced') {
					el.element.destroy();
					el.element = false;
				}
			}
		}, this);
		if (this.form.element) this.form.element.empty();
		this.alreadyFocused = false;
		this.firstError = false;
		this.elementToRemove = this.alreadyIndicated;
		this.alreadyIndicated = false;
		this.form.isValid = true;
	},	
	submitByAjax: function() {
		var url = this.form.getProperty('action');
		this.fireEvent('ajaxRequest');
		new Request({
			url: url,
			method: this.form.getProperty('method'),
			data : this.form.toQueryString(),
			evalScripts: this.options.ajaxEvalScripts,
			onFailure: function(instance){
				this.fireEvent('ajaxFailure', instance);
			}.bind(this),
			onSuccess: function(result){
				this.fireEvent('ajaxSuccess', result);
				if(this.options.ajaxResponseDiv) $(this.options.ajaxResponseDiv).set('html',result);
			}.bind(this)
		}).send();
	},
	onSubmit: function(event) {
		this.reinitialize();
		this.fireEvent('onSubmit');
		
		this.validations.each(function(el) {
			var validation = this.manageError(el,'submit');
			if(!validation) this.form.isValid = false;
		}, this);
	    
		if (this.form.isValid) {
			if (this.options.submitByAjax) {
				new Event(event).stop();
				this.submitByAjax();
			} else if(!this.options.submit) {
				new Event(event).stop();
			}
			this.fireEvent('validateSuccess');
			return true;
		} else {
			new Event(event).stop();
			if (this.elementToRemove && this.elementToRemove != this.firstError && this.options.display.indicateErrors == 1) {
				this.removeError(this.elementToRemove);
			}
			this.focusOnError(this.firstError);
			this.fireEvent('validateFailure');
			return false;
		}
	}
});

var Contador= new Class({
	Implements : Options,
	options:{
		a:"",
		maximo :400,
		mensaje:"",
		estiloMensaje:"",
		mensajeEn:"",
		colorEfecto1:"#7D4D25",
		colorEfecto2:"#FFFFFF"
		
	},
	initialize:function(options){		
		this.setOptions(options);
		this.options.mensaje="Count (m&aacute;x "+ this.options.maximo +")";
		var el=this.options.a;
		msg= new Element("span",{
			id:'___moo___conta__'+this.options.a,
			html:this.options.mensaje,
			'class':this.options.estiloMensaje
		});
		if(this.options.mensajeEn){
			$(this.options.mensajeEn).set("html",this.options.mensaje);
		}else{
			$(msg).injectAfter(this.options.a);
		}
		
		if($(this.options.a)){
			$(this.options.a)
			.addEvent("keyup",function(){
					var actual=this.options.maximo - ($(this.options.a).value.length).toInt();
				if(actual>=0){
					this.options.mensaje="Count (m&aacute;x "+actual+")";
					if(this.options.mensajeEn!=""){
						$(this.options.mensajeEn).set("html",this.options.mensaje);
					}else{
						$('___moo___conta__'+this.options.a).set("html",this.options.mensaje);
					}
				}else{
					$(this.options.a).highlight(this.options.colorEfecto1,this.options.colorEfecto2);
					value=$(this.options.a).get("value");
					if(value.length > this.options.maximo){
							value =  value.substring(0, this.options.maximo);
						$(this.options.a).set('value',value);
					}
					return false;
				}
			}.bind(this));
		}
	}
});


var ACarrusel= new Class({
	Implements : Options,
	contenedor:"",
	options:{
		anchoItem:"",
		altoItem:"",
		ver:2,
		avanze:2,
		anterior:"",
		siguiente:"",
		duracion:0.5,
		auto:"",
		anchoTotal:"",
		transicion:"linear",
		ruedita:"",
		controles:"si"
	},
	anchoTotal:"",
	timer:"",
	hijos:"",
	
	initialize:function (contenedor,options){
		this.setOptions(options);
		this.contenedor=$(contenedor);
		padre=this.contenedor.getParent().getStyle("width");
		var warp= new Element("div",{
			styles:{
				"overflow":"hidden",
				"position":"relative",
				"width":padre
			}
		});
		
		
		if(this.options.ruedita!=""){
			this.contenedor.addEvents({
				"mousewheel":function(e){
					var e = new Event(e).stop();
					if ( e.wheel > 0  ) {
						this.mover("adelante");
					}else{
						this.mover("atras");
					}
				
				}.bind(this)
			});
		}
		this.contenedor.getParent().grab(warp);
		warp.adopt(this.contenedor);
		var ancho=this.contenedor.getParent().getCoordinates();
		if(this.options.anchoItem=="" && this.options.altoItem==""){
			this.options.anchoItem= (ancho.width.toInt()/this.options.ver);
			this.options.altoItem= (ancho.height.toInt()/this.options.ver);
		}
		var nodos=this.contenedor.getChildren();
		this.hijos=nodos;
		this.anchoTotal=this.options.anchoItem * nodos.length;
		this.contenedor.setStyles({"overflow":"hidden","position":"relative","list-style":"none","margin":0,"padding":0,"width":this.anchoTotal });
		this.contenedor.getChildren()
		.setStyles({"float":"left","height":this.options.altoItem,"width":this.options.anchoItem})
		.each(function(e,k){
			//e.set("id","_item_"+(k+1).toInt());
			e.addEvents({
				"mouseenter":function(){
					if(this.options.auto!=""){
						this.detenerAutomovible();
					}
					//e.setStyle("cursor","pointer");
				}.bind(this),
				"mouseleave":function(){
					if(this.options.auto!=""){
						this.automovible();
					}
				}.bind(this)
			});
		}.bind(this));
		
		
		if(this.options.controles=="si"){
			$(this.options.anterior)
			.setStyle("cursor","pointer");
			$(this.options.siguiente)
			.setStyle("cursor","pointer");
			$(this.options.siguiente).
					addEvent("click",function(){
						this.mover("adelante");
				}.bind(this));
				
				$(this.options.anterior).
					addEvent("click",function(){
						this.mover("atras");
				}.bind(this));
		}
		
		if(this.options.auto!=""){
				this.automovible();
		}
	},
	automovible:function(){
		this.timer=this.mover.periodical(this.options.auto * 1000,this,["adelante"]);
	},
	detenerAutomovible:function(){
		$clear(this.timer);
	},
	mover:function(direccion){	
			
			if(direccion=="adelante"){
				actual=this.contenedor.getStyle("margin-left").toInt();
				this.contenedor.set("morph",{
					duration:this.options.duracion * 1000,wait:true,transition:this.options.transicion,
					onStart:function(){
						itemactual= - (this.contenedor.getStyle("margin-left").toInt());//this.anchoTotal
						aver=(itemactual/this.options.anchoItem)+1;
						if(aver>(this.hijos.length-this.options.avanze)){
							this.contenedor.get("morph").cancel();
							this.moverAlPrimero();
							return false;
						}
					}.bind(this)
				});
				this.contenedor.morph({
					"margin-left":  (actual - this.options.anchoItem * this.options.avanze)
					//"opacity" : [0.5,1]
				});
				
			}else if (direccion="atras"){
				actual=this.contenedor.getStyle("margin-left").toInt();
				this.contenedor.set("morph",{duration:this.options.duracion * 1000,wait:true,transition:this.options.transicion,
					onStart:function(){
						itemactual=(this.contenedor.getStyle("margin-left").toInt());//this.anchoTotal
						if(itemactual==0){
							this.contenedor.get("morph").cancel();
							return false;
						}
					}.bind(this)
				});
				this.contenedor.morph({
					"margin-left":  (actual + this.options.anchoItem * this.options.avanze)
					//"opacity" : [0.5,1]
				});
			}
	},
	moverAlPrimero:function(index){
		this.contenedor.set("morph",{duration:this.options.duracion * 1000,wait:true,transition:this.options.transicion});
		this.contenedor.morph({
			"margin-left":  0
			//"opacity" : [0.5,1]
		})
	}
});



var ImageZoom = new Class({
	Implements:Events,
	initialize: function(){
		this.generate();
	},
	generate:function(){
		this.zoomSize = 1.1; // x2 the size of the thumbnail
		
		this.thumb_url = $('foto_producto').getElement('a');
		this.thumb_image = this.thumb_url.getElement('img');
		
		this.thumbnail = new Asset.image( this.thumb_image.get('src'),{
			onload: function(){
				$('foto_producto').empty();
				this.thumbnail.setStyles({
					width:287,
					height:423
				});
				this.thumbnail.inject('foto_producto');
				this.generateZoomer( new Hash({ x:this.thumbnail.width , y:this.thumbnail.height }) );
			}.bind(this)
		});		
	},
	generateZoomer: function( thumb_size ){
		this.setDimensions('foto_producto',thumb_size.x,thumb_size.y);
		this.setDimensions('zoomer_big_container',thumb_size.x*this.zoomSize,thumb_size.y*this.zoomSize);
		
		this.bigImage = new Asset.image( this.thumb_url.get('href'), {
			id:'zoomer_image',
			onload: function(){				
				this.bigImage.inject('zoomer_big_container');
				/* determine the proportions between the thumbnail and the zoomed image*/
				var ratioX = this.bigImage.width/thumb_size.x;
				var ratioY = this.bigImage.height/thumb_size.y;
				/* set the size of the zoomed area on thumbnail */
				var regionWidth = (thumb_size.x/ratioX).toInt()*this.zoomSize;
				var regionHeight = (thumb_size.y/ratioY).toInt()*this.zoomSize;				
				new Element('div', {
					id: 'zoomer_region',
					styles: {
						'width': regionWidth,
						'height': regionHeight,
						'opacity': 0
					}
				}).injectInside('foto_producto');
				
				 if (Browser.Engine.trident) {
                        $('zoomer_region').setStyle("cursor", "url(images/zoomin.cur),move");
                 }else {
                        $('zoomer_region').setStyle("cursor", "url(images/zoomin.cur),move");
                 }
				
				/* move the zoomed image when the zoomer region is dragged on the thumbnail */
				new Drag('zoomer_region', {
					modifiers: {x: 'left', y: 'top'},
					grid:1,
					limit: {x:[0,(thumb_size.x - regionWidth)], y:[0, (thumb_size.y-regionHeight)]},
					onDrag: function(el){
						/* get the zoomed position on thumbnail */
						var pos = el.getPosition('foto_producto');
						/* calculate where the zoomed image should be positioned */
						var calcLeft = -(pos.x*ratioX);
						var calcTop = -(pos.y*ratioY);
						/* set a few conditions in case the ratio between the thumbnail and the zoomed image is a float number */
						var bigImgLeft = this.bigImage.width - (thumb_size.x*this.zoomSize);
						var bigImgTop = this.bigImage.height - (thumb_size.y*this.zoomSize);						
						var left = (-calcLeft) > bigImgLeft ? -bigImgLeft : calcLeft;
						var top = (-calcTop) > bigImgTop ? -bigImgTop : calcTop;
						/* set the position of the zoomed image according to the position of the zoomed area on thumbnail */
						this.setPosition('zoomer_image',left,top);
					}.bind(this)
				});	
				
				
				$('zoomer_region').addEvents({
					"mouseenter":function(){
						$('zoomer_big_container').fade("in");
					},
					"mouseleave":function(){
						$('zoomer_big_container').fade("out");
					}
				});
			
				$('foto_producto').addEvents({
					"mouseenter":function(){
						$('zoomer_big_container').fade("in");
					},
					"mouseleave":function(){
						$('zoomer_big_container').fade("out");
					},
					"mousemove":function(e){
						el=$('zoomer_region');
						pos=e.page;
						//var pos = el.getPosition('foto_producto');
						/* calculate where the zoomed image should be positioned */
						var calcLeft = -(pos.x*ratioX);
						var calcTop = -(pos.y*ratioY);
						/* set a few conditions in case the ratio between the thumbnail and the zoomed image is a float number */
						var bigImgLeft = this.bigImage.width - (thumb_size.x*this.zoomSize);
						var bigImgTop = this.bigImage.height - (thumb_size.y*this.zoomSize);						
						var left = (-calcLeft) > bigImgLeft ? -bigImgLeft : calcLeft;
						var top = (-calcTop) > bigImgTop ? -bigImgTop : calcTop;
						/* set the position of the zoomed image according to the position of the zoomed area on thumbnail */
						this.setPosition('zoomer_image',left,top);
					}.bind(this)
				});
			
				
				/* drag directly on the zoomed image. Also updates the zoomed region on the thumbnail */				
				this.DragBig = new Drag('zoomer_image',{
					modifiers: {x:'left',y:'top'},
					grid:1,
					onDrag: function(elem){
						var pos = elem.getPosition('zoomer_big_container');
						var left = pos.x;
						var top = pos.y;
						/* if the zoomed image is dragged outside boundaries, set the correct position */
						if(	pos.x>0 || pos.y>0 || -pos.x > this.bigImage.width-(thumb_size.x*this.zoomSize) || -pos.y > this.bigImage.height-(thumb_size.y*this.zoomSize)){							
							if(pos.x > 0) left = 0;
							if(pos.y > 0) top = 0;
							if ( -pos.x > this.bigImage.width-(thumb_size.x*this.zoomSize) ) left = -1*(this.bigImage.width-(thumb_size.x*this.zoomSize));
							if( -pos.y > this.bigImage.height-(thumb_size.y*this.zoomSize) ) top = -1*(this.bigImage.height-(thumb_size.y*this.zoomSize));
							
							this.setPosition('zoomer_image',left,top);					
						};
						/* moves the zoomed region on thumbnail according to the position of the zoomed image */
						this.setPosition('zoomer_region',-(left/ratioX),-(top/ratioY));						
					}.bind(this)
				})				
			}.bind(this)
		});		
	},
	
	setDimensions: function(element,width,height){
		$(element).setStyles({
			'width':width,
			'height':height
		});
	},
	
	setPosition: function(element,left,top){
		$(element).set({
			styles:{
				'left': left,
				'top':top
			}
		})
	},
	reinitialize:function(){
		this.generate();
	}
});

var Etnico= new Petnico();










