var Zoomer = Class.create({
	draggable: null,
	_refresh_base: null,
	_owidth: null,
	_oheight: null,
  _container_width: 943,
  _container_height: 382,
	_opened: null,
	initialize: function(){
	},
	
	//abre la ventana de aumento y cambia la imagen del boton que lo activa
	openWindow: function(){
    //desplazamos los elementos para dejar sitio a la ventana de zoom
		$('zoomDesc').morph('padding-top: 393px;', {duration: 0.5});
		$('padding-relacionados').morph('padding-top: 446px;', {duration: 0.5});
	
    // fade out de la foto principal
		new Effect.Opacity($('imagen_principal').parentNode, {from: 1.0, to: 0, duration: 0.3} );
	  // fade in del marco de aumento
		new Effect.Appear('aumento', {duration: 0.8});
		
    //cambiamos la lupa
		$$('.lupaAbrir').each(function(element){
			this.menosButton(element);
		}, this);
		
    //cargamos la imagen
		this.refreshImage();

		//estado de la ventana de aumento
		this._opened = true;
	},
	
 	refreshImage: function(){
		this._refresh_base = new RefreshBase();
		this._refresh_base.set_transparent_layer("transparent_layer_busy2");
		this._refresh_base.init($('imagen_principal').readAttribute('src'), " busyid_imageZoomContainer");
		this._refresh_base.asigna_destino("imageZoomContainer");
		this._refresh_base.asigna_coordenadas("auto",44,957,396);
		
		if ($('transparent_layer_busy2')==null){
			this._refresh_base.crea_capas();
		}
		var newImage 	= null;
		newImage 		= new Image();
		newImage.src 	= this._refresh_base.url.gsub("___tipo=tipo___", "tipo=base");
		newImage.id = "imagenZoom";

		// image is in cache (IE6 & IE7 ... Firefox can handle the onload well even file was in cache);
		if (newImage.complete) {
			$("imagenZoom").replace(newImage);
			this._refresh_base.remove_layers();
			if ($('lupa_refresh_image') != null) {
				$('lupa_refresh_image').setAttribute("href", this._refresh_base.url.gsub("&width", "&wo").gsub("&height", "&ho"));
			}	// image not in cache
			this.updateDraggable();
		}	else {
			newImage.onload = function(){
				$("imagenZoom").replace(newImage);
				this._refresh_base.elimina_capas();
				if ($('lupa_refresh_image') != null) {
					$('lupa_refresh_image').setAttribute("href", this._refresh_base.url.gsub("&width", "&wo").gsub("&height", "&ho"));
				}
				this.updateDraggable();
			}.bind(this);
		}
	},
	
	updateDraggable: function(){


			this.draggable = new Draggable('imagenZoom', 
													{ starteffect: false, 
														endeffect: false, 
														handle: 'handle',
														snap: function(x, y, draggable) {
                        			xoffset_parent =	draggable.element.up(0).clientWidth;
                        			yoffset_parent =	draggable.element.up(0).clientHeight;
                        			half_x_parent = xoffset_parent / 2;
                              half_y_parent = yoffset_parent / 2;
                              width = draggable.element.width;
                              height = draggable.element.height;
                              
                              // si x o y es mas pequeño que el container
                              // los limites son los del container
                              var new_x = x;
                              var new_y = y;
                                                            
/*
                              if (width <= xoffset_parent){
                                // la imagen es mas estrecha
                                new_x = (x < 0 ? 0 : x);
                              }else{
                                // la imagen es mas ancha
	                              var xmax = -(draggable.element.width - xoffset_parent);
	                              new_x = (x > 0 || draggable.element.width < xmax ? 0 : (x < xmax ? xmax : x));
                              }
                              
                              if (height <= yoffset_parent){
                                //la imagen es menos alta
                              }else{
                                //la imagen es mas alta
                              }
                              
                              if (width < xoffset_parent || height < yoffset_parent){
                                return [x, y];
                              }
                              

															var ymax = -(draggable.element.height - yoffset_parent);
                              

															var new_y = (y > 0 || draggable.element.height < ymax ? 0 : (y < ymax ? ymax : y));
//                              var new_x = (x > 0 ? 0 : x);
//                              var new_y = (y > 0 ? 0 : y);
															//(x > 0 ? 0 : x)
															//(y > 0 ? 0 : y)

*/															return [new_x,new_y];
/*
                              var new_x = (x < half_x_parent ? 
                                ( (width + x) < half_x_parent ? -(Math.abs(half_x_parent - width)) : x)
                                : 
                                half_x_parent
                              );
                              
                              var new_y = (y < half_y_parent ? 
                                ( (height + y) < half_y_parent ? -(Math.abs(half_y_parent - height)) : y)
                                : 
                                half_y_parent
                              );
                              return [new_x,new_y];
                              */
										  			}
													} 
												);


 		this._owidth = this.draggable.element.width;
		this._oheight = this.draggable.element.height;		
    this.calculateImageProportions();   
	},
	
  calculateImageProportions: function(){
    var pi = this._owidth / this._oheight;
    var pc = this._container_width / this._container_height;
    
    if (pi > pc){
      //ajustamos con x
      var x = this._container_width;
      var y = Math.round(x * pi);
       
    }else{
      //ajustamos con y
      var y = this._container_height;
      var x = Math.round(y * pi);  
     
    }
	  $('imagenZoom').setStyle({width: x+"px", height: y+"px"});
    this._minWidth = x;
    this._minHeight = y ;
  },
  
	//cierra la ventana de aumento y cambia la imagen del boton que lo activa
	closeWindow: function(){
		
		this.draggable.destroy();
		$('zoomDesc').morph('padding-top: 0px;', {duration: 0.5});
		$('padding-relacionados').morph('padding-top: 0px;', {duration: 0.5});
	
		new Effect.Opacity($('imagen_principal').parentNode, {from: 0, to: 1.0, duration: 0.3} );
		new Effect.Fade('aumento', {duration: 0.5});
		
		$$('.lupaAbrir').each(function(element){
			this.masButton(element);
		}, this);
    
    this._owidth = null;
    this._oheight = null;
		this._opened = false;
	},

	//cambia el boton de lupaMenos a lupaMas
	masButton: function(element){
		element.removeClassName('lupaCerrar');
		element.addClassName('lupaMas');
	},
	//cambia el boton de lupaMas a lupaMenos
	menosButton: function(element){
		element.removeClassName('lupaMas');
		element.addClassName('lupaCerrar');
	},
	
	//aumenta la imagen
	zoomIn: function(){
    var newWidth = $('imagenZoom').width * 1.20;
		var newHeight = $('imagenZoom').height * 1.20;

    if (newWidth < (this._owidth * 2) || newHeight < (this._oheight * 2)) {
      new Effect.Scale($('imagenZoom'), 120, {duration: 0.3});
      new Effect.Move($('imagenZoom'), {x: ($('imagenZoom').width - newWidth)/2, y: ($('imagenZoom').height - newHeight)/2, mode: 'relative', duration:0.3});
    }
	},
	//reduce la imagen
	zoomOut: function(){
		//valores que tendrá la imagen si actualizamos
		var newWidth = $('imagenZoom').width * 0.80;
		var newHeight = $('imagenZoom').height * 0.80;

    if (newWidth > (this._minWidth / 2) || newHeight > (this._minHeight / 2)){
      new Effect.Scale($('imagenZoom'), 80, {duration: 0.3});
      new Effect.Move($('imagenZoom'), {x: ($('imagenZoom').width - newWidth)/2, y: ($('imagenZoom').height - newHeight)/2, mode: 'relative', duration:0.3});
    }

	}
	


});
/* **************** Behaviors ***************** */
// When open/close is clicked
var OpenZoomWindow = Behavior.create({
	zoomer: null,
	initialize: function(zoomer){
		this.zoomer = zoomer;
	},
	onclick: function(e){
		Event.stop(e);

		if (this.element.hasClassName('lupaCerrar')){
			this.zoomer.closeWindow();
		}else{
			this.zoomer.openWindow();
		}
	}
	
});

// When Close Button is clicked
var CloseZoomWindow = Behavior.create({
	zoomer: null,
	initialize: function(zoomer){
		this.zoomer = zoomer;
	},
	
	onclick: function(e){
		Event.stop(e);
		this.zoomer.closeWindow();
	}
});
	
// When a photo is clicked for zooming
var RefreshZoomImage = Behavior.create({
	zoomer: null,
	_refresh_base: null,
	initialize: function(zoomer){
		this.zoomer = zoomer;
		
		this._refresh_base = new RefreshBase();
		this._refresh_base.set_transparent_layer("transparent_layer_busy2");
		this._refresh_base.init(this.element.readAttribute('href'), this.element.readAttribute("class"));
		this._refresh_base.asigna_destino("imageZoomContainer");

	},
	onclick: function(e){
		Event.stop(e);
		
		if (this.zoomer._opened == true){
			
			if ($('transparent_layer_busy2')==null){
				this._refresh_base.crea_capas();
			}
			this.llamada_ajax();
		}
	},

	llamada_ajax: function(){
		var newImage 	= null;
		newImage 		= new Image();
		newImage.src 	= this._refresh_base.url.gsub("___tipo=tipo___", "tipo=base");
		newImage.id = "imagenZoom";

		// image is in cache (IE6 & IE7 ... Firefox can handle the onload well even file was in cache);
		if (newImage.complete) {
			$("imagenZoom").replace(newImage);
			this._refresh_base.remove_layers();
			if ($('lupa_refresh_image') != null) {
				$('lupa_refresh_image').setAttribute("href", this._refresh_base.url.gsub("&width", "&wo").gsub("&height", "&ho"));
			}	// image not in cache
			this.zoomer.updateDraggable();
		}	else {
			newImage.onload = function(){
				$("imagenZoom").replace(newImage);
				this._refresh_base.elimina_capas();
				if ($('lupa_refresh_image') != null) {
					$('lupa_refresh_image').setAttribute("href", this._refresh_base.url.gsub("&width", "&wo").gsub("&height", "&ho"));
				}
				this.zoomer.updateDraggable();
			}.bind(this);
		}
	}
	
});
	

//Aumenta la imagen
var ZoomImage = Behavior.create({
	zoomer: null,
	initialize: function(zoomer){
		this.zoomer = zoomer;
	},
	onclick: function(e){
		Event.stop(e);
		if (this.element.hasClassName("lupaMenos")){
			this.zoomer.zoomOut();	
		}else{
			if (this.element.hasClassName("lupaAbrir") == false){
				this.zoomer.zoomIn();		
			}
		}
	}
});

var EnviaAmigo = Behavior.create({
  id_form: '',
  initialize: function() {
		var idf = this.element.className;
               idf = idf.gsub(/.*id_form_/, '');
               idf = idf.gsub(/\s+.*/, '');
               this.id_form = idf;
     },
     onclick: function(e) {
         Event.stop(e);
         var dialog = new Dialog({

			title: 'Envíaselo a un amigo',

			content: '<form id="formulario_amigo" action="/admin/users/sendmailfriend/'+this.id_form+'">  <div class="minicomment" style="color:#FF0000">* Campos obligatorios</div>          <div class="label"> Tu nombre   <span class="caution">*</span></div>          <div class="input"><input type="text" name="sended_mail[name]" id="sended_mail_name" size="26" /></div>     <div class="label"> Tu dirección de correo electrónico   <span class="caution">*</span></div>          <div class="input"><input type="text" name="sended_mail[mail_sender]" id="sended_mail_mail_sender" size="26" /></div>      <div class="label"> Nombre de tu amigo   <span class="caution">*</span></div>          <div class="input"><input type="text" name="sended_mail[nombre_amigo]" id="sended_mail_nombre_amigo" size="26" /></div>          <div class="explicacion"> Necesario para indicar a tu amigo quién le envía el mensaje  </div>                   <div class="label"> Dirección de correo de tu amigo   <span class="caution">*</span></div>          <div class="input"><input type="text" name="sended_mail[mail_destiny]" id="sended_mail_mail_destiny" size="26" /></div>          <div class="label"> Mensaje   </div>          <div class="input"><textarea name="sended_mail[message]" id="sended_mail_message" cols="36" rows="3"></textarea></div>          <div class="explicacion"> Puedes añadir un pequeño mensaje para tu amigo  </div></form>',

			focus: 'sended_mail_name',
                        width: 317,
			buttons: {

				'OK': function() {
                                          $("formulario_amigo").submit();					
				},

				'Cancel': Dialog.prototype.close

			}

		});
     }
});

/* Adding Behaviors */
	
var zoomer = new Zoomer();
//sobreescribir los behaviors de refresh image
Event.addBehavior({
	'.zoomOpen': OpenZoomWindow(zoomer),
	'.zoomClose': CloseZoomWindow(zoomer),
	'.refresh_image': RefreshZoomImage(zoomer),
	'.lupaMas': ZoomImage(zoomer),
	'.lupaMenos': ZoomImage(zoomer),
        '.envia_amigo_click': EnviaAmigo()
});
