/*
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.0',
  IE6:           navigator.userAgent.match(/MSIE (\d).\d/i) ? (RegExp.$1 == '6' ? true : false) : false
 };


 //Clase abstracta PanelsBox
 PanelsBox = Class.create(Abstract, {
  initialize: function(container){
   this.version = '1.0.3';
   this.container = $(container);
   this.panels = [];
   this.jumpers = [];
   this.previous = null;
   this.current = null;
   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){
   this.panels = this.container.select('.' + this.options.panelClassName).each(function(panel, index){panel.store('_index', index);});
   
   if(this.options.jumpersContainer){
    this.jumpers = $(this.options.jumpersContainer).select('.' + this.options.jumperClassName);
    
    if(this.jumpers.length){
     var difJumpers = this.panels.length - this.jumpers.length, refclone = null;
     for(var i = 0; i < difJumpers; i++){
      $(this.jumpers.last().parentNode).insert({after: refclone = $(this.jumpers.last().parentNode).clone(true)});
      this.jumpers.push(refclone.firstChild);
     }
     this.jumpers.each(function(jumper, index){jumper.store('_index', index).observe('click', this._click.bindAsEventListener(this));}, this);
     $(this.options.jumpersContainer).setStyle({display: 'block'});   //Muestra el contenedor de los jumpers
    }
   }
  },

  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){return e.findElement('a');},
  
  show: function(){this.updateCurrent(arguments[0]);},
  
  updateCurrent: function(){
   var panel = typeof arguments[0] == 'number' ? this.panels[arguments[0]] : arguments[0];
   this.previous = this.current || this.panels[0];
   this.current = $(panel);
  },
  
  //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);
  }
 });

}
catch(e){
 alert(e.name + ": " + e.message);
}


/**
 * 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;
 }
});
