/* LibJS Ilunabar 2.3.0 */

// Creamos el objeto ilunabar
var ilunabar = {conf: {}};

// En raras ocasiones necesitamos saber cual de los IE nos da por el culo
ilunabar.isIE7 = (/MSIE (\d+\.\d+);/.test(navigator.userAgent))? ((Number(RegExp.$1) == 7)? true : false) : false;
ilunabar.isIE8 = (/MSIE (\d+\.\d+);/.test(navigator.userAgent))? ((Number(RegExp.$1) == 8)? true : false) : false;
ilunabar.isIE9 = (/MSIE (\d+\.\d+);/.test(navigator.userAgent))? ((Number(RegExp.$1) == 9)? true : false) : false;

// Incorpora a window funciones para ejecutar con window.onload
ilunabar.loadEvent = function (fnc) {
  if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('load', fnc, false);
  } else {
    if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onload', fnc);
    }
  }
};

// Equivalente a Element.observe de prototype, es un experimento
ilunabar.observe = function (element, event, fnc) {
  if (typeof window.addEventListener != 'undefined') {
    element.addEventListener(event, fnc, false);
  } else {
    if (typeof window.attachEvent != 'undefined') {
      element.attachEvent('on'+event, fnc);
    }
  }
};

// Redirigimos a la URL indicada
ilunabar.redirect = function (url) {window.location = url;};

// Tomamos el texto del nodo y todos sus hijos
ilunabar.getText = function(element) {
  return $A($(element).childNodes).collect(function(node) {
    return ((node.nodeType == 3)? node.nodeValue : (node.hasChildNodes() ? ilunabar.getText(node) : ''));
  }).flatten().join('');
};

// Obtenemos la posición X e Y de un elemento
ilunabar.getXY = function (id) {
  var obj = document.getElementById(id);
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return [curleft,curtop];
};

// Obtenemos las dimensiones de la ventana
ilunabar.getWindowSize = function () {
  var width, height;
  this.width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
  this.height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
  return this;
};

// Efecto rollover con fade para imagenes, afecta a cualquier imagen que coincida con el selector
// ilunabar.rollOver({selector: '._rollOver', tiempo: 0.5, sufijo: '-hover'});
ilunabar.rollOver = function (params) {
  var imagenes = $$(params.selector);
  for (var i = 0; i < imagenes.length; i++) {
    var src = imagenes[i].readAttribute('src').match(/^(.*)(\.\w+)$/);
    src = src[1]+params.sufijo+src[2];
    var contenedor = new Element('span');
    var position = imagenes[i].getStyle('position') || 'relative';
    var top = imagenes[i].getStyle('top') || 0;
    var left = imagenes[i].getStyle('left') || 0;
    var zIndex = imagenes[i].getStyle('z-index') || 0;
    var display = (ilunabar.isIE7)? 'inline' : 'inline-block';
    contenedor.setStyle({position: position, top: top, left: left, zIndex: zIndex, display: display, background: 'url('+src+') no-repeat top left'});
    imagenes[i].insert({before: contenedor});
    contenedor.insert({top: imagenes[i]});
    imagenes[i].setStyle({position: 'relative', top: 0, left: 0});

    imagenes[i].observe('mouseover', function (evento) {
      this.observe('mouseout', function (evento) {
        new Effect.Opacity(this, {from: 0.0, to: 1.0, duration: params.tiempo});
      });
      new Effect.Opacity(this, {from: 1.0, to: 0.0, duration: params.tiempo});
    });
  }
};

// Efecto rollover con fade para imagenes en un menu, afecta a cualquier imagen que coincida con el selector.
// El idHover siempre esta hover.
// ilunabar.rollOverMenu({selector: '#menu img', tiempo: 0.5, sufijo: '-hover', idHover: 'current'});
ilunabar.rollOverMenu = function (params) {
  var imagenes = $$(params.selector);
  for (var i = 0; i < imagenes.length; i++) {
    var src = imagenes[i].readAttribute('src').match(/^(.*)(\.\w+)$/);
    src = src[1]+params.sufijo+src[2];
    var contenedor = new Element('span');
    var position = imagenes[i].getStyle('position') || 'relative';
    var top = imagenes[i].getStyle('top') || 0;
    var left = imagenes[i].getStyle('left') || 0;
    var zIndex = imagenes[i].getStyle('z-index') || 0;
    var display = (ilunabar.isIE7)? 'inline' : 'inline-block';
    contenedor.setStyle({position: position, top: top, left: left, zIndex: zIndex, display: display, background: 'url('+src+') no-repeat top left'});
    imagenes[i].insert({before: contenedor});
    contenedor.insert({top: imagenes[i]});
    imagenes[i].setStyle({position: 'relative', top: 0, left: 0});

    if (imagenes[i].identify() == params.idHover) {
      new Effect.Opacity(imagenes[i], {from: 1.0, to: 0.0, duration: params.tiempo});
    } else {
      imagenes[i].observe('mouseover', function (evento) {
        this.observe('mouseout', function (evento) {
          new Effect.Opacity(this, {from: 0.0, to: 1.0, duration: params.tiempo});
        });
        new Effect.Opacity(this, {from: 1.0, to: 0.0, duration: params.tiempo});
      });
    }
  }
};

/*
* Event.simulate(@element, eventName[, options]) -> Element
*
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
*
* $('foo').simulate('click'); // => fires "click" event on an element with id=foo
*
*/
(function () {
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }

  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  }

  Event.simulate = function (element, eventName) {
    var options = Object.extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    element = $(element);

    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) {eventType = name; break;}
    }

    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element
        );
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  }

  Element.addMethods({simulate: Event.simulate});
})();

