if (window.attachEvent) try { document.execCommand("BackgroundImageCache", false, true); } catch (e) {};

/**
 * Popup: creates a Popup window.
 * Popups accept all of the normal features of a window.
 */
Popup = Class.create();

Popup.prototype = {
  setOptions: function (options) {
    this.options = Object.extend({
      name        : null,
      center      : false, // centers the popup on the screen
      fillScreen  : false, // opens the browser window to the max (use with caution: can be very irritating)
    // from here on window features.
      width       : null, // width of the popup
      height      : null, // height of the popup
      top         : null, // left position of the popup
      left        : null, // right position of the popup
      location    : 0, // 0: address bar is invisible, 1: address bar is visible
      menubar     : 0, // 0: menu bar is invisible, 1: menu bar is visible (no use on mac browsers)
      resizable   : 1, // 0: popup is not resizable, 1: popup is resizable,
      scrollbars  : 0, // 0: scrollbars are invisible, 1: scrollbars are visible
      status      : 0, // 0: statusbar is invisible, 1: statusbar is visible
      toolbar     : 0, // 0: toolbar is invisible, 1: toolbar is visible
      directories : 0 // 0: bookmarks are invisible, 1: bookmarks are visible (no use on mac browsers)
    }, options || {})
  },
  initialize: function (href, options) {
    if (options.fillScreen) {
      options.width = screen.availWidth;
      options.height = screen.availHeight;
      options.left = 0;
      options.top = 0;
    }
    else if (options.center && options.width && options.height) {
      options.top = (screen.availHeight / 2) - (options.height / 2);
      options.left = (screen.availWidth / 2) - (options.width / 2);
    }
    this.setOptions(options);
    var f = [];
    var features = ['width', 'height','top', 'left', 'location', 'menubar',
      'resizable', 'scrollbars', 'status','toolbar','directories']; // these are all the options that go into the features string
    features.each(function (feature) {
      if (this.options[feature] != null && this.options[feature] != '') f.push(feature + '=' + this.options[feature]);
    }.bind(this));
    return window.open(href, options.name, options.features || f.join(','));
  }
}

/**
 * TabPage: creates a Tab Page.
 */
TabPage = Class.create();

TabPage.prototype = {
  setOptions: function (options) {
    this.options = Object.extend({
      activeTab: 0
    }, options || {});
  },
  initialize: function (container, options) {
    this.setOptions(options);
    this.container = $(container);
    Element.addClassName(this.container, 'TabPage');
    this.tabs = [];
    this.pages = [];
    this.activeTab = this.options.activeTab;
    Element.cleanWhitespace(this.container);
    var element = this.container.firstChild;
    while (element) {
      this.tabs.push(element);
      element = element.nextSibling;
      this.pages.push(element);
      element = element.nextSibling;
    }
    this.tabs.each(function (tab, index) {
      Element.addClassName(tab, "Tab");
      Event.observe(tab, 'click', function () {
        this.activateTab(index);
      }.bindAsEventListener(this));
    }.bind(this));
    this.pages.each(function (page, index) {
      Element.addClassName(page, "Page");
      page.style.display = 'none';
    });
    this.activateTab(this.options.activeTab);

  },
  activateTab: function (index) {
    if (index < this.tabs.length - 1) {
      for (var i=0; i < (this.tabs.length - 1); i++) {
        Element.removeClassName(this.tabs[i], 'Active');
        if (i < this.tabs.length - 1) Element.removeClassName(this.tabs[i+1], 'ActiveBefore')
        if (i > 0) Element.removeClassName(this.tabs[i-1], 'ActiveAfter');
      };
      Element.addClassName(this.tabs[index], 'Active');
      if (index < this.tabs.length) Element.addClassName(this.tabs[index+1], 'ActiveBefore');
      if (index > 0) Element.addClassName(this.tabs[index-1], 'ActiveAfter');

      this.pages[this.activeTab].style.display = 'none';
      this.pages[index].style.display = '';
      this.activeTab = index;
    }
  }
}

/**
 * ModalPopup: creates a Modal Popup frame.
 */
ModalPopup = Class.create();

ModalPopup.prototype = {
  setOptions: function (options) {
    this.options = Object.extend({
      title: null,
      modal: null,
      width: null,
      height: null,
      method: null,
      processScripts: null,
      autoAdjust: null,
      beforeLoad: null,
      afterLoad: null,
      beforeHide: null,
      afterHide: null,
      afterResize: null,
      onShow: null,
      onUpdate: null
    }, options || {})
  },
  initialize: function (url, options) {
    var __title = (typeof options.title) != "undefined" ? options.title : '&nbsp;';
    var __modal = (typeof options.modal) != "undefined" ? options.modal : true;
    var __width = (typeof options.width) != "undefined" ? options.width : 640;
    var __height = (typeof options.height) != "undefined" ? options.height : 480;
    var __method = (typeof options.method) != "undefined" ? options.method : 'get';
    var __processScripts = (typeof options.processScripts) != "undefined" ? options.processScripts : false;
    var __autoAdjust = (typeof options.autoAdjust) != "undefined" ? options.autoAdjust : false;
    var __transitions = (typeof options.transitions) != "undefined" ? options.transitions : true;
    
    var __beforeLoad = (typeof options.beforeLoad) != "undefined" ? options.beforeLoad : null;
    var __afterLoad = (typeof options.afterLoad) != "undefined" ? options.afterLoad : null;
    var __beforeHide = (typeof options.beforeHide) != "undefined" ? options.beforeHide : null;
    var __afterHide = (typeof options.afterHide) != "undefined" ? options.afterHide : null;
    var __afterResize = (typeof options.afterResize) != "undefined" ? options.afterResize : null;
    var __onShow = (typeof options.onShow) != "undefined" ? options.onShow : null;
    var __onUpdate = (typeof options.onUpdate) != "undefined" ? options.onUpdate : null;
    
    Modalbox.show(url, {title: __title, overlayClose: !__modal, slideDownDuration: 0, slideUpDuration: 0,
      width: __width, height: __height, overlayOpacity: 0.5, method: __method, processScripts: __processScripts,
      autoAdjust: __autoAdjust, transitions: __transitions, beforeLoad: __beforeLoad, afterLoad: __afterLoad,
      beforeHide: __beforeHide, afterHide: __afterHide, afterResize: __afterResize, onShow: __onShow,
      onUpdate: __onUpdate});
    if (__transitions) new Draggable('MB_window', {handle: 'MB_header', zindex: 10000});
  }
}

/**
 * Navigation: creates a Navigation.
 */
Navigation = Class.create();

Navigation.prototype = {
  setOptions: function (options) {
    this.options = Object.extend({
      menu_izq: false,
      private: false
    }, options || {})
  },
  initialize: function (url, options) {
    var idi = document.location.search.toQueryParams().idi;
    if (idi && url.indexOf("idi") == -1) {
      url += "&idi=" + idi;
    }
    if (navigator.appName == "Microsoft Internet Explorer") { $('navegacion_contenido').insert({before: '<div style="display: none;"></div>'}); }
    if (!options || (options.menu_izq == undefined) || options.menu_izq) {
      new Ajax.Updater($('navegacion'),'/wls/porquetuvuelves/menu/uiMenuDerecho?ajax=true&arg1=' + url, {method: 'post', encoding: 'UTF-8'});
    } else { $('navegacion_bottom').hide(); }
    if (!options || (options.private == undefined) || options.private) {
      new Ajax.Updater($('navegacion_areareservada'),'/wls/porquetuvuelves/jsp/AreaAcceso?privadas=' + ((url.indexOf("privadas") > -1) ? 'true' : 'false'), {method: 'post', encoding: 'UTF-8', evalScripts: 'false'});
    } else { $('navegacion_bottom_areareservada').hide(); }
    new Ajax.Updater($('banner_navegacion'),'/wls/porquetuvuelves/jsp/BannerDestacados', {method: 'post', encoding: 'UTF-8'});
  }
}

/**
 * IE recognizes :hover span tags.
 */
__sfHover = function(div) {
  if (navigator.appName == "Microsoft Internet Explorer") {
    var sfEls = document.getElementById(div).getElementsByTagName("span");
    for (var i=0; i<sfEls.length; i++) {
      sfEls[i].onmouseover = function() {
        this.className += " sfhover";
      }
      sfEls[i].onmouseout = function() {
        if (this.className == "sfhover") { this.removeAttribute("class"); }
        else { this.className = this.className.replace(new RegExp(" sfhover\\b"), ""); }
      }
    }
  }
}

/**
 * Necessary IE applies the styles well.
 */
if (navigator.appName == "Microsoft Internet Explorer") {
  setTimeout(function() {
    if (document.body && document.readyState == "complete") {
      document.body.className += " :screw-ie";
      var camino;
      if (camino = document.getElementById("camino")) camino.className += " :screw-ie";
    } else setTimeout(arguments.callee, 10);
  }, 10);
}

/**
 * Necessary IE process Ajax.Request.evalResponse() script comments correctly.
 */
if (navigator.appName == "Microsoft Internet Explorer") {
  String.prototype.evalScripts = function() {
    return this.extractScripts().map(function(script) {
      script = script.replace("<!--", "").replace("// -->", "");
      return eval(script);
    });
  };
}

/**
 * Define elements with tooltip.
 */
__createTooltips = function() {
  $$('img:[title!=""]', 'a:[title!=""]', 'span:[title!=""]', 'p:[title!=""]', 'area:[title!=""]',
    'input:[title!=""]', 'select:[title!=""]', 'textarea:[title!=""]', ".help").each(function(link) {
    new Tooltip(link, {backgroundColor: "#E90F00", borderColor: "#FFFFFF", textColor: "#FFF",
      textShadowColor: "#FFF", fitToDocument: 0});
  });
}

/**
 * Show modal popup if necessary.
 */
__showPopupMessage = function(auto_adjust) {
  if ((typeof __muestra_popup != "undefined") && __muestra_popup) {
    new ModalPopup("<div id='" + __muestra_popup + "-message' class='mensaje " + __muestra_popup + "'>" + __mensaje_popup + "<\/div>",
      {title: __titulo_popup, width: 430, height: 105, autoAdjust: (typeof auto_adjust != "undefined") ? auto_adjust : true});
  }
}

/**
 * Define textarea maxlength.
 */
__maxlengthTextArea = function() {
  var maxlength = new Array();
  if (textarea = $$('textarea:[maxlength!=""]')) {
    $R(0,textarea.size()-1).each(function(i) {
      if (maxlength[i] = parseInt(textarea[i].getAttribute("maxlength"), 10)) {
        $(textarea[i].name).observe('keypress', function(event) {
          return ((event.which == 8) || (event.which == 9) || (textarea[i].value.length = maxlength[i]));
        });
        $(textarea[i].name).observe('keyup', function(event) {
          $(textarea[i].name).value = textarea[i].value.substring(0, maxlength[i]);
        });
      }
    });
  }
}

__inicializa_pagina = function() {
  __createTooltips();
  __maxlengthTextArea();
  if (typeof inicializa_pagina == 'function') inicializa_pagina();
  __showPopupMessage();
}

FastInit.addOnLoad(__inicializa_pagina);

