var fjsGetFCKeditor = function(n, w, h, v, t, s) {
	var oFCKeditor = new FCKeditor(n);
	oFCKeditor.BasePath	= '/inc/fckeditor/';
	oFCKeditor.CheckBrowser = true;
	oFCKeditor.Height = w;
	oFCKeditor.Height = h;
	oFCKeditor.Value = v;
	oFCKeditor.ToolbarSet = t; // (Basic will be great for lamerz)
	oFCKeditor.Config['AutoDetectLanguage'] = true;
	oFCKeditor.Config['DefaultLanguage'] = 'es';
	oFCKeditor.Config['SkinPath'] = '/inc/fckeditor/editor/skins/' + s + '/'; // office2003 or silver
	oFCKeditor.Create();
}
/* 
Valerio's ScrollBar
*/
var ScrollBar = new Class({

	Implements: [Events, Options],

	options: {
		maxThumbSize: 10,
		arrowSize: 10,
		wheel: 8
	},

	initialize: function(content, track, thumb, options) {
		this.setOptions(options);

		this.content = $(content);
		this.track = $(track);
		this.thumb = $(thumb);

		this.bound = {
			'start': this.start.bind(this),
			'end': this.end.bind(this),
			'drag': this.drag.bind(this),
			'wheel': this.wheel.bind(this),
			'page': this.page.bind(this)
		};

		this.position = {};
		this.mouse = {};
		this.update();
		this.attach();
	},

	update: function() {

		this.contentSize = this.content.offsetHeight;
		this.contentScrollSize = this.content.scrollHeight;
		this.trackSize = this.track.offsetHeight;

		this.contentRatio = this.contentSize / this.contentScrollSize;

		this.thumbSize = (this.trackSize * this.contentRatio).limit(this.options.maxThumbSize, this.trackSize) - this.options.arrowSize;

		this.scrollRatio = this.contentScrollSize / this.trackSize;

		this.thumb.setStyle('height', this.thumbSize);

		this.updateThumbFromContentScroll();
		this.updateContentFromThumbPosition();
	},

	updateContentFromThumbPosition: function() {
		this.content.scrollTop = this.position.now * this.scrollRatio;
	},

	updateThumbFromContentScroll: function() {
		this.position.now = (this.content.scrollTop / this.scrollRatio).limit(this.options.arrowSize, (this.trackSize - this.thumbSize));
		this.thumb.setStyle('top', this.position.now);
	},

	attach: function() {
		this.thumb.addEvent('mousedown', this.bound.start);
		if (this.options.wheel) this.content.addEvent('mousewheel', this.bound.wheel);
		this.track.addEvent('mouseup', this.bound.page);
	},

	wheel: function(event) {
		this.content.scrollTop -= event.wheel * this.options.wheel;
		this.updateThumbFromContentScroll();
		event.stop();
	},

	page: function(event) {
		if (event.page.y > this.thumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
		else this.content.scrollTop -= this.content.offsetHeight;
		this.updateThumbFromContentScroll();
		event.stop();
	},

	start: function(event) {
		this.mouse.start = event.page.y;
		this.position.start = this.thumb.getStyle('top').toInt();
		document.addEvent('mousemove', this.bound.drag);
		document.addEvent('mouseup', this.bound.end);
		this.thumb.addEvent('mouseup', this.bound.end);
		event.stop();
	},

	end: function(event) {
		document.removeEvent('mousemove', this.bound.drag);
		document.removeEvent('mouseup', this.bound.end);
		this.thumb.removeEvent('mouseup', this.bound.end);
		event.stop();
	},

	drag: function(event) {
		this.mouse.now = event.page.y;
		this.position.now = (this.position.start + (this.mouse.now - this.mouse.start)).limit(0, (this.trackSize - this.thumbSize));
		this.updateContentFromThumbPosition();
		this.updateThumbFromContentScroll();
		event.stop();
	}

});

/*
Script: mootools.ddmenu.99.js
 ddmenu is a simple MooTools-based script to create you're own context menus
 
License:
 MIT-style license.

Author:
jan angel manolov <email@webhike.de>  <http://netjard.de/lab/ddmenu>

 Changelog:
 v.1.0 [6/17/08]
	- MooTools 1.2 Ready
 
 v0.99 [6/9/08]
	- the ddmenu works good, no bugs concidered since the last update.
	- waiting for the mootools 1.2 release, to get a final version of the ddmenu.
	- url chanched to <netjard.de/labs/ddmenu>
 
v.0.2.1 [2/11/08]
    Fixes for MooTools 1.2 Beta 2 

v.0.2 [1/1/08]
    Scroll-save, correct positioning
    Ctrl and Shift Switches
    Fade In
    CSS-Styles reworked and adapted
    This Demo Page and Google Code registration
    
v.0.1</span> [11/07]
    Initial Version with a basic menu script structure
    Event-calls and enableItems(), enableOnlyThisItems() Functions
    Adapted the complex when-menu-is-opened events on the System Context Menu Style

	
Use enableThisItemsOnly and enableItems to enable or disable menu items by they're ids

    enableThisItemsOnly ([item1,item2], true)   	-> disable all other
    enableThisItemsOnly (item)                    	-> same
    enableThisItemsOnly ([item1,item2], false)  	-> enable all other

    enableItems ([item1,item2])           			-> enable this items
    enableItems (item1)                   			-> same 
    enableItems ([item1,item2], false)    			-> disable this thems
    enableItems ()                        				-> enable all items    
    enableItems (false)                   			-> disable all      
*/

var DDMenu = new Class ({

    Implements: [Events, Options],
    
    options: {
        onOpen: $empty,
        onClose: $empty,
        onItemSelect: $empty, 
        observe_disabled_items: false,                                     //call onItemSelect() on disabled items?
        rightclick_to_open: true,                                          //open menu on rightclick (if browser supports contextmenu-events)
        crtl_switch: true,                                                 //allow to switch between default menu and dd
        shift_with_contentmenu: true, //not ie                                  						//show default & dd menu together
        fade_in: true,
        cursorx: 2,                                                        //distance to cursors-coords
        cursory: 1,
        opacity: 0.95                                                      //menu transparency
    },
    
    initialize: function (menu, bindon, options) {
    
        this.setOptions (options);
        this.eMenu = $(menu);
        this.eBindon = $(bindon);
        
        this.eMenu.setStyles ({ 
            position: 'absolute', 
            'z-index': 9999, 
            display: 'none'
        });

        this.open = this.open.bindWithEvent(this);
        this.close = this.close.bind(this);
        this.preOpenEvent = this.preOpenEvent.bind(this)
        this.menuEvent = this.menuEvent.bindWithEvent(this);
        
        this.clickedElement = $empty;
        
        this.eBindon.addEvents ({
            'mousedown': function () { this.eBindon.addEvent ('contextmenu', fbreak) }.bind(this),
            'mouseup': this.preOpenEvent
        });
        
        //this.eMenu.getElements('li.item a').addEvent('click', fbreak); //safari bug :(
        $$('#'+menu+' li a').addEvent('click', fbreak);
    },

    //while hidden

    preOpenEvent: function (event) {  
    
        if (event.shift) {
            this.eBindon.removeEvent ('contextmenu', fbreak);
        }
        else if (this.options.crtl_switch && event.rightClick && event.control) { //open browser default contextmenu
            this.eBindon.removeEvent ('contextmenu', fbreak);
            return true; 
        }
        
        event.preventDefault();
        if (this.eMenu.style.display == 'block') this.close(event);
        
        this.clickedElement = $(event.target);

        if (event.rightClick) {
            if (this.options.crtl_switch && event.control) return true;
            else if (this.options.rightclick_to_open) this.open(event);
        }
        if (event.control) this.open(event);
		  else return true;

        return false;        
    },
    
    
    open: function (event) { 
        
        this.eMenu.setStyles ({opacity: 0, display: 'block', 'z-index':99999, top:event.page.y + this.options.cursory, left:event.page.x + this.options.cursorx});
        
        var coords = {};
        this.eMenu.getPosition().y-$(document.body).getScroll().y+this.eMenu.getSize().y < $(document.body).getSize().y ?
            coords.y = event.page.y + this.options.cursory :
            coords.y = event.page.y - this.eMenu.getSize().y + this.options.cursory;
        if (coords.y<$(document.body).getScroll().y+1) coords.y = $(document.body).getScroll().y+1;
        
        this.eMenu.getPosition().x-$(document.body).getScroll().x+this.eMenu.getSize().x < $(document.body).getSize().x ?
            coords.x = event.page.x + this.options.cursorx :
            coords.x = event.page.x - this.eMenu.getSize().x + this.options.cursorx;

        if (coords.x<$(document.body).getScroll().x+1) coords.x = $(document.body).getScroll().x+1;
        
        if (event.shift) coords.x = event.page.x - this.eMenu.getSize().x - this.options.cursorx;

        this.eMenu.setStyles({ top: coords.y, left: coords.x });
        
        if (this.options.fade_in) {
            var op = this.options.opacity;
            var fadein = new Fx.Morph (this.eMenu, {duration:200}).start({ 'opacity': [.32, op] });
        }
        else this.eMenu.style.opacity = this.options.opacity;
        


        window.addEvent ('blur', function () { if (!Browser.Engine.trident) this.close() }.bind(this)); //ie throws currious blur events
        document.addEvent ('mousedown', this.menuEvent);
        
        this.eMenu.addEvents({
            'contextmenu': function () {return false},
            'mouseup': this.menuEvent
        });
        

        this.fireEvent('onOpen', event);
    },
    
    
    //while opened
    
    menuEvent: function (event) { 
        
        event.preventDefault();
        
        var item = $(event.target);

        if (item == this.eMenu || item == this.eMenu.getElement('ul')) return false; 
        
        item = this.ascendTo(item, ['item','sepline','title']); 
        
        if (item === false) {
            this.close(event); //outer event
        }
        else if (item.hasClass('item') && event.type == 'mouseup') {
            if (!(item.getElement('a').hasClass('disabled') && !this.options.observe_disabled_items)) {
                this.action(item); 
                this.close(event); 
            }
        }
		return true;
    },    
    
    
    close: function (event) {
            
        this.eMenu.style.display = 'none';         
          
        document.removeEvent ('mousedown', this.menuEvent);
        window.removeEvent ('blur', function () {if (!Browser.Engine.trident) this.close()}.bind(this));
        this.eMenu.removeEvents();
                     
        this.fireEvent('onClose', event);    
    },
    
    
    action: function (item) {
        
        //this.clickedElement.focus();
        this.fireEvent('onItemSelect', [item.get('id'), this.clickedElement, this.eBindon]);
        return;
    },
    
    
    ascendTo: function (el, peakto) {
    
        if (el == window) return false;
        
        var ascel = el;
                
        while (ascel.get('tag') != 'html') { 
            
            for (var i=0; i<peakto.length; i++) {
                if (ascel.hasClass(peakto[i])) return ascel;
            }
            ascel = ascel.getParent(); 
        }
        
        return false;        
    },
    
      
    

    
    enableThisItemsOnly: function (items, enable) {
        
        if (!$chk(enable) && enable!=false) enable = true;
        if ($type(items) == 'string') items = [items];
        if (!items.length) return;
        
        enable == true ?
            this.eMenu.getElements ('li.item a').addClass('disabled') :
            this.eMenu.getElements ('li.item a').removeClass('disabled');                

        items.each (function (item) {
            enable == true ? 
                this.eMenu.getElement('li#'+item+' a').removeClass('disabled') :
                this.eMenu.getElement('li#'+item+' a').addClass('disabled');
        }.bind(this));            
    },
    
    
    enableItems: function (items, enable) {
    
        if (!$chk(items) && items!=false) items = true;
        if ($type(items) == 'boolean') {
            items == true ? 
                this.eMenu.getElements ('li.item a').removeClass('disabled') : 
                this.eMenu.getElements ('li.item a').addClass('disabled');
            return;
        }     
    
        if (!$chk(enable) && enable!=false) enable = true;
        if ($type(items) == 'string') items = [items];

        items.each (function (item) {
            enable == true ? 
                this.eMenu.getElement('li#'+item+' a').removeClass('disabled') :
                this.eMenu.getElement('li#'+item+' a').addClass('disabled');
        }.bind(this));
    }
    
});


var fbreak = function () {return false;}

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent() {
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent() {
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2) {
    var currArg = args[i].toLowerCase();    

    switch (currArg) {	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {
    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

var Playlist = new Class({

		Implements: [Events, Options],

		options: {
			'swfLocation': '/swf/MooSound.swf'
		},

		initialize: function(options) {
			this.setOptions(options);
			window.addEvent('domready', function() { 
				this.swiffHome = new Element('div', {id: 'swiffHome'}).setStyles({position:'absolute','top':1,'left':1}).inject(document.body);
				this.obj = new Swiff(this.options.swfLocation, {width: 1, height: 1, container: this.swiffHome, swLiveConnect: true}); 
			}.bind(this));
			this.flashLoaded = false;
			this.loadQueue = [];
			this.sounds = new Hash();	
			this.playing = []; 
		},

		loadSounds: function(sounds, options) {
			if (!this.flashLoaded) {
				this.loadQueue.push([sounds,options]);
			} else {
				sounds = sounds || [];
				sounds.each(function(url) {
					this.loadSound(url, options);
				}, this);
			}
			return this;
		},

		loadSound: function(url, options) {
			if (!this.flashLoaded) { this.loadQueue.push([url,options]); }
			this.sounds.set(url, new Sound(url, this, options));
			return this;
		},

		stopSounds: function() {
			this.playing.each( function(sound) { sound.stop(); });
			return this;
		},

		playRandom: function() {
			var randomKey = this.sounds.getKeys().getRandom();
			this.stopSounds();
			var sound = this.sounds.get(randomKey);
			sound.start(0);
			return this;
		},

		onSoundLoaded: function(url) {
			this.sounds.get(url).fireEvent('onLoad');
		},

		onSoundComplete: function(url) {
			this.sounds.get(url).fireEvent('onComplete').fireEvent('onStop');
			return this;
		},

		onFlashLoaded: function() {
			this.flashLoaded = true;
			this.loadQueue.each(function(arr) { this.loadSounds(arr[0], arr[1]); }.bind(this));
		},

		registerID3: function(url, tag, value) {
			var sound = this.getSound(url);
			sound.id3.set(tag, value);
			sound.fireEvent('onID3', [tag, value]);
		},

		getSound: function(key) {
			return this.sounds.get(key);
		}

});

var Sound = new Class({ 

	Implements: [Options, Events],

	options: {
		autostart: false,  //autostart
		streaming: true,   //streaming
		volume: 50,        //volume to start at
		pan: 0,            //pan between -100 (left) and 100 (right)
		progressInterval: 500, //milliseconds between getProgress(); calls
		positionInterval: 500,//milliseconds between getPosition(); calls
		onRegister: $empty,//fires when the sound is registered
		onLoad: $empty,    //fires when the sound is downloaded
		onPlay: $empty,    //fires when the sound begins playing
		onPause: $empty,   //fires when the sound is paused
		onStop: $empty,    //fires when the sound stops playing
		onComplete: $empty, //fires when the sound completes playing
		onProgress: $empty,//fires when download makes progress
		onPosition: $empty,//fires when position within the song changes
		onID3: $empty      //fires when ID3 tags become available
	},

	initialize: function(url, manager, options) {
		this.setOptions(options);
		this.url = url;
		this.id3 = new Hash();
		this.manager = manager || Playlist;
		this.swf = this.manager.obj.toElement();
		this.playing = false;
		this.listeners = {};
		this.filesize = null;
		this.duration = null;
		this.pausedAt = 0;
		this.position = 0;
		this.register();
	},

	start: function(position) {
		var pos = position || this.pausedAt;
		this.swf.startSound(this.url, pos, this.options.volume, this.options.pan);
		this.fireEvent('onPlay');
		this.pausedAt = 0;
		return this;
	},

	stop: function() {
		this.swf.stopSound(this.url);
		this.fireEvent('onStop');
		return this;
	},

	jumpTo: function(seconds) {
		$clear(this.listeners.position);
		this.start(seconds);
	},

	pause: function() {
		this.swf.stopSound(this.url);
		this.pausedAt = this.getPosition();
		this.fireEvent('onPause', this.pausedAt);
		this.fireEvent('onStop');
	},

	setVolume: function(volume) {
		this.obj.setVolume(this.url, volume);
		this.options.volume = volume;
		return this;
	},

	setPan: function(pan) {
		this.swf.setPan(this.url, pan);
		this.options.pan = pan;
		return this;
	},

	getVolume: function() {
		return this.options.volume;
	},

	getPan: function() {
		return this.options.pan;
	},

	getID3: function(tag) {
		return this.id3.get(tag);	
	},

	getBytesLoaded: function() {
		return this.swf.getBytesLoaded(this.url);
	}, 

	getFilesize: function() {
		return this.swf.getBytesTotal(this.url);
	},

	getPosition: function() {
		return this.swf.getPosition(this.url);
	}, 

	getDuration: function() {
		return this.swf.getDuration(this.url);
	},

	checkProgress: function() {
		if ($type(this.filesize) !== "number") { this.filesize = this.getFilesize(); }
		var loaded = this.getBytesLoaded(); 
		if ($type(loaded) === "number" && loaded !== this.listeners.lastProgress) { 
			var total = this.getFilesize();
			this.listeners.lastProgress = loaded;
			this.fireEvent('onProgress', [loaded, total]); 
		}
	},

	checkPosition: function() {
		var position = this.getPosition();
		this.duration = this.getDuration();
		if ($type(position) === "number" && position !== this.listeners.lastPosition) { 
			this.listeners.lastPosition = position;
			this.fireEvent('onPosition', [(position / 1000).round(), (this.duration / 1000).round()]);
		}
	},

	register: function() {
		this.fireEvent('onRegister');
		if (this.options.streaming === false) {
			this.swf.preloadSound(this.url);
			this.listeners.progress = this.checkProgress.periodical(this.options.progressInterval, this);
		}
		this.addEvents({'onLoad': this.onLoad, 'onStop': this.onStop, 'onPlay': this.onPlay});
	},

	onLoad: function() {
		$clear(this.listeners.progress);
		this.checkProgress();
	},

	onPlay: function() {
		if (this.options.streaming === true) {
			this.listeners.progress = this.checkProgress.periodical(this.options.progressInterval, this);
		}
		this.playing = true;
		this.listeners.position = this.checkPosition.periodical(this.options.positionInterval, this);
		this.manager.playing.push(this);
	},

	onStop: function() {
		$clear(this.listeners.position);
		if (this.pausedAt === 0) { this.fireEvent('onPosition', [0, this.duration]); }
		this.playing = false;
	}

});

//Comment out and reinstanciate if you want to add your own options.
Playlist = new Playlist();

/*!
	Slimbox v1.7 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/

var Slimbox = (function() {

	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number,

	// Effects
	fxOverlay, fxResize, fxImage, fxBottom;

	/*
		Initialization
	*/

	win.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay", events: {click: close}}),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			sizer = new Element("div", {styles: {position: "relative"}}).adopt(
				prevLink = new Element("a", {id: "lbPrevLink", href: "#", events: {click: previous}}),
				nextLink = new Element("a", {id: "lbNextLink", href: "#", events: {click: next}})
			)
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "lbCloseLink", href: "#", events: {click: close}}),
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
	});


	/*
		Internal functions
	*/

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
		return options.closeKeys.contains(code) ? close()
			: options.nextKeys.contains(code) ? next()
			: options.previousKeys.contains(code) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			activeURL = images[imageIndex][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		fxImage.set(0);
		image.setStyles({backgroundImage: "url(" + activeURL + ")", display: ""});
		sizer.setStyle("width", preload.width);
		$$(sizer, prevLink, nextLink).setStyle("height", preload.height);

		caption.set("html", images[activeImage][1] || "");
		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));

		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2)), check = 0, fn;
		if (center.offsetHeight != centerHeight) {
			check = fxResize.start({height: centerHeight, top: top});
		}
		if (center.offsetWidth != centerWidth) {
			check = fxResize.start({width: centerWidth, marginLeft: -centerWidth/2});
		}
		fn = function() {
			bottomContainer.setStyles({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			fxImage.start(1);
		};
		if (check) {
			fxResize.chain(fn);
		}
		else {
			fn();
		}
	}

	function animateCaption() {
		if (prevImage >= 0) prevLink.style.display = "";
		if (nextImage >= 0) nextLink.style.display = "";
		fxBottom.set(-bottom.offsetHeight).start(0);
		bottomContainer.style.visibility = "";
	}

	function stop() {
		preload.onload = $empty;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
	}

	function close() {
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			center.style.display = "none";
			fxOverlay.cancel().chain(setup).start(0);
		}

		return false;
	}


	/*
		API
	*/

	Element.implement({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
					the image URL and the image caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
			});

			return links;
		}
	});

	return {
		open: function(_images, startImage, _options) {
			options = $extend({
				loop: false,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
				captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
				counterText: "Image {x} of {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
				nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxResize = new Fx.Morph(center, $extend({duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxBottom = new Fx.Tween(bottom, {property: "margin-top", duration: options.captionAnimationDuration});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images, startImage]];
				startImage = 0;
			}

			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);
			position();
			setup(1);

			images = _images;
			options.loop = options.loop && (images.length > 1);
			return changeImage(startImage);
		}
	};

})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	var links = $$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	});
	$$(links).slimbox({'loop': true, 'overlayOpacity': 0.4, 'resizeDuration': 512, 'resizeTransition': Fx.Transitions.Expo.easeInOut, 'initialWidth': 160, 'initialHeight': 160, 'animateCaption': true, 'showCounter': true, 'counterText': 'Imagen {x} de {y}'}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};

/***
 * MooRainbow
 *
 * @version		1.2b2
 * @license		MIT-style license
 * @author		Djamil Legato - < djamil [at] djamil.it >
 * @infos		http://moorainbow.woolly-sheep.net
 * @copyright	Author
 * 
 *
 */

var Rainbows = [];

var MooRainbow = new Class({
	options: {
		id: 'mooRainbow',
		prefix: 'moor-',
		imgPath: '/img/',
		startColor: [255, 0, 0],
		wheel: false,
		onComplete: $empty,
		onChange: $empty
	},
	
	initialize: function(el, options) {
		this.element = $(el); if (!this.element) return;
		this.setOptions(options);
		
		this.sliderPos = 0;
		this.pickerPos = {x: 0, y: 0};
		this.backupColor = this.options.startColor;
		this.currentColor = this.options.startColor;
		this.sets = {
			rgb: [],
			hsb: [],
			hex: []	
		};
		this.pickerClick = this.sliderClick  = false;
		if (!this.layout) this.doLayout();
		this.OverlayEvents();
		this.sliderEvents();
		this.backupEvent();
		if (this.options.wheel) this.wheelEvents();
		this.element.addEvent('click', function(e) { this.closeAll().toggle(e); }.bind(this));
				
		this.layout.overlay.setStyle('background-color', this.options.startColor.rgbToHex());
		this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex());

		this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w;
		this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h;
		
		this.manualSet(this.options.startColor);
		
		this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w;
		this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h;
		this.sliderPos = this.snippet('arrPos') - this.snippet('arrSize', 'int');

		if (window.khtml) this.hide();
	},
	
	toggle: function() {
		this[this.visible ? 'hide' : 'show']();
	},
	
	show: function() {
		this.rePosition();
		this.layout.setStyle('display', 'block');
		this.visible = true;
	},
	
	hide: function() {
		this.layout.setStyles({'display': 'none'});
		this.visible = false;
	},
	
	closeAll: function() {
		Rainbows.each(function(obj) { obj.hide(); });
		
		return this;
	},
	
	manualSet: function(color, type) {
		if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb';
		var rgb, hsb, hex;

		if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); } 
		else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); }
		else { hex = color; rgb = color.hexToRgb(true); hsb = rgb.rgbToHsb(); }
		
		this.setMooRainbow(rgb);
		this.autoSet(hsb);
	},
	
	autoSet: function(hsb) {
		var curH = this.snippet('curSize', 'int').h;
		var curW = this.snippet('curSize', 'int').w;
		var oveH = this.layout.overlay.height;
		var oveW = this.layout.overlay.width;
		var sliH = this.layout.slider.height;
		var arwH = this.snippet('arrSize', 'int');
		var hue;
		
		var posx = Math.round(((oveW * hsb[1]) / 100) - curW);
		var posy = Math.round(- ((oveH * hsb[2]) / 100) + oveH - curH);

		var c = Math.round(((sliH * hsb[0]) / 360)); c = (c == 360) ? 0 : c;
		var position = sliH - c + this.snippet('slider') - arwH;
		hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex();
		
		this.layout.cursor.setStyles({'top': posy, 'left': posx});
		this.layout.arrows.setStyle('top', position);
		this.layout.overlay.setStyle('background-color', hue);
		this.sliderPos = this.snippet('arrPos') - arwH;
		this.pickerPos.x = this.snippet('curPos').l + curW;
		this.pickerPos.y = this.snippet('curPos').t + curH;
	},
	
	setMooRainbow: function(color, type) {
		if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb';
		var rgb, hsb, hex;

		if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); } 
		else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); }
		else { hex = color; rgb = color.hexToRgb(); hsb = rgb.rgbToHsb(); }

		this.sets = {
			rgb: rgb,
			hsb: hsb,
			hex: hex
		};

		if (!$chk(this.pickerPos.x))
			this.autoSet(hsb);		

		this.RedInput.value = rgb[0];
		this.GreenInput.value = rgb[1];
		this.BlueInput.value = rgb[2];
		this.HueInput.value = hsb[0];
		this.SatuInput.value =  hsb[1];
		this.BrighInput.value = hsb[2];
		this.hexInput.value = hex;
		
		this.currentColor = rgb;

		this.chooseColor.setStyle('background-color', rgb.rgbToHex());
	},
	
	parseColors: function(x, y, z) {
		var s = Math.round((x * 100) / this.layout.overlay.width);
		var b = 100 - Math.round((y * 100) / this.layout.overlay.height);
		var h = 360 - Math.round((z * 360) / this.layout.slider.height) + this.snippet('slider') - this.snippet('arrSize', 'int');
		h -= this.snippet('arrSize', 'int');
		h = (h >= 360) ? 0 : (h < 0) ? 0 : h;
		s = (s > 100) ? 100 : (s < 0) ? 0 : s;
		b = (b > 100) ? 100 : (b < 0) ? 0 : b;

		return [h, s, b];
	},
	
	OverlayEvents: function() {
		var lim, curH, curW, inputs;
		curH = this.snippet('curSize', 'int').h;
		curW = this.snippet('curSize', 'int').w;
		inputs = $A(this.arrRGB).concat(this.arrHSB, this.hexInput);

		document.addEvent('click', function() { 
			if (this.visible) this.hide(this.layout); 
		}.bind(this));

		inputs.each(function(el) {
			el.addEvent('keydown', this.eventKeydown.bindWithEvent(this, el));
			el.addEvent('keyup', this.eventKeyup.bindWithEvent(this, el));
		}, this);
		[this.element, this.layout].each(function(el) {
			el.addEvents({
				'click': function(e) { new Event(e).stop(); },
				'keyup': function(e) {
					e = new Event(e);
					if (e.key == 'esc' && this.visible) this.hide(this.layout);
				}.bind(this)
			}, this);
		}, this);
		
		lim = {
			x: [0 - curW, (this.layout.overlay.width - curW)],
			y: [0 - curH, (this.layout.overlay.height - curH)]
		};

		this.layout.drag = new Drag(this.layout.cursor, {
			limit: lim,
			onBeforeStart: this.overlayDrag.bind(this),
			onStart: this.overlayDrag.bind(this),
			onDrag: this.overlayDrag.bind(this),
			snap: 0
		});	
		
		this.layout.overlay2.addEvent('mousedown', function(e) {
			e = new Event(e);
			this.layout.cursor.setStyles({
				'top': e.page.y - this.layout.overlay.getTop() - curH,
				'left': e.page.x - this.layout.overlay.getLeft() - curW
			});
			this.layout.drag.start(e);
		}.bind(this));
		
		this.okButton.addEvent('click', function() {
			if (this.currentColor == this.options.startColor) {
				this.hide();
				this.fireEvent('onComplete', [this.sets, this]);
			}
			else {
				this.backupColor = this.currentColor;
				this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex());
				this.hide();
				this.fireEvent('onComplete', [this.sets, this]);
			}
		}.bind(this));

		this.emptyButton.addEvent('click', function () {
			this.hide();
			this.sets = '';
			this.fireEvent('onComplete', [{
			rgb: [],
			hsb: [],
			hex: []	
		}, this]);
		}.bind(this));

		this.transp.addEvent('click', function () {
			this.hide();
			this.fireEvent('onComplete', ['transparent', this]);
		}.bind(this));
	},
	
	overlayDrag: function() {
		var curH = this.snippet('curSize', 'int').h;
		var curW = this.snippet('curSize', 'int').w;
		this.pickerPos.x = this.snippet('curPos').l + curW;
		this.pickerPos.y = this.snippet('curPos').t + curH;
		
		this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb');
		this.fireEvent('onChange', [this.sets, this]);
	},
	
	sliderEvents: function() {
		var arwH = this.snippet('arrSize', 'int'), lim;

		lim = [0 + this.snippet('slider') - arwH, this.layout.slider.height - arwH + this.snippet('slider')];
		this.layout.sliderDrag = new Drag(this.layout.arrows, {
			limit: {y: lim},
			modifiers: {x: false},
			onBeforeStart: this.sliderDrag.bind(this),
			onStart: this.sliderDrag.bind(this),
			onDrag: this.sliderDrag.bind(this),
			snap: 0
		});	
	
		this.layout.slider.addEvent('mousedown', function(e) {
			e = new Event(e);

			this.layout.arrows.setStyle(
				'top', e.page.y - this.layout.slider.getTop() + this.snippet('slider') - arwH
			);
			this.layout.sliderDrag.start(e);
		}.bind(this));
	},

	sliderDrag: function() {
		var arwH = this.snippet('arrSize', 'int'), hue;
		
		this.sliderPos = this.snippet('arrPos') - arwH;
		this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb');
		hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex();
		this.layout.overlay.setStyle('background-color', hue);
		this.fireEvent('onChange', [this.sets, this]);
	},
	
	backupEvent: function() {
		this.layout.backup.addEvent('click', function() {
			this.manualSet(this.backupColor);
			this.fireEvent('onChange', [this.sets, this]);
		}.bind(this));
	},
	
	wheelEvents: function() {
		var arrColors = $A(this.arrRGB).extend(this.arrHSB);

		arrColors.each(function(el) {
			el.addEvents({
				'mousewheel': this.eventKeys.bindWithEvent(this, el),
				'keydown': this.eventKeys.bindWithEvent(this, el)
			});
		}, this);
		
		[this.layout.arrows, this.layout.slider].each(function(el) {
			el.addEvents({
				'mousewheel': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider']),
				'keydown': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider'])
			});
		}, this);
	},
	
	eventKeys: function(e, el, id) {
		var wheel, type;
		id = (!id) ? el.id : this.arrHSB[0];

		if (e.type == 'keydown') {
			if (e.key == 'up') wheel = 1;
			else if (e.key == 'down') wheel = -1;
			else return;
		} else if (e.type == Element.Events.mousewheel.base) wheel = (e.wheel > 0) ? 1 : -1;
		
		if (this.arrRGB.contains(el)) type = 'rgb';
		else if (this.arrHSB.contains(el)) type = 'hsb';
		else type = 'hsb';

		if (type == 'rgb') {
			var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass;
			var value = (el.value.toInt() || 0) + wheel;
			value = (value > 255) ? 255 : (value < 0) ? 0 : value;

			switch(el.className) {
				case prefix + 'rInput': pass = [value, rgb[1], rgb[2]];	break;
				case prefix + 'gInput': pass = [rgb[0], value, rgb[2]];	break;
				case prefix + 'bInput':	pass = [rgb[0], rgb[1], value];	break;
				default : pass = rgb;
			}
			this.manualSet(pass);
			this.fireEvent('onChange', [this.sets, this]);
		} else {
			var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass;
			var value = (el.value.toInt() || 0) + wheel;

			if (el.className.test(/(HueInput)/)) value = (value > 359) ? 0 : (value < 0) ? 0 : value;
			else value = (value > 100) ? 100 : (value < 0) ? 0 : value;
			
			switch(el.className) {
				case prefix + 'HueInput': pass = [value, hsb[1], hsb[2]]; break;
				case prefix + 'SatuInput': pass = [hsb[0], value, hsb[2]]; break;
				case prefix + 'BrighInput':	pass = [hsb[0], hsb[1], value]; break;
				default : pass = hsb;
			}
			
			this.manualSet(pass, 'hsb');
			this.fireEvent('onChange', [this.sets, this]);
		}
		e.stop();
	},
	
	eventKeydown: function(e, el) {
		var n = e.code, k = e.key;

		if 	((!el.className.test(/hexInput/) && !(n >= 48 && n <= 57)) &&
			(k!='backspace' && k!='tab' && k !='delete' && k!='left' && k!='right'))
		e.stop();
	},
	
	eventKeyup: function(e, el) {
		var n = e.code, k = e.key, pass, prefix, chr = el.value.charAt(0);

		if (!$chk(el.value)) return;
		if (el.className.test(/hexInput/)) {
			if (chr != "#" && el.value.length != 6) return;
			if (chr == '#' && el.value.length != 7) return;
		} else {
			if (!(n >= 48 && n <= 57) && (!['backspace', 'tab', 'delete', 'left', 'right'].contains(k)) && el.value.length > 3) return;
		}
		
		prefix = this.options.prefix;

		if (el.className.test(/(rInput|gInput|bInput)/)) {
			if (el.value  < 0 || el.value > 255) return;
			switch(el.className) {
				case prefix + 'rInput': pass = [el.value, this.sets.rgb[1], this.sets.rgb[2]]; break;
				case prefix + 'gInput': pass = [this.sets.rgb[0], el.value, this.sets.rgb[2]]; break;
				case prefix + 'bInput': pass = [this.sets.rgb[0], this.sets.rgb[1], el.value]; break;
				default : pass = this.sets.rgb;
			}
			this.manualSet(pass);
			this.fireEvent('onChange', [this.sets, this]);
		}
		else if (!el.className.test(/hexInput/)) {
			if (el.className.test(/HueInput/) && el.value  < 0 || el.value > 360) return;
			else if (el.className.test(/HueInput/) && el.value == 360) el.value = 0;
			else if (el.className.test(/(SatuInput|BrighInput)/) && el.value  < 0 || el.value > 100) return;
			switch(el.className) {
				case prefix + 'HueInput': pass = [el.value, this.sets.hsb[1], this.sets.hsb[2]]; break;
				case prefix + 'SatuInput': pass = [this.sets.hsb[0], el.value, this.sets.hsb[2]]; break;
				case prefix + 'BrighInput': pass = [this.sets.hsb[0], this.sets.hsb[1], el.value]; break;
				default : pass = this.sets.hsb;
			}
			this.manualSet(pass, 'hsb');
			this.fireEvent('onChange', [this.sets, this]);
		} else {
			pass = el.value.hexToRgb(true);
			if (isNaN(pass[0])||isNaN(pass[1])||isNaN(pass[2])) return;

			if ($chk(pass)) {
				this.manualSet(pass);
				this.fireEvent('onChange', [this.sets, this]);
			}
		}
			
	},
			
	doLayout: function() {
		var id = this.options.id, prefix = this.options.prefix;
		var idPrefix = id + ' .' + prefix;

		this.layout = new Element('div', {
			'styles': {'display': 'block', 'position': 'absolute'},
			'id': id
		}).inject(document.body);
		
		Rainbows.push(this);

		var box = new Element('div', {
			'styles':  {'position': 'relative'},
			'class': prefix + 'box'
		}).inject(this.layout);
			
		var div = new Element('div', {
			'styles': {'position': 'absolute', 'overflow': 'hidden'},
			'class': prefix + 'overlayBox'
		}).inject(box);
		
		var ar = new Element('div', {
			'styles': {'position': 'absolute', 'zIndex': 1},
			'class': prefix + 'arrows'
		}).inject(box);
		ar.width = ar.getStyle('width').toInt();
		ar.height = ar.getStyle('height').toInt();
		
		var ov = new Element('img', {
			'styles': {'background-color': '#fff', 'position': 'relative', 'zIndex': 2},
			'src': this.options.imgPath + 'moor_woverlay.png',
			'class': prefix + 'overlay'
		}).inject(div);
		
		var ov2 = new Element('img', {
			'styles': {'position': 'absolute', 'top': 0, 'left': 0, 'zIndex': 2},
			'src': this.options.imgPath + 'moor_boverlay.png',
			'class': prefix + 'overlay'
		}).inject(div);
		
		if (window.ie6) {
			div.setStyle('overflow', '');
			var src = ov.src;
			ov.src = this.options.imgPath + 'blank.gif';
			ov.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
			src = ov2.src;
			ov2.src = this.options.imgPath + 'blank.gif';
			ov2.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		}
		ov.width = ov2.width = div.getStyle('width').toInt();
		ov.height = ov2.height = div.getStyle('height').toInt();

		var cr = new Element('div', {
			'styles': {'overflow': 'hidden', 'position': 'absolute', 'zIndex': 2},
			'class': prefix + 'cursor'	
		}).inject(div);
		cr.width = cr.getStyle('width').toInt();
		cr.height = cr.getStyle('height').toInt();
		
		var sl = new Element('img', {
			'styles': {'position': 'absolute', 'z-index': 2},
			'src': this.options.imgPath + 'moor_slider.png',
			'class': prefix + 'slider'
		}).inject(box);
		this.layout.slider = document.getElement('#' + idPrefix + 'slider');
		sl.width = sl.getStyle('width').toInt();
		sl.height = sl.getStyle('height').toInt();

		new Element('div', {
			'styles': {'position': 'absolute'},
			'class': prefix + 'colorBox'
		}).inject(box);

		new Element('div', {
			'styles': {'zIndex': 2, 'position': 'absolute'},
			'class': prefix + 'chooseColor'
		}).inject(box);
			
		this.layout.backup = new Element('div', {
			'styles': {'zIndex': 2, 'position': 'absolute', 'cursor': 'pointer'},
			'class': prefix + 'currentColor'
		}).inject(box);
		
		var R = new Element('label').inject(box).setStyle('position', 'absolute');
		var G = R.clone().inject(box).addClass(prefix + 'gLabel').appendText('G: ');
		var B = R.clone().inject(box).addClass(prefix + 'bLabel').appendText('B: ');
		R.appendText('R: ').addClass(prefix + 'rLabel');
		
		var inputR = new Element('input');
		var inputG = inputR.clone().inject(G).addClass(prefix + 'gInput');
		var inputB = inputR.clone().inject(B).addClass(prefix + 'bInput');
		inputR.inject(R).addClass(prefix + 'rInput');
		
		var HU = new Element('label').inject(box).setStyle('position', 'absolute');
		var SA = HU.clone().inject(box).addClass(prefix + 'SatuLabel').appendText('S: ');
		var BR = HU.clone().inject(box).addClass(prefix + 'BrighLabel').appendText('B: ');
		HU.appendText('H: ').addClass(prefix + 'HueLabel');

		var inputHU = new Element('input');
		var inputSA = inputHU.clone().inject(SA).addClass(prefix + 'SatuInput');
		var inputBR = inputHU.clone().inject(BR).addClass(prefix + 'BrighInput');
		inputHU.inject(HU).addClass(prefix + 'HueInput');
		SA.appendText(' %'); BR.appendText(' %');
		new Element('span', {'styles': {'position': 'absolute'}, 'class': prefix + 'ballino'}).set('html', " &deg;").injectAfter(HU);

		var hex = new Element('label').inject(box).setStyle('position', 'absolute').addClass(prefix + 'hexLabel').appendText('#hex: ').adopt(new Element('input').addClass(prefix + 'hexInput'));
		
		var ok = new Element('input', {
			'styles': {'position': 'absolute'},
			'type': 'button',
			'value': C_LANG_SELECCIONAR,
			'class': prefix + 'okButton'
		}).inject(box);

		var empty = new Element('input', {
			'styles': {'position': 'absolute'},
			'type': 'button',
			'value': C_LANG_VACIAR,
			'class': prefix + 'emptyButton'
		}).inject(box);

		var transp = new Element('a', {'style': {'position': 'absolute'}, 'href': '#', 'class': prefix + 'transp'}).inject(box);
		
		this.rePosition();

		var overlays = $$('#' + idPrefix + 'overlay');
		this.layout.overlay = overlays[0];
		this.layout.overlay2 = overlays[1];
		this.layout.cursor = document.getElement('#' + idPrefix + 'cursor');
		this.layout.arrows = document.getElement('#' + idPrefix + 'arrows');
		this.chooseColor = document.getElement('#' + idPrefix + 'chooseColor');
		this.layout.backup = document.getElement('#' + idPrefix + 'currentColor');
		this.RedInput = document.getElement('#' + idPrefix + 'rInput');
		this.GreenInput = document.getElement('#' + idPrefix + 'gInput');
		this.BlueInput = document.getElement('#' + idPrefix + 'bInput');
		this.HueInput = document.getElement('#' + idPrefix + 'HueInput');
		this.SatuInput = document.getElement('#' + idPrefix + 'SatuInput');
		this.BrighInput = document.getElement('#' + idPrefix + 'BrighInput');
		this.hexInput = document.getElement('#' + idPrefix + 'hexInput');

		this.arrRGB = [this.RedInput, this.GreenInput, this.BlueInput];
		this.arrHSB = [this.HueInput, this.SatuInput, this.BrighInput];
		this.okButton = document.getElement('#' + idPrefix + 'okButton');
		this.emptyButton = document.getElement('#' + idPrefix + 'emptyButton');
		this.transp = box.getElement('.' + prefix + 'transp');
		
		if (!window.khtml) this.hide();
	},
	rePosition: function() {
		var coords = this.element.getCoordinates();
		this.layout.setStyles({
			'left': coords.left,
			'top': coords.top + coords.height + 1
		});
	},
	
	snippet: function(mode, type) {
		var size; type = (type) ? type : 'none';

		switch(mode) {
			case 'arrPos':
				var t = this.layout.arrows.getStyle('top').toInt();
				size = t;
				break;
			case 'arrSize': 
				var h = this.layout.arrows.height;
				h = (type == 'int') ? (h/2).toInt() : h;
				size = h;
				break;		
			case 'curPos':
				var l = this.layout.cursor.getStyle('left').toInt();
				var t = this.layout.cursor.getStyle('top').toInt();
				size = {'l': l, 't': t};
				break;
			case 'slider':
				var t = this.layout.slider.getStyle('marginTop').toInt();
				size = t;
				break;
			default :
				var h = this.layout.cursor.height;
				var w = this.layout.cursor.width;
				h = (type == 'int') ? (h/2).toInt() : h;
				w = (type == 'int') ? (w/2).toInt() : w;
				size = {w: w, h: h};
		};
		return size;
	}
});

MooRainbow.implement(new Options);
MooRainbow.implement(new Events);

/*
Script: piechart.js

Dependencies:
	mootools-beta-1.2b2.js
	moocanvas.js

Author:
	Greg Houston, <http://greghoustondesign.com/>

Credits:
	Based on Stoyan Stefanov's Canvas Pie:< http://www.phpied.com/canvas-pie/>
	Color algorithm inspired by Jim Bumgardner:<http://www.krazydad.com/makecolors.php>

License:
	MIT License, <http://en.wikipedia.org/wiki/MIT_License>	
	
Example Usage:
	
<table class="pieChart">
    <tr><th>Browser</th> <th>Value</th></tr>
    <tr><td>Safari </td> <td>180  </td></tr>
    <tr><td>Firefox</td> <td>210  </td></tr>
    <tr><td>IE     </td> <td>30   </td></tr>
    <tr><td>Opera  </td> <td>120  </td></tr>
</table>

*/


var PieChartToolTiped = new Class({
	options: {
		pieChartRadius: 100,  // Half the width of your pie chart
    	td_label_index: 0,    // which TD contains the label			
    	td_index: 1           // which TD contains the data		
	},
	initialize: function(options) {
		this.setOptions(options);
		
		// Initialize variables
		this.pieChartRadius = this.options.pieChartRadius;	
		this.pieChartDiameter = this.pieChartRadius * 2;
		this.pieVertices = 12; // Does not include the center vertex
		this.arcIncrementMultiplier = 1 / this.pieVertices;
		this.index = 0;
		this.tableIndex = 1;
		this.areaIndex = 1;
		this.canvas = '';
		this.container = '';
		this.data_table = '';
		
		// Run Methods
		$$('.pieChart').each(function(el) {
			this.insertElements(el);
			this.makePieChart(el);			
		}.bind(this));
		this.addToolTips();		
	},
	insertElements: function(el) {
		
    	///// STEP 1 - Insert HTML Elements
	
		// Insert a div that will contain both the pie chart and it's legend
		this.container = new Element('div', {
			id: 'pieChartContainer' + this.tableIndex
		}).injectBefore($(el)).addClass('pieChartContainer');

		// Pull the table out of the page and put it in the pie chart container
		this.data_table = el.clone().injectBottom(this.container);
		el.dispose();
		
		// Insert a div that will contain both the pie chart canvas and it's image map overlay		
		new Element('div', {
			id: 'pieChartWrapper' + this.tableIndex
		}).injectTop(this.container).addClass('pieChartWrapper');
		
		// Insert the canvas to draw the pie on
		this.canvas = new Element('canvas', {
			id: 'canvas' + this.tableIndex,
			width: this.pieChartDiameter,
			height: this.pieChartDiameter
		}).injectInside(this.container.getElement('.pieChartWrapper')).addClass('pieChartCanvas');
		
		// Insert the map element. The area elements will be added later
		new Element('map', {		
			id: 'pieChartMap' + this.tableIndex,
			name: 'pieChartMap' + this.tableIndex
		}).injectBottom(this.container).addClass('pieChartMap');
		
		// Insert the blank transparent gif that is used for the image map
		new Asset.image('/img/spacer.gif', {
			alt: '',
			usemap: '#pieChartMap' + this.tableIndex,
			width: this.pieChartDiameter,
			height: this.pieChartDiameter
		}).injectInside(this.container.getElement('.pieChartWrapper')).setStyles({
				'width': this.pieChartDiameter,
				'height': this.pieChartDiameter
			});

		// Insert a div to insure layout integrity
		new Element('div').injectBottom(this.container).addClass('clear');
	
	},
	makePieChart: function() {

    	///// STEP 2 - Get the data

    	// Get the data[] from the table
    	var tds, data = [], color, colors = [], label, labels = [], value = 0, values = [], total = 0;
    	var trs = this.data_table.getElementsByTagName('tr'); // all TRs
    	
		// For each table row ...
		for (var i = 0; i < trs.length; i++) {
        	tds = trs[i].getElementsByTagName('td'); // Get the TDs for this row. There should two of them

			if (tds.length === 0) continue; //  no TDs here, move on

        	// Get the value, update total
			label = tds[this.options.td_label_index].innerHTML;
			labels[colors.length] = label; // Save value for tooltips
			
        	value = parseFloat(tds[this.options.td_index].innerHTML);
			values[colors.length] = value; // Save value for canvas and tooltips     	

        	total += value;

        	// Get color
        	color = this.getColor(i, trs.length);
        	colors[colors.length] = color; // Save color for corresponding pie slice
        	trs[i].style.backgroundColor = color; // Color this TR
    	}

    	///// STEP 3 - Draw pie on canvas

    	// get canvas context, determine radius and center
    	var ctx = this.canvas.getContext('2d');

		var tableLength = colors.length;
    	for (piece=0; piece < tableLength; piece++) {

        	var thisvalue = values[piece] / total;		
			var arcStartAngle = Math.PI * (- 0.5 + 2 * this.index); // -0.5 sets set the start to be top
			var arcEndAngle = Math.PI * (- 0.5 + 2 * (this.index + thisvalue));		

			ctx.beginPath();
			ctx.moveTo(this.pieChartRadius, this.pieChartRadius); // Center of the pie
			ctx.arc(  // draw next arc
            	this.pieChartRadius,
            	this.pieChartRadius,
            	this.pieChartRadius,
            	arcStartAngle,
            	arcEndAngle,
            	false
        	);
        	ctx.closePath();		
        	ctx.fillStyle = colors[piece]; // Color
        	ctx.fill();
		
			// Draw the same thing again to draw stroke properly in IE
			ctx.lineWidth = 1;
        	ctx.beginPath();
        	ctx.moveTo(this.pieChartRadius, this.pieChartRadius);

        	ctx.arc(  // draw next arc
            	this.pieChartRadius,
            	this.pieChartRadius,
            	this.pieChartRadius,
            	arcStartAngle, 
            	arcEndAngle,
            	false
        	);
        	ctx.closePath();		
			ctx.strokeStyle = "#FFF";
			ctx.stroke();

    		///// STEP 4 - Draw pie on image map
		
			var arcIncrement = (arcEndAngle - arcStartAngle) * this.arcIncrementMultiplier;
		
			var xx = this.pieChartRadius + Math.round(Math.cos(arcStartAngle) * this.pieChartRadius);
			var yy = this.pieChartRadius + Math.round(Math.sin(arcStartAngle) * this.pieChartRadius);
			
			var coord = [];
			var coordIndex = 1;
						
			for (i = 0; i < ((this.pieVertices * 2) - 2); i = i+2) {				
				var arcAngle = arcStartAngle + arcIncrement * coordIndex;
				coord[i] = this.pieChartRadius + Math.round(Math.cos(arcAngle) * this.pieChartRadius);				
				coord[i+1] = this.pieChartRadius + Math.round(Math.sin(arcAngle) * this.pieChartRadius);
				coordIndex++;			
			}
		
			var xxEnd = this.pieChartRadius + Math.round(Math.cos(arcEndAngle) * this.pieChartRadius);
			var yyEnd = this.pieChartRadius + Math.round(Math.sin(arcEndAngle) * this.pieChartRadius);			

			var myArea = 'area' + this.tableIndex + '-' + piece;
		
			new Element('area', {
				'id': myArea ,
				'shape': 'poly',
				'coords': this.pieChartRadius + ',' + this.pieChartRadius + ',' + + xx + ',' + yy + ',' + coord.join(',') +  ',' + xxEnd + ',' + yyEnd,
				'title': labels[piece] + ' :: ' + values[piece]
			}).injectInside(this.container.getElement('.pieChartMap'));

        	this.index += thisvalue; // increment progress tracker
    	}

	this.tableIndex++;
    	
	},
	addToolTips: function() {    

    		///// STEP 5 - Add Tooltips

			new Tips($$(document.getElementsByTagName('area')), {
				showDelay: 10,
				hideDelay: 10
			});	
	},
	getColor: function(i, totalSteps) {
		var colori = i * 100 / totalSteps;		
		var frequency = Math.PI*2 / totalSteps;
		var center = 190;
		var amplitude = 60;
        var rgb = [];	
		rgb[0] = Math.round(Math.sin(frequency * i + 0) * amplitude + center);
		rgb[1] = Math.round(Math.sin(frequency * i + 2) * amplitude + center);
		rgb[2] = Math.round(Math.sin(frequency * i + 4) * amplitude + center);	
		return 'rgb(' + rgb.join(',') + ')';
	}	
});
PieChartToolTiped.implement(new Options);

/**
* Chart class
* Create plots from table objet with plootr: http://utils.softr.net/plootr/
* Author: Patrice Ferlet (metal3d@copix.org)
* Licence: MIT
*/
var AIOTable2Chart = new Class({
	labels: '',
	datas: '',
	colors: '',
	target: '',
	legends: [],
	initialize: function(options) {
		//console.log('init')
		this.labels = new Array();
		this.datas = new Array();
		this.colors = new Array();
		this.options = Object.extend(this.options, options || {});
	},
	options: {
				padding: {left: 30, right: 0, top: 10, bottom: 30},
				barOrientation: 'vertical',
				colorScheme: 'blue'
	},
	setDatas: function (id) {
		this.target = id;
		var ob;
		var obname;
		var datas = {};
		var fulldatas = new Array();
		var legends = new Array();
		$$('#'+id+' tr').each(function (el,i) {
			if (i == 0) {
				//header
				ob = new Array();
				j=0;
				el.getElements('th').each(function(th) {
					 //console.debug(th);
					 if (th.get('text')!="") {			
					 	ob[j] ={v:j, label: th.get('text')};
					 	j++;
				 	 }						
				});
			} else {
				obname = '';
				try {
					var Zobname = el.getElements('th')[0].get('text');
					if (Zobname!="") {
						obname = Zobname.replace(/[^a-zA-Z0-9]/,'_');
					} else {
						obname = 'data_'+i;
					}
					
				} catch(e) {
					obname = 'data_'+i;
				}
				legends.push(obname);
				eval('datas.'+obname+'=new Array();');
				el.getElements('td').each(function(td,k) {
					//console.log(td);
					eval('datas.' + obname + '.push([k,td.get(\'text\').toInt()]);');	
				});
			}
		});
		this.datas = datas; 
		this.labels = ob;
		this.legends = legends;
		//console.debug(this);
	},
	createScheme: function () {
		if (this.options.colors) {
			colorScheme= new Hash();
			for (i in this.options.colors) {
				colorScheme.set(this.legends[i],this.options.colors[i]);
			}
			this.options.colorScheme = colorScheme.obj;
		}		
	},
	render: function(where) {
		this.options.xTicks = this.labels;
		this.createScheme();
		var plot = new AIOChart(where, this.options);
		// BACKHERE
		plot.addDataset(this.datas);
		plot.render();
		if (this.options.legend == true) {
			plot.addLegend(where);
		}
		plot.reset();
		plot = null;
	}
});

Element.implement({
	toChart: function(options) {
		this.options = Object.extend({
			type: 'bars',
			width: 550,
			height: 350,
			showInSide: true,
			shouldFill: true
		}, options || {});

		if (this.get('tag') != "table") {
			throw 'toChart() only works with tables !';
		}
		
		var container = new Element('div').injectAfter(this);
		
		var c = new AIOTable2Chart(this.options);
		c.setDatas(this.id);
		
		// console.debug(c);
		
		c.render(container);
		id = this.id;
		this.empty();
		container.id = id;
	}
});
/*
 * DatePicker
 * @author Rick Hopkins
 * @modified by Micah Nolte and Martin Va?ina
 * @version 0.3.2
 * @classDescription A date picker object. Created with the help of MooTools v1.11
 * MIT-style License.

-- start it up by doing this in your domready:

$$('input.DatePicker').each( function(el) {
	new DatePicker(el);
});

*/
var DatePicker = new Class({

	/* set and create the date picker text box */
	initialize: function(dp) {

		// Options defaults
		this.dayChars = 2; // number of characters in day names abbreviation
		this.dayNames = [C_LANG_DOMINGO, C_LANG_LUNES, C_LANG_MARTES, C_LANG_MIERCOLES, C_LANG_JUEVES, C_LANG_VIERNES, C_LANG_SABADO];
		this.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		this.format = 'dd/mm/yyyy';
		this.monthNames = [C_LANG_ENERO, C_LANG_FEBRERO, C_LANG_MARZO, C_LANG_ABRIL, C_LANG_MAYO, C_LANG_JUNIO, C_LANG_JULIO, C_LANG_AGOSTO, C_LANG_SEPTIEMBRE, C_LANG_OCTUBRE, C_LANG_NOVIEMBRE, C_LANG_DICIEMBRE];
		this.startDay = 7; // 1 = week starts on Monday, 7 = week starts on Sunday
		this.yearOrder = 'desc';
		this.yearRange = 10;
		this.yearStart = (new Date().getFullYear() + 7);

		// Finds the entered date, or uses the current date
		if (dp.value != '') {
			dp.then = new Date( dp.value.split('/')[2].toInt(), (dp.value.split('/')[1].toInt()-1).toInt(), dp.value.split('/')[0].toInt());
			dp.today = new Date();
		} else {
			dp.then = dp.today = new Date();
		}
		// Set beginning time and today, remember the original
		dp.oldYear = dp.year = dp.then.getFullYear();
		dp.oldMonth = dp.month = dp.then.getMonth();
		dp.oldDay = dp.then.getDate();
		dp.nowYear = dp.today.getFullYear();
		dp.nowMonth = dp.today.getMonth();
		dp.nowDay = dp.today.getDate();

		// Pull the rest of the options from the alt attr
		if (dp.alt) {
			// console.debug(dp.alt);
			options = JSON.decode(dp.alt);
		} else {
			if ($defined(options)) {
				options = [];
			} else {
				var options = [];
			}
		}
		dp.options = {
			monthNames: (options.monthNames && options.monthNames.length == 12 ? options.monthNames : this.monthNames) || this.monthNames, 
			daysInMonth: (options.daysInMonth && options.daysInMonth.length == 12 ? options.daysInMonth : this.daysInMonth) || this.daysInMonth, 
			dayNames: (options.dayNames && options.dayNames.length == 7 ? options.dayNames : this.dayNames) || this.dayNames,
			startDay : options.startDay || this.startDay,
			dayChars : options.dayChars || this.dayChars, 
			format: options.format || this.format,
			yearStart: options.yearStart || this.yearStart,
			yearRange: options.yearRange || this.yearRange,
			yearOrder: options.yearOrder || this.yearOrder
		};
		dp.setProperties({'id':dp.get('name'), 'readonly':true});
		dp.container = false;
		dp.calendar = false;
		dp.interval = null;
		dp.active = false;
		dp.onclick = dp.onfocus = this.create.pass(dp, this);
	},

	/* create the calendar */
	create: function(dp) {
		if (dp.calendar) return false;

		// Hide select boxes while calendar is up
		if (window.ie6) {
			$$('select').addClass('dp_hide');
		}
		
		/* create the outer container */
		dp.container = new Element('div', {'class': 'dp_container'}).injectBefore(dp);
		
		/* create timers */
		dp.container.onmouseover = dp.onmouseover = function() {
			$clear(dp.interval);
		};
		dp.container.onmouseout = dp.onmouseout = function() {
			dp.interval = setInterval(function() {
				if (!dp.active) this.remove(dp);
			}.bind(this), 500);
		}.bind(this);
		
		/* create the calendar */
		dp.calendar = new Element('div', {'class': 'dp_cal'}).injectInside(dp.container);
		
		/* create the date object */
		var date = new Date();
		
		/* create the date object */
		if (dp.month && dp.year) {
			date.setFullYear(dp.year, dp.month, 1);
		} else {
			dp.month = date.getMonth();
			dp.year = date.getFullYear();
			date.setDate(1);
		}
		dp.year % 4 == 0 ? dp.options.daysInMonth[1] = 29 : dp.options.daysInMonth[1] = 28;
		
		/* set the day to first of the month */
		var firstDay = (1 - (7 + date.getDay() - dp.options.startDay) % 7);
		
		/* create the month select box */
		monthSel = new Element('select', {'id': dp.id + '_monthSelect'});
		for (var m = 0; m < dp.options.monthNames.length; m++) {
			monthSel.options[m] = new Option(dp.options.monthNames[m], m);
			if (dp.month == m) monthSel.options[m].selected = true;
		}
		
		/* create the year select box */
		yearSel = new Element('select', {'id': dp.id + '_yearSelect'});
		i = 0;
		dp.options.yearStart ? dp.options.yearStart : dp.options.yearStart = date.getFullYear();
		if (dp.options.yearOrder == 'desc') {
			for (var y = dp.options.yearStart; y > (dp.options.yearStart - dp.options.yearRange - 1); y--) {
				yearSel.options[i] = new Option(y, y);
				if (dp.year == y) yearSel.options[i].selected = true;
				i++;
			}
		} else {
			for (var y = dp.options.yearStart; y < (dp.options.yearStart + dp.options.yearRange + 1); y++) {
				yearSel.options[i] = new Option(y, y);
				if (dp.year == y) yearSel.options[i].selected = true;
				i++;
			}
		}
		
		/* start creating calendar */
		calTable = new Element('table');
		calTableThead = new Element('thead');
		calSelRow = new Element('tr');
		calSelCell = new Element('th', {'colspan':'7'});
		monthSel.injectInside(calSelCell);
		yearSel.injectInside(calSelCell);
		calSelCell.injectInside(calSelRow);
		calSelRow.injectInside(calTableThead);
		calTableTbody = new Element('tbody');
		
		/* create day names */
		calDayNameRow = new Element('tr');
		for (var i = 0; i < dp.options.dayNames.length; i++) {
			calDayNameCell = new Element('th');
			calDayNameCell.appendText(dp.options.dayNames[(dp.options.startDay+i)%7].substr(0, dp.options.dayChars)); 
			calDayNameCell.injectInside(calDayNameRow);
		}
		calDayNameRow.injectInside(calTableTbody);
		
		/* create the day cells */
		while (firstDay <= dp.options.daysInMonth[dp.month]) {
			calDayRow = new Element('tr');
			for (i = 0; i < 7; i++) {
				if ((firstDay <= dp.options.daysInMonth[dp.month]) && (firstDay > 0)) {
					calDayCell = new Element('td', {'class': dp.id + '_calDay', 'axis': dp.year + '|' + (parseInt(dp.month) + 1) + '|' + firstDay}).appendText(firstDay).injectInside(calDayRow);
				} else {
					calDayCell = new Element('td', {'class':' dp_empty'}).appendText(' ').injectInside(calDayRow);
				}
				// Show the previous day
				if ( (firstDay == dp.oldDay) && (dp.month == dp.oldMonth ) && (dp.year == dp.oldYear) ) {
					calDayCell.addClass('dp_selected');
				}
				// Show today
				if ( (firstDay == dp.nowDay) && (dp.month == dp.nowMonth ) && (dp.year == dp.nowYear) ) {
					calDayCell.addClass('dp_today');
				}
				firstDay++;
			}
			calDayRow.injectInside(calTableTbody);
		}
		
		/* table into the calendar div */
		calTableThead.injectInside(calTable);
		calTableTbody.injectInside(calTable);
		calTable.injectInside(dp.calendar);
		
		/* set the onmouseover events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el) {
			el.onmouseover = function() {
				el.addClass('dp_roll');
			}.bind(this);
		}.bind(this));
		
		/* set the onmouseout events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el) {
			el.onmouseout = function() {
				el.removeClass('dp_roll');
			}.bind(this);
		}.bind(this));
		
		/* set the onclick events for all calendar days */
		$$('td.' + dp.id + '_calDay').each(function(el) {
			el.onclick = function() {
				ds = el.axis.split('|');
				dp.value = this.formatValue(dp, ds[0], ds[1], ds[2]);
				this.remove(dp);
			}.bind(this);
		}.bind(this));
		
		/* set the onchange event for the month & year select boxes */
		monthSel.onfocus = function() { dp.active = true; };
		monthSel.onchange = function() {
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);
		}.bind(this);
		
		yearSel.onfocus = function() { dp.active = true; };
		yearSel.onchange = function() {
			dp.month = monthSel.value;
			dp.year = yearSel.value;
			this.remove(dp);
			this.create(dp);
		}.bind(this);
		return true;
	},
	
	/* Format the returning date value according to the selected formation */
	formatValue: function(dp, year, month, day) {
		/* setup the date string variable */
		var dateStr = '';
		
		/* check the length of day */
		if (day < 10) day = '0' + day;
		if (month < 10) month = '0' + month;
		
		/* check the format & replace parts // thanks O'Rey */
		dateStr = dp.options.format.replace( /dd/i, day ).replace( /mm/i, month ).replace( /yyyy/i, year );
		dp.month = dp.oldMonth = '' + (month - 1) + '';
		dp.year = dp.oldYear = year;
		dp.oldDay = day;
		
		/* return the date string value */
		return dateStr;
	},
	
	/* Remove the calendar from the page */
	remove: function(dp) {
		$clear(dp.interval);
		dp.active = false;
		if (window.opera) dp.container.empty();
		else if (dp.container) dp.container.empty();
		dp.calendar = false;
		dp.container = false;
		$$('select.dp_hide').removeClass('dp_hide');
	}
});
