// 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...
//			<a href="url" class="magick_link magickid_xxx"> -> Muestra el contenido html de xxx que estaba
//                                                      escondido, o si estaba visible lo esconde
//      .cached_tabs -> Gestiona páginas de tabs y las cachea. La forma de uso está en la página
//											 de productos de la administración de 3sellers
//      .highlight_content_over .highlight_color_eeeeee -> Hace que el elemento adquiera el color eeeeee o
//													cualquier otro que le pasemos como argumento al poner el raton encima
//#################################################################
// 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";
		    });
		  }
		}
	},
	createCookie: function(name, value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	eraseCookie: function(name) {
		Tools.createCookie(name,"",-1);
	},
        getIdentificador: function(cadena, subcad) {
                var dest = cadena.gsub(new RegExp('.*'+subcad), '');
                dest = dest.gsub(/\s+.*/, '');
                return dest;
        }

};

//###############################################################
// HighlightContent Clase que hace que cuando el ratón pase por encima de algo el color cambie
// al pasado como argumento. Uso .highlight_content_over .highlight_color_FFFF99 hará que al pasar
// el ratón por encima se muestre el color FFFF99
//###############################################################

var HighlightContent = Behavior.create({
  colorTo: '',
  colorFrom: '',
	initialize: function() {
		var color = this.element.className;
    color = color.gsub(/.*highlight_color_/, '');
    color = color.gsub(/\s+.*/, '');
    this.colorTo = color;
    this.colorFrom = this.element.getStyle('background-color');
	},
	onmouseover: function(e) {
	  this.element.morph('background:#'+this.colorTo+';', {duration: 0.1});
	},
	onmouseout: function(e) {
		new Effect.Morph(this.element,{
  			style:'background-color:'+this.colorFrom
		}, {duration: 0.1});
	}
});

//###############################################################
// 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: "",
  with_confirm: false,
  init: function(href, clas) {
    this.url = href;
    var id_dest = clas;
    var with_confirm = id_dest.gsub(/.*with_confir/, '');
    with_confirm = with_confirm.gsub(/\s+.*/, '');
    if (with_confirm == "m") {
        this.with_confirm = true;
    }
    id_dest = id_dest.gsub(/.*busyid_/, '');
    id_dest = id_dest.gsub(/\s+.*/, '');
    this.id_destino = id_dest;
  },
  asigna_destino: function(dest) {
  	this.id_destino = 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();
  }
});

//###############################################################
// InputWindowBase Es una clase que permite crear ventanas para que el usuario introduzca texto simple
//
// ESTA SIN TERMINAR
//###############################################################

var InputWindowBase = Class.create({
  caption: "",
  main_layer_id: "",
  title: "",
  ok: "",
  id_destino: "",
  show: function(options) {
  	this.caption = options.caption;
  	this.title = options.title;
        this.ok = options.ok;
        this.ajax_call = options.ajax_call;
        var ancho = 370;
        var alto = 150;
        if (options.id_destino != null) {
            this.id_destino = options.id_destino;
        }
        if (options.width != null) {
            ancho = options.width;
        }
        if (options.height != null) {
            alto = options.height;
        }
        var ch = ""
        if (options.content_html != null) {
            ch = options.content_html
        }

  	this.build(ancho, alto, ch);
  },
  build: function(width, height, content_html) {
      var transparent_layer = $div();
      transparent_layer.setAttribute("id", "transparent_layer_busy");
      destino = $$("body")[0];
      var offsets = destino.positionedOffset();
      var ttop     = offsets[1];
      var tleft    = offsets[0];
      var twidth   = destino.clientWidth;
      var theight  = destino.clientHeight;
      transparent_layer.setStyle({
          position: "absolute",
          top: ttop+'px',
          left: tleft+'px',
          width: twidth+'px',
          height: theight+'px',
          backgroundColor: '#000000'
      });
      transparent_layer.setOpacity(0);

      var main_layer = $div();
      main_layer.setAttribute("id", "main_layer_xxxxxx");
      main_layer.setAttribute("class", "panel");
      main_layer_id = main_layer.id;
      var clear = $div();
	  clear.setAttribute("class", "clear");
      var cap = $h2();
      cap.innerHTML = this.title;
      main_layer.appendChild(cap);
      var cont = $div();
      cont.setAttribute("class", "panelbig_content");
      cont.setAttribute("id", "contenido_principal");

     var cad_onclick = "";
      var contenido = "";
      if (content_html != "") {
          contenido = content_html;
      }
      else {
          cad_onclick = '$(\'formulario_modal_input\').hide();$(\'loading_formulario_modal_input\').show();new Ajax.Updater(\''+this.id_destino+'\', \''+this.ok+'?input_value=\'+$F(\'input_value\'), {asynchronous:true, evalScripts:true,	onComplete: (new InputWindowBase()).hide()});return false;';
         if (this.ajax_call == null) {
             cad_onclick = '$(\'formulario_modal_input\').hide();$(\'loading_formulario_modal_input\').show();$(\'modal_input\').submit();return false;';
         }
          contenido =  '<div id="formulario_modal_input"><p>'+this.caption+'</p>';
         contenido = contenido + '<form id="modal_input" method="post" action="'+this.ok+'">';
         contenido = contenido + ' <input id="input_value" name="input_value" type="text" size="30" />';
          contenido = contenido + '</form>';
          contenido = contenido + '<div style="padding-left: 10px;">';
          contenido = contenido + '<a class="button" href="#" style="float: left; margin-top: 10px;" onclick="'+cad_onclick+'">ok</a>';
          contenido = contenido + '<a class="button" href="#" style="float: left; margin-left: 10px; margin-top: 10px;" onclick="(new InputWindowBase()).hide();return false;">cancel</a>';
          contenido = contenido + '<div class="clear"></div>';
          contenido = contenido + '</div></div><div id="loading_formulario_modal_input" style="display:none;height:'+height+'px;"><center><img src="/images/loading.gif" align="absmiddle" /></center></div>';
      }
      cont.innerHTML = contenido;

      main_layer.appendChild(cont);

      main_layer.setStyle({
          position: "absolute",
          top: ((document.viewport.getHeight()/2)-(height/2))+'px',
          left: ((document.viewport.getWidth()/2)-(width/2))+'px',
          width: width+'px',
          height: height+'px'
      });
      main_layer.appendChild(clear);
      main_layer.setOpacity(0);
      destino.appendChild(transparent_layer);
      destino.appendChild(main_layer);
      new Effect.Opacity(transparent_layer, {duration:0.3, from:0, to:0.6});
      new Effect.Opacity(main_layer, {duration:0.3, from:0, to:1});
  },
  hide: function() {
    main_layer = $("main_layer_xxxxxx");
	transparent_layer = $('transparent_layer_busy');
  	new Effect.Opacity(main_layer, {duration:0.3, from:1, to:0, afterFinish: this.remove_layers});
	new Effect.Opacity(transparent_layer, {duration:0.3, from:0.6, to:0, afterFinish: this.remove_layers});
  },
  remove_layers: function() {
  	transparent_layer = $('transparent_layer_busy');
    main_layer = $("main_layer_xxxxxx");
  	if (main_layer != null) {
            main_layer.remove();
        }
	if (transparent_layer != null) {
            transparent_layer.remove();
        }
  }
});

//###############################################################
// ConfirmWindow Muestra una simple ventana de confirmación
//###############################################################

var ConfirmWindow = Class.create({
    show: function(options) {
        b = new InputWindowBase();
         cad_onclick = '$(\'formulario_modal_input\').hide();$(\'loading_formulario_modal_input\').show();new Ajax.Updater(\''+options.id_destino+'\', \''+options.ok+'\', {asynchronous:true, evalScripts:true,	onComplete: (new InputWindowBase()).hide()});return false;';
         if (options.ajax_call == null) {
             cad_onclick = '$(\'formulario_modal_input\').hide();$(\'loading_formulario_modal_input\').show();$(\'modal_input\').submit();return true;';
         }
          contenido =  '<div id="formulario_modal_input"><p>'+options.caption+'</p>';
         contenido = contenido + '<form id="modal_input" method="post" action="'+options.ok+'">';
          contenido = contenido + '</form>';
          contenido = contenido + '<div style="padding-left: 10px;">';
          contenido = contenido + '<a class="button" href="#" style="float: left; margin-top: 10px;" onclick="'+cad_onclick+'">ok</a>';
          contenido = contenido + '<a class="button" href="#" style="float: left; margin-left: 10px; margin-top: 10px;" onclick="(new InputWindowBase()).hide();return false;">cancel</a>';
          contenido = contenido + '<div class="clear"></div>';
          contenido = contenido + '</div></div><div id="loading_formulario_modal_input" style="display:none;height:'+125+'px;"><center><img src="/images/loading.gif" align="absmiddle" /></center></div>';
        b.show({title: options.title, content_html: contenido, caption: options.caption, ok: options.ok, height: 125, ajax_call: options.ajax_call, id_destino: options.id_destino});
    }
});

//###############################################################
// 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);
		}
  }
});


//###############################################################
// MagickContent Muestra un contenido que estaba oculto en una capa, esto se puede usar para
// cargar contenido que no es necesario mostrar en un primer momento y que pinchando en un
// simple enlace se desplega
//###############################################################
var MagickContent = Behavior.create({
  id_destino: "",
  my_id: "",
  initialize: function() {
    var id_dest = this.element.readAttribute("class");
    this.my_id = this.element.readAttribute("id"); // Si el identificador de elemento es el mismo
    										// que el de destino el efecto es cerrar la capa

    id_dest = id_dest.gsub(/.*magickid_/, '');
    id_dest = id_dest.gsub(/\s+.*/, '');
    this.id_destino = id_dest;
  },
  onclick: function(e) {
  	Event.stop(e);

  	if ($(this.id_destino).visible()) {
  	  this.esconde_capa();
  	}
  	else {
  		this.muestra_capa();
  	}
  },
  esconde_capa: function() {
  	new Effect.SwitchOff($(this.id_destino), {duration:0.3});
  },
  muestra_capa: function() {
  	new Effect.SlideDown($(this.id_destino), {duration:0.3});
  }
});

//###############################################################
// 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 (this._refresh_base.with_confirm == true) {
          b = new ConfirmWindow();
          b.show({title: "¿Estás seguro?", caption: "¿Estás seguro de querer continuar?", ok: this._refresh_base.url, ajax_call: true, id_destino: this._refresh_base.id_destino});
        } else {
          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, {asynchronous:true, evalScripts:true,	onComplete: function(req) {this._refresh_base.elimina_capas(); Event.addBehavior.reload();}.bind(this)
		});
  }
});

//###############################################################
// CachedTabs Gestiona de forma automática páginas de tabs y las cachea para permitir el cambio
//            entre ellas de forma más eficiente
//###############################################################
var CachedTabs = Behavior.create({
  tabs: null,
  tab : null,
  caddestino : '',
  t_layer : '',
  initialize: function() {
  	// este array contendrá los tabs y el estado de los mismos - ya leidos o no
    this.tabs = new Array();

    x = 0;
    li_items = this.element.down(0);
    // creamos el array de elementos
    while (li_items != null) {
    	this.tabs[x] = {li:li_items, cached:false, index:x, _refresh_base: new RefreshBase()};
    	// En el caso de ser el 'current' lo marcamos como ya leido
    	if (li_items.hasClassName("current")) {
		  	this.tabs[x].cached = true;
		  }
    	this.tabs[x]._refresh_base.init(li_items.down(0).readAttribute('href'),' busyid_'+'div'+li_items.id);
    	// Añadimos el evento de gestión de onclick
    	Event.observe(li_items, 'click', this.click_button.bind(this));
    	li_items = li_items.next();
    	x = x + 1;
    }

  },
  click_button: function(e) {
  	Event.stop(e);
  	var x = 0;
  	var itemx = 0;
  	var tab_a_esconder = this.tabs[0];
  	while (x < this.tabs.size()) {
    	// Este es el tab que se va a ocultar
  	  if (this.tabs[x].li.hasClassName("current")) {
  	  	tab_a_esconder = this.tabs[x];
			  this.tabs[x].li.className = "";
  	  }
  	  // Este es el tab que se va a mostrar
  	  if (e.target.up(1).id==this.tabs[x].li.id) {
  	  	itemx = x;
  	  }
  	  x = x + 1;
  	}
  	// Mostramos el tab
  	e.target.up(1).className = "current";
  	this.muestra_tab(this.tabs[itemx], tab_a_esconder);
  },
  muestra_tab: function(tab, tab_a_esconder) {
    var caddestino = 'div'+tab.li.id;
    var t_layer = 'div'+tab_a_esconder.li.id;
    // Si ya estaba cacheado simplemente cambia la vista, sino hace la llamada ajax
    if (tab.cached == true) {
     $(t_layer).hide();
     $(caddestino).show();
    } else {
    	if ($('transparent_layer_busy') == null) {
    	  tab._refresh_base.asigna_destino(t_layer);
	 	    tab._refresh_base.crea_capas();
  	  }
    	this.llamada_ajax(tab, caddestino, t_layer);
    }
  },
  llamada_ajax: function(tab, caddestino, t_layer) {
  	this.tab = tab;
  	this.caddestino = caddestino;
  	this.t_layer = t_layer;
  	new Ajax.Updater(caddestino, tab._refresh_base.url, {
  		asynchronous:true,
  		evalScripts:true,
			onComplete: function() {
					this.tab.cached=true;
					this.tab._refresh_base.elimina_capas();
					$(this.t_layer).hide();
					$(this.caddestino).show();
			}.bind(this)
		});
  }
});


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

Event.addBehavior({
  '.refresh_image': RefreshImageContent(),
  '.refresh_html': RefreshHtmlContent(),
  '.magick_link': MagickContent(),
  '.highlight_content_over': HighlightContent(),
  '.cached_tabs': CachedTabs()
});
