// Libería AxtroScripts con funcionalidades y comportamientos para hacer las webs más dinámicas
// Usos:
//			<a href="url" class="refresh_image busyid_xxx"> -> Cambia la imagen con id xxx por la obtenida en 
//                                                      la url pasada en href. Muestra un cargando...
//
//			<a href="url" class="refresh_html busyid_xxx"> -> Cambia el contenido html de xxx por la  
//                                                      respuesta obtenida en la url pasada en 
//																											 href. Muestra un cargando...

//#################################################################
// El objeto tools define una serie de utilidades que se pueden utilizar de forma sencilla por el resto de 
// las clases. Como fix_ie_png que soluciona el problema de la transparencia de las imagenes PNG
//#################################################################

function hide_notice() {
        new Effect.Fade("notices_");
}


var Tools = {
	fix_ie_png: function() {
		if (Prototype.Browser.IE) {
			var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
		  if ((version >= 5.5) && (version < 7)) {
				$$('.ie-fix-opacity').each(function(poElement){
			 		// if IE5.5+ on win32, then display PNGs with AlphaImageLoader
					var cBGImg = poElement.currentStyle.backgroundImage;
					var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));
					poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
					poElement.style.backgroundImage = "none";
		    });
		  }
		}
	}
};

//###############################################################
// RefreshBase Es la clase que define el comportamiento base de los objetos que se refrescan
// vía AJAX. Muestra una capa de cargando para avisar al usuario de que se está realizando algo.
// Esta es la clase base, las clases que se usan son las clases que heredan de esta clase.
//###############################################################

var RefreshBase = Class.create({
  id_destino: "",
  url: "",
  init: function(href, clas) {
    this.url = href;
    var id_dest = clas;
    id_dest = id_dest.gsub(/.*busyid_/, '');
    id_dest = id_dest.gsub(/\s+.*/, '');
    this.id_destino = id_dest;
  },
  crea_capas: function() {
  	var transparent_layer = $div();
  	transparent_layer.setAttribute("id", "transparent_layer_busy");
  	destino = $(this.id_destino);
  	var offsets = destino.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = destino.clientWidth;
    var height  = destino.clientHeight;
  	transparent_layer.setStyle({
  		position: "absolute",
  		top: top+'px',
  		left: left+'px',
  		width: width+'px',
  		height: height+'px',
  		backgroundColor: '#000000'
  	});
		transparent_layer.setOpacity(0);
  	destino.up(0).appendChild(transparent_layer);
  	new Effect.Opacity(transparent_layer, {duration:0.5, from:0, to:0.6});
  	
  	// Creamos la imagen de cargando
  	img1 = $img();
  	img1.setAttribute("id", "img1_busy");
  	img1.setAttribute("src", "/images/ajax-loader-back.png");
  	img1.setAttribute("class", "ie-fix-opacity");
   	img1.setStyle({
  		position: "absolute",
  		top: top+'px',
  		left: left+'px',
  		marginLeft: Math.round((width/2 - 25))+'px',
  		marginTop: Math.round((height/2 - 25))+'px'
  	});
  	img2 = $img();
  	img2.setAttribute("id", "img2_busy");
  	img2.setAttribute("src", "/images/ajax-loader.gif");
   	img2.setStyle({
  		position: "absolute",
  		top: top+'px',
  		left: left+'px',
  		marginLeft: Math.round((width/2 - 15))+'px',
  		marginTop: Math.round((height/2 - 15))+'px'
  	});
  	
  	img1.setOpacity(0);
  	img2.setOpacity(0);
  	transparent_layer.up(0).appendChild(img1);
  	transparent_layer.up(0).appendChild(img2);
  	Tools.fix_ie_png();
  	new Effect.Opacity(img1, {duration:0.5, from:0, to:1});
  	new Effect.Opacity(img2, {duration:0.8, from:0, to:1});  	
  },
  elimina_capas: function() {
    img1 = $("img1_busy");
    img2 = $("img2_busy");
    transparent_layer = $("transparent_layer_busy");
  	new Effect.Opacity(img1, {duration:0.8, from:1, to:0});
  	new Effect.Opacity(img2, {duration:0.5, from:1, to:0});
  	new Effect.Opacity(transparent_layer, {duration:0.8, from:1, to:0, afterFinish: (new RefreshBase()).remove_layers});
  },
  remove_layers: function(e) {
  	img1 = $("img1_busy");
    img2 = $("img2_busy");
    transparent_layer = $("transparent_layer_busy");
  	img1.remove();
  	img2.remove();
  	transparent_layer.remove();
  }
});


//###############################################################
// RefreshImageContent Permite refrescar objetos tipo imagen
//###############################################################

var RefreshImageContent = Behavior.create({
  _refresh_base: null,
  initialize: function() {
    this._refresh_base = new RefreshBase();
    this._refresh_base.init(this.element.readAttribute('href'), this.element.readAttribute("class"));
  },
  onclick: function(e) {
  	Event.stop(e);
  	if ($('transparent_layer_busy') == null) {
  	  this._refresh_base.crea_capas();  	
  	}
  	this.llamada_ajax();
  },
  llamada_ajax: function() {
  	var newImage 	= null;
		newImage 		= new Image();
		newImage.src 	= this._refresh_base.url;
		newImage.id = "imagen_principal";

		// image is in cache (IE6 & IE7 ... Firefox can handle the onload well even file was in cache);
		if (newImage.complete) {
			$("imagen_principal").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
		} else {
			newImage.onload = function() {
				$("imagen_principal").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"));
				}
			}.bind(this);
		}
  }
});

//###############################################################
// RefreshHtmlContent Permite refrescar cualquier elemento con html
//###############################################################
var RefreshHtmlContent = Behavior.create({
  _refresh_base: null,
  initialize: function() {
    this._refresh_base = new RefreshBase();
    this._refresh_base.init(this.element.readAttribute('href'), this.element.readAttribute("class"));
  },
  onclick: function(e) {
  	Event.stop(e);
  	if ($('transparent_layer_busy') == null) {
  	  this._refresh_base.crea_capas();  	
  	}
  	this.llamada_ajax();
  },
  llamada_ajax: function() {
  	new Ajax.Updater(this._refresh_base.id_destino, this._refresh_base.url, {
			onComplete: this._refresh_base.elimina_capas
		});
  }
});


//###############################################################
//###############################################################
//###############################################################
//###############################################################
// Comportamientos
//###############################################################

Event.addBehavior({
  '.refresh_image': RefreshImageContent(),
  '.refresh_html': RefreshHtmlContent()
});


