var fdLocale = {
        months:[
                "Enero",
                "Febrero",
                "Marzo",
                "Abril",
                "Mayo",
                "Junio",
                "Julio",
                "Agosto",
                "Septiembre",
                "Octubre",
                "Noviembre",
                "Diciembre"
                ],
        fullDay:[
                "Lunes",
                "Martes",
                "Mi\u00e9rcoles",
                "Jueves",
                "Viernes",
                "S\u00e1bado",
                "Domingo"
                ],
        /* Only stipulate the dayAbbr should the first letter of the fullDay not suffice

        dayAbbr:[],
        */

        /* Only stipulate the firstDayOfWeek should the first day not be Monday

        firstDayOfWeek:0,
        */
        titles:[
                "Mes Anterior",
                "Mes Siguiente",
                "A\u00f1o anterior",
                "A\u00f1o Siguiente",
                "Hoy"
                ]
};


var voranet_locales = {
        main:{
            error: "Error",
            del: "Borrar",
            ok: "Aceptar",
            cancel: "Cancelar",
            alert: "Aviso"
        },
        link_window:{
            invalid_mail: "La dirección de correo introducida no es válida",
            send_mail: "Enviar correo electrónico a ",
            follow_link: "Ir a "
        },
        tree:{
            select_goal: "Seleccione primero un destino"
        },
        table:{
            invalid_values: "Debe introducir un número de filas y columnas válido",
            default_text: "Inserte su texto..."
        },
        galeria:{
                aniadida: "La galeria se ha añadido correctamente."
        },
        image:{
                added: "La imagen se ha añadido correctamente.",
                confirm: "La imagen será borrada del disco, ¿está seguro?"
        },
        document:{
                added: "El documento se ha añadido correctamente.",
                confirm: "El documento será borrado del disco, ¿está seguro?"
        },
        video:{
                added: "El vídeo se ha añadido correctamente."
        },
        flash:{
                added: "El flash se ha añadido correctamente."
        },
        folder:{
                confirm: "La carpeta será borrada del disco, ¿está seguro?"
        },
        gmaps:{
            new_mark: "Nuevo marcador",
            mark_text: "Introduzca un texto descriptivo",
            confirm_delete: "¿Desea borrar el mapa?",
            mark: "Marcador",
            added: "El mapa se ha añadido correctamente"
        },
        nicedit:{
            bold: "Negrita",
            italic: "Cursiva",
            underline: "Subrayado",
            left: "Alineado a la izquierda",
            center: "Centrado",
            right: "Alineado a la derecha",
            justify: "Justificado",
            ol: "Lista ordenada",
            ul: "Lista desordenada",
            subscript: "Subíndice",
            superscript: "Superíndice",
            strikethrough: "Tachado",
            indent: "Sangrar texto",
            outdent: "Quitar sangrado",
            hr: "Insertar separador",
            image: "Insertar imágenes",
            video: "Insertar vídeos",
            flash: "Insertar flash",
            document: "Insertar documentos",
            gallery: "Insertar galerías",
            gmap: "Insertar mapas",
            style: "Elija estilo",
            table: "Insertar tablas",
            link: "Añadir enlace",
            unlink: "Borrar enlace"
        },
        gallery: {
            play: "Reproducir",
            pause: "Pausa",
            previous: "Anterior",
            next: "Siguiente",
            image: "Imagen",
            of: "de"
        }
};


// jQuery Alert Dialogs Plugin
//
// Version 1.0
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 29 December 2008
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
// License:
// 
//		This plugin is licensed under the GNU General Public License: http://www.gnu.org/licenses/gpl.html
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;Aceptar&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Cancelar&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', 'popup_container',function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', 'popup_container',function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', 'popup_container',function(result) {
				if( callback ) callback(result);
			});
		},
		info: function(message, title, callback) {
			if( title == null ) title = 'Info';
			$.alerts._show(title, message, null, 'info', 'popup_container_info',function(result) {
				if( callback ) callback(result);
			});
		},
		infomessage: function(message, title, callback) {
			if( title == null ) title = 'Message';
			$.alerts._show(title, message, null, 'infomessage', 'popup_container_message',function(result) {
				if( callback ) callback(result);
			});
		},
		wait: function(message, title, callback) {
			if( title == null ) title = 'Wait';
			$.alerts._show(title, message, null, 'wait', 'popup_container_info',function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, class_name, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$(parent.document.body).append(
			  '<div id="popup_container" class="' + class_name + '">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) parent.$("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			parent.$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			parent.$("#popup_title").text(title);
			parent.$("#popup_content").addClass(type);
            if (type=="prompt" || type=="confirm") {
    			parent.$("#popup_message").text("<p>" + msg + "</p>");
            }
            else {
                parent.$("#popup_message").text(msg);
            }
			parent.$("#popup_message").html( parent.$("#popup_message").text());//.replace(/\n/g, '<br />') );
            if (type=="wait")
                parent.$("#popup_message").after('<img src="/images/thickbox/loadingAnimation.gif"/>');
			parent.$("#popup_container").css({
				minWidth: parent.$("#popup_container").outerWidth(),
				maxWidth: parent.$("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					parent.$("#popup_title").after('<a class="popup_close"></a>');
					parent.$("#popup_message").after('<div id="popup_panel"><input type="button" value="&nbsp;' + t('main.ok') + '&nbsp;" id="popup_ok" /></div>');
					parent.$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					parent.$(".popup_close").click( function() {
						$.alerts._hide();
						callback(true);
					});
					parent.$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) parent.$("#popup_ok").trigger('click');
					});
				break;
				case 'info':
					parent.$("#popup_title").after('<a class="popup_close" id="popup_ok"></a>');
					parent.$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					parent.$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) parent.$("#popup_ok").trigger('click');
					});
				case 'infomessage':
					parent.$("#popup_title").after('<a class="popup_close" id="popup_ok"></a>');
					parent.$("#popup_message").after('<div id="popup_panel"><input type="button" value="&nbsp;' + t('main.ok') + '&nbsp;" id="popup_btn_ok" /></div>');
					parent.$("#popup_ok, #popup_btn_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					parent.$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) parent.$("#popup_ok").trigger('click');
					});
				break;
				case 'wait':
					parent.$("#popup_title").after('<a id="popup_ok"></a>');
				break;
				case 'confirm':
					parent.$("#popup_message").after('<div id="popup_panel"><input type="button" value="&nbsp;' + t('main.ok') + '&nbsp;" id="popup_ok" /> <input type="button" value="&nbsp;' + t('main.cancel') + '&nbsp;" id="popup_cancel" /></div>');
					parent.$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					parent.$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					parent.$("#popup_ok").focus();
					parent.$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) parent.$("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) parent.$("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					parent.$("#popup_message").append('<input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="&nbsp;' + t('main.ok') + '&nbsp;" id="popup_ok" /> <input type="button" value="&nbsp;' + t('main.cancel') + '&nbsp;" id="popup_cancel" /></div>');
//					$("#popup_prompt").width( $("#popup_message").width() );
					parent.$("#popup_ok").click( function() {
						var val = parent.$("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					parent.$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					parent.$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) parent.$("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) parent.$("#popup_cancel").trigger('click');
					});
					if( value ) parent.$("#popup_prompt").val(value);
					parent.$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					parent.$("#popup_container").draggable({ handle: parent.$("#popup_title") });
					parent.$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			parent.$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$(parent.document.body).append('<div id="popup_overlay"></div>');
					parent.$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					parent.$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - (parent.$("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - (parent.$("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;

			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			parent.$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			parent.$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', function() {
							$.alerts._reposition();
						});
					break;
					case false:
						$(window).unbind('resize');
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

	jInfo = function(message, title, callback) {
		$.alerts.info(message, title, callback);
	};

	jMessage = function(message, title, callback) {
		$.alerts.infomessage(message, title, callback);
	};

	jWait = function(message, title, callback) {
		$.alerts.wait(message, title, callback);
	};
	
})(jQuery);


﻿
(function($){$().ajaxSend(function(a,xhr,s){xhr.setRequestHeader("Accept","text/javascript, text/html, application/xml, text/xml, */*");});})(jQuery);(function($){$.extend({fieldEvent:function(el,obs){var field=el[0]||el,e='change';if(field.type=='radio'||field.type=='checkbox')e='click';else if(obs&&field.type=='text'||field.type=='textarea')e='keyup';return e;}});$.fn.extend({delayedObserver:function(delay,callback){var el=$(this);if(typeof window.delayedObserverStack=='undefined')window.delayedObserverStack=[];if(typeof window.delayedObserverCallback=='undefined'){window.delayedObserverCallback=function(stackPos){observed=window.delayedObserverStack[stackPos];if(observed.timer)clearTimeout(observed.timer);observed.timer=setTimeout(function(){observed.timer=null;observed.callback(observed.obj,observed.obj.formVal());},observed.delay*1000);observed.oldVal=observed.obj.formVal();}}
window.delayedObserverStack.push({obj:el,timer:null,delay:delay,oldVal:el.formVal(),callback:callback});var stackPos=window.delayedObserverStack.length-1;if(el[0].tagName=='FORM'){$(':input',el).each(function(){var field=$(this);field.bind($.fieldEvent(field,delay),function(){observed=window.delayedObserverStack[stackPos];if(observed.obj.formVal()==observed.obj.oldVal)return;else window.delayedObserverCallback(stackPos);});});}else{el.bind($.fieldEvent(el,delay),function(){observed=window.delayedObserverStack[stackPos];if(observed.obj.formVal()==observed.obj.oldVal)return;else window.delayedObserverCallback(stackPos);});};},formVal:function(){var el=this[0];if(el.tagName=='FORM')return this.serialize();if(el.type=='checkbox'||self.type=='radio')return this.filter('input:checked').val()||'';else return this.val();}});})(jQuery);(function($){$.fn.extend({visualEffect:function(o){return this.effect(o);},Appear:function(speed,callback){return this.fadeIn(speed,callback);},BlindDown:function(speed,callback){this.show('blind',{direction:'vertical'},speed,callback);return this;},BlindUp:function(speed,callback){this.hide('blind',{direction:'vertical'},speed,callback);return this;},BlindRight:function(speed,callback){this.show('blind',{direction:'horizontal'},speed,callback);return this;},BlindLeft:function(speed,callback){this.hide('blind',{direction:'horizontal'},speed,callback);return this;},DropOut:function(speed,callback){this.hide('drop',{direction:'down'},speed,callback);return this;},DropIn:function(speed,callback){this.show('drop',{direction:'up'},speed,callback);return this;},Fade:function(speed,callback){return this.fadeOut(speed,callback);},Fold:function(speed,callback){this.hide('fold',{},speed,callback);return this;},FoldOut:function(speed,callback){this.show('fold',{},speed,callback);return this;},Grow:function(speed,callback){this.show('scale',{},speed,callback);return this;},Highlight:function(speed,callback){this.show('highlight',{},speed,callback);return this;},Puff:function(speed,callback){this.hide('puff',{},speed,callback);return this;},Pulsate:function(speed,callback){this.show('pulsate',{},speed,callback);return this;},Shake:function(speed,callback){this.show('shake',{},speed,callback);return this;},Shrink:function(speed,callback){this.hide('scale',{},speed,callback);return this;},Squish:function(speed,callback){this.hide('scale',{origin:['top','left']},speed,callback);return this;},SlideUp:function(speed,callback){this.hide('slide',{direction:'up'},speed,callback);return this;},SlideDown:function(speed,callback){this.show('slide',{direction:'up'},speed,callback);return this;},SwitchOff:function(speed,callback){this.hide('clip',{},speed,callback);return this;},SwitchOn:function(speed,callback){this.show('clip',{},speed,callback);return this;}});})(jQuery);

/* NicEdit - Micro Inline WYSIWYG
 * Copyright 2007-2008 Brian Kirchoff
 *
 * NicEdit is distributed under the terms of the MIT license
 * For more information visit http://nicedit.com/
 * Do not remove this copyright message
 */
var bkExtend = function(){
	var args = arguments;
	if (args.length == 1) args = [this, args[0]];
	for (var prop in args[1]) args[0][prop] = args[1][prop];
	return args[0];
};
function bkClass() { }
bkClass.prototype.construct = function() {};
bkClass.extend = function(def) {
  var classDef = function() {
      if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments); }
  };
  var proto = new this(bkClass);
  bkExtend(proto,def);
  classDef.prototype = proto;
  classDef.extend = this.extend;      
  return classDef;
};

var bkElement = bkClass.extend({
	construct : function(elm,d) {
		if(typeof(elm) == "string") {
			elm = (d || document).createElement(elm);
		}
		elm = $BK(elm);
		return elm;
	},
	
	appendTo : function(elm) {
		elm.appendChild(this);	
		return this;
	},
	
	appendBefore : function(elm) {
		elm.parentNode.insertBefore(this,elm);	
		return this;
	},
	
	addEvent : function(type, fn) {
		bkLib.addEvent(this,type,fn);
		return this;	
	},
	
	setContent : function(c) {
		this.innerHTML = c;
		return this;
	},
	
	pos : function() {
		var curleft = curtop = 0;
		var o = obj = this;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}
		var b = (!window.opera) ? parseInt(this.getStyle('border-width') || this.style.border) || 0 : 0;
		return [curleft+b,curtop+b+this.offsetHeight];
	},
	
	noSelect : function() {
		bkLib.noSelect(this);
		return this;
	},
	
	parentTag : function(t) {
		var elm = this;
		 do {
			if(elm && elm.nodeName && elm.nodeName.toUpperCase() == t) {
				return elm;
			}
			elm = elm.parentNode;
		} while(elm);
		return false;
	},
	
	hasClass : function(cls) {
		return this.className.match(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'));
	},
	
	addClass : function(cls) {
		if (!this.hasClass(cls)) { this.className += " nicEdit-"+cls };
		return this;
	},
	
	removeClass : function(cls) {
		if (this.hasClass(cls)) {
			this.className = this.className.replace(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'),' ');
		}
		return this;
	},

	setStyle : function(st) {
		var elmStyle = this.style;
		for(var itm in st) {
			switch(itm) {
				case 'float':
					elmStyle['cssFloat'] = elmStyle['styleFloat'] = st[itm];
					break;
				case 'opacity':
					elmStyle.opacity = st[itm];
					elmStyle.filter = "alpha(opacity=" + Math.round(st[itm]*100) + ")"; 
					break;
				case 'className':
					this.className = st[itm];
					break;
				default:
					//if(document.compatMode || itm != "cursor") { // Nasty Workaround for IE 5.5
						elmStyle[itm] = st[itm];
					//}		
			}
		}
		return this;
	},
	
	getStyle : function( cssRule, d ) {
		var doc = (!d) ? document.defaultView : d; 
		if(this.nodeType == 1)
		return (doc && doc.getComputedStyle) ? doc.getComputedStyle( this, null ).getPropertyValue(cssRule) : this.currentStyle[ bkLib.camelize(cssRule) ];
	},
	
	remove : function() {
		this.parentNode.removeChild(this);
		return this;	
	},
	
	setAttributes : function(at) {
		for(var itm in at) {
			this[itm] = at[itm];
		}
		return this;
	}
});

var bkLib = {
	isMSIE : (navigator.appVersion.indexOf("MSIE") != -1),
	
	addEvent : function(obj, type, fn) {
		(obj.addEventListener) ? obj.addEventListener( type, fn, false ) : obj.attachEvent("on"+type, fn);	
	},
	
	toArray : function(iterable) {
		var length = iterable.length, results = new Array(length);
    	while (length--) { results[length] = iterable[length] };
    	return results;	
	},
	
	noSelect : function(element) {
		if(element.setAttribute && element.nodeName.toLowerCase() != 'input' && element.nodeName.toLowerCase() != 'textarea') {
			element.setAttribute('unselectable','on');
		}
		for(var i=0;i<element.childNodes.length;i++) {
			bkLib.noSelect(element.childNodes[i]);
		}
	},
	camelize : function(s) {
		return s.replace(/\-(.)/g, function(m, l){return l.toUpperCase()});
	},
	inArray : function(arr,item) {
	    return (bkLib.search(arr,item) != null);
	},
	search : function(arr,itm) {
		for(var i=0; i < arr.length; i++) {
			if(arr[i] == itm)
				return i;
		}
		return null;	
	},
	cancelEvent : function(e) {
		e = e || window.event;
		if(e.preventDefault && e.stopPropagation) {
			e.preventDefault();
			e.stopPropagation();
		}
		return false;
	},
	domLoad : [],
	domLoaded : function() {
		if (arguments.callee.done) return;
		arguments.callee.done = true;
		for (i = 0;i < bkLib.domLoad.length;i++) bkLib.domLoad[i]();
	},
	onDomLoaded : function(fireThis) {
		this.domLoad.push(fireThis);
		if (document.addEventListener) {
			document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null);
		} else if(bkLib.isMSIE) {
			document.write("<style>.nicEdit-main p { margin: 0; }</style><scr"+"ipt id=__ie_onload defer " + ((location.protocol == "https:") ? "src='javascript:void(0)'" : "src=//0") + "><\/scr"+"ipt>");
			$BK("__ie_onload").onreadystatechange = function() {
			    if (this.readyState == "complete"){bkLib.domLoaded();}
			};
		}
	    window.onload = bkLib.domLoaded;
	}
};

function $BK(elm) {
	if(typeof(elm) == "string") {
		elm = document.getElementById(elm);
	}
	return (elm && !elm.appendTo) ? bkExtend(elm,bkElement.prototype) : elm;
}

var bkEvent = {
	addEvent : function(evType, evFunc) {
		if(evFunc) {
			this.eventList = this.eventList || {};
			this.eventList[evType] = this.eventList[evType] || [];
			this.eventList[evType].push(evFunc);
		}
		return this;
	},
	fireEvent : function() {
		var args = bkLib.toArray(arguments), evType = args.shift();
		if(this.eventList && this.eventList[evType]) {
			for(var i=0;i<this.eventList[evType].length;i++) {
				this.eventList[evType][i].apply(this,args);
			}
		}
	}	
};

function __(s) {
	return s;
}

Function.prototype.closure = function() {
  var __method = this, args = bkLib.toArray(arguments), obj = args.shift();
  return function() { if(typeof(bkLib) != 'undefined') { return __method.apply(obj,args.concat(bkLib.toArray(arguments))); } };
}
	
Function.prototype.closureListener = function() {
  	var __method = this, args = bkLib.toArray(arguments), object = args.shift(); 
  	return function(e) { 
  	e = e || window.event;
  	if(e.target) { var target = e.target; } else { var target =  e.srcElement };
	  	return __method.apply(object, [e,target].concat(args) ); 
	};
}		


/* START CONFIG */

var nicEditorConfig = bkClass.extend({
	buttons : {
		'bold' : {name : 'nicedit.bold', command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'},
		'italic' : {name : 'nicedit.italic', command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'},
		'underline' : {name : 'nicedit.underline', command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'},
		'left' : {name : 'nicedit.left', command : 'justifyleft', noActive : true},
		'center' : {name : 'nicedit.center', command : 'justifycenter', noActive : true},
		'right' : {name : 'nicedit.right', command : 'justifyright', noActive : true},
		'justify' : {name : 'nicedit.justify', command : 'justifyfull', noActive : true},
		'ol' : {name : 'nicedit.ol', command : 'insertorderedlist', tags : ['OL']},
		'ul' : 	{name : 'nicedit.ul', command : 'insertunorderedlist', tags : ['UL']},
		'subscript' : {name : 'nicedit.subscript', command : 'subscript', tags : ['SUB']},
		'superscript' : {name : 'nicedit.superscript', command : 'superscript', tags : ['SUP']},
		'strikethrough' : {name : 'nicedit.strikethrough', command : 'strikeThrough', css : {'text-decoration' : 'line-through'}},
//		'removeformat' : {name : __('Remove Formatting'), command : 'removeformat', noActive : true},
		'indent' : {name : 'nicedit.indent', command : 'indent', noActive : true},
		'outdent' : {name : 'nicedit.outdent', command : 'outdent', noActive : true}
//		'hr' : {name : __('Horizontal Rule'), command : 'insertHorizontalRule', noActive : true}
	},
//	iconsPath : '../nicEditorIcons.gif',
//	buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'],
//	iconList : {"bgcolor":1,"forecolor":2,"bold":3,"center":4,"hr":5,"indent":6,"italic":7,"justify":8,"left":9,"ol":10,"outdent":11,"removeformat":12,"right":13,"save":24,"strikethrough":15,"subscript":16,"superscript":17,"ul":18,"underline":19,"image":20,"link":21,"unlink":22,"close":23,"arrow":25}
	iconsPath : '/images/nicEditorIcons.gif',
	buttonList : ['bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','video','gallery','flash','document','gmap','upload','link','unlink','table','forecolor','bgcolor','hr'],
	iconList : {"xhtml":1,"bgcolor":2,"forecolor":3,"bold":4,"center":5,"hr":6,"indent":7,"italic":8,"justify":9,"left":10,"ol":11,"outdent":12,"removeformat":13,"right":14,"strikethrough":16,"subscript":17,"superscript":18,"ul":19,"underline":20,"image":21,"link":22,"unlink":23,"close":24,"arrow":26,"save":25,"gallery":27,"document":28,"gmap":29,"table":30,"video":31,"flash":32}
	
});
/* END CONFIG */


var nicEditors = {
	nicPlugins : [],
	editors : [],
	
	registerPlugin : function(plugin,options) {
		this.nicPlugins.push({p : plugin, o : options});
	},

	allTextAreas : function(nicOptions) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0;i<textareas.length;i++) {
			nicEditors.editors.push(new nicEditor(nicOptions).panelInstance(textareas[i]));
		}
		return nicEditors.editors;
	},
	
	findEditor : function(e) {
		var editors = nicEditors.editors;
		for(var i=0;i<editors.length;i++) {
			if(editors[i].instanceById(e)) {
				return editors[i].instanceById(e);
			}
		}
	}
};


var nicEditor = bkClass.extend({
	construct : function(o) {
		this.options = new nicEditorConfig();
		bkExtend(this.options,o);
		this.nicInstances = new Array();
		this.loadedPlugins = new Array();
		
		var plugins = nicEditors.nicPlugins;
		for(var i=0;i<plugins.length;i++) {
			this.loadedPlugins.push(new plugins[i].p(this,plugins[i].o));
		}
		nicEditors.editors.push(this);
		bkLib.addEvent(document.body,'mousedown', this.selectCheck.closureListener(this) );
	},
	
	panelInstance : function(e,o) {
		e = this.checkReplace($BK(e));
		var panelElm = new bkElement('DIV').setStyle({width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px'}).appendBefore(e);
		this.setPanel(panelElm);
		return this.addInstance(e,o);	
	},

	checkReplace : function(e) {
		var r = nicEditors.findEditor(e);
		if(r) {
			r.removeInstance(e);
			r.removePanel();
		}
		return e;
	},

	addInstance : function(e,o) {
		e = this.checkReplace($BK(e));
//		if( e.contentEditable || !!window.opera ) {
			var newInstance = new nicEditorInstance(e,o,this);
//		} else {
//			var newInstance = new nicEditorIFrameInstance(e,o,this);
//		}
		this.nicInstances.push(newInstance);
		return this;
	},
	
	removeInstance : function(e) {
		e = $BK(e);
		var instances = this.nicInstances;
		for(var i=0;i<instances.length;i++) {	
			if(instances[i].e == e) {
				instances[i].remove();
				this.nicInstances.splice(i,1);
			}
		}
	},

	removePanel : function(e) {
		if(this.nicPanel) {
			this.nicPanel.remove();
			this.nicPanel = null;
		}	
	},

	instanceById : function(e) {
		e = $BK(e);
		var instances = this.nicInstances;
		for(var i=0;i<instances.length;i++) {
			if(instances[i].e == e) {
				return instances[i];
			}
		}	
	},

	setPanel : function(e) {
		this.nicPanel = new nicEditorPanel($BK(e),this.options,this);
		this.fireEvent('panel',this.nicPanel);
		return this;
	},
	
	nicCommand : function(cmd,args) {	
		if(this.selectedInstance) {
                    try {
			this.selectedInstance.nicCommand(cmd,args);
                    } catch (e) {
//                        Ejecutamos el comando "a mano"
                        switch (cmd) {
                            case "justifycenter":
                            case "justifyleft":
                            case "justifyright":
                            case "justifyfull":
                                justify(cmd.replace("justify","").replace("full","justify"));

                        }
                    }
		}
	},
	
	getIcon : function(iconName,options) {
		var icon = this.options.iconList[iconName];
		var file = (options.iconFiles) ? options.iconFiles[iconName] : '';
		return {backgroundImage : "url('"+((icon) ? this.options.iconsPath : file)+"')", backgroundPosition : ((icon) ? ((icon-1)*-18) : 0)+'px 0px'};	
	},
		
	selectCheck : function(e,t) {
		var found = false;
		do{
			if(t.className && t.className.indexOf('nicEdit') != -1) {
				return false;
			}
		} while(t = t.parentNode);
		this.fireEvent('blur',this.selectedInstance,t);
		this.lastSelectedInstance = this.selectedInstance;
		this.selectedInstance = null;
		return false;
	},
   // Función añadida para añadir imágenes dentro del editor
   insertImage:function(url,alt,style,width,height) {
           nicEditor_actual_selected.e.focus()
           this.selectedInstance = nicEditor_actual_selected;
           this.im = this.selectedInstance.selElm().parentTag("IMG");
           if(!this.im){
             var A="javascript:nicImTemp();";
             this.selectedInstance.nicCommand("insertImage",A);
             var imgs=this.selectedInstance.getElm().getElementsByTagName("IMG");
             var salir = false;
             for(var i=0;(i<imgs.length) && !salir;i++){
                if(imgs[i].getAttribute("src")==A){
                    this.im=$BK(imgs[i])
                    salir = true;
                }
            }
           }
           if (this.im) {
               this.im.setAttributes({src:url,alt:alt,width:width,height:height});
               this.im.addClass(style);
           }
   },
   // Función añadida para añadir documentos dentro del editor
   insertDocument:function(name,id) {
       nicEditor_actual_selected.e.focus();
       this.selectedInstance = nicEditor_actual_selected;
        this.ln=this.selectedInstance.selElm().parentTag("A");

		if(!this.ln) {
			var tmp = 'javascript:nicTemp();';
			this.selectedInstance.nicCommand("createlink",tmp);
            var D=this.selectedInstance.getElm().getElementsByTagName("A");
            var salir = false;
            for(var C=0;C<D.length && !salir;C++){
            	if(D[C].getAttribute("href")==tmp){
                	this.ln =  $BK(D[C])
                    salir = true
                }
            }
		}
		if(this.ln) {
			this.ln.setAttributes({
				href : "documents/download/" + id,
				title : "Descargar documento"
//				target : this.inputs['target'].options[this.inputs['target'].selectedIndex].value
			});
		}
       else {
           var enlace = "<a href=\"/documents/download/" + id + "\">" + name + "</a>";
           insert_content(enlace);
//           document.execCommand("createlink", true, "/documents/download/" + id)
           //this.selectedInstance.nicCommand("createlink", "/documents/download/" + id);
         //  $(nicEditor_actual_selected.e).html($(nicEditor_actual_selected.e).html() + enlace);
       }



//		if(!this.ln){
//			var B="javascript:nicTemp();";
//			this.selectedInstance.nicCommand("createlink",B);
//
//            var D=this.selectedInstance.getElm().getElementsByTagName("A");
//            var salir = false;
//            for(var C=0;C<D.length && !salir;C++){
//            	if(D[C].getAttribute("href")==B){
//                	this.ln =  $BK(D[C])
//                    salir = true
//                }
//            }
//
//		}
//		if(this.ln) {
//            //Si teníamos un texto seleccionado entra por aquí
//            alert("1");
//			this.ln.setAttributes({
//            href:"/documents/download/" + id,
//			title:"Descargar documento"
//		})
//       }
//       else {
//           alert("2");
//           var enlace = "\<a href=\"/documents/download/" + id + "\">" + name + "</a>";
//           this.selectedInstance.nicCommand("createlink", "/documents/download/" + id);
//         //  $(nicEditor_actual_selected.e).html($(nicEditor_actual_selected.e).html() + enlace);
//       }
   }
});
nicEditor = nicEditor.extend(bkEvent);

 
var nicEditorInstance = bkClass.extend({
	isSelected : false,
	
	construct : function(e,options,nicEditor) {
		this.ne = nicEditor;
		this.elm = this.e = e;
		this.options = options || {};
		
		newX = parseInt(e.getStyle('width')) || e.clientWidth;
		newY = parseInt(e.getStyle('height')) || e.clientHeight;
		this.initialHeight = newY-8;
		
		var isTextarea = (e.nodeName.toLowerCase() == "textarea");
		if(isTextarea || this.options.hasPanel) {
			var ie7s = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat"))
			var s = {width: newX+'px', border : '1px solid #ccc', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' };
			s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null;
			this.editorContain = new bkElement('DIV').setStyle(s).appendBefore(e);
			var editorElm = new bkElement('DIV').setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain);

			e.setStyle({display : 'none'});
				
			editorElm.innerHTML = e.innerHTML;		
			if(isTextarea) {
				editorElm.setContent(e.value);
				this.copyElm = e;
				var f = e.parentTag('FORM');
				if(f) { bkLib.addEvent( f, 'submit', this.saveContent.closure(this)); }
			}
			editorElm.setStyle((ie7s) ? {height : newY+'px'} : {overflow: 'hidden'});
			this.elm = editorElm;	
		}
		this.ne.addEvent('blur',this.blur.closure(this));

		this.init();
		this.blur();
	},
	
	init : function() {
		this.elm.setAttribute('contentEditable','true');	
		if(this.getContent() == "") {
			this.setContent('<br/>');
		}
		this.instanceDoc = document.defaultView;
		this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this));
		this.ne.fireEvent('add',this);
	},
	
	remove : function() {
		this.saveContent();
		if(this.copyElm || this.options.hasPanel) {
			this.editorContain.remove();
			this.e.setStyle({'display' : 'block'});
			this.ne.removePanel();
		}
		this.disable();
		this.ne.fireEvent('remove',this);
	},
	
	disable : function() {
		this.elm.setAttribute('contentEditable','false');
	},
	
	getSel : function() {
		return (window.getSelection) ? window.getSelection() : document.selection;	
	},
	
	getRng : function() {
		var s = this.getSel();
		if(!s) { return null; }
		return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange();
	},
	
	selRng : function(rng,s) {
		if(window.getSelection) {
			s.removeAllRanges();
			s.addRange(rng);
		} else {
			rng.select();
		}
	},
	
	selElm : function() {
		var r = this.getRng();
		if(r.startContainer) {
			var contain = r.startContainer;
			if(r.cloneContents().childNodes.length == 1) {
				for(var i=0;i<contain.childNodes.length;i++) {
					var rng = contain.childNodes[i].ownerDocument.createRange();
					rng.selectNode(contain.childNodes[i]);					
					if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 &&
						r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) {
						return $BK(contain.childNodes[i]);
					}
				}
			}
			return $BK(contain);
		} else {
			return $BK((this.getSel().type == "Control") ? r.item(0) : r.parentElement());
		}
	},
	
	saveRng : function() {
		this.savedRange = this.getRng();
		this.savedSel = this.getSel();
	},
	
	restoreRng : function() {
		if(this.savedRange) {
			this.selRng(this.savedRange,this.savedSel);
		}
	},
	
	keyDown : function(e,t) {
		if(e.ctrlKey) {
			this.ne.fireEvent('key',this,e);
		}
	},
	
	selected : function(e,t) {
		if(!t) {t = this.selElm()}
		if(!e.ctrlKey) {
			var selInstance = this.ne.selectedInstance;
			if(selInstance != this) {
				if(selInstance) {
					this.ne.fireEvent('blur',selInstance,t);
				}
				this.ne.selectedInstance = this;	
				this.ne.fireEvent('focus',selInstance,t);
			}
			this.ne.fireEvent('selected',selInstance,t);
			this.isFocused = true;
			this.elm.addClass('selected');
		}
		return false;
	},
	
	blur : function() {
		this.isFocused = false;
		this.elm.removeClass('selected');
	},
	
	saveContent : function() {
		if(this.copyElm || this.options.hasPanel) {
			this.ne.fireEvent('save',this);
			(this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent();
		}	
	},
	
	getElm : function() {
		return this.elm;
	},
	
	getContent : function() {
		this.content = this.getElm().innerHTML;
		this.ne.fireEvent('get',this);
		return this.content;
	},
	
	setContent : function(e) {
		this.content = e;
		this.ne.fireEvent('set',this);
		this.elm.innerHTML = this.content;	
	},
	
	nicCommand : function(cmd,args) {
		document.execCommand(cmd,false,args);
	}		
});

var nicEditorIFrameInstance = nicEditorInstance.extend({
	savedStyles : [],
	
	init : function() {	
		var c = this.elm.innerHTML.replace(/^\s+|\s+$/g, '');
		this.elm.innerHTML = '';
		(!c) ? c = "<br/>" : c;
		this.initialContent = c;
		
		this.elmFrame = new bkElement('iframe').setAttributes({'src' : 'javascript:;', 'frameBorder' : 0, 'allowTransparency' : 'true', 'scrolling' : 'no'}).setStyle({height: '100px', width: '100%'}).addClass('frame').appendTo(this.elm);

		if(this.copyElm) { this.elmFrame.setStyle({width : (this.elm.offsetWidth-4)+'px'}); }
		
		var styleList = ['font-size','font-family','font-weight','color'];
		for(itm in styleList) {
			this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm);
		}
     	
		setTimeout(this.initFrame.closure(this),50);
	},
	
	disable : function() {
		this.elm.innerHTML = this.getContent();
	},
	
	initFrame : function() {
		var fd = $BK(this.elmFrame.contentWindow.document);
		fd.designMode = "on";		
		fd.open();
		var css = this.ne.options.externalCSS;
		fd.write('<html><head>'+((css) ? '<link href="'+css+'" rel="stylesheet" type="text/css" />' : '')+'</head><body id="nicEditContent" style="margin: 0 !important; background-color: transparent !important;">'+this.initialContent+'</body></html>');
		fd.close();
		this.frameDoc = fd;

		this.frameWin = $BK(this.elmFrame.contentWindow);
		this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles);
		this.instanceDoc = this.frameWin.document.defaultView;
		
		this.heightUpdate();
		this.frameDoc.addEvent('mousedown', this.selected.closureListener(this)).addEvent('keyup',this.heightUpdate.closureListener(this)).addEvent('keydown',this.keyDown.closureListener(this)).addEvent('keyup',this.selected.closure(this));
		this.ne.fireEvent('add',this);
	},
	
	getElm : function() {
		return this.frameContent;
	},
	
	setContent : function(c) {
		this.content = c;
		this.ne.fireEvent('set',this);
		this.frameContent.innerHTML = this.content;	
		this.heightUpdate();
	},
	
	getSel : function() {
		return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection;
	},
	
	heightUpdate : function() {	
		this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight,this.initialHeight)+'px';
	},
    
	nicCommand : function(cmd,args) {
		this.frameDoc.execCommand(cmd,false,args);
		setTimeout(this.heightUpdate.closure(this),100);
	}

	
});
var nicEditorPanel = bkClass.extend({
	construct : function(e,options,nicEditor) {
		this.elm = e;
		this.options = options;
		this.ne = nicEditor;
		this.panelButtons = new Array();
		this.buttonList = bkExtend([],this.ne.options.buttonList);
		
		this.panelContain = new bkElement('DIV').setStyle({overflow : 'hidden', width : '100%', borderLeft : '1px solid #e6e6e6', backgroundColor : '#f2f2f2',padding: '4px 0'}).addClass('panelContain');
		this.panelElm = new bkElement('DIV').setStyle({margin : '2px', marginTop : '0px', zoom : 1, overflow : 'hidden'}).addClass('panel').appendTo(this.panelContain);
		this.panelContain.appendTo(e);

		var opt = this.ne.options;
		var buttons = opt.buttons;
		for(button in buttons) {
				this.addButton(button,opt,true);
		}
		this.reorder();
		e.noSelect();
	},
	
	addButton : function(buttonName,options,noOrder) {
		var button = options.buttons[buttonName];
		var type = (button['type']) ? eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';') : nicEditorButton;
		var hasButton = bkLib.inArray(this.buttonList,buttonName);
		if(type && (hasButton || this.ne.options.fullPanel)) {
			this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne));
			if(!hasButton) {	
				this.buttonList.push(buttonName);
			}
		}
	},
	
	findButton : function(itm) {
		for(var i=0;i<this.panelButtons.length;i++) {
			if(this.panelButtons[i].name == itm)
				return this.panelButtons[i];
		}	
	},
	
	reorder : function() {
		var bl = this.buttonList;
		for(var i=0;i<bl.length;i++) {
			var button = this.findButton(bl[i]);
			if(button) {
				this.panelElm.appendChild(button.margin);
			}
		}	
	},
	
	remove : function() {
		this.elm.remove();
	}
});
var nicEditorButton = bkClass.extend({
	
	construct : function(e,buttonName,options,nicEditor) {
		this.options = options.buttons[buttonName];
		this.name = buttonName;
		this.ne = nicEditor;
		this.elm = e;

		this.margin = new bkElement('DIV').setStyle({'float' : 'left', marginTop : '2px'}).appendTo(e);
		this.contain = new bkElement('DIV').setStyle({width : '20px', height : '20px'}).addClass('buttonContain').appendTo(this.margin);
		this.border = new bkElement('DIV').setStyle({backgroundColor : '#f2f2f2', border : '1px solid #f2f2f2'}).appendTo(this.contain);
		this.button = new bkElement('DIV').setStyle({width : '18px', height : '18px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass('button').setStyle(this.ne.getIcon(buttonName,options)).appendTo(this.border);
        name_translate = t(this.options.name);
        this.button.setAttributes({title: name_translate});
//		this.button.addEvent('mouseover', this.hoverOn.closure(this)).addEvent('mouseout',this.hoverOff.closure(this)).addEvent('mousedown',this.mouseClick.closure(this)).noSelect();
		this.button.addEvent('mousedown',this.mouseClick.closure(this)).noSelect();
		if(!window.opera) {
			this.button.onmousedown = this.button.onclick = bkLib.cancelEvent;
		}
		
		nicEditor.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)).addEvent('key',this.key.closure(this));
		
		this.disable();
		this.init();
	},
	
	init : function() {  },
	
	hide : function() {
		this.contain.setStyle({display : 'none'});
	},
	
	updateState : function() {
		if(this.isDisabled) { this.setBg(); }
		else if(this.isHover) { this.setBg('hover'); }
		else if(this.isActive) { this.setBg('active'); }
		else { this.setBg(); }
	},
	
	setBg : function(state) {
		switch(state) {
			case 'hover':
				var stateStyle = {border : '1px solid #666', backgroundColor : '#ddd'};
				break;
			case 'active':
				var stateStyle = {border : '1px solid #666', backgroundColor : '#ccc'};
				break;
			default:
				var stateStyle = {border : '1px solid #f2f2f2', backgroundColor : '#f2f2f2'};
		}
		this.border.setStyle(stateStyle).addClass('button-'+state);
	},
	
	checkNodes : function(e) {
		var elm = e;	
		do {
			if(this.options.tags && bkLib.inArray(this.options.tags,elm.nodeName)) {
				this.activate();
				return true;
			}
		} while(elm = elm.parentNode && elm.className != "nicEdit");
		elm = $BK(e);
		while(elm.nodeType == 3) {
			elm = $BK(elm.parentNode);
		}
		if(this.options.css) {
			for(itm in this.options.css) {
				if(elm.getStyle(itm,this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) {
					this.activate();
					return true;
				}
			}
		}
		this.deactivate();
		return false;
	},
	
	activate : function() {
		if(!this.isDisabled) {
			this.isActive = true;
			this.updateState();	
			this.ne.fireEvent('buttonActivate',this);
		}
	},
	
	deactivate : function() {
		this.isActive = false;
		this.updateState();	
		if(!this.isDisabled) {
			this.ne.fireEvent('buttonDeactivate',this);
		}
	},
	
	enable : function(ins,t) {
		this.isDisabled = false;
		this.contain.setStyle({'opacity' : 1}).addClass('buttonEnabled');
		this.updateState();
		this.checkNodes(t);
	},
	
	disable : function(ins,t) {		
		this.isDisabled = true;
		this.contain.setStyle({'opacity' : 0.6}).removeClass('buttonEnabled');
		this.updateState();	
	},
	
	toggleActive : function() {
		(this.isActive) ? this.deactivate() : this.activate();	
	},
	
	hoverOn : function() {
		if(!this.isDisabled) {
			this.isHover = true;
			this.updateState();
			this.ne.fireEvent("buttonOver",this);
		}
	}, 
	
	hoverOff : function() {
		this.isHover = false;
		this.updateState();
		this.ne.fireEvent("buttonOut",this);
	},
	
	mouseClick : function() {
		if(this.options.command) {
			this.ne.nicCommand(this.options.command,this.options.commandArgs);
			if(!this.options.noActive) {
				this.toggleActive();
			}
		}
		this.ne.fireEvent("buttonClick",this);
	},
	
	key : function(nicInstance,e) {
		if(this.options.key && e.ctrlKey && String.fromCharCode(e.keyCode || e.charCode).toLowerCase() == this.options.key) {
			this.mouseClick();
			if(e.preventDefault) e.preventDefault();
		}
	}
	
});

 
var nicPlugin = bkClass.extend({
	
	construct : function(nicEditor,options) {
		this.options = options;
		this.ne = nicEditor;
		this.ne.addEvent('panel',this.loadPanel.closure(this));
		
		this.init();
	},

	loadPanel : function(np) {
		var buttons = this.options.buttons;
		for(var button in buttons) {
			np.addButton(button,this.options);
		}
		np.reorder();
	},

	init : function() {  }
});



 
 /* START CONFIG */
var nicPaneOptions = { };
/* END CONFIG */

var nicEditorPane = bkClass.extend({
	construct : function(elm,nicEditor,options,openButton) {
		this.ne = nicEditor;
		this.elm = elm;
		this.pos = elm.pos();
		
		this.contain = new bkElement('div').setStyle({zIndex : '99999', overflow : 'hidden', position : 'absolute', left : this.pos[0]+'px', top : this.pos[1]+'px'})
		this.pane = new bkElement('div').setStyle({fontSize : '12px', border : '1px solid #ccc', 'overflow': 'hidden', padding : '4px', textAlign: 'left', backgroundColor : '#ffffc9'}).addClass('pane').setStyle(options).appendTo(this.contain);
		
		if(openButton && !openButton.options.noClose) {
			this.close = new bkElement('div').setStyle({'float' : 'right', height: '16px', width : '16px', cursor : 'pointer'}).setStyle(this.ne.getIcon('close',nicPaneOptions)).addEvent('mousedown',openButton.removePane.closure(this)).appendTo(this.pane);
		}
		
		this.contain.noSelect().appendTo(document.body);
		
		this.position();
		this.init();	
	},
	
	init : function() { },
	
	position : function() {
		if(this.ne.nicPanel) {
			var panelElm = this.ne.nicPanel.elm;	
			var panelPos = panelElm.pos();
			var newLeft = panelPos[0]+parseInt(panelElm.getStyle('width'))-(parseInt(this.pane.getStyle('width'))+8);
			if(newLeft < this.pos[0]) {
				this.contain.setStyle({left : newLeft+'px'});
			}
		}
	},
	
	toggle : function() {
		this.isVisible = !this.isVisible;
		this.contain.setStyle({display : ((this.isVisible) ? 'block' : 'none')});
	},
	
	remove : function() {
		if(this.contain) {
			this.contain.remove();
			this.contain = null;
		}
	},
	
	append : function(c) {
		c.appendTo(this.pane);
	},
	
	setContent : function(c) {
		this.pane.setContent(c);
	}
	
});


 
var nicEditorAdvancedButton = nicEditorButton.extend({
	
	init : function() {
		this.ne.addEvent('selected',this.removePane.closure(this)).addEvent('blur',this.removePane.closure(this));	
	},
	
	mouseClick : function() {
		if(!this.isDisabled) {
			if(this.pane && this.pane.pane) {
				this.removePane();
			} else {
				this.pane = new nicEditorPane(this.contain,this.ne,{width : (this.width || '270px'), backgroundColor : '#fff'},this);
				this.addPane();
				this.ne.selectedInstance.saveRng();
			}
		}
	},
	
	addForm : function(f,elm) {
		this.form = new bkElement('form').addEvent('submit',this.submit.closureListener(this));
		this.pane.append(this.form);
		this.inputs = {};
		
		for(itm in f) {
			var field = f[itm];
			var val = '';
			if(elm) {
				val = elm.getAttribute(itm);
			}
			if(!val) {
				val = field['value'] || '';
			}
			var type = f[itm].type;
			
			if(type == 'title') {
					new bkElement('div').setContent(field.txt).setStyle({fontSize : '14px', fontWeight: 'bold', padding : '0px', margin : '2px 0'}).appendTo(this.form);
			} else {
				var contain = new bkElement('div').setStyle({overflow : 'hidden', clear : 'both'}).appendTo(this.form);
				if(field.txt) {
					new bkElement('label').setAttributes({'for' : itm}).setContent(field.txt).setStyle({margin : '2px 4px', fontSize : '13px', width: '50px', lineHeight : '20px', textAlign : 'right', 'float' : 'left'}).appendTo(contain);
				}
				
				switch(type) {
					case 'text':
						this.inputs[itm] = new bkElement('input').setAttributes({id : itm, 'value' : val, 'type' : 'text'}).setStyle({margin : '2px 0', fontSize : '13px', 'float' : 'left', height : '20px', border : '1px solid #ccc', overflow : 'hidden'}).setStyle(field.style).appendTo(contain);
						break;
					case 'check':
						this.inputs[itm]=new bkElement("input").setAttributes({id:itm,value:val,type:"checkbox"}).setStyle({margin:"2px 7pt",fontSize:"13px","float":"left",height:"20px",border:"1px solid #ccc",overflow:"hidden"}).setStyle(field.style).appendTo(contain);
						break;
					case 'select':
						this.inputs[itm] = new bkElement('select').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left', margin : '2px 0'}).appendTo(contain);
						for(opt in field.options) {
							var o = new bkElement('option').setAttributes({value : opt, selected : (opt == val) ? 'selected' : ''}).setContent(field.options[opt]).appendTo(this.inputs[itm]);
						}
						break;
					case 'content':
						this.inputs[itm] = new bkElement('textarea').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left'}).setStyle(field.style).appendTo(contain);
						this.inputs[itm].value = val;
				}	
			}
		}
		new bkElement('input').setAttributes({'type' : 'submit'}).setStyle({backgroundColor : '#f2f2f2',border : '1px solid #ccc', margin : '3px 0', 'float' : 'left', 'clear' : 'both'}).appendTo(this.form);
		this.form.onsubmit = bkLib.cancelEvent;	
	},
	
	submit : function() { },
	
	findElm : function(tag,attr,val) {
		var list = this.ne.selectedInstance.getElm().getElementsByTagName(tag);
		for(var i=0;i<list.length;i++) {
			if(list[i].getAttribute(attr) == val) {
				return $BK(list[i]);
			}
		}
	},
	
	removePane : function() {
		if(this.pane) {
			this.pane.remove();
			this.pane = null;
			this.ne.selectedInstance.restoreRng();
		}	
	}	
});


var nicButtonTips = bkClass.extend({
	construct : function(nicEditor) {
		this.ne = nicEditor;
		nicEditor.addEvent('buttonOver',this.show.closure(this)).addEvent('buttonOut',this.hide.closure(this));

	},
	
	show : function(button) {
		this.timer = setTimeout(this.create.closure(this,button),400);
	},
	
	create : function(button) {
		this.timer = null;
		if(!this.pane) {
			this.pane = new nicEditorPane(button.button,this.ne,{fontSize : '12px', marginTop : '5px'});
			this.pane.setContent(button.options.name);
		}		
	},
	
	hide : function(button) {
		if(this.timer) {
			clearTimeout(this.timer);
		}
		if(this.pane) {
			this.pane = this.pane.remove();
		}
	}
});
nicEditors.registerPlugin(nicButtonTips);


 
 /* START CONFIG */
var nicSelectOptions = {
	buttons : {
		'fontSize' : {name : __('Select Font Size'), type : 'nicEditorFontSizeSelect', command : 'fontsize'},
		'fontFamily' : {name : __('Select Font Family'), type : 'nicEditorFontFamilySelect', command : 'fontname'},
		'fontFormat' : {name : __('Select Font Format'), type : 'nicEditorFontFormatSelect', command : 'formatBlock'}
	}
};

/* END CONFIG */
var nicEditorSelect = bkClass.extend({
	
	construct : function(e,buttonName,options,nicEditor) {
		this.options = options.buttons[buttonName];
		this.elm = e;
		this.ne = nicEditor;
		this.name = buttonName;
		this.selOptions = new Array();
		
		this.margin = new bkElement('div').setStyle({'float' : 'left', margin : '2px 1px 0 1px'}).appendTo(this.elm);
		this.contain = new bkElement('div').setStyle({width: '90px', height : '20px', cursor : 'pointer', overflow: 'hidden'}).addClass('selectContain').addEvent('click',this.toggle.closure(this)).appendTo(this.margin);
		this.items = new bkElement('div').setStyle({overflow : 'hidden', zoom : 1, border: '1px solid #ccc', paddingLeft : '3px', backgroundColor : '#fff'}).appendTo(this.contain);
		this.control = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'right', height: '18px', width : '16px'}).addClass('selectControl').setStyle(this.ne.getIcon('arrow',options)).appendTo(this.items);
		this.txt = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'left', width : '66px', height : '14px', marginTop : '1px', fontFamily : 'sans-serif', textAlign : 'center', fontSize : '12px'}).addClass('selectTxt').appendTo(this.items);
		
		if(!window.opera) {
			this.contain.onmousedown = this.control.onmousedown = this.txt.onmousedown = bkLib.cancelEvent;
		}
		
		this.margin.noSelect();
		
		this.ne.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this));
		
		this.disable();
		this.init();
	},
	
	disable : function() {
		this.isDisabled = true;
		this.close();
		this.contain.setStyle({opacity : 0.6});
	},
	
	enable : function(t) {
		this.isDisabled = false;
		this.close();
		this.contain.setStyle({opacity : 1});
	},
	
	setDisplay : function(txt) {
		this.txt.setContent(txt);
	},
	
	toggle : function() {
		if(!this.isDisabled) {
			(this.pane) ? this.close() : this.open();
		}
	},
	
	open : function() {
		this.pane = new nicEditorPane(this.items,this.ne,{width : '88px', padding: '0px', borderTop : 0, borderLeft : '1px solid #ccc', borderRight : '1px solid #ccc', borderBottom : '0px', backgroundColor : '#fff'});
		
		for(var i=0;i<this.selOptions.length;i++) {
			var opt = this.selOptions[i];
			var itmContain = new bkElement('div').setStyle({overflow : 'hidden', borderBottom : '1px solid #ccc', width: '88px', textAlign : 'left', overflow : 'hidden', cursor : 'pointer'});
			var itm = new bkElement('div').setStyle({padding : '0px 4px'}).setContent(opt[1]).appendTo(itmContain).noSelect();
			itm.addEvent('click',this.update.closure(this,opt[0])).addEvent('mouseover',this.over.closure(this,itm)).addEvent('mouseout',this.out.closure(this,itm)).setAttributes('id',opt[0]);
			this.pane.append(itmContain);
			if(!window.opera) {
				itm.onmousedown = bkLib.cancelEvent;
			}
		}
	},
	
	close : function() {
		if(this.pane) {
			this.pane = this.pane.remove();
		}	
	},
	
	over : function(opt) {
		opt.setStyle({backgroundColor : '#ccc'});			
	},
	
	out : function(opt) {
		opt.setStyle({backgroundColor : '#fff'});
	},
	
	
	add : function(k,v) {
		this.selOptions.push(new Array(k,v));	
	},
	
	update : function(elm) {
		this.ne.nicCommand(this.options.command,elm);
		this.close();	
	}
});

var nicEditorFontSizeSelect = nicEditorSelect.extend({
	sel : {1 : '1&nbsp;(8pt)', 2 : '2&nbsp;(10pt)', 3 : '3&nbsp;(12pt)', 4 : '4&nbsp;(14pt)', 5 : '5&nbsp;(18pt)', 6 : '6&nbsp;(24pt)'},
	init : function() {
		this.setDisplay('Font&nbsp;Size...');
		for(itm in this.sel) {
			this.add(itm,'<font size="'+itm+'">'+this.sel[itm]+'</font>');
		}		
	}
});

var nicEditorFontFamilySelect = nicEditorSelect.extend({
	sel : {'arial' : 'Arial','comic sans ms' : 'Comic Sans','courier new' : 'Courier New','georgia' : 'Georgia', 'helvetica' : 'Helvetica', 'impact' : 'Impact', 'times new roman' : 'Times', 'trebuchet ms' : 'Trebuchet', 'verdana' : 'Verdana'},
	
	init : function() {
		this.setDisplay('Font&nbsp;Family...');
		for(itm in this.sel) {
			this.add(itm,'<font face="'+itm+'">'+this.sel[itm]+'</font>');
		}
	}
});

var nicEditorFontFormatSelect = nicEditorSelect.extend({
		sel : {'p' : 'Paragraph', 'pre' : 'Pre', 'h6' : 'Heading&nbsp;6', 'h5' : 'Heading&nbsp;5', 'h4' : 'Heading&nbsp;4', 'h3' : 'Heading&nbsp;3', 'h2' : 'Heading&nbsp;2', 'h1' : 'Heading&nbsp;1'},
		
	init : function() {
		this.setDisplay('Font&nbsp;Format...');
		for(itm in this.sel) {
			var tag = itm.toUpperCase();
			this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>');
		}
	}
});

//nicEditors.registerPlugin(nicPlugin,nicSelectOptions);



/* START CONFIG */
var nicLinkOptions = {
	buttons : {
		'link' : {name : 'nicedit.link', type : 'nicLinkButton', tags : ['A']},
		'unlink' : {name : 'nicedit.unlink',  command : 'unlink', noActive : true}
	}
};
/* END CONFIG */

//var nicLinkButton = nicEditorAdvancedButton.extend({
//	addPane : function() {
//		this.ln = this.ne.selectedInstance.selElm().parentTag('A');
//		this.addForm({
//			'' : {type : 'title', txt : 'Add/Edit Link'},
//			'href' : {type : 'text', txt : 'URL', value : 'http://', style : {width: '150px'}},
//			'title' : {type : 'text', txt : 'Title'},
//			'target' : {type : 'select', txt : 'Open In', options : {'' : 'Current Window', '_blank' : 'New Window'},style : {width : '100px'}}
//		},this.ln);
//	},
//
//	submit : function(e) {
//		var url = this.inputs['href'].value;
//		if(url == "http://" || url == "") {
//			alert("You must enter a URL to Create a Link");
//			return false;
//		}
//		this.removePane();
//
//		if(!this.ln) {
//			var tmp = 'javascript:nicTemp();';
//			this.ne.nicCommand("createlink",tmp);
//			this.ln = this.findElm('A','href',tmp);
//		}
//		if(this.ln) {
//			this.ln.setAttributes({
//				href : this.inputs['href'].value,
//				title : this.inputs['title'].value,
//				target : this.inputs['target'].options[this.inputs['target'].selectedIndex].value
//			});
//		}
//	}
//});
//
//nicEditors.registerPlugin(nicPlugin,nicLinkOptions);



/* START CONFIG */
var nicColorOptions = {
	buttons : {
		'forecolor' : {name : __('Change Text Color'), type : 'nicEditorColorButton', noClose : true},
		'bgcolor' : {name : __('Change Background Color'), type : 'nicEditorBgColorButton', noClose : true}
	}
};
/* END CONFIG */

var nicEditorColorButton = nicEditorAdvancedButton.extend({	
	addPane : function() {
			var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'};
			var colorItems = new bkElement('DIV').setStyle({width: '270px'});
			
			for(var r in colorList) {
				for(var b in colorList) {
					for(var g in colorList) {
						var colorCode = '#'+colorList[r]+colorList[g]+colorList[b];
						
						var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
						var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
						var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);
						
						if(!window.opera) {
							colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
						}

					}	
				}	
			}
			this.pane.append(colorItems.noSelect());	
	},
	
	colorSelect : function(c) {
		this.ne.nicCommand('foreColor',c);
		this.removePane();
	},
	
	on : function(colorBorder) {
		colorBorder.setStyle({border : '2px solid #000'});
	},
	
	off : function(colorBorder,colorCode) {
		colorBorder.setStyle({border : '2px solid '+colorCode});		
	}
});

var nicEditorBgColorButton = nicEditorColorButton.extend({
	colorSelect : function(c) {
		this.ne.nicCommand('hiliteColor',c);
		this.removePane();
	}	
});

//nicEditors.registerPlugin(nicPlugin,nicColorOptions);



/* START CONFIG */
//var nicImageOptions = {
//	buttons : {
//		'image' : {name : 'Add Image', type : 'nicImageButton', tags : ['IMG']}
//	}
//
//};
/* END CONFIG */

//var nicImageButton = nicEditorAdvancedButton.extend({
//	addPane : function() {
//		this.im = this.ne.selectedInstance.selElm().parentTag('IMG');
//		this.addForm({
//			'' : {type : 'title', txt : 'Add/Edit Image'},
//			'src' : {type : 'text', txt : 'URL', 'value' : 'http://', style : {width: '150px'}},
//			'alt' : {type : 'text', txt : 'Alt Text', style : {width: '100px'}},
//			'align' : {type : 'select', txt : 'Align', options : {none : 'Default','left' : 'Left', 'right' : 'Right'}}
//		},this.im);
//	},
//
//	submit : function(e) {
//		var src = this.inputs['src'].value;
//		if(src == "" || src == "http://") {
//			alert("You must enter a Image URL to insert");
//			return false;
//		}
//		this.removePane();
//
//		if(!this.im) {
//			var tmp = 'javascript:nicImTemp();';
//			this.ne.nicCommand("insertImage",tmp);
//			this.im = this.findElm('IMG','src',tmp);
//		}
//		if(this.im) {
//			this.im.setAttributes({
//				src : this.inputs['src'].value,
//				alt : this.inputs['alt'].value,
//				align : this.inputs['align'].value
//			});
//		}
//	}
//});

//nicEditors.registerPlugin(nicPlugin,nicImageOptions);




/* START CONFIG */
var nicSaveOptions = {
	buttons : {
		'save' : {name : __('Save this content'), type : 'nicEditorSaveButton'}
	}
};
/* END CONFIG */

var nicEditorSaveButton = nicEditorButton.extend({
	init : function() {
		if(!this.ne.options.onSave) {
			this.margin.setStyle({'display' : 'none'});
		}
	},
	mouseClick : function() {
		var onSave = this.ne.options.onSave;
		var selectedInstance = this.ne.selectedInstance;
		onSave(selectedInstance.getContent(), selectedInstance.elm.id, selectedInstance);
	}
});

//nicEditors.registerPlugin(nicPlugin,nicSaveOptions);



var estilos_disponibles = {
                        "Título":"h2",
						"Titulo icono":"<h2 class='titulo-icono'>{{texto}}</h2>",
						"Titulo obras":"<h2 class='titulo-obras'>{{texto}}</h2>",
						"Marca registrada":"<span class='marca-registrada'>{{texto}}</span>",
                        "Subtítulo":"h3",
                        "Ninguno":"none"
                    };

var nicEditor_actual;
var nicEditor_actual_selected;
var nicEditor_actual_selected_id;
var nicEditor_temp_tag;

var nicHrOptions = {
	buttons : {
		'hr' : {name : 'nicedit.hr', type : 'nicHrButton'}
	}
};

var nicImageOptions = {
	buttons : {
		'image' : {name : 'nicedit.image', type : 'nicImageButton', tags : ['IMG']}
	}
};

var nicVideoOptions = {
	buttons : {
		'video' : {name : 'nicedit.video', type : 'nicVideoButton', tags : ['VID']}
	}
};

var nicFlashOptions = {
	buttons : {
		'flash' : {name : 'nicedit.flash', type : 'nicFlashButton', tags : ['OBJECT']}
	}
};

var nicGalleryOptions = {
	buttons : {
		'gallery' : {name : 'nicedit.gallery', type : 'nicGalleryButton', tags : ['']}
	}
};

var nicGmapOptions = {
	buttons : {
		'gmap' : {name : 'nicedit.gmap', type : 'nicGmapButton', tags : ['']}
	}
};

var nicDocumentOptions = {
	buttons : {
		'document' : {name : 'nicedit.document', type : 'nicDocumentButton', tags : ['A']}
	}
};

var nicHrButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
            if(!this.isDisabled){
                insert_content("<div class=\"hr\"><hr/></div>");
                return false;
            }
	}
});
nicEditors.registerPlugin(nicPlugin,nicHrOptions);

var nicImageButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
            if(!this.isDisabled){
                insert_temp_tag();
                tb_show("Imágenes","/images/index?height=500&width=650&type=image",false);
                return false;
            }
	}
});
nicEditors.registerPlugin(nicPlugin,nicImageOptions);

var nicVideoButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            insert_temp_tag();
            tb_show("Vídeos","/videos/index?height=500&width=650&type=video",false);
            return false;
		}
	}
});
nicEditors.registerPlugin(nicPlugin,nicVideoOptions);

var nicFlashButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            insert_temp_tag();
            tb_show("Flashes","/flashobjects/index?height=500&width=650&type=flashobject",false);
            return false;
		}
	}
});
nicEditors.registerPlugin(nicPlugin,nicFlashOptions);


var nicGalleryButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            nicEditor_actual = this.ne;
            nicEditor_actual_selected = this.ne.selectedInstance;
            nicEditor_actual_selected_id = $(this)[0].ne.selectedInstance.e.id;
//            tb_show("Galerías Multimedia","/galeriamultimedias/index?height=500&width=650&type=gallery",false);
            tb_show("Galerías","/images/index?height=500&width=650&type=gallery",false);
            return false;
		}
	}
});
nicEditors.registerPlugin(nicPlugin,nicGalleryOptions);

var nicGmapButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            if (typeof(gmaps_loaded)=="undefined") {
                $("#" + $(this.ne.selectedInstance.e).next().next(".gmap").attr("id")).html("<iframe class=\"iframe_gmaps\" id=\"iframe_gmaps\" src=\"" + private_url + "/gmaps/gmaps_alone/" + $(this.ne.selectedInstance.e).next().next(".gmap").attr("id") + "\"></iframe>");
                $("#" + $(this.ne.selectedInstance.e).next().next(".gmap").attr("id")).show();
            }
            else {
                add_gmap(this.ne.selectedInstance.e);
            }
            return false;
		}
	}
});
nicEditors.registerPlugin(nicPlugin,nicGmapOptions);

var nicDocumentButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
//            nicEditor_actual = this.ne;
//            nicEditor_actual_selected = this.ne.selectedInstance;
//            nicEditor_actual_selected_id = $(this)[0].ne.selectedInstance.e.id;
            insert_temp_tag();
            tb_show("Documentos","/documents/index?height=500&width=650&type=documents",false);
            return false;
		}
	},
	addPane:function(){
		this.im=this.ne.selectedInstance.selElm().parentTag("A");
		this.addForm({
									"":{type:"title",txt:"Add/Edit Document"},
									src:{type:"text",txt:"URL",value:"http://",style:{width:"150px"}},
									alt:{type:"text",txt:"Alt Text",style:{width:"100px"}},
									align:{type:"select",txt:"Align",options:{left:"Left",right:"Right"}}
								},this.im)
	},
	submit:function(B){
		var C=this.inputs.src.value;
		if(C==""||C=="http://"){
			alert("You must enter a Image URL to insert");
			return false
		}
		this.removePane();
		if(!this.im){
			var A="javascript:nicImTemp();";
			this.ne.nicCommand("insertImage",A);
			this.im=this.findElm("IMG","src",A)
		}
		if(this.im){
			this.im.setAttributes({src:this.inputs.src.value,alt:this.inputs.alt.value,align:this.inputs.align.value})
		}
	}
});
nicEditors.registerPlugin(nicPlugin,nicDocumentOptions);

/*******************************************************************************/
/*******                                 Listado de estilos                                       ******/
/*******************************************************************************/



var nicStyleSelectOptions = {
	buttons : {
		'style' : {name : "nicedit.style", type : 'nicEditorStylesSelect'}
	}
};


var nicEditorStyleSelect=bkClass.extend({
	construct:function(D,A,C,B){
		this.options=C.buttons[A];
		this.elm=D;
		this.ne=B;
		this.name=A;
		this.selOptions=new Array();
		this.margin=new bkElement("div").setStyle({"float":"left",margin:"2px 1px 0 1px"}).appendTo(this.elm);
		this.contain=new bkElement("div").setStyle({width:"90px",height:"20px",cursor:"pointer",overflow:"hidden"}).addClass("selectContain").addEvent("click",this.toggle.closure(this)).appendTo(this.margin);
		this.items=new bkElement("div").setStyle({overflow:"hidden",zoom:1,border:"1px solid #ccc",paddingLeft:"3px",backgroundColor:"#fff"}).appendTo(this.contain);
		this.control=new bkElement("div").setStyle({overflow:"hidden","float":"right",height:"18px",width:"16px"}).addClass("selectControl").setStyle(this.ne.getIcon("arrow",C)).appendTo(this.items);
		this.txt=new bkElement("div").setStyle({overflow:"hidden","float":"left",width:"66px",height:"14px",marginTop:"1px",fontFamily:"sans-serif",textAlign:"center",fontSize:"12px"}).addClass("selectTxt").appendTo(this.items);
		if(!window.opera){
			this.contain.onmousedown=this.control.onmousedown=this.txt.onmousedown=bkLib.cancelEvent
		}
		this.margin.noSelect();
		this.ne.addEvent("selected",this.enable.closure(this)).addEvent("blur",this.disable.closure(this));
		this.disable();
		this.init()
	},
	disable:function(){
		this.isDisabled=true;
		this.close();
		this.contain.setStyle({opacity:0.6})
	},
	enable:function(A){
		this.isDisabled=false;
		this.close();
		this.contain.setStyle({opacity:1})
	},
	setDisplay:function(A){
		this.txt.setContent(A)
	},
	toggle:function(){
		if(!this.isDisabled){
			(this.pane)?this.close():this.open()
		}
	},
	open:function(){
		this.pane=new nicEditorPane(this.items,this.ne,{width:"88px",padding:"0px",position:"fixed",borderTop:0,borderLeft:"1px solid #ccc",borderRight:"1px solid #ccc",borderBottom:"0px",backgroundColor:"#fff"});
		for(var C=0;C<this.selOptions.length;C++){
			var B=this.selOptions[C];
			var A=new bkElement("div").setStyle({overflow:"hidden",borderBottom:"1px solid #ccc",width:"88px",textAlign:"left",overflow:"hidden",cursor:"pointer"});
			var D=new bkElement("div").setStyle({padding:"0px 4px"}).setContent(B[1]).appendTo(A).noSelect();
			D.addEvent("click",this.update.closure(this,B[0])).addEvent("mouseover",this.over.closure(this,D)).addEvent("mouseout",this.out.closure(this,D)).setAttributes("id",B[0]);
			this.pane.append(A);
			if(!window.opera){
				D.onmousedown=bkLib.cancelEvent
			}
		}
	},
	close:function(){
		if(this.pane){
			this.pane=this.pane.remove()
		}
	},
	over:function(A){
		A.setStyle({backgroundColor:"#ccc"})
	},
	out:function(A){
		A.setStyle({backgroundColor:"#fff"})
	},
	add:function(B,A){
		this.selOptions.push(new Array(B,A))
	},
	update:function(A){
        if (A=="h1" || A=="h2" || A=="h3" || A=="h4" || A=="h5" || A=="h6" || A=="p" || A=="none") {
            if (A=="none"){
                A="pre"
            }
            this.ne.selectedInstance.nicCommand("formatBlock", "<" + A.toUpperCase() + ">");
            re_ini1 = new RegExp("<pre([^>]*?)>(.*?)</pre>", "ig");
            contenido = this.ne.selectedInstance.getContent().replace(/\r/g, '').replace(/\n/g, '');
            if (contenido.match(re_ini1)){
                    contenido_parrafo = contenido.match(re_ini1).toString();
                    deletable_tags=["h1","h2","h3","h4","h5","h6","div","span","b","i","u","s","ul","ol","li","blockquote","p","sub","sup","hr","pre","font"];
                    for (tag in deletable_tags){
                            ini_tag = "<" + deletable_tags[tag] + "([^>]*?)>";
                            fin_tag = "</" + deletable_tags[tag] + ">";
                            re1 = new RegExp(ini_tag, "igm");
                            re2 = new RegExp(fin_tag, "igm");
                        contenido_parrafo = contenido_parrafo.replace(re1,"");
                        contenido_parrafo = contenido_parrafo.replace(re2,"");
                    }
                    re_final = new RegExp("<pre([^>]*?)>(.*?)</pre>", "ig");
                    contenido = contenido.replace(re_final,contenido_parrafo);
                    this.ne.selectedInstance.setContent(contenido);
            }
        } else {
            trozos = A.split("{{texto}}");
            insert_block(trozos[0],trozos[1]);
        }
		this.close();
	}
});

var nicEditorStylesSelect=nicEditorStyleSelect.extend({
	sel:estilos_disponibles, //{"p":"Hola","h1":"Adios"},
	init:function(){
		this.setDisplay("Estilo...");
		for(itm in this.sel){
			var A=itm;//.toUpperCase();
			this.add(this.sel[itm],"<p style=\"padding: 0px; margin: 0px;\">"+A+"</p>");
		}
	}
});

nicEditors.registerPlugin(nicPlugin,nicStyleSelectOptions);

var nicTableOptions = {
	buttons : {
		'table' : {name : 'nicedit.table', type : 'nicTableButton', tags : ['TABLE']}
		//'unlink' : {name : 'Remove Link',  command : 'unlink', noActive : true}
	}
};

var nicTableButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            insert_temp_tag();
            tb_show("Tablas","/nicedit/table?height=136&width=330",false);
            return false;
		}
	}
});

nicEditors.registerPlugin(nicPlugin,nicTableOptions);

var nicLinkButton=nicEditorAdvancedButton.extend({
	mouseClick:function(){
		if(!this.isDisabled){
            insert_temp_tag();
            tb_show("Enlaces","/nicedit/link?height=189&width=500",false);
            return false;
		}
	}
});

nicEditors.registerPlugin(nicPlugin,nicLinkOptions);

var nicSelectStyleOptions = {
	buttons : {
		'fontStyle' : {name : 'nicedit.table', type : 'nicEditorStyleSelect', command : 'formatBlock'}
	}
};

var nicEditorStyleSelect = nicEditorSelect.extend({
//		sel : {'p' : 'Paragraph', 'pre' : 'Pre', 'h6' : 'Heading&nbsp;6', 'h5' : 'Heading&nbsp;5', 'h4' : 'Heading&nbsp;4', 'h3' : 'Heading&nbsp;3', 'h2' : 'Heading&nbsp;2', 'h1' : 'Heading&nbsp;1'},
		sel : {'h2' : 'T&iacute;tulo', 'h3' : 'Subt&iacute;tulo', 'h4' : 'Subt&iacute;tulo 4'},

	init : function() {
		this.setDisplay('Estilo...');
		for(itm in this.sel) {
			var tag = itm.toUpperCase();
			this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>');
		}
	}
});

//nicEditors.registerPlugin(nicPlugin,nicSelectStyleOptions);




/*
        DatePicker v4.4 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency-decoder in any derivative work - thanks.
        
        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/
var datePickerController;

(function() {

// Detect the browser language
datePicker.languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
datePicker.languageinfo = datePicker.languageinfo ? datePicker.languageinfo.toLowerCase().replace(/-[a-z]+$/, "") : 'es';

// Load the appropriate language file
var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script');
var loc = scriptFiles[scriptFiles.length - 1].src.substr(0, scriptFiles[scriptFiles.length - 1].src.lastIndexOf("/")) + "/lang/" + datePicker.languageinfo + ".js";

//var script  = document.createElement('script');
//script.type = "text/javascript";
//script.src  = loc;
//script.setAttribute("charset", "utf-8");
///*@cc_on
///*@if(@_win32)
//        var bases = document.getElementsByTagName('base');
//        if (bases.length && bases[0].childNodes.length) {
//                bases[0].appendChild(script);
//        } else {
//                document.getElementsByTagName('head')[0].appendChild(script);
//        };
//@else @*/
//document.getElementsByTagName('head')[0].appendChild(script);
///*@end
//@*/
//script  = null;

// Defaults should the locale file not load
datePicker.months       = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
datePicker.fullDay      = ["Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo"];
datePicker.titles       = ["Mes anterior","Mes siguiente","Año anterior","Año siguiente", "Hoy", "Ver Calendario"];

datePicker.getDaysPerMonth = function(nMonth, nYear) {
        nMonth = (nMonth + 12) % 12;
        return (((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) ? 29: [31,28,31,30,31,30,31,31,30,31,30,31][nMonth];
};

function datePicker(options) {

        this.defaults          = {};
        for(opt in options) { this[opt] = this.defaults[opt] = options[opt]; };
        
        this.date              = new Date();
        this.yearinc           = 1;
        this.timer             = null;
        this.pause             = 1000;
        this.timerSet          = false;
        this.fadeTimer         = null;
        this.interval          = new Date();
        this.firstDayOfWeek    = this.defaults.firstDayOfWeek = this.dayInc = this.monthInc = this.yearInc = this.opacity = this.opacityTo = 0;
        this.dateSet           = null;
        this.visible           = false;
        this.disabledDates     = [];
        this.enabledDates      = [];
        this.nbsp              = String.fromCharCode( 160 );
        var o = this;

        o.events = {
                onblur:function(e) {
                        o.removeKeyboardEvents();
                },
                onfocus:function(e) {
                        o.addKeyboardEvents();
                },
                onkeydown: function (e) {
                        o.stopTimer();
                        if(!o.visible) return false;

                        if(e == null) e = document.parentWindow.event;
                        var kc = e.keyCode ? e.keyCode : e.charCode;

                        if( kc == 13 ) {
                                // close (return)
                                var td = document.getElementById(o.id + "-date-picker-hover");
                                if(!td || td.className.search(/out-of-range|day-disabled/) != -1) return o.killEvent(e);
                                o.returnFormattedDate();
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 27) {
                                // close (esc)
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 32 || kc == 0) {
                                // today (space)
                                o.date =  new Date();
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        // Internet Explorer fires the keydown event faster than the JavaScript engine can
                        // update the interface. The following attempts to fix this.
                        /*@cc_on
                        @if(@_win32)
                                if(new Date().getTime() - o.interval.getTime() < 100) return o.killEvent(e);
                                o.interval = new Date();
                        @end
                        @*/

                        if ((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) {
                                if (kc > 96) kc -= (96-48);
                                kc -= 49;
                                o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7;
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        if ( kc < 37 || kc > 40 ) return true;

                        var d = new Date( o.date ).valueOf();

                        if ( kc == 37 ) {
                                // ctrl + left = previous month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() - 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 1 );
                                };
                        } else if ( kc == 39 ) {
                                // ctrl + right = next month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() + 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 1 );
                                };
                        } else if ( kc == 38 ) {
                                // ctrl + up = next year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() + 1)) );
                                        d.setFullYear( d.getFullYear() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 7 );
                                };
                        } else if ( kc == 40 ) {
                                // ctrl + down = prev year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() - 1)) );
                                        d.setFullYear( d.getFullYear() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 7 );
                                };
                        };

                        var tmpDate = new Date(d);

                        if(o.outOfRange(tmpDate)) return o.killEvent(e);
                        
                        var cacheDate = new Date(o.date);
                        o.date = tmpDate;

                        if(cacheDate.getFullYear() != o.date.getFullYear() || cacheDate.getMonth() != o.date.getMonth()) o.updateTable();
                        else {
                                o.disableTodayButton();
                                var tds = o.table.getElementsByTagName('td');
                                var txt;
                                var start = o.date.getDate() - 6;
                                if(start < 0) start = 0;

                                for(var i = start, td; td = tds[i]; i++) {
                                        txt = Number(td.firstChild.nodeValue);
                                        if(isNaN(txt) || txt != o.date.getDate()) continue;
                                        o.removeHighlight();
                                        td.id = o.id + "-date-picker-hover";
                                        td.className = td.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                                };
                        };
                        return o.killEvent(e);
                },
                gotoToday: function(e) {
                        o.date = new Date();
                        o.updateTable();
                        return o.killEvent(e);
                },
                onmousedown: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        var found = false;
                        while(el.parentNode) {
                                if(el.id && (el.id == "fd-"+o.id || el.id == "fd-but-"+o.id)) {
                                        found = true;
                                        break;
                                };
                                try {
                                        el = el.parentNode;
                                } catch(err) {
                                        break;
                                };
                        };
                        if(found) return true;
                        o.stopTimer();
                        datePickerController.hideAll();
                },
                onmouseover: function(e) {
                        o.stopTimer();
                        var txt = this.firstChild.nodeValue;
                        if(this.className == "out-of-range" || txt.search(/^[\d]+$/) == -1) return;
                        
                        o.removeHighlight();
                        
                        this.id = o.id+"-date-picker-hover";
                        this.className = this.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                        
                        o.date.setDate(this.firstChild.nodeValue);
                        o.disableTodayButton();
                },
                onclick: function(e) {
                        if(o.opacity != o.opacityTo || this.className.search(/out-of-range|day-disabled/) != -1) return false;
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;
                        while ( el.nodeType != 1 ) el = el.parentNode;
                        var d = new Date( o.date );
                        var txt = el.firstChild.data;
                        if(txt.search(/^[\d]+$/) == -1) return;
                        var n = Number( txt );
                        if(isNaN(n)) { return true; };
                        d.setDate( n );
                        o.date = d;
                        o.returnFormattedDate();
                        if(!o.staticPos) o.hide();
                        o.stopTimer();
                        return o.killEvent(e);
                },
                incDec: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        if(el && el.className && el.className.search('fd-disabled') != -1) { return false; }
                        datePickerController.addEvent(document, "mouseup", o.events.clearTimer);
                        o.timerInc      = 800;
                        o.dayInc        = arguments[1];
                        o.yearInc       = arguments[2];
                        o.monthInc      = arguments[3];
                        o.timerSet      = true;

                        o.updateTable();
                        return true;
                },
                clearTimer: function(e) {
                        o.stopTimer();
                        o.timerInc      = 1000;
                        o.yearInc       = 0;
                        o.monthInc      = 0;
                        o.dayInc        = 0;
                        datePickerController.removeEvent(document, "mouseup", o.events.clearTimer);
                }
        };
        o.stopTimer = function() {
                o.timerSet = false;
                window.clearTimeout(o.timer);
        };
        o.removeHighlight = function() {
                if(document.getElementById(o.id+"-date-picker-hover")) {
                        document.getElementById(o.id+"-date-picker-hover").className = document.getElementById(o.id+"-date-picker-hover").className.replace("date-picker-hover", "");
                        document.getElementById(o.id+"-date-picker-hover").id = "";
                };
        };
        o.reset = function() {
                for(def in o.defaults) { o[def] = o.defaults[def]; };
        };
        o.setOpacity = function(op) {
                o.div.style.opacity = op/100;
                o.div.style.filter = 'alpha(opacity=' + op + ')';
                o.opacity = op;
        };
        o.fade = function() {
                window.clearTimeout(o.fadeTimer);
                o.fadeTimer = null;
                delete(o.fadeTimer);
                
                var diff = Math.round(o.opacity + ((o.opacityTo - o.opacity) / 4));

                o.setOpacity(diff);

                if(Math.abs(o.opacityTo - diff) > 3 && !o.noTransparency) {
                        o.fadeTimer = window.setTimeout(o.fade, 50);
                } else {
                        o.setOpacity(o.opacityTo);
                        if(o.opacityTo == 0) {
                                o.div.style.display = "none";
                                o.visible = false;
                        } else {
                                o.visible = true;
                        };
                };
        };
        o.killEvent = function(e) {
                e = e || document.parentWindow.event;
                
                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on
                @if(@_win32)
                e.cancelBubble = true;
                e.returnValue = false;
                @end
                @*/
                return false;
        };
        o.getElem = function() {
                return document.getElementById(o.id.replace(/^fd-/, '')) || false;
        };
        o.setRangeLow = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.low = o.defaults.low = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setRangeHigh = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.high = o.defaults.high = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDays = function(dayArray) {
                o.disableDays = o.defaults.disableDays = dayArray;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01])$/) != -1) fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = fin;
                        o.enabledDates = [];
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.setEnabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01]|\*\*)$/) != -1 && dateArray[i] != "********") fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = [];
                        o.enabledDates = fin;
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.getDisabledDates = function(y, m) {
                if(o.enabledDates.length) return o.getEnabledDates(y, m);
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                for(var i = o.disabledDates.length; i-- ;) {
                        var tmp = o.disabledDates[i].replace("****", y).replace("**", m);
                        if(tmp < Number(String(y)+m+"01") || tmp > Number(y+String(m)+d)) continue;
                        obj[tmp] = 1;
                };
                return obj;
        };
        o.getEnabledDates = function(y, m) {
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                var day,tmp,de,me,ye,disabled;
                for(var dd = 1; dd <= d; dd++) {
                        day = dd < 10 ? "0" + String(dd) : dd;
                        disabled = true;
                        for(var i = o.enabledDates.length; i-- ;) {
                                tmp = o.enabledDates[i];
                                ye  = String(o.enabledDates[i]).substr(0,4);
                                me  = String(o.enabledDates[i]).substr(4,2);
                                de  = String(o.enabledDates[i]).substr(6,2);

                                if(ye == y && me == m && de == day) {
                                        disabled = false;
                                        break;
                                }
                                
                                if(ye == "****" || me == "**" || de == "**") {
                                        if(ye == "****") tmp = tmp.replace(/^\*\*\*\*/, y);
                                        if(me == "**")   tmp = tmp = tmp.substr(0,4) + String(m) + tmp.substr(6,2);
                                        if(de == "**")   tmp = tmp.replace(/\*\*/, day);

                                        if(tmp == String(y + String(m) + day)) {
                                                disabled = false;
                                                break;
                                        };
                                };
                        };
                        if(disabled) obj[String(y + String(m) + day)] = 1;
                };
                return obj;
        };
        o.setFirstDayOfWeek = function(e) {
                if ( e == null ) e = document.parentWindow.event;
                var elem = e.target != null ? e.target : e.srcElement;
                if(elem.tagName.toLowerCase() != "th") {
                        while(elem.tagName.toLowerCase() != "th") elem = elem.parentNode;
                };
                var cnt = 0;
                while(elem.previousSibling) {
                        elem = elem.previousSibling;
                        if(elem.tagName.toLowerCase() == "th") cnt++;
                };
                o.firstDayOfWeek = (o.firstDayOfWeek + cnt) % 7;
                o.updateTableHeaders();
                return o.killEvent(e);
        };
        o.truePosition = function(element) {
                var pos = o.cumulativeOffset(element);
                if(window.opera) { return pos; }
                var iebody      = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
                var dsocleft    = document.all ? iebody.scrollLeft : window.pageXOffset;
                var dsoctop     = document.all ? iebody.scrollTop  : window.pageYOffset;
                var posReal     = o.realOffset(element);
                return [pos[0] - posReal[0] + dsocleft, pos[1] - posReal[1] + dsoctop];
        };
        o.realOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.scrollTop  || 0;
                        l += element.scrollLeft || 0;
                        element = element.parentNode;
                } while (element);
                return [l, t];
        };
        o.cumulativeOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.offsetTop  || 0;
                        l += element.offsetLeft || 0;
                        element = element.offsetParent;
                } while (element);
                return [l, t];
        };
        o.resize = function() {
                if(!o.created || !o.getElem()) return;
                
                o.div.style.visibility = "hidden";
                if(!o.staticPos) { o.div.style.left = o.div.style.top = "0px"; }
                o.div.style.display = "block";
                
                var osh = o.div.offsetHeight;
                var osw = o.div.offsetWidth;
                
                o.div.style.visibility = "visible";
                o.div.style.display = "none";
                
                if(!o.staticPos) {
                        var elem          = document.getElementById('fd-but-' + o.id);
                        var pos           = o.truePosition(elem);
                        var trueBody      = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
                        var scrollTop     = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollTop;
                        var scrollLeft    = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollLeft;

                        if(parseInt(trueBody.clientWidth+scrollLeft) < parseInt(osw+pos[0])) {
                                o.div.style.left = Math.abs(parseInt((trueBody.clientWidth+scrollLeft) - osw)) + "px";
                        } else {
                                o.div.style.left  = pos[0] + "px";
                        };

                        if(parseInt(trueBody.clientHeight+scrollTop) < parseInt(osh+pos[1]+elem.offsetHeight+2)) {
                                o.div.style.top   = Math.abs(parseInt(pos[1] - (osh + 2))) + "px";
                        } else {
                                o.div.style.top   = Math.abs(parseInt(pos[1] + elem.offsetHeight + 2)) + "px";
                        };
                };
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(o.staticPos) return;
                o.iePopUp.style.top    = o.div.style.top;
                o.iePopUp.style.left   = o.div.style.left;
                o.iePopUp.style.width  = osw + "px";
                o.iePopUp.style.height = (osh - 2) + "px";
                @end
                @*/
        };
        o.equaliseDates = function() {
                var clearDayFound = false;
                var tmpDate;
                for(var i = o.low; i <= o.high; i++) {
                        tmpDate = String(i);
                        if(!o.disableDays[new Date(tmpDate.substr(0,4), tmpDate.substr(6,2), tmpDate.substr(4,2)).getDay() - 1]) {
                                clearDayFound = true;
                                break;
                        };
                };
                if(!clearDayFound) o.disableDays = o.defaults.disableDays = [0,0,0,0,0,0,0];
        };
        o.outOfRange = function(tmpDate) {
                if(!o.low && !o.high) return false;

                var level = false;
                if(!tmpDate) {
                        level = true;
                        tmpDate = o.date;
                };
                
                var d  = (tmpDate.getDate() < 10) ? "0" + tmpDate.getDate() : tmpDate.getDate();
                var m  = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1;
                var y  = tmpDate.getFullYear();
                var dt = String(y)+String(m)+String(d);

                if(o.low && parseInt(dt) < parseInt(o.low)) {
                        if(!level) return true;
                        o.date = new Date(o.low.substr(0,4), o.low.substr(4,2)-1, o.low.substr(6,2), 5, 0, 0);
                        return false;
                };
                if(o.high && parseInt(dt) > parseInt(o.high)) {
                        if(!level) return true;
                        o.date = new Date( o.high.substr(0,4), o.high.substr(4,2)-1, o.high.substr(6,2), 5, 0, 0);
                };
                return false;
        };
        o.createButton = function() {
                if(o.staticPos) { return; };
                
                var but;
                
                if(!document.getElementById("fd-but-" + o.id)) {
                        var inp = o.getElem();
                        
                        but = document.createElement('a');
                        but.href = "#";

                        var span = document.createElement('span');
                        span.appendChild(document.createTextNode(String.fromCharCode( 160 )));

                        but.className = "date-picker-control";
                        but.title = (typeof(fdLocale) == "object" && options.locale && fdLocale.titles.length > 5) ? fdLocale.titles[5] : "";

                        but.id = "fd-but-" + o.id;
                        but.appendChild(span);

                        if(inp.nextSibling) {
                                inp.parentNode.insertBefore(but, inp.nextSibling);
                        } else {
                                inp.parentNode.appendChild(but);
                        };
                } else {
                        but = document.getElementById("fd-but-" + o.id);
                };

                but.onclick = but.onpress = function(e) {
                        e = e || window.event;
                        var inpId = this.id.replace('fd-but-','');
                        try { var dp = datePickerController.getDatePicker(inpId); } catch(err) { return false; };

                        if(e.type == "press") {
                                var kc = e.keyCode != null ? e.keyCode : e.charCode;
                                if(kc != 13) { return true; };
                                if(dp.visible) {
                                        hideAll();
                                        return false;
                                };
                        };

                        if(!dp.visible) {
                                datePickerController.hideAll(inpId);
                                dp.show();
                        } else {
                                datePickerController.hideAll();
                        };
                        return false;
                };
                but = null;
        },
        o.create = function() {
                
                function createTH(details) {
                        var th = document.createElement('th');
                        if(details.thClassName) th.className = details.thClassName;
                        if(details.colspan) {
                                /*@cc_on
                                /*@if (@_win32)
                                th.setAttribute('colSpan',details.colspan);
                                @else @*/
                                th.setAttribute('colspan',details.colspan);
                                /*@end
                                @*/
                        };
                        /*@cc_on
                        /*@if (@_win32)
                        th.unselectable = "on";
                        /*@end@*/
                        return th;
                };
                
                function createThAndButton(tr, obj) {
                        for(var i = 0, details; details = obj[i]; i++) {
                                var th = createTH(details);
                                tr.appendChild(th);
                                var but = document.createElement('span');
                                but.className = details.className;
                                but.id = o.id + details.id;
                                but.appendChild(document.createTextNode(details.text));
                                but.title = details.title || "";
                                if(details.onmousedown) but.onmousedown = details.onmousedown;
                                if(details.onclick)     but.onclick     = details.onclick;
                                if(details.onmouseout)  but.onmouseout  = details.onmouseout;
                                th.appendChild(but);
                        };
                };
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(!document.getElementById("iePopUpHack")) {
                                o.iePopUp = document.createElement('iframe');
                                o.iePopUp.src = "javascript:'<html></html>';";
                                o.iePopUp.setAttribute('className','iehack');
                                o.iePopUp.scrolling="no";
                                o.iePopUp.frameBorder="0";
                                o.iePopUp.name = o.iePopUp.id = "iePopUpHack";
                                document.body.appendChild(o.iePopUp);
                        } else {
                                o.iePopUp = document.getElementById("iePopUpHack");
                        };
                @end
                @*/
                
                if(typeof(fdLocale) == "object" && o.locale) {
                        datePicker.titles  = fdLocale.titles;
                        datePicker.months  = fdLocale.months;
                        datePicker.fullDay = fdLocale.fullDay;
                        // Optional parameters
                        if(fdLocale.dayAbbr) datePicker.dayAbbr = fdLocale.dayAbbr;
                        if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek;
                };
                
                o.div = document.createElement('div');
                o.div.style.zIndex = 9999;
                o.div.id = "fd-"+o.id;
                o.div.className = "datePicker";
                
                if(!o.staticPos) {
                        document.getElementsByTagName('body')[0].appendChild(o.div);
                } else {
                        elem = o.getElem();
                        if(!elem) {
                                o.div = null;
                                return;
                        };
                        o.div.className += " staticDP";
                        o.div.setAttribute("tabIndex", "0");
                        o.div.onfocus = o.events.onfocus;
                        o.div.onblur  = o.events.onblur;
                        elem.parentNode.insertBefore(o.div, elem.nextSibling);
                        if(o.hideInput && elem.type && elem.type == "text") elem.setAttribute("type", "hidden");
                };
                
                //var nbsp = String.fromCharCode( 160 );
                var tr, row, col, tableHead, tableBody;

                o.table = document.createElement('table');
                o.div.appendChild( o.table );
                
                tableHead = document.createElement('thead');
                o.table.appendChild( tableHead );
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                // Title Bar
                o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
                tr.appendChild( o.titleBar );
                tr = null;
                
                var span = document.createElement('span');
                span.className = "month-display";
                o.titleBar.appendChild(span);

                span = document.createElement('span');
                span.className = "year-display";
                o.titleBar.appendChild(span);

                span = null;
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                createThAndButton(tr, [{className:"prev-but", id:"-prev-year-but", text:"\u00AB", title:datePicker.titles[2], onmousedown:function(e) { o.events.incDec(e,0,-1,0); }, onmouseout:o.events.clearTimer },{className:"prev-but", id:"-prev-month-but", text:"\u2039", title:datePicker.titles[0], onmousedown:function(e) { o.events.incDec(e,0,0,-1); }, onmouseout:o.events.clearTimer },{colspan:3, className:"today-but", id:"-today-but", text:datePicker.titles.length > 4 ? datePicker.titles[4] : "Today", onclick:o.events.gotoToday},{className:"next-but", id:"-next-month-but", text:"\u203A", title:datePicker.titles[1], onmousedown:function(e) { o.events.incDec(e,0,0,1); }, onmouseout:o.events.clearTimer },{className:"next-but", id:"-next-year-but", text:"\u00BB", title:datePicker.titles[3], onmousedown:function(e) { o.events.incDec(e,0,1,0); }, onmouseout:o.events.clearTimer }]);

                tableBody = document.createElement('tbody');
                o.table.appendChild( tableBody );

                for(var rows = 0; rows < 7; rows++) {
                        row = document.createElement('tr');

                        if(rows != 0) tableBody.appendChild(row);
                        else          tableHead.appendChild(row);
                        
                        for(var cols = 0; cols < 7; cols++) {
                                col = (rows == 0) ? document.createElement('th') : document.createElement('td');

                                row.appendChild(col);
                                if(rows != 0) {
                                        col.appendChild(document.createTextNode(o.nbsp));
                                        col.onmouseover = o.events.onmouseover;
                                        col.onclick = o.events.onclick;
                                } else {
                                        col.className = "date-picker-day-header";
                                        col.scope = "col";
                                };
                                col = null;
                        };
                        row = null;
                };

                // Table headers
                var but;
                var ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                for ( var y = 0; y < 7; y++ ) {
                        if(y > 0) {
                                but = document.createElement("span");
                                but.className = "fd-day-header";
                                but.onclick = ths[y].onclick = o.setFirstDayOfWeek;
                                but.appendChild(document.createTextNode(o.nbsp));
                                ths[y].appendChild(but);
                                but = null;
                        } else {
                                ths[y].appendChild(document.createTextNode(o.nbsp));
                        };
                };
                
                o.ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                o.trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                
                o.updateTableHeaders();
                
                tableBody = tableHead = tr = createThAndButton = createTH = null;

                if(o.low && o.high && (o.high - o.low < 7)) { o.equaliseDates(); };
                
                o.created = true;
                
                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.addEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');
                                datePickerController.addEvent(mmN, "change", o.changeHandler);
                                datePickerController.addEvent(ddN, "change", o.changeHandler);
                        };
                        
                        o.show();
                } else {
                        o.createButton();
                        o.resize();
                        o.fade();
                };
        };
        o.changeHandler = function() {
                o.setDateFromInput();
                o.updateTable();
        };
        o.setDateFromInput = function() {
                function m2c(val) {
                        return String(val).length < 2 ? "00".substring(0, 2 - String(val).length) + String(val) : val;
                };

                o.dateSet = null;
                
                var elem = o.getElem();
                if(!elem) return;

                if(!o.splitDate) {
                        var date = datePickerController.dateFormat(elem.value, o.format.search(/m-d-y/i) != -1);
                } else {
                        var mmN = document.getElementById(o.id+'-mm');
                        var ddN = document.getElementById(o.id+'-dd');
                        var tm = parseInt(mmN.tagName.toLowerCase() == "input"  ? mmN.value  : mmN.options[mmN.selectedIndex].value, 10);
                        var td = parseInt(ddN.tagName.toLowerCase() == "input"  ? ddN.value  : ddN.options[ddN.selectedIndex].value, 10);
                        var ty = parseInt(elem.tagName.toLowerCase() == "input" ? elem.value : elem.options[elem.selectedIndex || 0].value, 10);
                        var date = datePickerController.dateFormat(tm + "/" + td + "/" + ty, true);
                };

                var badDate = false;
                if(!date) {
                        badDate = true;
                        date = String(new Date().getFullYear()) + m2c(new Date().getMonth()+1) + m2c(new Date().getDate());
                };

                var d,m,y;
                y = Number(date.substr(0, 4));
                m = Number(date.substr(4, 2)) - 1;
                d = Number(date.substr(6, 2));

                var dpm = datePicker.getDaysPerMonth(m, y);
                if(d > dpm) d = dpm;

                if(new Date(y, m, d) == 'Invalid Date' || new Date(y, m, d) == 'NaN') {
                        badDate = true;
                        o.date = new Date();
                        o.date.setHours(5);
                        return;
                };

                o.date = new Date(y, m, d);
                o.date.setHours(5);

                if(!badDate) o.dateSet = new Date(o.date);
                m2c = null;
        };
        o.setSelectIndex = function(elem, indx) {
                var len = elem.options.length;
                indx = Number(indx);
                for(var opt = 0; opt < len; opt++) {
                        if(elem.options[opt].value == indx) {
                                elem.selectedIndex = opt;
                                return;
                        };
                };
        },
        o.returnFormattedDate = function() {

                var elem = o.getElem();
                if(!elem) return;
                
                var d                   = (o.date.getDate() < 10) ? "0" + o.date.getDate() : o.date.getDate();
                var m                   = ((o.date.getMonth() + 1) < 10) ? "0" + (o.date.getMonth() + 1) : o.date.getMonth() + 1;
                var yyyy                = o.date.getFullYear();
                var disabledDates       = o.getDisabledDates(yyyy, m);
                var weekDay             = ( o.date.getDay() + 6 ) % 7;

                if(!(o.disableDays[weekDay] || String(yyyy)+m+d in disabledDates)) {

                        if(o.splitDate) {
                                var ddE = document.getElementById(o.id+"-dd");
                                var mmE = document.getElementById(o.id+"-mm");

                                if(ddE.tagName.toLowerCase() == "input") { ddE.value = d; }
                                else { o.setSelectIndex(ddE, d); /*ddE.selectedIndex = d - 1;*/ };
                                
                                if(mmE.tagName.toLowerCase() == "input") { mmE.value = m; }
                                else { o.setSelectIndex(mmE, m); /*mmE.selectedIndex = m - 1;*/ };
                                
                                if(elem.tagName.toLowerCase() == "input") elem.value = yyyy;
                                else {
                                        o.setSelectIndex(elem, yyyy); /*
                                        for(var opt = 0; opt < elem.options.length; opt++) {
                                                if(elem.options[opt].value == yyyy) {
                                                        elem.selectedIndex = opt;
                                                        break;
                                                };
                                        };
                                        */
                                };
                        } else {
                                elem.value = o.format.replace('y',yyyy).replace('m',m).replace('d',d).replace(/-/g,o.divider);
                        };
                        // HACK: Falla en IEx
//                        if(!elem.type || elem.type && elem.type != "hidden"){ elem.focus(); }
                        if(o.staticPos) {
                                o.dateSet = new Date( o.date );
                                o.updateTable();
                        };
                        
                        // Programmatically fire the onchange event
                        if(document.createEvent) {
                                var onchangeEvent = document.createEvent('HTMLEvents');
                                onchangeEvent.initEvent('change', true, false);
                                elem.dispatchEvent(onchangeEvent);
                        } else if(document.createEventObject) {
                                elem.fireEvent('onchange');
                        };
                };
        };
        o.disableTodayButton = function() {
                var today = new Date();
                document.getElementById(o.id + "-today-but").className = document.getElementById(o.id + "-today-but").className.replace("fd-disabled", "");
                if(o.outOfRange(today) || (o.date.getDate() == today.getDate() && o.date.getMonth() == today.getMonth() && o.date.getFullYear() == today.getFullYear())) {
                        document.getElementById(o.id + "-today-but").className += " fd-disabled";
                        document.getElementById(o.id + "-today-but").onclick = null;
                } else {
                        document.getElementById(o.id + "-today-but").onclick = o.events.gotoToday;
                };
        };
        o.updateTableHeaders = function() {
                var d, but;
                var ths = o.ths;
                for ( var y = 0; y < 7; y++ ) {
                        d = (o.firstDayOfWeek + y) % 7;
                        ths[y].title = datePicker.fullDay[d];

                        if(y > 0) {
                                but = ths[y].getElementsByTagName("span")[0];
                                but.removeChild(but.firstChild);
                                but.appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                                but.title = datePicker.fullDay[d];
                                but = null;
                        } else {
                                ths[y].removeChild(ths[y].firstChild);
                                ths[y].appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                        };
                };
                o.updateTable();
        };

        o.updateTable = function(noCallback) {

                if(o.timerSet) {
                        var d = new Date(o.date);
                        d.setDate( Math.min(d.getDate()+o.dayInc, datePicker.getDaysPerMonth(d.getMonth()+o.monthInc,d.getFullYear()+o.yearInc)) );
                        d.setMonth( d.getMonth() + o.monthInc );
                        d.setFullYear( d.getFullYear() + o.yearInc );
                        o.date = d;
                };
                
                if(!noCallback && "onupdate" in datePickerController && typeof(datePickerController.onupdate) == "function") datePickerController.onupdate(o);

                o.outOfRange();
                o.disableTodayButton();
                
                // Set the tmpDate to the second day of this month (to avoid daylight savings time madness on Windows)
                var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 2 );
                tmpDate.setHours(5);

                var tdm = tmpDate.getMonth();
                var tdy = tmpDate.getFullYear();

                // Do the disableDates for this year and month
                var disabledDates = o.getDisabledDates(o.date.getFullYear(), o.date.getMonth() + 1);

                var today = new Date();

                // Previous buttons out of range
                var b = document.getElementById(o.id + "-prev-year-but");
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy - 1), Number(tdm), datePicker.getDaysPerMonth(Number(tdm), tdy-1)))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == -1) o.stopTimer();
                };

                b = document.getElementById(o.id + "-prev-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, (Number(tdm) - 1), datePicker.getDaysPerMonth(Number(tdm)-1, tdy)))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == -1)  o.stopTimer();
                };

                // Next buttons out of range
                b= document.getElementById(o.id + "-next-year-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy + 1), Number(tdm), 1))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == 1)  o.stopTimer();
                };

                b = document.getElementById(o.id + "-next-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, Number(tdm) + 1, 1))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == 1)  o.stopTimer();
                };

                b = null;
                
                var cd = o.date.getDate();
                var cm = o.date.getMonth();
                var cy = o.date.getFullYear();
                
                // Title Bar
                var span = o.titleBar.getElementsByTagName("span");
                while(span[0].firstChild) span[0].removeChild(span[0].firstChild);
                while(span[1].firstChild) span[1].removeChild(span[1].firstChild);
                span[0].appendChild(document.createTextNode(datePicker.months[cm] + o.nbsp));
                span[1].appendChild(document.createTextNode(cy));

                tmpDate.setDate( 1 );
                        
                var dt, cName, td, tds, i;
                var weekDay = ( tmpDate.getDay() + 6 ) % 7;
                var firstColIndex = (( (weekDay - o.firstDayOfWeek) + 7 ) % 7) - 1;
                var dpm = datePicker.getDaysPerMonth(cm, cy);

                var todayD = today.getDate();
                var todayM = today.getMonth();
                var todayY = today.getFullYear();
                
                var c = "class";
                /*@cc_on
                @if(@_win32)
                c = "className";
                @end
                @*/

                var stub = String(tdy) + (String(tdm+1).length < 2 ? "0" + (tdm+1) : tdm+1);
                
                for(var row = 0; row < 6; row++) {

                        tds = o.trs[row].getElementsByTagName('td');

                        for(var col = 0; col < 7; col++) {
                        
                                td = tds[col];
                                td.removeChild(td.firstChild);

                                td.setAttribute("id", "");
                                td.setAttribute("title", "");

                                i = (row * 7) + col;
                        
                                if(i > firstColIndex && i <= (firstColIndex + dpm)) {
                                        dt = i - firstColIndex;

                                        tmpDate.setDate(dt);
                                        td.appendChild(document.createTextNode(dt));
                                        
                                        if(o.outOfRange(tmpDate)) {
                                                td.setAttribute(c, "out-of-range");
                                        } else {

                                                cName = [];
                                                weekDay = ( tmpDate.getDay() + 6 ) % 7;

                                                if(dt == todayD && tdm == todayM && tdy == todayY) {
                                                        cName.push("date-picker-today");
                                                };

                                                if(o.dateSet != null && o.dateSet.getDate() == dt && o.dateSet.getMonth() == tdm && o.dateSet.getFullYear() == tdy) {
                                                        cName.push("date-picker-selected-date");
                                                };
                                                
                                                if(o.disableDays[weekDay] || stub + String(dt < 10 ? "0" + dt : dt) in disabledDates) {
                                                        cName.push("day-disabled");
                                                } else if(o.highlightDays[weekDay]) {
                                                        cName.push("date-picker-highlight");
                                                };
                                                
                                                if(cd == dt) {
                                                        td.setAttribute("id", o.id + "-date-picker-hover");
                                                        cName.push("date-picker-hover");
                                                };
                                                
                                                cName.push("dm-" + dt + '-' + (tdm + 1) + " " + " dmy-" + dt + '-' + (tdm + 1) + '-' + tdy);
                                                td.setAttribute(c, cName.join(' '));
                                                td.setAttribute("title", datePicker.months[cm] + o.nbsp + dt + "," + o.nbsp + cy);
                                        };
                                } else {
                                        td.appendChild(document.createTextNode(o.nbsp));
                                        td.setAttribute(c, "date-picker-unused");
                                };
                        };
                };

                if(o.timerSet) {
                        o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8));
                        o.timer = window.setTimeout(o.updateTable, o.timerInc);
                };
        };
        o.addKeyboardEvents = function() {
                datePickerController.addEvent(document, "keypress", o.events.onkeydown);
                /*@cc_on
                @if(@_win32)
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                @end
                @*/
                if(window.devicePixelRatio) {
                        datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                        datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                };
        };
        o.removeKeyboardEvents =function() {
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.removeEvent(document, "keydown",  o.events.onkeydown);
        };
        o.show = function() {
                var elem = o.getElem();
                if(!elem || o.visible || elem.disabled) return;

                o.reset();
                o.setDateFromInput();
                o.updateTable();
                
                if(!o.staticPos) o.resize();
                
                datePickerController.addEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);

                if(!o.staticPos) { o.addKeyboardEvents(); };
                
                o.opacityTo = o.noTransparency ? 99 : 90;
                o.div.style.display = "block";
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(!o.staticPos) o.iePopUp.style.display = "block";
                @end
                @*/

                o.fade();
                o.visible = true;
        };
        o.hide = function() {
                if(!o.visible) return;
                o.stopTimer();
                if(o.staticPos) return;
                
                datePickerController.removeEvent(document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",  o.events.clearTimer);
                o.removeKeyboardEvents();
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp.style.display = "none";
                @end
                @*/
                
                o.opacityTo = 0;
                o.fade();
                o.visible = false;
                var elem = o.getElem();
                // HACK: Falla en IEx
//                if(!elem.type || elem.type && elem.type != "hidden") { elem.focus(); };
        };
        o.destroy = function() {
                // Cleanup for Internet Explorer
                datePickerController.removeEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",   o.events.clearTimer);
                o.removeKeyboardEvents();

                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.removeEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');

                                datePickerController.removeEvent(mmN, "change", o.changeHandler);
                                datePickerController.removeEvent(ddN, "change", o.changeHandler);
                        };
                        o.div.onfocus = o.div.onblur = null;
                };
                
                var ths = o.table.getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        th.onmouseover = th.onmouseout = th.onmousedown = th.onclick = null;
                };
                
                var tds = o.table.getElementsByTagName("td");
                for(var i = 0, td; td = tds[i]; i++) {
                        td.onmouseover = td.onclick = null;
                };

                var butts = o.table.getElementsByTagName("span");
                for(var i = 0, butt; butt = butts[i]; i++) {
                        butt.onmousedown = butt.onclick = butt.onkeypress = null;
                };
                
                o.ths = o.trs = null;
                
                clearTimeout(o.fadeTimer);
                clearTimeout(o.timer);
                o.fadeTimer = o.timer = null;
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp = null;
                @end
                @*/
                
                if(!o.staticPos && document.getElementById(o.id.replace(/^fd-/, 'fd-but-'))) {
                        var butt = document.getElementById(o.id.replace(/^fd-/, 'fd-but-'));
                        butt.onclick = butt.onpress = null;
                };
                
                if(o.div && o.div.parentNode) {
                        o.div.parentNode.removeChild(o.div);
                };
                
                o.titleBar = o.table = o.div = null;
                o = null;
        };
        o.create();
};

datePickerController = function() {
        var datePickers = {};
        var uniqueId    = 0;
        
        var addEvent = function(obj, type, fn) {
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        };
        var removeEvent = function(obj, type, fn) {
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        };
        var hideAll = function(exception) {
                var dp;
                for(dp in datePickers) {
                        if(!datePickers[dp].created || datePickers[dp].staticPos) continue;
                        if(exception && exception == datePickers[dp].id) { continue; };
                        if(document.getElementById(datePickers[dp].id))  { datePickers[dp].hide(); };
                };
        };
        var cleanUp = function() {
                var dp;
                for(dp in datePickers) {
                        if(!document.getElementById(datePickers[dp].id)) {
                                if(!datePickers[dp].created) continue;
                                datePickers[dp].destroy();
                                datePickers[dp] = null;
                                delete datePickers[dp];
                        };
                };
        };
        var destroy = function() {
                for(dp in datePickers) {
                        if(!datePickers[dp].created) continue;
                        datePickers[dp].destroy();
                        datePickers[dp] = null;
                        delete datePickers[dp];
                };
                datePickers = null;
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(document.getElementById("iePopUpHack")) {
                                document.body.removeChild(document.getElementById("iePopUpHack"));
                        };
                @end
                @*/
                datePicker.script = null;
                removeEvent(window, 'load', datePickerController.create);
                removeEvent(window, 'unload', datePickerController.destroy);
        };
        var dateFormat = function(dateIn, favourMDY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/,    d:5, m:3, y:1 }   // ymd
                        ];

                var start;
                var cnt = 0;
                while(cnt < 3) {
                        start = (cnt + (favourMDY ? 4 : 3)) % 3;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + m;
                                if(d.length == 1) d = "0" + d;
                                if(y.length != 4) y = (parseInt(y) < 50) ? '20' + y : '19' + y;
                                return String(y)+m+d;
                        };
                        cnt++;
                };
                return 0;
        };
        var joinNodeLists = function() {
                if(!arguments.length) { return []; }
                var nodeList = [];
                for (var i = 0; i < arguments.length; i++) {
                        for (var j = 0, item; item = arguments[i][j]; j++) {
                                nodeList[nodeList.length] = item;
                        };
                };
                return nodeList;
        };
        var addDatePicker = function(inpId, options) {
                if(!(inpId in datePickers)) {
                        datePickers[inpId] = new datePicker(options);
                };
        };
        var getDatePicker = function(inpId) {
                if(!(inpId in datePickers)) { throw "No datePicker has been created for the form element with an id of '" + inpId.toString() + "'"; };
                return datePickers[inpId];
        };
        var grepRangeLimits = function(sel) {
                var range = [];
                for(var i = 0; i < sel.options.length; i++) {
                        if(sel.options[i].value.search(/^\d\d\d\d$/) == -1) { continue; };
                        if(!range[0] || Number(sel.options[i].value) < range[0]) { range[0] = Number(sel.options[i].value); };
                        if(!range[1] || Number(sel.options[i].value) > range[1]) { range[1] = Number(sel.options[i].value); };
                };
                return range;
        };
        var create = function(inp) {
                if(!(typeof document.createElement != "undefined" && typeof document.documentElement != "undefined" && typeof document.documentElement.offsetWidth == "number")) return;

                var inputs  = (inp && inp.tagName) ? [inp] : joinNodeLists(document.getElementsByTagName('input'), document.getElementsByTagName('select'));
                var regExp1 = /disable-days-([1-7]){1,6}/g;             // the days to disable
                var regExp2 = /no-transparency/g;                       // do not use transparency effects
                var regExp3 = /highlight-days-([1-7]){1,7}/g;           // the days to highlight in red
                var regExp4 = /range-low-(\d\d\d\d-\d\d-\d\d)/g;        // the lowest selectable date
                var regExp5 = /range-high-(\d\d\d\d-\d\d-\d\d)/g;       // the highest selectable date
                var regExp6 = /format-(d-m-y|m-d-y|y-m-d)/g;            // the input/output date format
                var regExp7 = /divider-(dot|slash|space|dash)/g;        // the character used to divide the date
                var regExp8 = /no-locale/g;                             // do not attempt to detect the browser language
                var regExp9 = /no-fade/g;                               // always show the datepicker
                var regExp10 = /hide-input/g;                           // hide the input
                
                for(var i=0, inp; inp = inputs[i]; i++) {
                        if(inp.className && (inp.className.search(regExp6) != -1 || inp.className.search(/split-date/) != -1) && ((inp.tagName.toLowerCase() == "input" && (inp.type == "text" || inp.type == "hidden")) || inp.tagName.toLowerCase() == "select")) {

                                if(inp.id && document.getElementById('fd-'+inp.id)) { continue; };
                                
                                if(!inp.id) { inp.id = "fdDatePicker-" + uniqueId++; };
                                
                                var options = {
                                        id:inp.id,
                                        low:"",
                                        high:"",
                                        divider:"/",
                                        format:"d-m-y",
                                        highlightDays:[0,0,0,0,0,1,1],
                                        disableDays:[0,0,0,0,0,0,0],
                                        locale:inp.className.search(regExp8) == -1,
                                        splitDate:0,
                                        noTransparency:inp.className.search(regExp2) != -1,
                                        staticPos:inp.className.search(regExp9) != -1,
                                        hideInput:inp.className.search(regExp10) != -1
                                };

                                if(!options.staticPos) {
                                        options.hideInput = false;
                                } else {
                                        options.noTransparency = true;
                                };
                                
                                // Split the date into three parts ?
                                if(inp.className.search(/split-date/) != -1) {
                                        if(document.getElementById(inp.id+'-dd') && document.getElementById(inp.id+'-mm') && document.getElementById(inp.id+'-dd').tagName.search(/input|select/i) != -1 && document.getElementById(inp.id+'-mm').tagName.search(/input|select/i) != -1) {
                                                options.splitDate = 1;
                                        };
                                };
                                
                                // Date format(variations of d-m-y)
                                if(inp.className.search(regExp6) != -1) {
                                        options.format = inp.className.match(regExp6)[0].replace('format-','');
                                };
                                
                                // What divider to use, a "/", "-", "." or " "
                                if(inp.className.search(regExp7) != -1) {
                                        var dividers = { dot:".", space:" ", dash:"-", slash:"/" };
                                        options.divider = (inp.className.search(regExp7) != -1 && inp.className.match(regExp7)[0].replace('divider-','') in dividers) ? dividers[inp.className.match(regExp7)[0].replace('divider-','')] : "/";
                                };

                                // The days to highlight
                                if(inp.className.search(regExp3) != -1) {
                                        var tmp = inp.className.match(regExp3)[0].replace(/highlight-days-/, '');
                                        options.highlightDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.highlightDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The days to disable
                                if(inp.className.search(regExp1) != -1) {
                                        var tmp = inp.className.match(regExp1)[0].replace(/disable-days-/, '');
                                        options.disableDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.disableDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The lower limit
                                if(inp.className.search(/range-low-today/i) != -1) {
                                        options.low = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp4) != -1) {
                                        options.low = datePickerController.dateFormat(inp.className.match(regExp4)[0].replace(/range-low-/, ''), false);
                                        if(!options.low) {
                                                options.low = '';
                                        };
                                };

                                // The higher limit
                                if(inp.className.search(/range-high-today/i) != -1 && inp.className.search(/range-low-today/i) == -1) {
                                        options.high = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp5) != -1) {
                                        options.high = datePickerController.dateFormat(inp.className.match(regExp5)[0].replace(/range-high-/, ''), false);
                                        if(!options.high) {
                                                options.high = '';
                                        };
                                };

                                // Always round lower & higher limits if a selectList involved
                                if(inp.tagName.search(/select/i) != -1) {
                                        var range = grepRangeLimits(inp);
                                        options.low  = options.low  ? range[0] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[0] + "/01/01");
                                        options.high = options.high ? range[1] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[1] + "/12/31");
                                };

                                addDatePicker(inp.id, options);
                        };
                };
        }
        
        return {
                addEvent:addEvent,
                removeEvent:removeEvent,
                create:create,
                destroy:destroy,
                cleanUp:cleanUp,
                addDatePicker:addDatePicker,
                getDatePicker:getDatePicker,
                dateFormat:dateFormat,
                datePickers:datePickers,
                hideAll:hideAll
        };
}();

})();

datePickerController.addEvent(window, 'load', datePickerController.create);
datePickerController.addEvent(window, 'unload', datePickerController.destroy);


/*
 * jQuery gallerificPlus plugin
 *
 * Copyright (c) 2008 Matt Gifford (http://www.mattgifford.co.uk)
 * Licensed under the Creative Commons Attribution-Noncommercial-ShareAlike License
 * http://creativecommons.org/licenses/by-nc-sa/3.0/
 *
 * Thanks to Trent Foley (Gallerific plugin author - http://www.twospy.com)
 * and Leandro Vieira Pinho (jQuery Lightbox plugin author - http://leandrovieira.com), whose amazing plugins I adapted and integrated to work together.
 * I wouldn't have had anything to work with if it wasn't for those guys, so thank you very VERY much.
 */
;(function($) {
        function t(key) {
           return eval("voranet_locales." + key);
        }
	// Write noscript style
	document.write("<style type='text/css'>.noscript{display:none}</style>");

	var ver = 'gallerifficPlus0.3';
	var galleryOffset = 0;
	var galleries = [];
	var allImages = [];
	var historyCurrentHash;
	var historyBackStack;
	var historyForwardStack;
	var isFirst = false;
	var dontCheck = false;
	var isInitialized = false;

	function getHash() {
		var hash = location.hash;
		if (!hash) return -1;
		hash = hash.replace(/^.*#/, '');
		if (isNaN(hash)) return -1;
		return (+hash);
	}

	function registerGallery(gallery) {
		galleries.push(gallery);

		// update the global offset value
		galleryOffset += gallery.data.length;
	}

	function getGallery(hash) {
		for (i = 0; i < galleries.length; i++) {
			var gallery = galleries[i];
			if (hash < (gallery.data.length+gallery.offset))
				return gallery;
		}
		return 0;
	}

	function historyCallback() {
		// Using present location.hash always (seems to work, unlike the hash argument passed to this callback)
		var hash = getHash();
		if (hash < 0) return;

		var gallery = getGallery(hash);
		if (!gallery) return;

		var index = hash-gallery.offset;
		gallery.goto(index);
	}

	function historyInit() {
		if (isInitialized) return;
		isInitialized = true;

		var current_hash = location.hash;

		historyCurrentHash = current_hash;
		if ($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (historyCurrentHash == '') {
				historyCurrentHash = '#';
			}
		} else if ($.browser.safari) {
			// etablish back/forward stacks
			historyBackStack = [];
			historyBackStack.length = history.length;
			historyForwardStack = [];
			isFirst = true;
		}

		setInterval(function() { historyCheck(); }, 100);
	}

	function historyAddHistory(hash) {
		// This makes the looping function do something
		historyBackStack.push(hash);
		historyForwardStack.length = 0; // clear forwardStack (true click occured)
		isFirst = true;
	}

	function historyCheck() {
		if ($.browser.safari) {
			if (!dontCheck) {
				var historyDelta = history.length - historyBackStack.length;

				if (historyDelta) { // back or forward button has been pushed
					isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) historyForwardStack.unshift(historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) historyBackStack.push(historyForwardStack.shift());
					}
					var cachedHash = historyBackStack[historyBackStack.length - 1];
					if (cachedHash != undefined) {
						historyCurrentHash = location.hash;
						historyCallback();
					}
				} else if (historyBackStack[historyBackStack.length - 1] == undefined && !isFirst) {
					historyCallback();
					isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != historyCurrentHash) {
				historyCurrentHash = current_hash;
				historyCallback();
			}
		}
	}

	var defaults = {
		delay:                3000,
		numThumbs:            20,
		preloadAhead:         40, // Set to -1 to preload all images
		enableTopPager:       true,
		enableBottomPager:    true,
		imageContainerSel:    '',
		thumbsContainerSel:   '',
		controlsContainerSel: '',
		titleContainerSel:    '',
		descContainerSel:     '',
		downloadLinkSel:      '',
		renderSSControls:     true,
		renderNavControls:    true,
		playLinkText:         "<img src=\"/images/base/icons/play.png\"/>",
		pauseLinkText:     "<img src=\"/images/base/icons/pause.png\"/>",
		prevLinkText:        "<img src=\"/images/base/icons/rewind.png\"/>",
		nextLinkText:        "<img src=\"/images/base/icons/forward.png\"/>",
		playLinkTitle:         t("gallery.play"),
		pauseLinkTitle:     t("gallery.pause"),
		prevLinkTitle:        t("gallery.previous"),
		nextLinkTitle:        t("gallery.next"),
		nextPageLinkText:     t("gallery.next")+' &rsaquo;',
		prevPageLinkText:     '&lsaquo; '+t("gallery.previous"),
		autoPlay:			  false,

		// Configuration related to overlay
		overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
		overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
		// Configuration related to navigation
		fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
		// Configuration related to images
		imageLoading:			'/images/gallerific/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
		imageBtnPrev:			'/images/gallerific/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
		imageBtnNext:			'/images/gallerific/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
		imageBtnClose:			'/images/gallerific/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
		imageBlank:				'/images/gallerific/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
		// Configuration related to container image box
		containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
		containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
		// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
		txtImage:				t("gallery.image"),	// (string) Specify text "Image"
		txtOf:					t("gallery.of"),		// (string) Specify text "of"
		// Configuration related to keyboard navigation
		keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
		keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
		keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
		// Don´t alter these variables in any way
		imageArray:				[],
		activeImage:			0,
                clickableImage:             false,
		// Allow keyboard navigation on gallery as well as lightbox?
		galleryKeyboardNav:		true		// (boolean) Boolean that informs if the keyboard navigation will be used with the gallery (as it is used with the lightbox).

	};

	// lightbox specific functions

	function buildLightBox(image,gallery,current) {

		gallery.pause();

		// Hide some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
		$('embed, object, select').css({ 'visibility' : 'hidden' });
		// Call the function to create the markup structure; style some elements; assign events in some elements.
		_set_interface();
		// Unset total images in imageArray
		defaults.imageArray.length = 0;
		// Unset image active information
		defaults.activeImage = 0;

		if ( gallery.data.length == 1 ) {
			defaults.imageArray.push(new Array(gallery.data[current].gallery_size,gallery.data[current].title));
		} else {
			// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references
			for ( var i = 0; i < gallery.data.length; i++ ) {
				defaults.imageArray.push(new Array(gallery.data[i].gallery_size,gallery.data[i].title));
			}
		}
		while ( defaults.imageArray[defaults.activeImage][0] != gallery.data[current].gallery_size ) {
			defaults.activeImage++;
		}
		// Call the function that prepares image exibition
		_set_image_to_view();
	}

	/**
	 * Create the jQuery lightBox plugin interface
	 *
	 * The HTML markup will be like that:
		<div id="jquery-overlay"></div>
		<div id="jquery-lightbox">
			<div id="lightbox-container-image-box">
				<div id="lightbox-container-image">
					<img src="../fotos/XX.jpg" id="lightbox-image">
					<div id="lightbox-nav">
						<a href="#" id="lightbox-nav-btnPrev"></a>
						<a href="#" id="lightbox-nav-btnNext"></a>
					</div>
					<div id="lightbox-loading">
						<a href="#" id="lightbox-loading-link">
							<img src="../images/lightbox-ico-loading.gif">
						</a>
					</div>
				</div>
			</div>
			<div id="lightbox-container-image-data-box">
				<div id="lightbox-container-image-data">
					<div id="lightbox-image-details">
						<span id="lightbox-image-details-caption"></span>
						<span id="lightbox-image-details-currentNumber"></span>
					</div>
					<div id="lightbox-secNav">
						<a href="#" id="lightbox-secNav-btnClose">
							<img src="../images/lightbox-btn-close.gif">
						</a>
					</div>
				</div>
			</div>
		</div>
	 *
	 */
	function _set_interface() {
		// Apply the HTML markup into body tag
		$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + defaults.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + defaults.imageBtnClose + '"></a></div></div></div></div>');
		// Get page sizes
		var arrPageSizes = ___getPageSize();
		// Style overlay and show it
		$('#jquery-overlay').css({
			backgroundColor:	defaults.overlayBgColor,
			opacity:			defaults.overlayOpacity,
			width:				arrPageSizes[0],
			height:				arrPageSizes[1]
		}).fadeIn();
		// Get page scroll
		var arrPageScroll = ___getPageScroll();
		// Calculate top and left offset for the jquery-lightbox div object and show it
		$('#jquery-lightbox').css({
			top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
			left:	arrPageScroll[0]
		}).show();
		// Assigning click events in elements to close overlay
		$('#jquery-overlay,#jquery-lightbox').click(function() {
			_finish();
		});
		// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
		$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
			_finish();
			return false;
		});
		// If window was resized, calculate the new overlay dimensions
		$(window).resize(function() {
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				width:		arrPageSizes[0],
				height:		arrPageSizes[1]
			});
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			});
		});
	}


	/**
	 * Prepares image exibition; doing a image´s preloader to calculate it´s size
	 *
	 */
	function _set_image_to_view() { // show the loading
		// Show the loading
		$('#lightbox-loading').show();
		if ( defaults.fixedNavigation ) {
			$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
		} else {
			// Hide some elements
			$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
		}
		// Image preload process
		var objImagePreloader = new Image();
		objImagePreloader.onload = function() {
			$('#lightbox-image').attr('src',defaults.imageArray[defaults.activeImage][0]);
			// Perfomance an effect in the image container resizing it
			_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
			//	clear onLoad, IE behaves irratically with animated gifs otherwise
			objImagePreloader.onload=function(){};
		};
		objImagePreloader.src = defaults.imageArray[defaults.activeImage][0];
	};

	/**
	 * Perfomance an effect in the image container resizing it
	 *
	 * @param integer intImageWidth The image´s width that will be showed
	 * @param integer intImageHeight The image´s height that will be showed
	 */
	function _resize_container_image_box(intImageWidth,intImageHeight) {
		// Get current width and height
		var intCurrentWidth = $('#lightbox-container-image-box').width();
		var intCurrentHeight = $('#lightbox-container-image-box').height();
		// Get the width and height of the selected image plus the padding
		var intWidth = (intImageWidth + (defaults.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
		var intHeight = (intImageHeight + (defaults.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
		// Diferences
		var intDiffW = intCurrentWidth - intWidth;
		var intDiffH = intCurrentHeight - intHeight;
		// Perfomance the effect
		$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },defaults.containerResizeSpeed,function() { _show_image(); });
		if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
			if ( $.browser.msie ) {
				___pause(250);
			} else {
				___pause(100);
			}
		}
		$('#lightbox-container-image-data-box').css({ width: intImageWidth });
		$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (defaults.containerBorderSize * 2) });
	};

	/**
	 * Show the prepared image
	 *
	 */
	function _show_image() {
		$('#lightbox-loading').hide();
		$('#lightbox-image').fadeIn(function() {
			_show_image_data();
			_set_navigation();
		});
		_preload_neighbor_images();
	};

	/**
	 * Show the image information
	 *
	 */
	function _show_image_data() {
		$('#lightbox-container-image-data-box').slideDown('fast');
		$('#lightbox-image-details-caption').hide();
		if ( defaults.imageArray[defaults.activeImage][1] ) {
			$('#lightbox-image-details-caption').html(defaults.imageArray[defaults.activeImage][1]).show();
		}
		// If we have a image set, display 'Image X of X'
		if ( defaults.imageArray.length > 1 ) {
			$('#lightbox-image-details-currentNumber').html(defaults.txtImage + ' ' + ( defaults.activeImage + 1 ) + ' ' + defaults.txtOf + ' ' + defaults.imageArray.length).show();
		}
	}

	// handles the reloaction of the URL hash variable when the previous/next buttons are clicked within the lightbox UI.
	function changeThumbnail(activeImg) {
		location.href = '#'+activeImg;

		// IE we need to explicity call goto
		/*if ($.browser.msie) {
			this.goto(activeImg);
		}*/
	}

	/**
	 * Display the button navigations
	 *
	 */
	function _set_navigation() {
		$('#lightbox-nav').show();

		// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
		$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + defaults.imageBlank + ') no-repeat' });

		// Show the prev button, if not the first image in set
		if ( defaults.activeImage != 0 ) {
			if ( defaults.fixedNavigation ) {
				$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + defaults.imageBtnPrev + ') left 15% no-repeat' })
					.unbind()
					.bind('click',function() {
						defaults.activeImage = defaults.activeImage - 1;
						changeThumbnail();
						_set_image_to_view();
						return false;
					});
			} else {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnPrev').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + defaults.imageBtnPrev + ') left 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + defaults.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					defaults.activeImage = defaults.activeImage - 1;
					changeThumbnail(defaults.activeImage);
					_set_image_to_view();
					return false;
				});
			}
		}

		// Show the next button, if not the last image in set
		if ( defaults.activeImage != ( defaults.imageArray.length -1 ) ) {
			if ( defaults.fixedNavigation ) {
				$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + defaults.imageBtnNext + ') right 15% no-repeat' })
					.unbind()
					.bind('click',function() {
						defaults.activeImage = defaults.activeImage + 1;
						changeThumbnail(defaults.activeImage);
						_set_image_to_view();
						return false;
					});
			} else {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnNext').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + defaults.imageBtnNext + ') right 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + defaults.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					defaults.activeImage = defaults.activeImage + 1;
					changeThumbnail(defaults.activeImage);
					_set_image_to_view();
					return false;
				});
			}
		}
		// Enable keyboard navigation
		_enable_keyboard_navigation();
	}

	/**
	 * Enable a support to keyboard navigation
	 *
	 */
	function _enable_keyboard_navigation() {
		$(document).keydown(function(objEvent) {
			_keyboard_action(objEvent);
		});
	}
	/**
	 * Disable the support to keyboard navigation
	 *
	 */
	function _disable_keyboard_navigation() {
		$(document).unbind();
	}


	/**
	 * Perform the keyboard actions
	 *
	 */
	function _keyboard_action(objEvent) {
		// To ie
		if ( objEvent == null ) {
			keycode = event.keyCode;
			escapeKey = 27;
		// To Mozilla
		} else {
			keycode = objEvent.keyCode;
			escapeKey = objEvent.DOM_VK_ESCAPE;
		}
		// Get the key in lower case form
		key = String.fromCharCode(keycode).toLowerCase();
		// Verify the keys to close the ligthBox
		if ( ( key == defaults.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
			_finish();
		}
		// Verify the key to show the previous image
		if ( ( key == defaults.keyToPrev ) || ( keycode == 37 ) ) {
			// If we´re not showing the first image, call the previous
			if ( defaults.activeImage != 0 ) {
				defaults.activeImage = defaults.activeImage - 1;
				changeThumbnail(defaults.activeImage);
				_set_image_to_view();
				_disable_keyboard_navigation();
			}
		}
		// Verify the key to show the next image
		if ( ( key == defaults.keyToNext ) || ( keycode == 39 ) ) {
			// If we´re not showing the last image, call the next
			if ( defaults.activeImage != ( defaults.imageArray.length - 1 ) ) {
				defaults.activeImage = defaults.activeImage + 1;
				changeThumbnail(defaults.activeImage);
				_set_image_to_view();
				_disable_keyboard_navigation();
			}
		}
	}
	/**
	 * Preload prev and next images being showed
	 *
	 */
	function _preload_neighbor_images() {
		if ( (defaults.imageArray.length -1) > defaults.activeImage ) {
			objNext = new Image();
			objNext.src = defaults.imageArray[defaults.activeImage + 1][0];
		}
		if ( defaults.activeImage > 0 ) {
			objPrev = new Image();
			objPrev.src = defaults.imageArray[defaults.activeImage -1][0];
		}
	}
	/**
	 * Remove jQuery lightBox plugin HTML markup
	 *
	 */
	function _finish() {
		$('#jquery-lightbox').remove();
		$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
		// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
		$('embed, object, select').css({ 'visibility' : 'visible' });
	}
	/**
	 / THIRD FUNCTION
	 * getPageSize() by quirksmode.com
	 *
	 * @return Array Return an array with page width, height and window width, height
	 */
	function ___getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};
	/**
	 / THIRD FUNCTION
	 * getPageScroll() by quirksmode.com
	 *
	 * @return Array Return an array with x,y page scroll values.
	 */
	function ___getPageScroll() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};
	 /**
	  * Stop the code execution from a escified time in milisecond
	  *
	  */
	 function ___pause(ms) {
		var date = new Date();
		curDate = null;
		do { var curDate = new Date(); }
		while ( curDate - date < ms);
	 };

	// end of lightbox functions


	function clickHandler(gallery) {
		gallery.pause();
		return false;
	}

	$.fn.galleriffic = function(thumbsContainerSel, settings) {
		//  Extend Gallery Object
		$.extend(this, {
			ver: function() {
				return ver;
			},

			buildDataFromThumbs: function() {
				this.data = [];
				var gallery = this;
				this.$thumbsContainer.find('li').each(function(i) {
					var $a = $(this).find('a');
					var $img = $a.find('img:first');
					gallery.data.push({slide:$a.attr('href'),thumb:$img.attr('src'),original:$a.attr('original'),gallery_size:$($a.children()[$a.children().length-1]).attr('src'),title:$a.attr('title'),description:$a.attr('description'),hash:gallery.offset+i});
				});
				return this;
			},

			isPreloadComplete: false,

			preloadInit: function() {
				if (this.settings.preloadAhead == 0) return this;

				this.preloadStartIndex = this.currentIndex;
				var nextIndex = this.getNextIndex(this.preloadStartIndex);
				return this.preloadRecursive(this.preloadStartIndex, nextIndex);
			},

			preloadRelocate: function(index) {
				// By changing this startIndex, the current preload script will restart
				this.preloadStartIndex = index;
				return this;
			},

			preloadRecursive: function(startIndex, currentIndex) {
				// Check if startIndex has been relocated
				if (startIndex != this.preloadStartIndex) {
					var nextIndex = this.getNextIndex(this.preloadStartIndex);
					return this.preloadRecursive(this.preloadStartIndex, nextIndex);
				}

				var gallery = this;

				// Now check for preloadAhead count
				var preloadCount = currentIndex - startIndex;
				if (preloadCount < 0)
					preloadCount = this.data.length-1-startIndex+currentIndex;
				if (this.settings.preloadAhead >= 0 && preloadCount > this.settings.preloadAhead) {
					// Do this in order to keep checking for relocated start index
					setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
					return this;
				}

				var imageData = this.data[currentIndex];

				// If already loaded, continue
				if (imageData.$image)
					return this.preloadNext(startIndex, currentIndex);

				// Preload the image
				var image = new Image();

				image.onload = function() {
					imageData.$image = this;
					gallery.preloadNext(startIndex, currentIndex);
				};

				image.alt = imageData.title;
				//image.src = imageData.slide;
                                image.src = imageData.gallery_size;

				return this;
			},

			preloadNext: function(startIndex, currentIndex) {
				var nextIndex = this.getNextIndex(currentIndex);
				if (nextIndex == startIndex) {
					this.isPreloadComplete = true;
				} else {
					// Use set timeout to free up thread
					var gallery = this;
					setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
				}
				return this;
			},

			getNextIndex: function(index) {
				var nextIndex = index+1;
				if (nextIndex >= this.data.length)
					nextIndex = 0;
				return nextIndex;
			},

			getPrevIndex: function(index) {
				var prevIndex = index-1;
				if (prevIndex < 0)
					prevIndex = this.data.length-1;
				return prevIndex;
			},

			pause: function() {
				if (this.interval)
					this.toggleSlideshow();

				return this;
			},

			play: function() {
				if (!this.interval)
					this.toggleSlideshow();

				return this;
			},

			toggleSlideshow: function() {
				if (this.interval) {
					clearInterval(this.interval);
					this.interval = 0;

					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls span').removeClass().addClass('play')
							.attr('title', this.settings.playLinkTitle)
							.html(this.settings.playLinkText);
					}
				} else {
					this.ssAdvance();

					var gallery = this;
					this.interval = setInterval(function() {
						gallery.ssAdvance();
					}, this.settings.delay);

					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls span').removeClass().addClass('pause')
							.attr('title', this.settings.pauseLinkTitle)
							.html(this.settings.pauseLinkText);
					}
				}

				return this;
			},

			ssAdvance: function() {
				var nextIndex = this.getNextIndex(this.currentIndex);
				var nextHash = this.data[nextIndex].hash;

				// Seems to be working on both FF and Safari
				location.href = '#'+nextHash;

				// IE we need to explicity call goto
				if ($.browser.msie) {
					this.goto(nextIndex);
				}

				return this;
			},

			goto: function(index) {
				if (index < 0) index = 0;
				else if (index >= this.data.length) index = this.data.length-1;
				this.currentIndex = index;
				this.preloadRelocate(index);
				return this.refresh();
			},

			refresh: function() {
				if (this.$imageContainer) {
					var imageData = this.data[this.currentIndex];
					var isFading = 1;
					var gallery = this;

					// hide img
					this.$imageContainer.fadeOut('fast', function() {
						isFading = 0;

						// Update Controls
						if (gallery.$controlsContainer) {
							gallery.$controlsContainer
								.find('div.nav-controls a.prev').attr('href', '#'+gallery.data[gallery.getPrevIndex(gallery.currentIndex)].hash).end()
								.find('div.nav-controls a.next').attr('href', '#'+gallery.data[gallery.getNextIndex(gallery.currentIndex)].hash);
						}

						// Replace Title
						if (gallery.$titleContainer) {
							gallery.$titleContainer.empty().html(imageData.title);
						}

						// Replace Description
						if (gallery.$descContainer) {
							gallery.$descContainer.empty().html(imageData.description);
						}

						// Update Download Link
						if (gallery.$downloadLink) {
							gallery.$downloadLink.attr('href', imageData.original);
						}

						if (imageData.$image) {
							gallery.buildImage(imageData.$image);
						}
					});

					if (this.onFadeOut) this.onFadeOut();

					if (!imageData.$image) {
						var image = new Image();
						// Wire up mainImage onload event
						image.onload = function() {
							imageData.$image = this;

							if (!isFading) {
								gallery.buildImage(imageData.$image);
							}
						};

						// set alt and src
						image.alt = imageData.title;
						image.src = imageData.gallery_size;
					}

					// This causes the preloader (if still running) to relocate out from the currentIndex
					this.relocatePreload = true;
				}

				return this.syncThumbs();
			},

			buildImage: function(image) {
				if (this.$imageContainer) {
                                    $(image).removeAttr("width");
                                    $(image).removeAttr("height");
                                    var clickable = this.settings.clickableImage;
                                    defaults.overlayBgColor = this.settings.overlayBgColor;
                                    defaults.overlayOpacity = this.settings.overlayOpacity;
                                    this.$imageContainer.empty();

					var gallery = this;

					var thisImageIndex = this.currentIndex;

					// Setup image
					this.$imageContainer
						//.append('<span class="image-wrapper"><a class="advance-link" rel="history" href="#'+this.data[this.getNextIndex(this.currentIndex)].hash+'" title="'+image.alt+'"></a></span>')
						.append('<span class="image-wrapper"><a class="advance-link" rel="history" title="'+image.alt+'"></a></span>')
						.find('a')
						.append(image)
						//.click(function() { clickHandler(gallery); })
						.click(function() { if (clickable) { buildLightBox(image,gallery,thisImageIndex); }})
						.end()
						.fadeIn('fast');

					if (this.onFadeIn) this.onFadeIn();
				}

				return this;
			},

			syncThumbs: function() {
		        if (this.$thumbsContainer) {
					var page = Math.floor(this.currentIndex / this.settings.numThumbs);
			        if (page != this.currentPage) {
			            this.currentPage = page;
			            this.updateThumbs();
					} else {
						var selectedThumb = this.currentIndex % this.settings.numThumbs;

						// Remove existing selected class and add selected class to new thumb
						this.$thumbsContainer
							.find('ul.thumbs li.selected')
							.removeClass('selected')
							.end()
							//.find('ul.thumbs a[href="#'+this.currentIndex+'"]')
							.find('ul.thumbs li').eq(selectedThumb)
							.addClass('selected');
					}
				}

				return this;
			},

			updateThumbs: function() {
				if (this.$thumbsContainer) {
					// Initialize currentPage to first page
					if (this.currentPage < 0)
						this.currentPage = 0;

					var startIndex = this.currentPage*this.settings.numThumbs;
			        var stopIndex = startIndex+this.settings.numThumbs-1;
			        if (stopIndex >= this.data.length)
						stopIndex = this.data.length-1;

					var needsPagination = this.data.length > this.settings.numThumbs;

					// Clear thumbs container
					this.$thumbsContainer.empty();

					// Rebuild top pager
					this.$thumbsContainer.append('<div class="top pagination"></div>');
					if (needsPagination && this.settings.enableTopPager) {
						this.buildPager(this.$thumbsContainer.find('div.top'));
					}

					// Rebuild thumbs
					var $ulThumbs = this.$thumbsContainer.append('<ul class="thumbs"></ul>').find('ul.thumbs');
					for (i=startIndex; i<=stopIndex; i++) {
						var selected = '';

						if (i==this.currentIndex)
							selected = ' class="selected"';

						var imageData = this.data[i];
						$ulThumbs.append('<li'+selected+'><a rel="history" href="#'+imageData.hash+'" title="'+imageData.title+'"><img src="'+imageData.thumb+'" alt="'+imageData.title+'" /></a></li>');
					}

					// Rebuild bottom pager
					if (needsPagination && this.settings.enableBottomPager) {
						this.$thumbsContainer.append('<div class="bottom pagination"></div>');
						this.buildPager(this.$thumbsContainer.find('div.bottom'));
					}

					// Add click handlers
					var gallery = this;
					this.$thumbsContainer.find('a[rel="history"]').click(function() { clickHandler(gallery); });
				}

				return this;
			},

			buildPager: function(pager) {
				var startIndex = this.currentPage*this.settings.numThumbs;

				// Prev Page Link
				if (this.currentPage > 0) {
					var prevPage = startIndex - this.settings.numThumbs;
					pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.settings.prevPageLinkText+'">'+this.settings.prevPageLinkText+'</a>');
				}

				// Page Index Links
				for (i=this.currentPage-3; i<=this.currentPage+3; i++) {
					var pageNum = i+1;

					if (i == this.currentPage)
						pager.append('<strong>'+pageNum+'</strong>');
					else {
						var imageIndex = i*this.settings.numThumbs;
						if (i>=0 && i<this.numPages) {
							pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageNum+'">'+pageNum+'</a>');
						}
					}
				}

				// Next Page Link
				var nextPage = startIndex+this.settings.numThumbs;
				if (nextPage < this.data.length) {
					pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.settings.nextPageLinkText+'">'+this.settings.nextPageLinkText+'</a>');
				}

				return this;
			}
		});

		// Now initialize the gallery
		this.settings = $.extend({}, defaults, settings);

		if (this.settings.galleryKeyboardNav) {
			_enable_keyboard_navigation();
		}

		if (this.interval)
			clearInterval(this.interval);

		this.interval = 0;

		if (this.settings.imageContainerSel) this.$imageContainer = $(this.settings.imageContainerSel);
		if (this.settings.thumbsContainerSel) this.$thumbsContainer = $(this.settings.thumbsContainerSel);
		if (this.settings.titleContainerSel) this.$titleContainer = $(this.settings.titleContainerSel);
		if (this.settings.descContainerSel) this.$descContainer = $(this.settings.descContainerSel);
		if (this.settings.downloadLinkSel) this.$downloadLink = $(this.settings.downloadLinkSel);

		// Set the hash index offset for this gallery
		this.offset = galleryOffset;

		// This is for backward compatibility
		if (thumbsContainerSel instanceof Array) {
			this.data = thumbsContainerSel;
		} else {
			this.$thumbsContainer = $(thumbsContainerSel);
			this.buildDataFromThumbs();
		}

		// Add this gallery to the global galleries array
		registerGallery(this);

		this.numPages = Math.ceil(this.data.length/this.settings.numThumbs);
		this.currentPage = -1;
		this.currentIndex = 0;
		var gallery = this;

		// Setup controls
		if (this.settings.controlsContainerSel) {
			this.$controlsContainer = $(this.settings.controlsContainerSel).empty();

			if (this.settings.renderSSControls) {
				this.$controlsContainer
					.append('<div class="ss-controls"><span class="play" title="'+this.settings.playLinkTitle+'">'+this.settings.playLinkText+'</span></div>')
					.find('div.ss-controls span')
					.click(function() { gallery.toggleSlideshow(); });
			}

			if (this.settings.renderNavControls) {
				this.$controlsContainer
					.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.settings.prevLinkTitle+'">'+this.settings.prevLinkText+'</a><a class="next" rel="history" title="'+this.settings.nextLinkTitle+'">'+this.settings.nextLinkText+'</a></div>')
					.find('a[rel="history"]')
					.click(function() { clickHandler(gallery); });
			}
		}

		// Initialize history only once when the first gallery on the page is initialized
		historyInit();

		// Build image
		var hash = getHash();
		var hashGallery = (hash >= 0) ? getGallery(hash) : 0;
		var gotoIndex = (hashGallery && this == hashGallery) ? (hash-this.offset) : 0;
		this.goto(gotoIndex);

		// Kickoff Image Preloader after 1 second
		setTimeout(function() { gallery.preloadInit(); }, 1000);

		// autoplay  - run the transitions as soon as the gallery has been loaded if autoPlay is true
		if(this.settings.autoPlay) {
			gallery.play();
		}

		return this;
	};

})(jQuery);

/** 
 * flowplayer.js 3.0.6. The Flowplayer API
 * 
 * Copyright 2009 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * 
 * Flowplayer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Flowplayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Flowplayer.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Version: 3.0.6 - Wed Feb 25 2009 21:56:07 GMT-0000 (GMT+00:00)
 */
(function(){function log(args){console.log("$f.fireEvent",[].slice.call(args));}function clone(obj){if(!obj||typeof obj!='object'){return obj;}var temp=new obj.constructor();for(var key in obj){if(obj.hasOwnProperty(key)){temp[key]=clone(obj[key]);}}return temp;}function each(obj,fn){if(!obj){return;}var name,i=0,length=obj.length;if(length===undefined){for(name in obj){if(fn.call(obj[name],name,obj[name])===false){break;}}}else{for(var value=obj[0];i<length&&fn.call(value,i,value)!==false;value=obj[++i]){}}return obj;}function el(id){return document.getElementById(id);}function extend(to,from,skipFuncs){if(to&&from){each(from,function(name,value){if(!skipFuncs||typeof value!='function'){to[name]=value;}});}}function select(query){var index=query.indexOf(".");if(index!=-1){var tag=query.substring(0,index)||"*";var klass=query.substring(index+1,query.length);var els=[];each(document.getElementsByTagName(tag),function(){if(this.className&&this.className.indexOf(klass)!=-1){els.push(this);}});return els;}}function stopEvent(e){e=e||window.event;if(e.preventDefault){e.stopPropagation();e.preventDefault();}else{e.returnValue=false;e.cancelBubble=true;}return false;}function bind(to,evt,fn){to[evt]=to[evt]||[];to[evt].push(fn);}function makeId(){return"_"+(""+Math.random()).substring(2,10);}var Clip=function(json,index,player){var self=this;var cuepoints={};var listeners={};self.index=index;if(typeof json=='string'){json={url:json};}extend(this,json,true);each(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var evt="on"+this;if(evt.indexOf("*")!=-1){evt=evt.substring(0,evt.length-1);var before="onBefore"+evt.substring(2);self[before]=function(fn){bind(listeners,before,fn);return self;};}self[evt]=function(fn){bind(listeners,evt,fn);return self;};if(index==-1){if(self[before]){player[before]=self[before];}if(self[evt]){player[evt]=self[evt];}}});extend(this,{onCuepoint:function(points,fn){if(arguments.length==1){cuepoints.embedded=[null,points];return self;}if(typeof points=='number'){points=[points];}var fnId=makeId();cuepoints[fnId]=[points,fn];if(player.isLoaded()){player._api().fp_addCuepoints(points,index,fnId);}return self;},update:function(json){extend(self,json);if(player.isLoaded()){player._api().fp_updateClip(json,index);}var conf=player.getConfig();var clip=(index==-1)?conf.clip:conf.playlist[index];extend(clip,json,true);},_fireEvent:function(evt,arg1,arg2,target){if(evt=='onLoad'){each(cuepoints,function(key,val){if(val[0]){player._api().fp_addCuepoints(val[0],index,key);}});return false;}target=target||self;if(evt=='onCuepoint'){var fn=cuepoints[arg1];if(fn){return fn[1].call(player,target,arg2);}}if(evt=='onStart'||evt=='onUpdate'){extend(target,arg1);if(!target.duration){target.duration=arg1.metaData.duration;}else{target.fullDuration=arg1.metaData.duration;}}var ret=true;each(listeners[evt],function(){ret=this.call(player,target,arg1,arg2);});return ret;}});if(json.onCuepoint){var arg=json.onCuepoint;self.onCuepoint.apply(self,typeof arg=='function'?[arg]:arg);delete json.onCuepoint;}each(json,function(key,val){if(typeof val=='function'){bind(listeners,key,val);delete json[key];}});if(index==-1){player.onCuepoint=this.onCuepoint;}};var Plugin=function(name,json,player,fn){var listeners={};var self=this;var hasMethods=false;if(fn){extend(listeners,fn);}each(json,function(key,val){if(typeof val=='function'){listeners[key]=val;delete json[key];}});extend(this,{animate:function(props,speed,fn){if(!props){return self;}if(typeof speed=='function'){fn=speed;speed=500;}if(typeof props=='string'){var key=props;props={};props[key]=speed;speed=500;}if(fn){var fnId=makeId();listeners[fnId]=fn;}if(speed===undefined){speed=500;}json=player._api().fp_animate(name,props,speed,fnId);return self;},css:function(props,val){if(val!==undefined){var css={};css[props]=val;props=css;}json=player._api().fp_css(name,props);extend(self,json);return self;},show:function(){this.display='block';player._api().fp_showPlugin(name);return self;},hide:function(){this.display='none';player._api().fp_hidePlugin(name);return self;},toggle:function(){this.display=player._api().fp_togglePlugin(name);return self;},fadeTo:function(o,speed,fn){if(typeof speed=='function'){fn=speed;speed=500;}if(fn){var fnId=makeId();listeners[fnId]=fn;}this.display=player._api().fp_fadeTo(name,o,speed,fnId);this.opacity=o;return self;},fadeIn:function(speed,fn){return self.fadeTo(1,speed,fn);},fadeOut:function(speed,fn){return self.fadeTo(0,speed,fn);},getName:function(){return name;},getPlayer:function(){return player;},_fireEvent:function(evt,arg,arg2){if(evt=='onUpdate'){var json=player._api().fp_getPlugin(name);if(!json){return;}extend(self,json);delete self.methods;if(!hasMethods){each(json.methods,function(){var method=""+this;self[method]=function(){var a=[].slice.call(arguments);var ret=player._api().fp_invoke(name,method,a);return ret=='undefined'?self:ret;};});hasMethods=true;}}var fn=listeners[evt];if(fn){fn.apply(self,arg);if(evt.substring(0,1)=="_"){delete listeners[evt];}}}});};function Player(wrapper,params,conf){var
self=this,api=null,html,commonClip,playlist=[],plugins={},listeners={},playerId,apiId,playerIndex,activeIndex,swfHeight,wrapperHeight;extend(self,{id:function(){return playerId;},isLoaded:function(){return(api!==null);},getParent:function(){return wrapper;},hide:function(all){if(all){wrapper.style.height="0px";}if(api){api.style.height="0px";}return self;},show:function(){wrapper.style.height=wrapperHeight+"px";if(api){api.style.height=swfHeight+"px";}return self;},isHidden:function(){return api&&parseInt(api.style.height,10)===0;},load:function(fn){if(!api&&self._fireEvent("onBeforeLoad")!==false){each(players,function(){this.unload();});html=wrapper.innerHTML;flashembed(wrapper,params,{config:conf});if(fn){fn.cached=true;bind(listeners,"onLoad",fn);}}return self;},unload:function(){try{if(!api||api.fp_isFullscreen()){return self;}}catch(error){return self;}if(self._fireEvent("onBeforeUnload")===false){return false;}api.fp_close();api=null;if(html.replace(/\s/g,'')!==''){wrapper.innerHTML=html;}self._fireEvent("onUnload");return self;},getClip:function(index){if(index===undefined){index=activeIndex;}return playlist[index];},getCommonClip:function(){return commonClip;},getPlaylist:function(){return playlist;},getPlugin:function(name){var plugin=plugins[name];if(!plugin&&self.isLoaded()){var json=self._api().fp_getPlugin(name);if(json){plugin=new Plugin(name,json,self);plugins[name]=plugin;}}return plugin;},getScreen:function(){return self.getPlugin("screen");},getControls:function(){return self.getPlugin("controls");},getConfig:function(copy){return copy?clone(conf):conf;},getFlashParams:function(){return params;},loadPlugin:function(name,url,props,fn){if(typeof props=='function'){fn=props;props={};}var fnId=fn?makeId():"_";self._api().fp_loadPlugin(name,url,props,fnId);var arg={};arg[fnId]=fn;var p=new Plugin(name,null,self,arg);plugins[name]=p;return p;},getState:function(){return api?api.fp_getState():-1;},play:function(clip){function play(){if(clip!==undefined){self._api().fp_play(clip);}else{self._api().fp_play();}}if(api){play();}else{self.load(function(){play();});}return self;},getVersion:function(){var js="flowplayer.js 3.0.6";if(api){var ver=api.fp_getVersion();ver.push(js);return ver;}return js;},_api:function(){if(!api){throw"Flowplayer "+self.id()+" not loaded. Try moving your call to player's onLoad event";}return api;},_dump:function(){console.log(listeners);},setClip:function(clip){self.setPlaylist([clip]);},getIndex:function(){return playerIndex;}});each(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,Fullscreen*,FullscreenExit,Error").split(","),function(){var name="on"+this;if(name.indexOf("*")!=-1){name=name.substring(0,name.length-1);var name2="onBefore"+name.substring(2);self[name2]=function(fn){bind(listeners,name2,fn);return self;};}self[name]=function(fn){bind(listeners,name,fn);return self;};});each(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,reset,close,setPlaylist").split(","),function(){var name=this;self[name]=function(arg){if(!api){return self;}var ret=(arg===undefined)?api["fp_"+name]():api["fp_"+name](arg);return ret=='undefined'?self:ret;};});self._fireEvent=function(a){if(typeof a=='string'){a=[a];}var evt=a[0];var arg0=a[1];var arg1=a[2];var arg2=a[3];if(conf.debug){log(a);}if(!api&&evt=='onLoad'&&arg0=='player'){api=api||el(apiId);swfHeight=api.clientHeight;each(playlist,function(){this._fireEvent("onLoad");});each(plugins,function(name,p){p._fireEvent("onUpdate");});commonClip._fireEvent("onLoad");}if(evt=='onLoad'&&arg0!='player'){return;}if(evt=='onError'){if(typeof arg0=='string'||(typeof arg0=='number'&&typeof arg1=='number')){arg0=arg1;arg1=arg2;}}if(evt=='onContextMenu'){each(conf.contextMenu[arg0],function(key,fn){fn.call(self);});return;}if(evt=='onPluginEvent'){var name=arg0.name||arg0;var p=plugins[name];if(p){p._fireEvent("onUpdate",arg0);p._fireEvent(arg1,a.slice(3));}return;}if(evt=='onPlaylistReplace'){playlist=[];var index=0;each(arg0,function(){playlist.push(new Clip(this,index++,self));});}var ret=true;if(typeof arg0=='number'&&arg0<playlist.length){activeIndex=arg0;var clip=playlist[arg0];if(clip){ret=clip._fireEvent(evt,arg1,arg2);}if(!clip||ret!==false){ret=commonClip._fireEvent(evt,arg1,arg2,clip);}}var i=0;each(listeners[evt],function(){ret=this.call(self,arg0,arg1);if(this.cached){listeners[evt].splice(i,1);}if(ret===false){return false;}i++;});return ret;};function init(){if($f(wrapper)){$f(wrapper).getParent().innerHTML="";playerIndex=$f(wrapper).getIndex();players[playerIndex]=self;}else{players.push(self);playerIndex=players.length-1;}wrapperHeight=parseInt(wrapper.style.height,10)||wrapper.clientHeight;if(typeof params=='string'){params={src:params};}playerId=wrapper.id||"fp"+makeId();apiId=params.id||playerId+"_api";params.id=apiId;conf.playerId=playerId;if(typeof conf=='string'){conf={clip:{url:conf}};}if(typeof conf.clip=='string'){conf.clip={url:conf.clip};}conf.clip=conf.clip||{};if(wrapper.getAttribute("href",2)&&!conf.clip.url){conf.clip.url=wrapper.getAttribute("href",2);}commonClip=new Clip(conf.clip,-1,self);conf.playlist=conf.playlist||[conf.clip];var index=0;each(conf.playlist,function(){var clip=this;if(typeof clip=='object'&&clip.length){clip=""+clip;}if(typeof clip=='string'){clip={url:clip};}each(conf.clip,function(key,val){if(conf.clip[key]!==undefined&&clip[key]===undefined&&typeof val!='function'){clip[key]=val;}});conf.playlist[index]=clip;clip=new Clip(clip,index,self);playlist.push(clip);index++;});each(conf,function(key,val){if(typeof val=='function'){bind(listeners,key,val);delete conf[key];}});each(conf.plugins,function(name,val){if(val){plugins[name]=new Plugin(name,val,self);}});if(!conf.plugins||conf.plugins.controls===undefined){plugins.controls=new Plugin("controls",null,self);}params.bgcolor=params.bgcolor||"#000000";params.version=params.version||[9,0];params.expressInstall='http://www.flowplayer.org/swf/expressinstall.swf';function doClick(e){if(!self.isLoaded()&&self._fireEvent("onBeforeClick")!==false){self.load();}return stopEvent(e);}html=wrapper.innerHTML;if(html.replace(/\s/g,'')!==''){if(wrapper.addEventListener){wrapper.addEventListener("click",doClick,false);}else if(wrapper.attachEvent){wrapper.attachEvent("onclick",doClick);}}else{if(wrapper.addEventListener){wrapper.addEventListener("click",stopEvent,false);}self.load();}}if(typeof wrapper=='string'){flashembed.domReady(function(){var node=el(wrapper);if(!node){throw"Flowplayer cannot access element: "+wrapper;}else{wrapper=node;init();}});}else{init();}}var players=[];function Iterator(arr){this.length=arr.length;this.each=function(fn){each(arr,fn);};this.size=function(){return arr.length;};}window.flowplayer=window.$f=function(){var instance=null;var arg=arguments[0];if(!arguments.length){each(players,function(){if(this.isLoaded()){instance=this;return false;}});return instance||players[0];}if(arguments.length==1){if(typeof arg=='number'){return players[arg];}else{if(arg=='*'){return new Iterator(players);}each(players,function(){if(this.id()==arg.id||this.id()==arg||this.getParent()==arg){instance=this;return false;}});return instance;}}if(arguments.length>1){var swf=arguments[1];var conf=(arguments.length==3)?arguments[2]:{};if(typeof arg=='string'){if(arg.indexOf(".")!=-1){var instances=[];each(select(arg),function(){instances.push(new Player(this,clone(swf),clone(conf)));});return new Iterator(instances);}else{var node=el(arg);return new Player(node!==null?node:arg,swf,conf);}}else if(arg){return new Player(arg,swf,conf);}}return null;};extend(window.$f,{fireEvent:function(){var a=[].slice.call(arguments);var p=$f(a[0]);return p?p._fireEvent(a.slice(1)):null;},addPlugin:function(name,fn){Player.prototype[name]=fn;return $f;},each:each,extend:extend});if(document.all){window.onbeforeunload=function(){$f("*").each(function(){if(this.isLoaded()){this.close();}});};}if(typeof jQuery=='function'){jQuery.prototype.flowplayer=function(params,conf){if(!arguments.length||typeof arguments[0]=='number'){var arr=[];this.each(function(){var p=$f(this);if(p){arr.push(p);}});return arguments.length?arr[arguments[0]]:new Iterator(arr);}return this.each(function(){$f(this,clone(params),conf?clone(conf):{});});};}})();(function(){var jQ=typeof jQuery=='function';function isDomReady(){if(domReady.done){return false;}var d=document;if(d&&d.getElementsByTagName&&d.getElementById&&d.body){clearInterval(domReady.timer);domReady.timer=null;for(var i=0;i<domReady.ready.length;i++){domReady.ready[i].call();}domReady.ready=null;domReady.done=true;}}var domReady=jQ?jQuery:function(f){if(domReady.done){return f();}if(domReady.timer){domReady.ready.push(f);}else{domReady.ready=[f];domReady.timer=setInterval(isDomReady,13);}};function extend(to,from){if(from){for(key in from){if(from.hasOwnProperty(key)){to[key]=from[key];}}}return to;}function asString(obj){switch(typeOf(obj)){case'string':obj=obj.replace(new RegExp('(["\\\\])','g'),'\\$1');obj=obj.replace(/^\s?(\d+)%/,"$1pct");return'"'+obj+'"';case'array':return'['+map(obj,function(el){return asString(el);}).join(',')+']';case'function':return'"function()"';case'object':var str=[];for(var prop in obj){if(obj.hasOwnProperty(prop)){str.push('"'+prop+'":'+asString(obj[prop]));}}return'{'+str.join(',')+'}';}return String(obj).replace(/\s/g," ").replace(/\'/g,"\"");}function typeOf(obj){if(obj===null||obj===undefined){return false;}var type=typeof obj;return(type=='object'&&obj.push)?'array':type;}if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};});}function map(arr,func){var newArr=[];for(var i in arr){if(arr.hasOwnProperty(i)){newArr[i]=func(arr[i]);}}return newArr;}function getHTML(p,c){var ie=document.all;var html='<object width="'+p.width+'" height="'+p.height+'"';if(ie&&!p.id){p.id="_"+(""+Math.random()).substring(9);}if(p.id){html+=' id="'+p.id+'"';}if(p.w3c||!ie){html+=' data="'+p.src+'" type="application/x-shockwave-flash"';}else{html+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';}html+='>';if(p.w3c||ie){html+='<param name="movie" value="'+p.src+'" />';}var e=extend({},p);e.width=e.height=e.id=e.w3c=e.src=null;for(var k in e){if(e[k]!==null){html+='<param name="'+k+'" value="'+e[k]+'" />';}}var vars="";if(c){for(var key in c){if(c[key]!==null){vars+=key+'='+(typeof c[key]=='object'?asString(c[key]):c[key])+'&';}}vars=vars.substring(0,vars.length-1);html+='<param name="flashvars" value=\''+vars+'\' />';}html+="</object>";return html;}function Flash(root,opts,flashvars){var version=flashembed.getVersion();extend(this,{getContainer:function(){return root;},getConf:function(){return conf;},getVersion:function(){return version;},getFlashvars:function(){return flashvars;},getApi:function(){return root.firstChild;},getHTML:function(){return getHTML(opts,flashvars);}});var required=opts.version;var express=opts.expressInstall;var ok=!required||flashembed.isSupported(required);if(ok){opts.onFail=opts.version=opts.expressInstall=null;root.innerHTML=getHTML(opts,flashvars);}else if(required&&express&&flashembed.isSupported([6,65])){extend(opts,{src:express});flashvars={MMredirectURL:location.href,MMplayerType:'PlugIn',MMdoctitle:document.title};root.innerHTML=getHTML(opts,flashvars);}else{if(root.innerHTML.replace(/\s/g,'')!==''){}else{root.innerHTML="<h2>Flash version "+required+" or greater is required</h2>"+"<h3>"+(version[0]>0?"Your version is "+version:"You have no flash plugin installed")+"</h3>"+(root.tagName=='A'?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>");if(root.tagName=='A'){root.href='http://www.adobe.com/go/getflashplayer';}}}if(!ok&&opts.onFail){var ret=opts.onFail.call(this);if(typeof ret=='string'){root.innerHTML=ret;}}}window.flashembed=function(root,conf,flashvars){if(typeof root=='string'){var el=document.getElementById(root);if(el){root=el;}else{domReady(function(){flashembed(root,conf,flashvars);});return;}}if(!root){return;}var opts={width:'100%',height:'100%',allowfullscreen:true,allowscriptaccess:'always',quality:'high',version:null,onFail:null,expressInstall:null,w3c:false};if(typeof conf=='string'){conf={src:conf};}extend(opts,conf);return new Flash(root,opts,flashvars);};extend(window.flashembed,{getVersion:function(){var version=[0,0];if(navigator.plugins&&typeof navigator.plugins["Shockwave Flash"]=="object"){var _d=navigator.plugins["Shockwave Flash"].description;if(typeof _d!="undefined"){_d=_d.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var _m=parseInt(_d.replace(/^(.*)\..*$/,"$1"),10);var _r=/r/.test(_d)?parseInt(_d.replace(/^.*r(.*)$/,"$1"),10):0;version=[_m,_r];}}else if(window.ActiveXObject){try{var _a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{_a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version=[6,0];_a.AllowScriptAccess="always";}catch(ee){if(version[0]==6){return;}}try{_a=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(eee){}}if(typeof _a=="object"){_d=_a.GetVariable("$version");if(typeof _d!="undefined"){_d=_d.replace(/^\S+\s+(.*)$/,"$1").split(",");version=[parseInt(_d[0],10),parseInt(_d[2],10)];}}}return version;},isSupported:function(version){var now=flashembed.getVersion();var ret=(now[0]>version[0])||(now[0]==version[0]&&now[1]>=version[1]);return ret;},domReady:domReady,asString:asString,getHTML:getHTML});if(jQ){jQuery.prototype.flashembed=function(conf,flashvars){return this.each(function(){flashembed(this,conf,flashvars);});};}})();

/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();

/*
 * FancyBox - jQuery Plugin
 * simple and fancy lightbox alternative
 *
 * Copyright (c) 2009 Janis Skarnelis
 * Examples and documentation at: http://fancybox.net
 * 
 * Version: 1.2.6 (16/11/2009)
 * Requires: jQuery v1.3+
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(p($){$.q.1Q=p(){J O.2n(p(){n b=$(O).u(\'2o\');8(b.1d(/^3i\\(["\']?(.*\\.2p)["\']?\\)$/i)){b=3j.$1;$(O).u({\'2o\':\'3k\',\'1e\':"3l:3m.3n.3o(3p=D, 3q="+($(O).u(\'3r\')==\'2q-3s\'?\'3t\':\'3u\')+", 13=\'"+b+"\')"}).2n(p(){n a=$(O).u(\'1u\');8(a!=\'2r\'&&a!=\'2s\')$(O).u(\'1u\',\'2s\')})}})};n l,4,1f=F,X=1v 1w,1x,1y=1,1z=/\\.(3v|3w|2p|3x|3y)(.*)?$/i;n m=1A,18=$.14.1g&&$.14.2t.1R(0,1)==6&&!19.3z,1S=18||($.14.1g&&$.14.2t.1R(0,1)==7);$.q.r=p(o){n j=$.2u({},$.q.r.2v,o);n k=O;p 2w(){l=O;4=$.2u({},j);2x();J F};p 2x(){8(1f)J;8($.1T(4.1U)){4.1U()}4.v=[];4.t=0;8(j.v.Y>0){4.v=j.v}C{n a={};8(!l.1B||l.1B==\'\'){n a={K:l.K,G:l.G};8($(l).1C("1l:1D").Y){a.S=$(l).1C("1l:1D")}C{a.S=$(l)}8(a.G==\'\'||1V a.G==\'1m\'){a.G=a.S.2y(\'1W\')}4.v.2z(a)}C{n b=$(k).1e("a[1B="+l.1B+"]");n a={};3A(n i=0;i<b.Y;i++){a={K:b[i].K,G:b[i].G};8($(b[i]).1C("1l:1D").Y){a.S=$(b[i]).1C("1l:1D")}C{a.S=$(b[i])}8(a.G==\'\'||1V a.G==\'1m\'){a.G=a.S.2y(\'1W\')}4.v.2z(a)}}}3B(4.v[4.t].K!=l.K){4.t++}8(4.1E){8(18){$(\'1X, 1Y, 1Z\').u(\'21\',\'3C\');$("#T").u(\'A\',$(U).A())}$("#T").u({\'3D-3E\':4.2A,\'22\':4.2B}).Z()}$(19).11("23.L 24.L",$.q.r.2C);1h()};p 1h(){$("#1n, #1o, #1i, #H").1a();n b=4.v[4.t].K;8(b.1d("1j")||l.3F.2D("1j")>=0){$.q.r.1F();1p(\'<1j s="2E" 3G="2F.q.r.2G()" 3H="3I\'+P.1b(P.3J()*3K)+\'" 2H="0" 3L="0" 13="\'+b+\'"></1j>\',4.1G,4.1H)}C 8(b.1d(/#/)){n c=19.3M.K.3N(\'#\')[0];c=b.3O(c,\'\');c=c.1R(c.2D(\'#\'));1p(\'<9 s="3P">\'+$(c).2I()+\'</9>\',4.1G,4.1H)}C 8(b.1d(1z)){X=1v 1w;X.13=b;8(X.3Q){25()}C{$.q.r.1F();$(X).Q().11(\'3R\',p(){$("#M").1a();25()})}}C{$.q.r.1F();$.3S(b,p(a){$("#M").1a();1p(\'<9 s="3T">\'+a+\'</9>\',4.1G,4.1H)})}};p 25(){n a=X.E;n b=X.A;n c=(4.N*2)+40;n d=(4.N*2)+26;n w=$.q.r.1q();8(4.2J&&(a>(w[0]-c)||b>(w[1]-d))){n e=P.28(P.28(w[0]-c,a)/a,P.28(w[1]-d,b)/b);a=P.1b(e*a);b=P.1b(e*b)}1p(\'<1l 1W="" s="3U" 13="\'+X.13+\'" />\',a,b)};p 2K(){8((4.v.Y-1)>4.t){n a=4.v[4.t+1].K||F;8(a&&a.1d(1z)){1I=1v 1w();1I.13=a}}8(4.t>0){n a=4.v[4.t-1].K||F;8(a&&a.1d(1z)){1I=1v 1w();1I.13=a}}};p 1p(a,b,c){1f=D;n d=4.N;8(1S||m){$("#y")[0].15.2L("A");$("#y")[0].15.2L("E")}8(d>0){b+=d*2;c+=d*2;$("#y").u({\'z\':d+\'R\',\'2M\':d+\'R\',\'2N\':d+\'R\',\'B\':d+\'R\',\'E\':\'2O\',\'A\':\'2O\'});8(1S||m){$("#y")[0].15.2P(\'A\',\'(O.2Q.3V - \'+d*2+\')\');$("#y")[0].15.2P(\'E\',\'(O.2Q.3W - \'+d*2+\')\')}}C{$("#y").u({\'z\':0,\'2M\':0,\'2N\':0,\'B\':0,\'E\':\'2R%\',\'A\':\'2R%\'})}8($("#x").16(":V")&&b==$("#x").E()&&c==$("#x").A()){$("#y").1J(\'29\',p(){$("#y").1r().1K($(a)).2a("1L",p(){1s()})});J}n w=$.q.r.1q();n e=(c+26)>w[1]?w[3]:(w[3]+P.1b((w[1]-c-26)*0.5));n f=(b+40)>w[0]?w[2]:(w[2]+P.1b((w[0]-b-40)*0.5));n g={\'B\':f,\'z\':e,\'E\':b+\'R\',\'A\':c+\'R\'};8($("#x").16(":V")){$("#y").1J("1L",p(){$("#y").1r();$("#x").2b(g,4.2S,4.2T,p(){$("#y").1K($(a)).2a("1L",p(){1s()})})})}C{8(4.2c>0&&4.v[4.t].S!==1m){$("#y").1r().1K($(a));n h=4.v[4.t].S;n i=$.q.r.2d(h);$("#x").u({\'B\':(i.B-20-4.N)+\'R\',\'z\':(i.z-20-4.N)+\'R\',\'E\':$(h).E()+(4.N*2),\'A\':$(h).A()+(4.N*2)});8(4.2e){g.22=\'Z\'}$("#x").2b(g,4.2c,4.2U,p(){1s()})}C{$("#y").1a().1r().1K($(a)).Z();$("#x").u(g).2a("1L",p(){1s()})}}};p 2V(){8(4.t!==0){$("#1o, #2W").Q().11("17",p(e){e.2X();4.t--;1h();J F});$("#1o").Z()}8(4.t!=(4.v.Y-1)){$("#1n, #2Y").Q().11("17",p(e){e.2X();4.t++;1h();J F});$("#1n").Z()}};p 1s(){8($.14.1g){$("#y")[0].15.1M(\'1e\');$("#x")[0].15.1M(\'1e\')}2V();2K();$(U).11("1N.L",p(e){8(e.2f==27&&4.2Z){$.q.r.1c()}C 8(e.2f==37&&4.t!==0){$(U).Q("1N.L");4.t--;1h()}C 8(e.2f==39&&4.t!=(4.v.Y-1)){$(U).Q("1N.L");4.t++;1h()}});8(4.30){$("#y").17($.q.r.1c)}8(4.1E&&4.31){$("#T").11("17",$.q.r.1c)}8(4.33){$("#1i").11("17",$.q.r.1c).Z()}8(1V 4.v[4.t].G!==\'1m\'&&4.v[4.t].G.Y>0){n a=$("#x").1u();$(\'#H 9\').3X(4.v[4.t].G).2I();$(\'#H\').u({\'z\':a.z+$("#x").34()-32,\'B\':a.B+(($("#x").35()*0.5)-($(\'#H\').E()*0.5))}).Z()}8(4.1E&&18){$(\'1X, 1Y, 1Z\',$(\'#y\')).u(\'21\',\'V\')}8($.1T(4.2g)){4.2g(4.v[4.t])}8($.14.1g){$("#x")[0].15.1M(\'1e\');$("#y")[0].15.1M(\'1e\')}1f=F};J O.Q(\'17.L\').11(\'17.L\',2w)};$.q.r.2C=p(){n w=$.q.r.1q();8(4.2h&&$("#x").16(\':V\')){n a=$("#x").35();n b=$("#x").34();n c={\'z\':(b>w[1]?w[3]:w[3]+P.1b((w[1]-b)*0.5)),\'B\':(a>w[0]?w[2]:w[2]+P.1b((w[0]-a)*0.5))};$("#x").u(c);$(\'#H\').u({\'z\':c.z+b-32,\'B\':c.B+((a*0.5)-($(\'#H\').E()*0.5))})}8(18&&$("#T").16(\':V\')){$("#T").u({\'A\':$(U).A()})}8($("#M").16(\':V\')){$("#M").u({\'B\':((w[0]-40)*0.5+w[2]),\'z\':((w[1]-40)*0.5+w[3])})}};$.q.r.1t=p(a,b){J 3Y($.3Z(a.41?a[0]:a,b,D))||0};$.q.r.2d=p(a){n b=a.42();b.z+=$.q.r.1t(a,\'43\');b.z+=$.q.r.1t(a,\'44\');b.B+=$.q.r.1t(a,\'45\');b.B+=$.q.r.1t(a,\'46\');J b};$.q.r.2G=p(){$("#M").1a();$("#2E").Z()};$.q.r.1q=p(){J[$(19).E(),$(19).A(),$(U).47(),$(U).48()]};$.q.r.36=p(){8(!$("#M").16(\':V\')){38(1x);J}$("#M > 9").u(\'z\',(1y*-40)+\'R\');1y=(1y+1)%12};$.q.r.1F=p(){38(1x);n w=$.q.r.1q();$("#M").u({\'B\':((w[0]-40)*0.5+w[2]),\'z\':((w[1]-40)*0.5+w[3])}).Z();$("#M").11(\'17\',$.q.r.1c);1x=49($.q.r.36,4a)};$.q.r.1c=p(){1f=D;$(X).Q();$(U).Q("1N.L");$(19).Q("23.L 24.L");$("#T, #y, #1i").Q();$("#1i, #M, #1o, #1n, #H").1a();1O=p(){8($("#T").16(\':V\')){$("#T").1J("29")}$("#y").1r();8(4.2h){$(19).Q("23.L 24.L")}8(18){$(\'1X, 1Y, 1Z\').u(\'21\',\'V\')}8($.1T(4.2i)){4.2i()}1f=F};8($("#x").16(":V")!==F){8(4.2j>0&&4.v[4.t].S!==1m){n a=4.v[4.t].S;n b=$.q.r.2d(a);n c={\'B\':(b.B-20-4.N)+\'R\',\'z\':(b.z-20-4.N)+\'R\',\'E\':$(a).E()+(4.N*2),\'A\':$(a).A()+(4.N*2)};8(4.2e){c.22=\'1a\'}$("#x").3a(F,D).2b(c,4.2j,4.3b,1O)}C{$("#x").3a(F,D).1J(\'29\',1O)}}C{1O()}J F};$.q.r.3c=p(){n a=\'\';a+=\'<9 s="T"></9>\';a+=\'<9 s="M"><9></9></9>\';a+=\'<9 s="x">\';a+=\'<9 s="3d">\';a+=\'<9 s="1i"></9>\';a+=\'<9 s="W"><9 I="W" s="4b"></9><9 I="W" s="4c"></9><9 I="W" s="4d"></9><9 I="W" s="4e"></9><9 I="W" s="4f"></9><9 I="W" s="4g"></9><9 I="W" s="4h"></9><9 I="W" s="4i"></9></9>\';a+=\'<a K="2k:;" s="1o"><1P I="2l" s="2W"></1P></a><a K="2k:;" s="1n"><1P I="2l" s="2Y"></1P></a>\';a+=\'<9 s="y"></9>\';a+=\'</9>\';a+=\'</9>\';a+=\'<9 s="H"></9>\';$(a).3e("4j");$(\'<3f 4k="0" 4l="0" 4m="0"><3g><1k I="H" s="4n"></1k><1k I="H" s="4o"><9></9></1k><1k I="H" s="4p"></1k></3g></3f>\').3e(\'#H\');8($.14.1g){$(".W").1Q()}8(18){$("9#T").u("1u","2r");$("#M 9, #1i, .H, .2l").1Q();$("#3d").4q(\'<1j s="3h" 13="2k:F;" 4r="2q" 2H="0"></1j>\');n b=$(\'#3h\')[0].4s.U;b.4t();b.1c()}};$.q.r.2v={N:10,2J:D,2e:D,2c:0,2j:0,2S:4u,2U:\'2m\',3b:\'2m\',2T:\'2m\',1G:4v,1H:4w,1E:D,2B:0.3,2A:\'#4x\',2Z:D,33:D,31:D,30:D,2h:D,v:[],1U:1A,2g:1A,2i:1A};$(U).4y(p(){m=$.14.1g&&!$.4z;8($("#x").Y<1){$.q.r.3c()}})})(2F);',62,284,'||||opts||||if|div||||||||||||||var||function|fn|fancybox|id|itemCurrent|css|itemArray||fancy_outer|fancy_content|top|height|left|else|true|width|false|title|fancy_title|class|return|href|fb|fancy_loading|padding|this|Math|unbind|px|orig|fancy_overlay|document|visible|fancy_bg|imagePreloader|length|show||bind||src|browser|style|is|click|IE6|window|hide|round|close|match|filter|busy|msie|_change_item|fancy_close|iframe|td|img|undefined|fancy_right|fancy_left|_set_content|getViewport|empty|_finish|getNumeric|position|new|Image|loadingTimer|loadingFrame|imageRegExp|null|rel|children|first|overlayShow|showLoading|frameWidth|frameHeight|objNext|fadeOut|append|normal|removeAttribute|keydown|__cleanup|span|fixPNG|substr|oldIE|isFunction|callbackOnStart|typeof|alt|embed|object|select||visibility|opacity|resize|scroll|_proceed_image|60||min|fast|fadeIn|animate|zoomSpeedIn|getPosition|zoomOpacity|keyCode|callbackOnShow|centerOnScroll|callbackOnClose|zoomSpeedOut|javascript|fancy_ico|swing|each|backgroundImage|png|no|absolute|relative|version|extend|defaults|_initialize|_start|attr|push|overlayColor|overlayOpacity|scrollBox|indexOf|fancy_frame|jQuery|showIframe|frameborder|html|imageScale|_preload_neighbor_images|removeExpression|right|bottom|auto|setExpression|parentNode|100|zoomSpeedChange|easingChange|easingIn|_set_navigation|fancy_left_ico|stopPropagation|fancy_right_ico|enableEscapeButton|hideOnContentClick|hideOnOverlayClick||showCloseButton|outerHeight|outerWidth|animateLoading||clearInterval||stop|easingOut|build|fancy_inner|appendTo|table|tr|fancy_bigIframe|url|RegExp|none|progid|DXImageTransform|Microsoft|AlphaImageLoader|enabled|sizingMethod|backgroundRepeat|repeat|crop|scale|jpg|gif|bmp|jpeg|XMLHttpRequest|for|while|hidden|background|color|className|onload|name|fancy_iframe|random|1000|hspace|location|split|replace|fancy_div|complete|load|get|fancy_ajax|fancy_img|clientHeight|clientWidth|text|parseInt|curCSS||jquery|offset|paddingTop|borderTopWidth|paddingLeft|borderLeftWidth|scrollLeft|scrollTop|setInterval|66|fancy_bg_n|fancy_bg_ne|fancy_bg_e|fancy_bg_se|fancy_bg_s|fancy_bg_sw|fancy_bg_w|fancy_bg_nw|body|cellspacing|cellpadding|border|fancy_title_left|fancy_title_main|fancy_title_right|prepend|scrolling|contentWindow|open|300|560|340|666|ready|boxModel'.split('|'),0,{}));

/* jQuery Image Magnify script v1.1
* This notice must stay intact for usage
* Author: Dynamic Drive at http://www.dynamicdrive.com/
* Visit http://www.dynamicdrive.com/ for full source code

* Nov 16th, 09 (v1.1): Adds ability to dynamically apply/reapply magnify effect to an image, plus magnify to a specific width in pixels.
*/

//$.noConflict();

$.imageMagnify={
	dsettings: {
		magnifyby: 3, //default increase factor of enlarged image
		duration: 500, //default duration of animation, in millisec
		imgopacity: 0.2 //opacify of original image when enlarged image overlays it
 	},
	cursorcss: 'url(/images/base/magnify.cur), -moz-zoom-in', //Value for CSS's 'cursor' attribute, added to original image
	zIndexcounter: 100,

	refreshoffsets:function($window, $target, warpshell){
		var $offsets=$target.offset();
		var winattrs={x:$window.scrollLeft(), y:$window.scrollTop(), w:$window.width(), h:$window.height()};
		warpshell.attrs.x=$offsets.left; //update x position of original image relative to page
		warpshell.attrs.y=$offsets.top;
		warpshell.newattrs.x=winattrs.x+winattrs.w/2-warpshell.newattrs.w/2;
		warpshell.newattrs.y=winattrs.y+winattrs.h/2-warpshell.newattrs.h/2;
		if (warpshell.newattrs.x<winattrs.x+5){ //no space to the left?
			warpshell.newattrs.x=winattrs.x+5;
		}
		else if (warpshell.newattrs.x+warpshell.newattrs.w > winattrs.x+winattrs.w){//no space to the right?
			warpshell.newattrs.x=winattrs.x+5;
		}
		if (warpshell.newattrs.y<winattrs.y+5){ //no space at the top?
			warpshell.newattrs.y=winattrs.y+5;
		}
	},

	magnify:function($, $target, options){
		var setting={}; //create blank object to store combined settings
		var setting=$.extend(setting, this.dsettings, options);
		var attrs=(options.thumbdimensions)? {w:options.thumbdimensions[0], h:options.thumbdimensions[1]} : {w:$target.outerWidth(), h:$target.outerHeight()};
		var newattrs={};
		newattrs.w=(setting.magnifyto)? setting.magnifyto : Math.round(attrs.w*setting.magnifyby);
		newattrs.h=(setting.magnifyto)? Math.round(attrs.h*newattrs.w/attrs.w) : Math.round(attrs.h*setting.magnifyby);
		$target.css('cursor', $.imageMagnify.cursorcss);
		if ($target.data('imgshell')){
			$target.data('imgshell').$clone.remove();
			$target.css({opacity:1}).unbind('click.magnify');
		}
		var $clone=$target.clone().css({position:'absolute', left:0, top:0, visibility:'hidden', border:'1px solid gray', cursor:'pointer'}).appendTo(document.body);
        var img_orig = $clone.attr("src");
        $clone.attr("src",img_orig.replace(new RegExp("[0-9]*x[0-9]*_"),""));
		$clone.data('$relatedtarget', $target); //save $target image this enlarged image is associated with
		$target.data('imgshell', {$clone:$clone, attrs:attrs, newattrs:newattrs});
		$target.bind('click.magnify', function(e){ //action when original image is clicked on
			var $this=$(this).css({opacity:setting.imgopacity});
			var imageinfo=$this.data('imgshell');
			$.imageMagnify.refreshoffsets($(window), $this, imageinfo); //refresh offset positions of original and warped images
			var $clone=imageinfo.$clone;
			$clone.stop().css({zIndex:++$.imageMagnify.zIndexcounter, left:imageinfo.attrs.x, top:imageinfo.attrs.y, width:imageinfo.attrs.w, height:imageinfo.attrs.h, opacity:0, visibility:'visible'})
			.animate({opacity:1, left:imageinfo.newattrs.x, top:imageinfo.newattrs.y, width:imageinfo.newattrs.w, height:imageinfo.newattrs.h}, setting.duration,
			function(){ //callback function after warping is complete
				//none added
			}); //end animate
		}); //end click
		$clone.click(function(e){ //action when magnified image is clicked on
			var $this=$(this);
			var imageinfo=$this.data('$relatedtarget').data('imgshell');
			$.imageMagnify.refreshoffsets($(window), $this.data('$relatedtarget'), imageinfo); //refresh offset positions of original and warped images
			$this.stop().animate({opacity:0, left:imageinfo.attrs.x, top:imageinfo.attrs.y, width:imageinfo.attrs.w, height:imageinfo.attrs.h},  setting.duration,
			function(){
				$this.hide();
				$this.data('$relatedtarget').css({opacity:1}); //reveal original image
			}); //end animate
		}); //end click
	}
};

$.fn.imageMagnify=function(options){
	//var $=$
	return this.each(function(){ //return $ obj
		var $imgref=$(this);
		if (this.tagName!="IMG")
			return true; //skip to next matched element
		if (parseInt($imgref.css('width'))>0 && parseInt($imgref.css('height'))>0 || options.thumbdimensions){ //if image has explicit width/height attrs defined
			$.imageMagnify.magnify($, $imgref, options);
		}
		else if (this.complete){ //account for IE not firing image.onload
			$.imageMagnify.magnify($, $imgref, options);
		}
		else{
			$(this).bind('load', function(){
				$.imageMagnify.magnify($, $imgref, options);
			})
		}
	})
};

$.fn.applyMagnifier=function(options){ //dynamic version of imageMagnify() to apply magnify effect to an image dynamically
	//var $=$
	return this.each(function(){ //return $ obj
		var $imgref=$(this);
		if (this.tagName!="IMG")
			return true; //skip to next matched element

	})

};


//** The following applies the magnify effect to images with class="magnify" and optional "data-magnifyby" and "data-magnifyduration" attrs
//** It also looks for links with attr rel="magnify[targetimageid]" and makes them togglers for that image

$(document).ready(function($){
	var $targets=$('.magnify');
	$targets.each(function(i){
		var $target=$(this);
		var options={};
		if ($target.attr('data-magnifyto'))
			options.magnifyto=parseFloat($target.attr('data-magnifyto'));
		if ($target.attr('data-magnifyby'))
			options.magnifyby=parseFloat($target.attr('data-magnifyby'));
		if ($target.attr('data-magnifyduration'))
			options.duration=parseInt($target.attr('data-magnifyduration'));
		$target.imageMagnify(options)
	});
	var $triggers=$('a[rel^="magnify["]');
	$triggers.each(function(i){
		var $trigger=$(this);
		var targetid=$trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, ''); //parse 'id' from rel='magnify[id]'
		$trigger.data('magnifyimageid', targetid);
		$trigger.click(function(e){
			$('#'+$(this).data('magnifyimageid')).trigger('click.magnify');
			e.preventDefault()
		})
	})
});


var flowplayer_key="#@77da14f1f33c7deaec4";

$(document).ready(
    function()
    {
        // Establecemos el click para todos los reproductores de vídeo de la página
        $("a.videoplayer").click(function() {
           $(this).flowplayer("/swf/flowplayer.swf",{ key: flowplayer_key });
           return false;
        });
        $("a.videoplayer_playlist").each(function() {
            $.ajax({
                async:true,
                dataType:'script',
                url: "/videos/load_playlist/" + $(this).attr("id").split("_")[1]
            });

        });
        // Cargamos todos los flash de la página
        $("div.flash_container").each(function() {
            var flashvars = {};
            var params = {
                wmode: "transparent"
            };
            var attributes = {
                wmode: "transparent"
            };
            id = $(this).attr("id").split("_")[1];
            width = $(this).attr("width");
            height = $(this).attr("height");
            file = $(this).attr("file");
            div_id = "flash_replace_" + id;
            swfobject.embedSWF(file, div_id, width, height, "8.0.0","",flashvars,params,attributes);

        });
        // Todos los enlaces de tipo nicedit_external_link han de abrirse en una ventana nueva
        $("a[rel='external']").click(function() {
            window.open($(this).attr("href"));
            return false;
        });
                //Ocultamos los divs vacíos
        $(".botones-cms").each(function() {
            if ($(this).children().length==0) {
                $(this).hide();
            }
        });
        $(".gmap").each(function() {
            if ($(this).children().length==0) {
                $(this).hide();
            }
        });
        $(".galeria").each(function() {
            if ($(this).children().length==0) {
                $(this).hide();
            }
        });
		$("a.ampliar-imagen").fancybox({
			"overlayOpacity": 0.6,
			"overlayColor": '#000'
		}
		
		);

    	timeOutFondo(5);
	}
    );

function load_videos_from_folder(folder,videos,width,height) {
    var pl = [];
    for(var i=0;i<videos.length;i++) {
       pl.push({url: videos[i]});
    }
    $("a.videoplayer_playlist[id=videos_" + folder + "]").click(function() {
        $(this).flowplayer("/swf/flowplayer.swf",{ key: flowplayer_key,  playlist: pl, plugins: {controls: {playlist: true }} });
        return false;
    });
}

function load_videos_from_folder_and_start(folder,videos,width,height) {
    var pl = [];
    for(var i=0;i<videos.length;i++) {
       pl.push({url: videos[i]});
    }
    $("a.videoplayer_playlist[id=videos_" + folder + "]").flowplayer("/swf/flowplayer.swf",{ key: flowplayer_key, playlist: pl, plugins: {controls: {playlist: true }} });
}

function addCodeToFunction(func,code){
    if(func == undefined)
	return code;
    else{
	return function(){
	    func();
	    code();
	}
    }
}

function selectPestanaProducto(pestana){
	//quitamos todos los sel
	$(".pestanias-producto UL LI").removeClass("sel");
	//Ponemos el de esta pestana
	$("#enlace-pestana-"+pestana).addClass("sel");
	//Ocultamos todos los bloques
	$(".pestania-producto").hide();
	//Y mostramos el actual
	$(".pestania-"+pestana).show();
}

function addSectionSetEditable(){
	$(".caso-section:last .editable").each(function() {
        myNicEditor.addInstance($(this).attr("id"));
    });
    var initial_texto = "";
    $(".caso-section:last .editable").focus(function() {
        if(/- -(.*?)- -/.test(jQuery.trim($(this).html()))){
            initial_texto = $(this).html();
            $(this).html("");
        }
        nicEditor_actual_selected = obtener_nicedit_instance($(this).attr("id"));
        nicEditor_actual_selected_id = $(this).attr("id");
        //Si es editor de fichero abro la ventana emergente
    if ($(this).hasClass("file_editable")) {
        //$(".file_editable").focus(function() {
            editar_file($(this));
        }
    //);
    });
    $(".caso-section:last .editable").blur(function() {
        if (jQuery.trim($(this).html())==""){
            $(this).html(initial_texto);
        }
    });	
}

function addTextoSetEditable(id_el){
	$("#"+id_el+" .texto-section:last .editable").each(function() {
        myNicEditor.addInstance($(this).attr("id"));
    });
    var initial_texto = "";
    $("#"+id_el+" .texto-section:last .editable").focus(function() {
        if(/- -(.*?)- -/.test(jQuery.trim($(this).html()))){
            initial_texto = $(this).html();
            $(this).html("");
        }
        nicEditor_actual_selected = obtener_nicedit_instance($(this).attr("id"));
        nicEditor_actual_selected_id = $(this).attr("id");
        //Si es editor de fichero abro la ventana emergente
    if ($(this).hasClass("file_editable")) {
        //$(".file_editable").focus(function() {
            editar_file($(this));
        }
    //);
    });
    $("#"+id_el+" .texto-section:last .editable").blur(function() {
        if (jQuery.trim($(this).html())==""){
            $(this).html(initial_texto);
        }
    });	
}

//Ir a un ancla
function irA(elemID){
    var offsetTrail = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined" && navigator.appName == "Microsoft Internet Explorer") {
        offsetLeft += parseInt(document.body.leftMargin);
        offsetTop += parseInt(document.body.topMargin);
    }
    window.scrollTo(offsetLeft, offsetTop)
}

//Abre el glob de info de un distribuidor y le hace foco
function openDistribuidor(id_point){
	m = ""
	localizarDistribuidor(id_point); //Localizar en los resultados de la busqueda
	for(i=0; i < markers.length; i++){
		if(markers[i].id_point == id_point){
			markers[i].openInfoWindowHtml(markers[i].texto);
			//window["map_0"].panTo(new GLatLng(markers[i].getLatLng().lat(),markers[i].getLatLng().lng()));
			break;
		}
	}
	//Aumentamos el zoom
	window["map_0"].setZoom(12);
}
//Resalta el elemento en los resultados de la busqueda
function localizarDistribuidor(id_point){
	$(".localizacion").removeClass("localizado");
	$(".localizacion-"+id_point).addClass("localizado");	
}

function cambiarImagenObra(i){
	//$("#slideshow_38").fadeOut();
	//$("#imagen-obra").html('<img src="'+url+'" alt="'+alt+'" />');
	//$("#slideshow_38").fadeIn();
    $("#slideshow_38").fadeOut(500, function(){
            $(".image-wrapper").hide();
			$("#imagen-obra-"+i).show()
			$("#slideshow_38").fadeIn(500);
        });
	
}


/* Funcion para cambiar los fondos.
 * Se acompaña de un partial que esta en comun/fondos_cabecera que pinta las capas necesarias, la funcion timeOutFondos
 * y la maquetación oportuna de la public.css
 * Para cambiar el numero de imágenes:
 * - Cambiar el maxFondo en la funcion cambiaFondo() por el numero de fondos
 * - Cambiar el n_fondos en el partial por el numero de fondos
 * - Darle estilos al nuevo fondo en la public para que coja el bg oportuno
 */

var actualFondo = 1; //Contiene el numero de fondo actual
function cambiaFondo(){
	maxFondo = 2; //Numero de fondos, cambiar para mas fondos
	clase = "fondo-rotatorio"; //clase del fondo
	nextFondo = actualFondo + 1; //calculamos el siguiente
	if(nextFondo > maxFondo){ //y lo reiniciamos si nos pasamos
		nextFondo = 1;
	}
	
	//Objetos actual y siguiente
	actual = $("."+clase+actualFondo);
	next = $("."+clase+nextFondo);
	
	//Los divs exteriores, q son los q movemos
	actualOut = $(".contenedor-"+clase+actualFondo);
	nextOut = $(".contenedor-"+clase+nextFondo);	
	
	//Ponemos al siguiente visible
	next.css("display","block");
	//movemos el siguiente a delante del actual
	actualOut.before(nextOut);
	//Desaparecemos el actual
	actual.fadeOut(6000);
	
	//Movemos el contandor
	actualFondo = nextFondo;
	//Y reiniciamos la cuenta periodica
	timeOutFondo(12);
}

//Funcion para poner el timeout, debe estar en el $(document).ready para q se llame la primera vez
function timeOutFondo(segundos){
	setTimeout("cambiaFondo()", segundos*1000);
}
