/*
Copyright (c) 2009 Emilio Lucia - http://web.alimagen.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the 
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit 
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the 
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/


try{
 if(typeof PanelsBox == 'undefined' && typeof Usefull == 'undefined'){
  var PanelsBox = null, Usefull = null;
 }
 else{
  throw{
   name: "Error de variables",
   message: "Hay duplicidad de variables."
  }
 }
 
 
 //Objeto Usefull
 Usefull = {
  version: '1.0.4',            //versión del objeto Usefull
  libVersion: '1.0.2',         //versión de la librería Usefull
  requiredPrototype: '1.6.1',
  IE6: navigator.userAgent.match(/MSIE (\d).\d/i) ? (RegExp.$1 == '6' ? true : false) : false,
  domLoaded: false,
  
  convertVersionString: function(versionString){return parseInt(versionString.replace(/\./g, ""));},
  
  testPrototypeVersion: function(prototypeVersion){
   if(typeof Prototype == 'undefined' || typeof Element == 'undefined' || typeof Element.Methods == 'undefined' ||
      this.convertVersionString(Prototype.Version) < this.convertVersionString(prototypeVersion)){
    throw{
     name: "Error de version",
     message: "Se necesita Prototype >= " + prototypeVersion
    }   
   }
   return true;
  }
 };
 
 Usefull.testPrototypeVersion(Usefull.requiredPrototype);
 document.observe("dom:loaded", function(e){Usefull.domLoaded = true;});

 //Clase abstracta PanelsBox
 PanelsBox = Class.create(Abstract, {
  initialize: function(container){
   this.version = '1.1.0';
   this.container = container;
   this.containerId = null;
   this.jumpersContainerId = null;
   this.panels = [];
   this.jumpers = [];
   this.previous = null;
   this.current = null;
   this.previousIndex = null;
   this.currentIndex = null;
   this.building = false;
   this.options = {
    initial:            0,                  //puede ser posición (empezando por 0) o id del panel  
    jumperClassName:    'PB-jumper',
    jumpersContainer:   null,               //Si se ha ocultado con CSS permite mostrarlo
    panelClassName:     'PB-panel',
    selectedClassName:  'PB-selected'
   };
   
   document.observe("dom:loaded", this.onLoadDom.bindAsEventListener(this));
   Event.observe(window,'load', this.onLoadDoc.bindAsEventListener(this));
  },

  onLoadDom: function(e){
   var opts = this.options;     //comprimir código
   
   this.building = true;
   
   this.container = $(this.container);                //convertir el id a referencia al elemento
   this.containerId = this.container.identify();
   this.panels = this.container.select('.' + opts.panelClassName).each(function(panel, index){panel.store('_index', index);});
   
   if(!this.panels.length) return;
   
   if(opts.jumpersContainer){
    opts.jumpersContainer = $(opts.jumpersContainer);          //convertir el id a referencia al elemento
    this.jumpersContainerId = opts.jumpersContainer.identify();
    
    with(opts.jumpersContainer){
     this.jumpers = select('.' + opts.jumperClassName);
     setStyle({display: 'block'});   //Muestra el contenedor de los jumpers
    }
    
    with(this.jumpers){
     if(length){
      var difJumpers = this.panels.length - length, refclone = null;
      for(var i = 0; i < difJumpers; i++){
       last().up('li').insert({after: refclone = last().up('li').clone(true)});
       push(refclone.firstChild);
      }
      each(function(jumper, index){jumper.store('_index', index).observe('click', this._click.bindAsEventListener(this));}, this);
     }
    }
   }
  },

  onLoadDoc: function(e){
   var initialIndex = 0;
   switch(typeof this.options.initial){
    case 'number':
     initialIndex = this.validateIndex(this.options.initial);
     break;
    case 'string':
     initialIndex = $(this.options.initial).retrieve('_index');
   }

   this.show(initialIndex);
  },

  _click: function(e){
   var element = e.findElement('a');
   return element.hasClassName(this.options.selectedClassName) ? null : element;
  },
  
  //show ( índice o referencia del/al panel )
  show: function(){this.updateCurrent(arguments[0]);},
  
  //updateCurrent ( índice o referencia del/al panel )
  updateCurrent: function(){
   var panel = typeof arguments[0] == 'number' ? this.panels[arguments[0]] : arguments[0];
   this.previous = this.current;
   this.current = $(panel);
   if(this.previous) this.previousIndex = this.previous.retrieve('_index');
   this.currentIndex = this.current.retrieve('_index');
  },
  
  //Primer índice válido
  firstIndex: function(){return 0;},
  
  //Último índice válido
  lastIndex: function(){return this.panels.length - 1;},
  
  validateIndex: function(panelIndex){
   if(typeof panelIndex == 'undefined'){
    alert('El panel al que saltar no est&aacute; definido correctamente.');
    return this.firstIndex();
   }
   return panelIndex < this.firstIndex() ? this.firstIndex() : (panelIndex > this.lastIndex() ? this.lastIndex() : panelIndex);
  },
  
  updateJumpers: function(){
   if(this.options.selectedClassName && this.jumpers.length && this.previous) this.jumpers.invoke('removeClassName', this.options.selectedClassName);
  },
  
  build: function(){
   document.observe("protocarrusel:rebuilded", this.onLoadDom.bindAsEventListener(this));
   document.observe("protocarrusel:rebuilded", this.onLoadDoc.bindAsEventListener(this));
   $(this.container).fire("protocarrusel:rebuilded");
  },
  
  rebuild: function(){
   this.container = $(this.containerId);
   this.options.jumpersContainer = $(this.jumpersContainerId);
   this.build();
  }
 });

}
catch(e){
 alert(e.name + ": " + e.message);
}

//Extensiones de Element
//Version 1.0.1
Element.addMethods({
 accumulateDimensions: function(elem, dimsArray){return dimsArray.inject(0, function(acc, dim, n){return acc + parseInt($(elem).getStyle(dim));});},
 getOnlyWidth: function(elem){return $(elem).getWidth() - $(elem).accumulateDimensions(['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight'])},
 getOnlyHeight: function(elem){return $(elem).getHeight() - $(elem).accumulateDimensions(['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom'])}
});


/**
 * Javascript code to store data as JSON strings in cookies. 
 * It uses prototype.js 1.5.1 (http://www.prototypejs.org)
 * 
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/jsoncookies
 * License: Apache Software License 2
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.5
 * Updated: Jan 26, 2009 
 * 
 * Change Log:
 *   v 0.5
 *   -  Changed License from CC to Apache 2
 *   v 0.4
 *   -  Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
 *   -  Removed the parameter name from the initialize function
 *   -  Changed the way expires date was being calculated. (Thanks David)
 *   v 0.3
 *   -  Removed dependancy on json.js (http://www.json.org/json.js)
 *   -  empty() function only deletes the cookies set by CookieJar
 */

//Clase CookieJar
var CookieJar = Class.create(Abstract, {
 initialize: function(options){
  this.appendString = "_CJ_";          //Append before all cookie names to differntiate them.
  this.options = Object.extend({
   expires:      3600,    // seconds (1 hr)
   path:         '',      // cookie path
   domain:       '',      // cookie domain
   secure:       ''       // secure ?
  }, options || {});
 
  if(this.options.expires != ''){
   var date = new Date();
   date = new Date(date.getTime() + (this.options.expires * 1000));
   this.options.expires = '; expires=' + date.toGMTString();
  }
  if(this.options.path != '') this.options.path = '; path=' + escape(this.options.path);
  if(this.options.domain != '') this.options.domain = '; domain=' + escape(this.options.domain);
  if(this.options.secure == 'secure') this.options.secure = '; secure';
  else this.options.secure = '';
 },

 //Adds a name values pair.
 put: function(name, value){
  name = this.appendString + name;
  switch(typeof value) {
   case 'undefined':
   case 'function' :
   case 'unknown'  : return false;
   case 'boolean'  : 
   case 'string'   : 
   case 'number'   : value = String(value.toString());
  }
  var cookie_str = name + "=" + escape(Object.toJSON(value));
  try{with(this.options) document.cookie = cookie_str + expires + path + domain + secure;}
  catch(e){return false;}
  return true;
 },

 //Removes a particular cookie (name value pair) form the Cookie Jar.
 remove: function(name){
  var CJRe = new RegExp("^" + this.appendString);
  if(!name.match(CJRe)) name = this.appendString + name;
  cookie = this.options;
  try{
   var date = new Date();
   date.setTime(date.getTime() - (3600 * 1000));
   var expires = '; expires=' + date.toGMTString();
   document.cookie = name + "=" + expires + cookie.path + cookie.domain + cookie.secure;
  }
  catch (e){
   return false;
  }
  return true;
 },

 //Return a particular cookie by name.
 get: function(name){
  var CJRe = new RegExp("^" + this.appendString);
  if(!name.match(CJRe)) name = this.appendString + name;
  var cookies = document.cookie.match(name + '=(.*?)(;|$)');
  if(cookies) return (unescape(cookies[1])).evalJSON();
  else return null;
 },

 //Empties the Cookie Jar. Deletes all the cookies.
 empty: function(){
  keys = this.getKeys();
  for(var i = 0; i < keys.length; i++) this.remove(keys[i]);
 },
 
 //Returns all cookies as a single object
 getPack: function() {
  pack = {};
  keys = this.getKeys();
  for(var i = 0; i < keys.length; i++) pack[keys[i]] = this.get(keys[i]);
  return pack;
 },

 //Returns all keys.
 getKeys: function() {
  keys = $A();
  keyRe= /[^=; ]+(?=\=)/g;
  str  = document.cookie;
  CJRe = new RegExp("^" + this.appendString);
  while((match = keyRe.exec(str)) != undefined){
   if(CJRe.test(match[0].strip())) keys.push(match[0].strip().gsub("^" + this.appendString,""));
  }
  return keys;
 }
});