/*
Script: DynaSlideShow.js
	Class for a nice Slide Show.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var DynaSlideShow = new Class({
	mode: 'alpha',
	modes: ['top', 'right', 'bottom', 'left', 'alpha'],
	sizes: {w: 315, h: 175},
	fxOptions: {duration: 500},
	interval: 4000,

	initialize: function(items,options){
		if (options) {
			for (var o in options) {
				this[o] = options[o];
			}
		}
		//
		if (this.buttons) {
			this.buttons.previous.addEvent('click', this.previous.bind(this, [true]));
			this.buttons.next.addEvent('click', this.next.bind(this, [true]));
		}
		this._current = 0;
		this._previous = null;
		this.items = items.setStyle('display', 'none');
		this.items[this._current].setStyle('display', 'block');
		this.disabled = false;
		this.attrs = {
			left: ['left', - this.sizes.w, 0, 'px'],
			top: ['top', - this.sizes.h, 0, 'px'],
			right: ['left', this.sizes.w, 0, 'px'],
			bottom: ['top', this.sizes.h, 0, 'px'],
			alpha: ['opacity', 0, 1, '']
		};
		this.rand = this.mode == 'rand';
		this.sequence = typeof(this.mode) == 'object' ? this.mode : false;
		this.curseq = 0;
		this.timer = null;
	},

	walk: function(n, manual) {
		if (this._current !== n && !this.disabled) {
			this.disabled = true;
			if (manual) {
				this.stop();
			}
			if (this.rand) {
				this.mode = this.modes.getRandom();
			} else if (this.sequence) {
				this.mode = this.sequence[this.curseq];
				this.curseq += this.curseq + 1 < this.sequence.length ? 1 : - this.curseq;
			}
			this._previous = this._current; 
			this._current = n;
			var a = this.attrs[this.mode].associate(['p', 'f', 't', 'u']);
			for (var i = 0; i < this.items.length; i++) {
				if (this._current === i) {
					this.items[i].setStyles($extend({'display': 'block', 'z-index': '2'}, JSON.decode('{"' + a.p + '": "' + a.f + a.u + '"}')));
				} else if (this._previous === i) {
					this.items[i].setStyles({'z-index': '1'});
				} else {
					this.items[i].setStyles({'display': 'none', 'z-index': '0'});
				}
			}
			this.items[n].set('tween', {onComplete: this.onComplete.bind(this)}).tween(a.p, a.f, a.t);
		}
	},
	
	play: function(wait) {
		this.stop();
		if (!wait) {
			this.next();
		}
		this.timer = this.next.periodical(this.interval, this, [false]);
	},

	stop: function() {
		$clear(this.timer);
	},

	next: function(manual) {
		this.walk(this._current + 1 < this.items.length ? this._current + 1 : 0, manual);
	},

	previous: function(manual) {
		this.walk(this._current > 0 ? this._current - 1 : this.items.length - 1, manual);
	},

	onComplete: function() {
		this.disabled = false;
		this.items[this._previous].setStyle('display', 'none');
		if (this.onWalk) {
			this.onWalk(this._current);
		}
	}
});

/*
Script: MultiUpload.js
	Class for a Upload Multiple Files in a single input file tag.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var MultiUpload = new Class({
	initialize: function(input_element, max, name_suffix_template, show_filename_only, remove_empty_element, allowed_ext_types, ext_types_with_screener, allowed_ext_screener_types) {
		this.elements = [];
		this.uid_lookup = {}; 
		this.uid = 0;
		if ($defined(max)) {
			this.max = max;
		} else {
			this.max = 0;
		}
		if ($defined(name_suffix_template)) {
			this.name_suffix_template = name_suffix_template;
		} else {
			this.name_suffix_template= '_{id}';
		}
		if ($defined(show_filename_only)) {
			this.show_filename_only = show_filename_only;
		} else {
			this.show_filename_only = false;
		}
		if ($defined(remove_empty_element)) {
			this.remove_empty_element = remove_empty_element;
		} else {
			this.remove_empty_element = false;
		}
		if ($defined(allowed_ext_types)) {
			this.allowed_ext_types = allowed_ext_types.toLowerCase();
		} else {
			this.allowed_ext_types = '*';
		}
		if ($defined(ext_types_with_screener)) {
			this.ext_types_with_screener = ext_types_with_screener.toLowerCase();
		} else {
			this.ext_types_with_screener = '';
		}
		if ($defined(allowed_ext_screener_types)) {
			this.allowed_ext_screener_types = allowed_ext_screener_types.toLowerCase();
		} else {
			this.allowed_ext_screener_types = '*';
		}
		$(input_element);
		this.id = input_element.id;
		this.name = input_element.name;
		this.form = input_element.form;
		this.initializeElement(input_element);
		var container = new Element('div', {'id': 'cont', 'class': 'multiupload'});
		this.list = new Element('div', {'class': 'list'});
		container.injectAfter(input_element);
		container.adopt(input_element);
		container.adopt(this.list);
		// Not send last empty element
		if (this.remove_empty_element) {
			input_element.form.addEvent('submit',function() {this.elements.getLast().element.disabled = true;}.bind(this));
		}
	},
	fjsDrawPopup: function(uid, cfile) {
		var jdescpopup = new Element('div', {'class': 'cxcmsdiv', 'id': 'jdescpopup', 'name': 'jdescpopup'}).inject(document.body);
		var pos = $('cont').getPosition();
		var height = 192;
		var width = 384;
		var left = (pos.x + (width / 3)).round();
		var top = (pos.y - (height / 2)).round();
		jdescpopup.setStyles({'background-color': '#FFFFFF', 'border': '10px solid #EFEFEF', 'cursor': 'move', 'height': height, 'left': left, 'position': 'absolute', 'text-align': 'center', 'top': top, 'visibility': 'visible', 'width': width, 'vertical-align': 'middle'});
		var closebutton = new Element('img', {'alt': 'Cerrar Ventana', 'id': 'close', 'src': '/ico/xpplain/16x16/' + 'error.png', 'title': 'Cerrar Ventana'}).inject(jdescpopup);
		closebutton.setStyles({'cursor': 'pointer', 'left': width - 24, 'position': 'absolute', 'text-align': 'right', 'top': 8, 'vertical-align': 'top'});
		closebutton.addEvent('click', function(e) {
			e.stop();
			$('jdescpopup').destroy();
		});
		var savebutton = new Element('img', {'alt': 'Guardar', 'id': 'save', 'src': '/ico/xpplain/16x16/' + 'disk_blue_window.png', 'title': 'Guardar'}).inject(jdescpopup);
		savebutton.setStyles({'cursor': 'pointer', 'left': width - 24, 'position': 'absolute', 'text-align': 'right', 'top': height - 24, 'vertical-align': 'bottom'});
		savebutton.addEvent('click', function() {
			if ($defined($('inputtext' + uid))) {
				var cname_content = $('inputtext' + uid).value;
			} else {
				var cname_content = "";
			}
			if ($defined($('textarea' + uid))) {
				var cdesc_content = $('textarea' + uid).value;
			} else {
				var cdesc_content = "";
			}
			if (!$defined($('cname_' + uid))) {
				var input_hidden_cname = new Element('input', {'id': 'cname_' + uid, 'name': 'cname_' + uid, 'type': 'hidden', 'value': cname_content}).inject($('cont'));
				$('cb' + uid).setProperties({'alt': 'Editar Comentario', 'src': '/ico/xpplain/16x16/' + 'message_edit.png', 'title': 'Editar Comentario'});
			} else {
				$('cname_' + uid).value = cname_content;
			}
			if (!$defined($('cdesc_' + uid))) {
				var input_hidden_cdesc = new Element('input', {'id': 'cdesc_' + uid, 'name': 'cdesc_' + uid, 'type': 'hidden', 'value': cdesc_content}).inject($('cont'));
				$('cb' + uid).setProperties({'alt': 'Editar Comentario', 'src': '/ico/xpplain/16x16/' + 'message_edit.png', 'title': 'Editar Comentario'});
			} else {
				$('cdesc_' + uid).value = cdesc_content;
			}
			$('jdescpopup').destroy();
		});
		var icontainer = new Element('div', {'id': 'icontainer'}).inject(jdescpopup);
		icontainer.setStyles({'cursor': 'default', 'height': height - 84, 'left': 10, 'position': 'absolute', 'text-align': 'center', 'top': 32, 'width': width - 20, 'vertical-align': 'middle'});
		var span_text_inputtext = new Element('span', {'class': 'sublist'}).set('text', 'Título ').inject(icontainer);
		var inputtext = new Element('input', {'class': 'cxcmsinputtext', 'id': 'inputtext' + uid, 'maxlength': 255, 'name': 'inputtext' + uid, 'size': 72, 'type': 'text'}).inject(icontainer).addEvent('click', function () {inputtext.focus();});
		if ($defined($('cname_' + uid))) {
			var inputtext_content = $('cname_' + uid).value;
			$('inputtext' + uid).setProperty('value', inputtext_content);
		}
		var span_text_textarea = new Element('span', {'class': 'sublist'}).set('text', 'Descripción').inject(icontainer);
		var textarea = new Element('textarea', {'class': 'cxcmsinputtextarea', 'id': 'textarea' + uid, 'name': 'textarea' + uid, 'rows': 4, 'cols': 64}).inject(icontainer).addEvent('click', function () {textarea.focus();});
		if ($defined($('cdesc_' + uid))) {
			var textarea_content = $('cdesc_' + uid).value;
			$('textarea' + uid).setProperty('value', textarea_content);
		}
		var span_text_file = new Element('span', {'class': 'sublist'}).set('text', 'Cambiando título y descripcíón para: ' + cfile + ' (' + uid + ')').inject(icontainer).setStyle('vertical-align', 'bottom');
		drag = new Drag.Move($(jdescpopup), {});
	},
	fjsShowLoad: function() {
		var loadingbutton = new Element('img', {'alt': 'Por favor espere...', 'id': 'loading', 'src': '/img/loading.gif', 'title': 'Por favor espere...'}).inject($('jdescpopup'));
		var ht = 32;
		var wt = 32;
		loadingbutton.setStyles({'cursor': 'pointer', 'height': ht, 'hspace': 0, 'left': (width / 2) - (wt / 2), 'position': 'absolute', 'text-align': 'center', 'top': (height / 2) - (ht / 2), 'vspace': 0, 'width': wt, 'vertical-align': 'middle'});
	},
	fjsKillLoad: function() {
		if ($defined($('loading'))) {
			$('loading').destroy();
		}
	},
	addRow: function() {
		if (this.max == 0 || this.elements.length <= this.max) {
			current_element = this.elements.getLast();
			var name = current_element.element.value;
			if (this.show_filename_only) {
				if (name.contains('\\')) {
					name = name.substring(name.lastIndexOf('\\') + 1);
				} else if (name.contains('//')) {
					name = name.substring(name.lastIndexOf('//') + 1);
				}
			}
			if (this.allowed_ext_types.contains(name.split('.')[1].toLowerCase()) == true || this.allowed_ext_types.contains('*') == true) {
				var item = new Element('span').set('text', name);
				var delete_button = new Element('img', {'alt': 'Borrar', 'src': '/ico/cross_small.gif', 'title': 'Borrar', 'events': {'click': function(uid) {this.deleteRow(uid);}.pass(current_element.uid, this)}});
				var comments_button = new Element('img', {'alt': 'Comentario', 'id': 'cb' + current_element.uid, 'src': '/ico/xpplain/16x16/' + 'message.png', 'title': 'Comentario', 'events': {'click': function(uid) {this.fjsDrawPopup(uid, name);}.pass(current_element.uid, this)}});
				if (this.ext_types_with_screener.contains(name.split('.')[1].toLowerCase()) == true) {
					var sub_text = new Element('span', {'class': 'sublist'}).set('text', 'Miniatura: ');
					var sub_input_file = new Element('input', {'id': 'ffilescrnr', 'name': 'ffilescrnr', 'type': 'file'});
					var sub_text_no_check = new Element('span', {'class': 'sublist'}).set('text', ' Sin Miniatura: ');
					var sub_input_check = new Element('input', {'type': 'checkbox'});
					sub_input_file.id = sub_input_file.id + this.name_suffix_template.replace( /\{id\}/, this.elements.length - 1);
					sub_input_file.name = sub_input_file.name + this.name_suffix_template.replace( /\{id\}/, this.elements.length - 1);
					sub_input_file.addEvent('change', function() {
						if (this.show_filename_only) {
							if (sub_input_file.value.contains('\\')) {
								sub_name = sub_input_file.value.substring(sub_input_file.value.lastIndexOf('\\') + 1);
							} else if (sub_input_file.value.contains('//')) {
								sub_name = sub_input_file.value.substring(sub_input_file.value.lastIndexOf('//') + 1);
							} else {
								sub_name = sub_input_file.value;
							}
						}
						if (this.allowed_ext_screener_types.contains(sub_input_file.value.split('.')[1].toLowerCase()) == true) {
							sub_input_file.setStyle('visibility', 'hidden');
							sub_text_no_check.destroy();
							sub_input_check.destroy();
							var sub_tmp_text = sub_text.get('text');
							sub_text.set('text', sub_tmp_text + sub_name);
						} else {
							sub_input_file.value = "";
							sub_name = "";
							alert( 'Error: extensión no en lista de tipos aceptados para miniaturas: ' + this.allowed_ext_screener_types);
						}
					}.bind(this));
					if (this.remove_empty_element) {
						sub_input_file.addEvent('submit', function() {
							if (sub_input_file.value == "") {
								sub_input_file.destroy();
							}
						}.bind(this));
					}
					sub_input_check.addEvent('click', function(e) {
						if (confirm('Esta seguro de querer item "' +  name + '" sin miniatura?')) {
							sub_input_file.destroy();
							sub_input_check.setProperties({'disabled': '"disabled"', 'readonly': '"readonly"'});
						} else {
							e.stop();
							sub_input_check.checked = false;
						}
					}.bind(this));
					var row_element = new Element('div', {'class': 'item'}).adopt(delete_button).adopt(item).adopt(comments_button).adopt(sub_text).adopt(sub_input_file).adopt(sub_text_no_check).adopt(sub_input_check);
				} else if (this.allowed_ext_screener_types.contains(name.split('.')[1].toLowerCase()) == true) {
					var sub_text_ubicacion = new Element('span', {'class': 'sublist'}).set('text', ' Ubicación: ');
					var sub_text_media = new Element('span', {'class': 'sublist'}).set('text', 'Media');
					var sub_input_radio_media = new Element('input', {'alt': 'Media', 'checked': 'checked', 'id': 'iuse_' + current_element.uid, 'name': 'iuse_' + current_element.uid, 'title': 'Media', 'type': 'radio', 'value': '1'});
					var sub_text_header = new Element('span', {'class': 'sublist'}).set('text', 'Header');
					var sub_input_radio_header = new Element('input', {'alt': 'Header', 'id': 'iuse_' + current_element.uid, 'name': 'iuse_' + current_element.uid, 'title': 'Header', 'type': 'radio', 'value': '2'});
					var sub_text_submenu = new Element('span', {'class': 'sublist'}).set('text', 'Submenu');
					var sub_input_radio_submenu = new Element('input', {'alt': 'Submenu', 'id': 'iuse_' + current_element.uid, 'name': 'iuse_' + current_element.uid, 'title': 'Submenu', 'type': 'radio', 'value': '3'});
					var row_element = new Element('div', {'class': 'item'}).adopt(delete_button).adopt(item).adopt(comments_button).adopt(sub_text).adopt(sub_input_file).adopt(sub_text_ubicacion).adopt(sub_text_media).adopt(sub_input_radio_media).adopt(sub_text_header).adopt(sub_input_radio_header).adopt(sub_text_submenu).adopt(sub_input_radio_submenu);
				} else {
					var row_element = new Element('div', {'class': 'item'}).adopt(delete_button).adopt(item).adopt(comments_button);
				}
				this.list.adopt(row_element);
				current_element.row = row_element;
				var new_input = new Element('input', {'type':'file', 'disabled': (this.elements.length == this.max) ? true : false});
				this.initializeElement(new_input);
				current_element.element.style.position = 'absolute';
				current_element.element.style.left = '-1000px';
				new_input.injectAfter(current_element.element);
			} else {
				alert( 'Error: extensión no en lista de tipos aceptados: ' + this.allowed_ext_types );
			}
		} else {
			alert( 'No se permite subir más de ' + this.max + ' archivos'  );
		}
	},
	deleteRow: function(uid) {
		deleted_row = this.elements[this.uid_lookup[uid]];
		var todelete;
		if (this.show_filename_only) {
			if (deleted_row.element.value.contains('\\')) {
				todelete = deleted_row.element.value.substring(deleted_row.element.value.lastIndexOf('\\') + 1);
			} else if (deleted_row.element.value.contains('//')) {
				todelete = deleted_row.element.value.substring(deleted_row.element.value.lastIndexOf('//') + 1);
			} else {
				todelete = deleted_row.element.value;
			}
		}
		if (confirm('Esta seguro de querer remover el item "' +  todelete + '" de la cola de subida?')) {
			this.elements.getLast().element.disabled = false;
			deleted_row.element.destroy();
			deleted_row.row.destroy();
			delete(this.elements[this.uid_lookup[uid]]);
			var new_elements = [];
			this.uid_lookup = {};
			for (var i = 0; i < this.elements.length; i++ ) {
				if ($defined(this.elements[i])) {
					this.elements[i].element.id = this.id + this.name_suffix_template.replace( /\{id\}/, new_elements.length);
					this.elements[i].element.name = this.name + this.name_suffix_template.replace( /\{id\}/, new_elements.length);
					this.uid_lookup[this.elements[i].uid] = new_elements.length;
					new_elements.push(this.elements[i]);
				}
			}
			this.elements = new_elements;
		}
	},
	initializeElement: function(element) {
		element.addEvent('change', function() {this.addRow()}.bind(this));
		element.id = this.id + this.name_suffix_template.replace( /\{id\}/, this.elements.length);
		element.name = this.name + this.name_suffix_template.replace( /\{id\}/, this.elements.length );
		this.uid_lookup[this.uid] = this.elements.length;
		this.elements.push({'uid':this.uid, 'element':element});
		this.uid++;
	}
});

/*
fjsCheckAvailability()
	Function to checking availability of names on a DB via JSON. Based on MooTools JSon.js.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var fjsCheckMultipleAvailability = function (e, i) {
	e.each(function(el) {
		fjsCheckAvailability(el, i);
	});
}
var fjsCheckAvailability = function (e, i) {
	c = (e.name.lastIndexOf('_') != -1 ? e.name.split('_')[0] : e.name);
	i = (e.name.lastIndexOf('_') != -1 ? e.name.split('_')[1] : (typeof(i) == 'number' && i > 0 ? i : 0));
	t = (typeof(e.title) == 'string' && e.title != '' ? (e.title.lastIndexOf('::') != -1 ? e.title.split('::')[0] : e.title) : 'tmods');
	f = (typeof(e.title) == 'string' && e.title != '' ? (e.title.lastIndexOf('::') != -1 ? e.title.split('::')[1] : '') : '');
	itlang = (t == 'tconsts' || t == 'ticons' ? (f != '' ? $(f).itlang.value : 1) : 1);
	isys = (t == 'ticons' ? (f != '' ? fjsGetRadioCheckedValue($(f).isys) : 1) : 1);
	// alert(e.name + ': ' + c + ' ' + i  + ' ' + t + ' ' + C_WEB_URL + '?cmod=json&p=gf&t=' + t + '&c=' + c + '&i=' + e.value + ' ' + itlang + ' ' + isys);
 	if (e.value != '' && e.value != C_WEB_URL + '?cmod=') {
		var fjsCheckData = function(rows) {
			rows.each(function(row) {
				if (row.a != 0 && row.a != i) {
					e.setStyle('background', '#FFEEEE');
					if ($defined($('warning.png_i' + e.name))) {
						$('warning.png_i' + e.name).setProperties({'alt': 'No Disponible', 'src': '/ico/xpplain/16x16/' + 'warning.png', 'title': 'No Disponible'});
					} else if ($defined($('check2.png_i' + e.name))) {
						$('check2.png_i' + e.name).setProperties({'alt': 'No Disponible', 'src': '/ico/xpplain/16x16/' + 'warning.png', 'title': 'No Disponible'});
					}
				} else if (row.a == 0 || row.a == i) {
					e.setStyle('background', '#EEFFEE');
					if ($defined($('warning.png_i' + e.name))) {
						$('warning.png_i' + e.name).setProperties({'alt': 'Disponible', 'src': '/ico/xpplain/16x16/' + 'check2.png', 'title': 'Disponible'});
					} else if ($defined($('check2.png_i' + e.name))) {
						$('check2.png_i' + e.name).setProperties({'alt': 'Disponible', 'src': '/ico/xpplain/16x16/' + 'check2.png', 'title': 'Disponible'});
					}
				}
			});
			if ($defined($('clink')) && e.name == 'curl') {
				$('clink').value = C_WEB_URL + '?cmod=' + e.value;
				fjsCheckAvailability($('clink'), i);
			}
		}
		var request = new Request.JSON({
			data: {'i': escape(e.value), 'itlang': itlang, 'isys': isys},
			url: C_WEB_URL + '?cmod=json&p=gf&t=' + t + '&c=' + c,
			onComplete: function(jsonObj) {
				fjsCheckData(jsonObj.jtable);
			}
		}).send();
	} else {
		e.setStyle('background', '#FFEEEE');
		if ($defined($('warning.png_i' + e.name))) {
			$('warning.png_i' + e.name).setProperties({'alt': 'No Disponible', 'src': '/ico/xpplain/16x16/' + 'warning.png', 'title': 'No Disponible'});
		} else if ($defined($('check2.png_i' + e.name))) {
			$('check2.png_i' + e.name).setProperties({'alt': 'No Disponible', 'src': '/ico/xpplain/16x16/' + 'warning.png', 'title': 'No Disponible'});
		}
	}
}

/*
fjsDynaFixPNG()
	Function to fix some IE < 6 transparency PNG issues.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var fjsDynaFixPNG = function() {
	if (Browser.Engine.trident) {
		var av = navigator.appVersion.split("MSIE");
		var v = parseFloat(av[1]);
		if ((v >= 5.5) && (v <= 7) && (document.body.filters)) {
		   	for (var i = 0; i < document.images.length; i++) {
			  	var img = document.images[i];
			  	var imgName = img.src.toLowerCase();
			  	if (imgName.substring(imgName.length - 3, imgName.length) == "png") {
				 	var imgID = (img.id) ? "id='" + img.id + "' " : "";
					var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				 	var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				 	var imgStyle = "display: inline-block; " + img.style.cssText;
				 	if (img.align == "left") imgStyle = "float: left; " + imgStyle;
				 	if (img.align == "right") imgStyle = "float: right; " + imgStyle;
				 	if (img.parentElement.href) imgStyle = "cursor: pointer; " + imgStyle;
				 	var strNewHTML = "<span " + imgID + imgClass + imgTitle	+ " style=\"" + "width: " + img.width + "px; height: " + img.height + "px;" + imgStyle + "; " + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"	+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
				 	img.outerHTML = strNewHTML;
				 	i--;
			  	}
		   	}
		}
	}
}

/*
Script: DynaMenu.js
	Class for a JSON.request enabled infinite categories menu.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var DynaMenu = new Class({

	Implements: [Events, Options],

	options: {
		showDelay: 0,
		curl: C_WEB_URL + '?cmod=json&p=menu',
		sid: 0,
		preload: false,
		opacity: false
	},

	initialize: function() {
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options || null);
		window.onerror = function(){return true;};
		if (params.elements) this.attach(params.elements);
	},
	
	attach: function(elements) {
		var showDelay = this.options.showDelay;
		var curl = this.options.curl;
		var sid = this.options.sid;
		$$(elements).each(function(element) {
			element.setStyle('cursor', 'pointer');
			element.addEvent('click', function(e) {
				e.stop();
				loadingbutton = new Element('img', {'alt': 'Por favor espere...', 'id': 'loading', 'src': '/img/riowait.gif', 'title': 'Por favor espere...'}).inject($('cubiertamaincontainer'));
				loadingbutton.setStyles({'cursor': 'pointer', 'height': 14, 'hspace': 0, 'left': (1024 / 2) - (64 / 2), 'position': 'absolute', 'text-align': 'center', 'top': (768 / 2) - (14 / 2), 'vspace': 0, 'width': 64, 'vertical-align': 'middle'});
				var id = element.getProperty('rev');
				var ib = element.getProperty('rel');
				if ($defined($('divcontainer'))) {
					$('divcontainer').fade('out');
					$('divcontainer').destroy();
				}
				var request = new Request.JSON({
					url: curl + '&n=jtree&ib=' + ib + '&id=' + id,
					onComplete: function(jsonObj) {
						fjsDropTree(jsonObj.jtree);
						fjsDisplayTree(jsonObj.jtree);
					}
				}).send();
			});
		});
		var fjsDropTree = function(jtree) {
			jtree.each(function(jbranch) {
				if (Browser.Engine.trident || Browser.Engine.webkit) {
					if (jbranch.jump == "yes") {
						window.location = C_WEB_URL + '?cmod=' + jbranch.curl;
						return false;
					}
				}
				if (jbranch.jump == "out") {
					navmenu = $('DynaNavMenu').get('html').replace(/\s+$/, ""); // Right trim()
					if (!navmenu.search(jbranch.cname) == -1) {
						$('DynaNavMenu').empty();
						navmenu.split(' » ' + jbranch.cname).join('');
						$('DynaNavMenu').set('html', navmenu + ' » ' + jbranch.cname + '  ');
					}
					if ($defined($("li" + jbranch.curl))) {
						$("li" + jbranch.curl).destroy();
					}
				}
				if (jbranch.jump == "no") {
					if ($defined($("li" + jbranch.curl))) {
						$("li" + jbranch.curl).destroy();
					}
				}
				if (jbranch.jump == "in") {
					navmenu = $('DynaNavMenu').get('html').replace(/\s+$/, ""); // Right trim()
					if (navmenu.search(jbranch.cname) == -1) {
						$('DynaNavMenu').empty();
						$('DynaNavMenu').set('html', navmenu + ' » ' + jbranch.cname + '  ');
					}
				}
				return true;
			});
			return true;
		}
		var fjsDisplayTree = function(jtree) {
			jtree.each(function(jbranch) {
				if (jbranch.jump == "yes") {
					window.location = C_WEB_URL + '?cmod=' + jbranch.curl;
					return false;
				} else if (jbranch.jump == "in") {
					if ($defined($('endli'))) {
						$('endli').fade('out');
						$('endli').destroy();
					}
					licontainer = $("li" + jbranch.curl);
					divcontainer = new Element('div', {'id': 'divcontainer'}).injectAfter(licontainer);
					divcontainer.injectAfter(licontainer);
					$$('.cxcmsdynalimenu').setStyles({'background': 'url(/ico/ico_menu_still.gif)', 'background-image': 'url(/ico/ico_menu_still.gif)', 'background-repeat': 'no-repeat'});
					$$('.cxcmsdynalisubmenu').setStyles({'background': 'none', 'background-image': 'none'});
					licontainer.setStyles({'background': 'url(/ico/ico_menu_twist.gif)', 'background-image': 'url(/ico/ico_menu_twist.gif)', 'background-repeat': 'no-repeat'});
					e = new Element('li', {'class': 'cxcmsdynalisubmenu', 'id': "endli"}).injectAfter(divcontainer);
					e.setStyles({'background': 'none', 'background-image': 'none', 'opacity': '0'});
					ea = new Element('a', {'class': 'DynaSubMenu', 'id': "ea"}).inject(e);
					ea.set('text', 'NO SE VE');
					if ($defined(jbranch.chtml) && jbranch.chtml != "") {
						var cubierta = $('cubiertamaincontainer');
						cubierta.setStyle('opacity','0');
						var eop = '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>';
						var callhtml = decodeURIComponent(jbranch.chtml).replace(/\+/g," ");
						if (callhtml.search(eop) == -1) {
							var chtml = callhtml;
						} else {
							var achtml = callhtml.split(eop);
							var chtml = achtml[0] + '<p align="right"><a href="?cmod=' + jbranch.curl + '&ipage=2">Siguiente <img alt="Siguiente" class="cxcmsimgabsmiddle" id="navigate_right.png_1222362052" src="/ico/xpshadow/16x16/navigate_right.png" title="Siguiente"></a></p>';
						}
						cubierta.set('html', chtml);
						cubierta.fade('in');
					} else {
						if ($defined($('loading'))) {
							$('loading').destroy();
						}
						// $('cubiertamaincontainer').fade('out');
						// $('cubiertamaincontainer').empty();
					}
				} else if (jbranch.jump == "no") {
					var li = new Element('li', {'class': 'cxcmsdynalisubmenu', 'id': "li" + jbranch.curl}).injectAfter(divcontainer);
					li.setStyles({'background': 'none', 'background-image': 'none', 'opacity': '0'});
					var a = new Element('a', {'class': 'DynaSubMenu', 'href': '?cmod=' + jbranch.curl, 'id': "a" + jbranch.curl, 'rel': jbranch.id, 'rev': jbranch.ibelong}).inject(li);
					a.set('text', jbranch.cname);
					li.fade('in');
				}
				return true;
			});
			return true;
		}
	}
});

/*
Script: DynaIcons.js
	Class for a nice Icon picker in a popup.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var DynaIcons = new Class({

	Implements: [Number, Events, Options],

	options: {
		id: 1,
		cext: '.png',
		isys: 1,
		curl: C_WEB_URL + '?cmod=json&p=ico',
		a: 128
	},

	initialize: function(element, options) {
		this.setOptions(options);
		var icontochange = $(element);
		var cid = this.options.id; 
		var s = this.options.isys; 
		var a = this.options.a;
		var ext = this.options.cext;
		var curl = this.options.curl;
		var i = 1;
		var t = a;
		var d = 1;
		var ojsonCMSDisplayParams = new Hash.Cookie('cjsonCMSDisplayParams', {autoSave: false, duration: (7 * 365)});
		var is = 4 + (icontochange.getWidth() < 48 && icontochange.getWidth() > 0 ? icontochange.getWidth() : (ojsonCMSDisplayParams.get('icosize') > 0 ? ojsonCMSDisplayParams.get('icosize') : fjsGetAppropiateValues(4)));
		var height = ((is * (a.sqrt() - 3)) + 84).round();
		var width = ((is * (a.sqrt() + 4)) + 20).round();
		// alert(width + "x" + height);
		icontochange.setStyle('cursor', 'pointer');
		icontochange.addEvent('click', function(e) {
			e.stop();
			var request = new Request.JSON({
				url: curl + '&s=' + s + '&i=' + i + '&t=' + t + '&e=' + ext,
				onComplete: function(jsonObj) {
					fjsDisplayIcons(jsonObj.jicoset);
				}
			}).send();
			fjsDrawPopup = function(ico) {
				if ($defined($('jicopopup'))) {
					var jicopopup = $('jicopopup');
					fjsKillIcons();
					fjsKillLoading();
				} else {
					var jicopopup = new Element('div', {'class': 'cxcmsdiv', 'id': 'jicopopup', 'name': 'jicopopup'}).inject(document.body);
				}
				var pos = $(icontochange).getPosition();
				var left = (pos.x - (width + a)).round();
				var top = (pos.y - (height / 2)).round();
				jicopopup.setStyles({'background-color': '#FFFFFF', 'border': '10px solid #EFEFEF', 'cursor': 'move', 'height': height, 'left': left, 'position': 'absolute', 'text-align': 'center', 'top': top, 'visibility': 'visible', 'width': width, 'vertical-align': 'middle'});
				if ($defined($('legend'))) {
					var legend = $('legend');
				} else {
					var legend = new Element('div', {'id': 'legend', 'title': 'Mover Ventana'}).inject(jicopopup);
				}
				legend.set('html', i + " / " + t + " (" + ico[1]['icohm'] + ")");
				legend.setStyles({'cursor': 'move', 'font-weight': 'bolder', 'left': 4, 'position': 'absolute', 'text-align': 'left', 'top': 0, 'vertical-align': 'middle'});
				if ($defined($('closebutton'))) {
					var closebutton = $('closebutton');
				} else {
					var closebutton = new Element('img', {'alt': 'Cerrar Ventana', 'id': 'close', 'src': '/img/closelabel.gif', 'title': 'Cerrar Ventana'}).inject(jicopopup);
				}
				closebutton.setStyles({'cursor': 'pointer', 'left': width - 64, 'position': 'absolute', 'text-align': 'right', 'top': 0, 'vertical-align': 'top'});
				closebutton.addEvent('click', function(e) {
					e.stop();
					fjsKillIcons();
				});
				if ($defined($('icontainer'))) {
					var icontainer = $('icontainer');
				} else {
					var icontainer = new Element('div', {'id': 'icontainer'}).inject(jicopopup);
				icontainer.setStyles({'cursor': 'default', 'height': height - 84, 'left': 10, 'position': 'absolute', 'text-align': 'center', 'top': 32, 'width': width - 20, 'vertical-align': 'middle'});
				}
				if ($defined($('leftbutton'))) {
					var leftbutton = $('leftbutton');
				} else {
					var leftbutton = new Element('img', {'alt': 'Anteriores', 'id': 'left', 'src': '/img/prevlabel.gif', 'title': 'Anteriores'}).inject(jicopopup);
				}
				leftbutton.setStyles({'cursor': 'pointer', 'left': 0, 'position': 'absolute', 'text-align': 'left', 'top': height - 32, 'vertical-align': 'bottom'});
				leftbutton.addEvent('click', function(e) {
					e.stop();
					fjsShowLoading();
					h = ico[1]['icohm'];
					st = i + " " + t;
					i = (i === 1 && t === a && d === 1 ? h - (h % a) + 1 : (i <= 1 ? 1 : i - a));
					t = (i === (h - (h % a) + 1) && t === a && d === 1 ? h : (t <= a ? a : (i <= 1 ? a : (t >= h - (h % a) && i >= t - (h % a) - a ? t - (h % a) : t - a))));
					d = ((i === 1 && t === a) || (i === (h - (h % a) + 1) && t === h) ? 1 : 0);
					// alert(st + " => " + i + " " + t + " : " + d);
					var request = new Request.JSON({
						url: curl + '&s=' + s + '&i=' + i + '&t=' + t + '&e=' + ext,
						onComplete: function(jsonObj) {
							fjsDisplayIcons(jsonObj.jicoset);
						}
					}).send();
				});
				if ($defined($('rightbutton'))) {
					var rightbutton = $('rightbutton');
				} else {
					var rightbutton = new Element('img', {'alt': 'Próximos', 'id': 'next', 'src': '/img/nextlabel.gif', 'title': 'Próximos'}).inject(jicopopup);
				}
				rightbutton.setStyles({'cursor': 'pointer', 'left': width - 64, 'position': 'absolute', 'text-align': 'right', 'top': height - 32, 'vertical-align': 'bottom'});
				rightbutton.addEvent('click', function(e) {
					e.stop();
					fjsShowLoading();
					h = ico[1]['icohm'];
					st = i + " " + t;
					i = (i === (h - (h % a) + 1) && t === h && d === 1 ? 1 : (i <= h - a ? (i + a >= h ? h - (h % a) : i + a) : (i >= h - (h % a) ? h - (h % a) + 1 : h - a)));
					t = (i === 1 && t === h && d === 1 ? a : (t <= h ? (t + a >= h ? h : t + a) : h));
					d = ((i === (h - (h % a) + 1) && t === h) || (i === 1 && t === a) ? 1 : 0);
					// alert(st + " => " + i + " " + t + " : " + d);
					var request = new Request.JSON({
						url: curl + '&s=' + s + '&i=' + i + '&t=' + t + '&e=' + ext,
						onComplete: function(jsonObj) {
							fjsDisplayIcons(jsonObj.jicoset);
						}
					}).send();
				});
				drag = new Drag.Move($(jicopopup), {});
			};
			fjsShowLoading = function() {
				var loadingbutton = new Element('img', {'alt': 'Por favor espere...', 'id': 'loading', 'src': '/img/loading.gif', 'title': 'Por favor espere...'}).inject($('jicopopup'));
				var ht = 32;
				var wt = 32;
				loadingbutton.setStyles({'cursor': 'pointer', 'height': ht, 'hspace': 0, 'left': (width / 2) - (wt / 2), 'position': 'absolute', 'text-align': 'center', 'top': (height / 2) - (ht / 2), 'vspace': 0, 'width': wt, 'vertical-align': 'middle'});
			};
			fjsKillLoading = function() {
				if ($defined($('loading'))) {
					$('loading').destroy();
				}
			};
			fjsDisplayIcons = function(ico) {
				fjsDrawPopup(ico);
				fjsShowLoading();
				ico.each(function(ico) {
					var thumb = new Element('img', {'hspace': 2, 'id': ico.icofile, 'src': ico.icopath + ico.icofile, 'title': ico.icofile, 'vspace': 2}).inject($('icontainer'));
					thumb.setStyles({'cursor': 'pointer', 'text-align': 'center', 'vertical-align': 'middle'});
					var cfile = element.get('id');
					var cpath = ico.icopath + ico.icofile;
					var backupsrc = $(cfile).getProperty('src');
					var backupvalue = $('cvalue_' + cid).getProperty('value');
					$(ico.icofile).addEvent('mouseover', function(e) {
						e.stop();
						$(cfile).setProperty('src', cpath);
						$('cvalue_' + cid).setProperty('value', ico.icofile);
					});
					$(ico.icofile).addEvent('mouseout', function(e) {
						e.stop();
						$(cfile).setProperty('src', backupsrc);
						$('cvalue_' + cid).setProperty('value', backupvalue);
					});
					$(ico.icofile).addEvent('click', function(e) {
						e.stop();
						$(cfile).setProperty('src', cpath);
						$('cvalue_' + cid).setProperty('value', ico.icofile);
						fjsKillIcons();
					});
				});
				fjsKillLoading();
			};
			fjsKillIcons = function(ico) {
				$('icontainer').empty();
				$('jicopopup').setStyle('visibility', 'hidden');
			};
		});
	}
});

/*
Script: DynaZoom.js and DynaScroller.js
	Class for creating nice zoom/magnifiying glass-like scroll windows that follow the mouse cursor when hovering an image element. Plus title and caption. Based on MooTools plugin Tips.js.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/
var DynaZoom = new Class({

	Implements: [Events, Options],

	options: {
		onShow: function(zoom){
			zoom.setStyle('visibility', 'visible');
		},
		onHide: function(zoom){
			zoom.setStyle('visibility', 'hidden');
		},
		showDelay: 64,
		hideDelay: 64,
		scrollDelay: 8,
		className: null,
		offsets: {x: 64, y: 32},
		fixed: false,
		glass: false,
		debug: false,
		debugPos: false,
		debugMouse: false,
		opacity: false,
		preload: false
	},

	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options || null);
		this.zoomwindow = new Element('div', {'id': 'zoomwindow'}).inject(document.body);
		if (this.options.preload) {
			this.zoomcache = new Element('div', {'id': 'zoomcache'}).inject(document.body);
		}
		if (this.options.glass) {
			this.dynazoomcursor = Element('div', {'id': 'dynazoomcursor', 'class': 'zoomcursor'}).inject(document.body);
		}
		if (this.options.className) this.zoomwindow.addClass(this.options.className);
		this.zoomcontainer = new Element('div', {'id': 'zoomcontainer'}).inject(this.zoomwindow);
		this.zoomwindow.setStyles({'border': '10px solid #fff', position: 'absolute', top: 0, left: 0, visibility: 'hidden'});
		if (params.elements) this.attach(params.elements);
	},
	
	attach: function(elements){
		var count = 0;
		$$(elements).each(function(element) {
			var title = element.retrieve('zoom:title', element.get('title'));
			var longdesc = element.retrieve('zoom:longdesc', element.get('longdesc') || element.get('href'));
			var dynaimg = element.retrieve('zoom:alt', element.get('alt'));
			if (this.options.preload) {
				var preloadqueue = this.zoomcache.get('html') + '<img id="cacheimage' + count + '" src="' + dynaimg + '" style="position: absolute; top: 0; left: 0; visibility: hidden;" />';
				this.zoomcache.set('html', preloadqueue);
			}
			var enter = element.retrieve('zoom:enter', this.elementEnter.bindWithEvent(this, element));
			var leave = element.retrieve('zoom:leave', this.elementLeave.bindWithEvent(this, element));
			var move = element.retrieve('zoom:move', this.elementMove.bindWithEvent(this, element));
			element.addEvents({mouseenter: enter, mouseleave: leave, mousemove: move});
			if (this.options.glass) {
				var vanish = this.dynazoomcursor.retrieve('zoom:vanish', this.elementVanish.bindWithEvent(this, this.dynazoomcursor));
				this.dynazoomcursor.addEvent('mouseover', vanish);
				element.setStyle('cursor', 'none');
			} else {
				element.setStyle('cursor', 'crosshair');
			}
			element.store('zoom:alter', element.get('alt'));
			element.erase('alt');
			element.store('zoom:native', element.get('title'));
			element.erase('title');
			count = count + 1;
		}, this);
		return this;
	},
	
	detach: function(elements){
		$$(elements).each(function(element){
			element.removeEvent('mouseenter', element.retrieve('zoom:enter') || $empty);
			element.removeEvent('mouseleave', element.retrieve('zoom:leave') || $empty);
			element.removeEvent('mousemove', element.retrieve('zoom:move') || $empty);
			element.eliminate('zoom:enter').eliminate('zoom:leave').eliminate('zoom:move');
			if (this.options.glass){
				this.dynazoomcursor.removeEvent('mouseover', this.dynazoomcursor.retrieve('zoom:vanish') || $empty);
				this.dynazoomcursor.eliminate('zoom:vanish');
			}
			var orig = element.retrieve('zoom:alter');
			if (orig) element.set('alt', orig);
			var original = element.retrieve('zoom:native');
			if (original) element.set('title', original);
		});
		return this;
	},
	
	elementEnter: function(event, element) {
		if (this.options.opacity) {
			$(document.body).fade(this.options.opacity);
		}
		$A(this.zoomcontainer.childNodes).each(Element.dispose);
		this.dynaframe = new Element('div', {'id': 'dynaframe'}).inject(this.zoomcontainer);
		this.dynainside = new Element('div', {'id': 'dynainside'}).inject(this.dynaframe);
		var title = element.retrieve('zoom:title');
		if (title) {
			this.titleElement = new Element('div', {'id': 'zoomtitle', 'class': 'zoomtitle'}).inject(this.zoomcontainer, 'bottom');
			this.fill(this.titleElement, title);
			
		}
		var longdesc = element.retrieve('zoom:longdesc');
		if (longdesc) {
			this.textElement = new Element('div', {'id': 'zoomlongdesc', 'class': 'zoomlongdesc'}).inject(this.zoomcontainer, 'bottom');
			this.fill(this.textElement, longdesc);
		}
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
		this.position((!this.options.fixed) ? event : {page: element.getPosition()});
		this.dynascroll = new DynaScroller(element, {debug: this.options.debug, scrollDelay: this.options.scrollDelay, preload: this.options.preload, glass: this.options.glass, onChange: function(x, y) {
				var frame = $('dynaframe');
				var imgnum = $A($$('.DynaZoom')).indexOf(element);
				var dynaimgid = 'cacheimage' + imgnum;
				if (this.options.preload) {
					var dynaimage = $(dynaimgid);
					var dynaimgstr = dynaimage.retrieve('zoom:src', dynaimage.get('src'));
					var sizei = {x: dynaimage.width, y: dynaimage.height};
				} else {
					if (!$defined($(dynaimgid))) {
						var dynaimgstr = element.retrieve('zoom:alt', element.get('alt'));
						var dynaimage = new Element('img', {'id': 'cacheimage' + imgnum, 'src': dynaimgstr}).inject($(document.body));
						dynaimage.setStyles({'position': 'absolute', 'top': 0, 'left': 0, 'visibility': 'hidden'});
					} else {
						var dynaimage = $(dynaimgid);
						var dynaimgstr = dynaimage.retrieve('zoom:src', dynaimage.get('src'));
					}
					var sizei = {x: dynaimage.width, y: dynaimage.height};
				}
				var sizet = {x: element.width, y: element.height};
				var scalex = (sizei['x'] / sizet['x']);
				var scaley = (sizei['y'] / sizet['y']);
				var pos = element.getPosition();
				if (this.options.glass) {
					var dynazoomcursor = $('dynazoomcursor')
					var sizecursorx = sizet['x'] / (scalex / 1.5);
					var sizecursory = sizet['y'] / (scaley / 1.5);
					dynazoomcursor.setStyles({'width': sizecursorx, 'height': sizecursory, 'left': (x + pos.x - (sizecursorx / 2)), 'top': (y + pos.y - (sizecursory / 2)), 'visibility': 'visible', 'opacity': 0.5});
					// dynazoomcursor.fireEvent('mouseenter', dynazoomcursor);
				}
				var sizeframex = sizet['x'] * (scalex / 2);
				var sizeframey = sizet['y'] * (scaley / 2);
				$('dynaframe').setStyles({'overflow': 'hidden', 'width': sizeframex, 'height': sizeframey});
				$('dynainside').setStyles({'background': 'url(' + dynaimgstr + ')', 'background-repeat': 'no-repeat', 'width': sizei['x'], 'height': sizei['y']});
				($defined($('zoomtitle')) ? $('zoomtitle').setStyle('width', sizeframex) : '');
				($defined($('zoomlongdesc')) ? $('zoomlongdesc').setStyle('width', sizeframex) : '');
				var xp = (x * (scalex / 2)) + x;
				var yp = (y * (scaley / 2)) + x;
				frame.scrollTo(xp, yp);
				if (this.options.debug) {
					var debug = ($defined($('debug')) ? $('debug') : $('zoomtitle'));
					debug.set('text', 'X: ' + x + ' Y: ' + y + ' Xp: ' + xp + ' Yp: ' + yp + ' (Escala X: ' + scalex + ' Escala Y: ' + scaley + ')' + ' (Frame X: ' + sizeframex + ' Frame Y: ' + sizeframey + ')' + ' (Cursor size X: ' + sizecursorx + ' Cursor size Y: ' + sizecursory + ')' + ' (left: ' + (x + pos.x) + ' top: ' + (y + pos.y) + ')');
				}
			}
		});
/*		if (this.options.opacity) {
			element.addEvent('click', function () { 
				$('zoomwindow').fade(0);
				$(document.body).fade(0);
			});
		} */
		element.addEvent('mouseout', this.dynascroll.stop.bind(this.dynascroll));
		element.addEvent('mousemove', this.dynascroll.start.bind(this.dynascroll));
		element.addEvent('mouseleave', this.dynascroll.stop.bind(this.dynascroll));
	},
	
	elementLeave: function(event) {
		if (this.options.opacity) {
			$(document.body).fade(1);
		}
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},
	
	elementMove: function(event, element) {
		if (this.options.debugMouse) {
			var debugmouse = ($defined($('debugmouse')) ? $('debugmouse') : $('zoomtitle'));
			var size = element.getSize(), scroll = element.getScrollSize(), pos = element.getPosition(), change = {'x': 0, 'y': 0}, page = event.page;
			for (var z in page){
				if (page[z] < (size[z] + pos[z]) && scroll[z] != 0)
					change[z] = (page[z] - size[z] - pos[z]);
				else if (page[z] + size[z] > (size[z] + pos[z]) && size[z] + size[z] != scroll[z])
					change[z] = (page[z] - pos[z]);
			}
			if (change.y || change.x) { 
				debugmouse.set('text', 'X: ' + (pos['x'] + change.x) + ' Y: ' + (pos['y'] + change.y));
			}
		}
		if (this.options.glass) {
			$('dynazoomcursor').setStyles({'left': 0, 'top': 0, 'visibility': 'hidden'});
		}
	},
	
	elementVanish: function(event, element) {
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
		this.position((!this.options.fixed) ? event : {page: element.getPosition()});
		this.fireEvent('show', this.zoomwindow);
	},
	
	position: function(event) {
		var size = window.getSize(), scroll = window.getScrollSize();
		var zoom = {x: this.zoomwindow.offsetWidth, y: this.zoomwindow.offsetHeight};
		var props = {x: 'left', y: 'top'};
		var debugposition;
		for (var z in props) {
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + zoom[z] - scroll[z]) > size[z]) pos = event.page[z] - this.options.offsets[z] - zoom[z];
			this.zoomwindow.setStyle(props[z], pos);
			if (this.options.debugPos) {
				if (!$defined(debugposition)) {
					var debugposition = pos;
				}
				var debugpos = ($defined($('debugpos')) ? $('debugpos') : $('zoomlongdesc'));
				debugpos.set('text', 'window size: left: ' + size['x'] +  ' top: ' + size['y'] + ' scroll size: left: ' + scroll['x'] +  ' top: ' + scroll['y'] + ' zoom size: left: ' + zoom['x'] +  ' top: ' + zoom['y'] + ' SO left: ' + debugposition + ' top: ' + pos);
			}
		}
	},
	
	fill: function(element, contents){
		(typeof contents == 'string') ? element.set('html', contents) : element.adopt(contents);
	},

	show: function() {
		this.fireEvent('show', this.zoomwindow);
	},

	hide: function() {
		this.fireEvent('hide', this.zoomwindow);
	}

});

var DynaScroller = new Class({

	Implements: [Events, Options],

	options: {
		debug: false,
		preload: true,
		glass: false,
		scrollDelay: 50,
		onChange: function(x, y){
			this.element.scrollTo(x, y);
		}
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.timer = null;
		this.coord = this.getCoords.bind(this);
	},

	start: function(){
		this.element.addEvent('mousemove', this.coord);
	},

	stop: function(){
		this.element.removeEvent('mousemove', this.coord);
		this.timer = $clear(this.timer);
	},

	getCoords: function(event){
		this.page = event.page;
		if (!this.timer) this.timer = this.scroll.periodical(this.options.scrollDelay, this);
	},

	scroll: function(){
		var size = this.element.getSize(), scroll = this.element.getScrollSize(), pos = this.element.getPosition(), change = {'x': 0, 'y': 0};
		for (var z in this.page){
			if (this.page[z] < (size[z] + pos[z]) && scroll[z] != 0)
				change[z] = (this.page[z] - size[z] - pos[z]);
			else if (this.page[z] + size[z] > (size[z] + pos[z]) && size[z] + size[z] != scroll[z])
				change[z] = (this.page[z] - pos[z]);
		}
		if (change.y || change.x) this.fireEvent('change', [scroll.x + change.x, scroll.y + change.y]);
	}

});

function fjsValidateFormContact() {
	var okSoFar = true
	with (document.formmailer) {
		var foundAt = cemail.value.indexOf("@", 0)
		if (foundAt < 1 && okSoFar) {
			okSoFar = false;
			alert ("Ingrese una dirección de e-mail válida.");
			cemail.focus();
		}
		/* var e1 = email.value;
		var e2 = email.value;
		if (!(e1 == e2) && okSoFar) {
			okSoFar = false;
			alert ("Su dirección de e-mail no coincide. Por favor ingresela nuevamente.");
			email.focus();
		} */
		if (caddress.value == "" && okSoFar) {
			okSoFar = false;
			alert("Por favor ingrese su Dirección.");
			caddress.focus();
		}
		if (cname.value == "" && okSoFar) {
			okSoFar = false;
			alert("Por favor ingrese su Nombre.");
			cname.focus();
		}
		if (clastname.value == "" && okSoFar) {
			okSoFar = false;
			alert("Por favor ingrese su Apellido.");
			clastname.focus();
		}
		if (csubject.value == "" && okSoFar) {
			okSoFar = false;
			alert("Por favor ingrese el motivo o asunto.");
			csubject.focus();
		}
		/*  if (msg.value == "" && okSoFar) {
			okSoFar = false;
			alert("Por favor transcriba su mensaje.");
			msg.focus();
		} */
		if (okSoFar==true) {
			submit();
		}
	}
}
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function fjsGetRadioCheckedValue(o) {
	if (!o) {
		return "";
	}
	var l = o.length;
	if (l == 'undefined') {
		if (o.checked) {
			return o.value;
		} else {
			return "";
		}
	}
	for(var i = 0; i < l; i++) {
		if(o[i].checked) {
			return o[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function fjsSetRadioCheckedValue(o, v) {
	if (!o) {
		return;
	}
	var l = o.length;
	if (l == 'undefined') {
		o.checked = (o.value == v.toString());
		return;
	}
	for (var i = 0; i < l; i++) {
		o[i].checked = false;
		if (o[i].value == v.toString()) {
			o[i].checked = true;
		}
	}
}

function reproduce(id, mp3) {
	document.getElementById(id).playSound(mp3);
}
function play_pause() {
	document.getElementById(id).togglePause();
}
function stop() {
	document.getElementById(id).stop();
}
function onSoundComplete() {
	alert("Canción completada!");
}
function restrictinput(maxlength, e, placeholder) {
	if (window.event && event.srcElement.value.length >= maxlength) {
		return false;
	} else if (e.target && e.target == eval(placeholder) && e.target.value.length >= maxlength) {
		var pressedkey = /[a-zA-Z0-9\.\,\/]/; //detect alphanumeric keys
		if (pressedkey.test(String.fromCharCode(e.which))) {
			e.stopPropagation();
		}
	}
	return true;
}
function countlimit(maxlength, e, placeholder) {
	var theform = eval(placeholder);
	var lengthleft = maxlength - theform.value.length;
	var placeholderobj = document.all ? document.all[placeholder] : document.getElementById(placeholder);
	if (window.event || e.target && e.target == eval(placeholder)) {
		if (lengthleft < 0) {
			theform.value = theform.value.substring(0, maxlength);
		}
		placeholderobj.innerHTML = lengthleft;
	}
}
function displaylimit(theform, thelimit) {
	var limit_text = '<b><span id="' + theform.toString() + '">' + thelimit + '</span></b> caracteres faltan para el límite.';
	if (document.all || ns6) {
		document.write(limit_text);
	}
	if (document.all) {
		eval(theform).onkeypress = function(){ return restrictinput(thelimit, event, theform) }
		eval(theform).onkeyup = function(){ countlimit(thelimit, event, theform) }
	} else if (ns6) {
		document.body.addEventListener('keypress', function(event) { restrictinput(thelimit, event, theform) }, true); 
		document.body.addEventListener('keyup', function(event) { countlimit(thelimit, event, theform) }, true);
	}
}
function openpopup(popurl) {
	winpops = window.open(popurl, "", "width=600, height=500, scrollbars=no")
}
///***********************************
// DoCheck(decimal, string, string). El verdadero validador.
// **********************************/
function DoCheck(decTemp, strCampo, strAlerta) {
	var err = "";
	var err1 = "el número no puede ser nulo.";
	var err2 = "el número no puede ser negativo.";
	var err3 = "el numero no puede contener caractebValidacion aparte de nùmeros, puntos o comas.";
	var err4 = "el número no puede tener tantas comas.";
	var errA = "En el " + strCampo + ", ";
	var errB = "\nPosibles causas: " + strAlerta + "\n";
	 
	var esValido = true;
	var nErrores = 0;
	
	//ver si no es nulo
	if (decTemp == null) {
		esValido = false;
		nErrores = nErrores + 1;
			if (nErrores < 2){
			err = err + errA + err1 + errB;}
	 }
		
	//ver si es negativo
	if (decTemp < 0) {
		esValido = false;
		nErrores = nErrores + 1;
			if (nErrores < 2){
			err = err + errA + err2 + errB;}
	 }
	
	//vars
	var cI;
	var nCount = 0;
	//Ver si hay mas de una coma, o de puntos
	for (cI = 0; cI < decTemp.length; cI++){
	 var ch = decTemp.charAt(cI);
		if (ch==",") nCount=nCount+1;
		if (ch==".") nCount=nCount+1;
			if (nCount>1) {esValido = false;
						nErrores = nErrores + 1;
						if (nErrores < 2){
							err = err + errA + err4 + errB;
							break;
						}
			}
		 }
			
	//Ver si cada caracter es valido	
	for (cI = 0; cI < decTemp.length; cI++){
	 var ch = decTemp.charAt(cI);
			if ((ch == ".") || (ch == ",")) 
			{ break; }
			
				else if ((ch < "0") || (ch > "9")) {
						esValido = false;
						nErrores = nErrores + 1;
							if (nErrores < 2){
							err = err + errA + err4 + errB;
							break;
							}
					}
			 }
	
	//Dar el alerta!
	if (!esValido) alert (err);
	return esValido;
}
function checkearlogin() {
	var cpass = document.forms.flogon.cpass.value;
	var cuser = document.forms.flogon.cuser.value;
	var submitOk = "True";
	var mensaje = "Faltan los siguientes datos.\n";
	if (cpass == "") {
		mensaje = mensaje + "Password incorrecto\n";
		submitOk = "False";
	}
	if(cuser == "") {
		mensaje = mensaje + "Nombre de Usuario\n";
		submitOk = "False";
	}
	if (submitOk == "False") {
		alert(mensaje);
		return false;
	} else {
		return true;
	}
}
function fjsInfoOrDelete(e) {
/*	if (f.type == "button") {
		var fs = document.forms;
		if (fs.length > 0) {
			for (var i = 0; i < fs.length; i++) {
				var fi = document.forms[i];
				for (var j = 0; j < fi.length; j++) {
					var e = fi.elements[j];
					if (e === f) {
						var n = $(fi.name);
					}
				}
			}
		}
	} else {
		var n = $(f);
	}
	var t = $((typeof(c) == "undefined" ? "csearch" : c));
	if(t.value != "" && t.value != (typeof(cmsg) == "undefined" ? "Buscar" : cmsg)) {
		n.submit();
	} else {
		alert((typeof(clej) == "undefined" ? "Ingrese el texto a buscar por favor. (Más de 2 letras)." : clej));
	} */
}

function fjsNoRightClick(msg) {
	window.addEvent('click', function(e) {
		if (e.rightClick) {
			e.stop();
			alert(C_MSG_NO_RIGHT_CLICK);
		}
	});
	function rightClickIE(e) {
		if (Browser.Engine.trident || Browser.Engine.webkit) {
			if (event.button == 2 || event.button == 3) {
				alert(msg);
				return false;
			}
		}
		return true;
	}
	document.onmousedown = rightClickIE;
}
// csshorizontalmenu
var fjsActivateMenu = function(nav) {
    /* currentStyle restricts the Javascript to IE only */
	if (document.all && document.getElementById(nav).currentStyle) {  
       var navroot = document.getElementById(nav);
		/* Get all the list items within the menu */
		var lis = navroot.getElementsByTagName("LI");  
        for (i = 0; i < lis.length; i++) {
           /* If the LI has another menu level */
            if(lis[i].lastChild.tagName == "UL"){
                /* assign the function to the LI */
             	lis[i].onmouseover = function() {	
                   /* display the inner menu */
                   this.lastChild.style.display = "block";
                }				
                lis[i].onmouseout = function() {                       
                   this.lastChild.style.display = "none";
                }
            }
        }
  }
}

//document.onkeypress=keypress;
/* window.onload= function(){ *
    /* pass the function the id of the top level UL */
    /* remove one, when only using one menu */
    /* activateMenu('nav'); */
   // activateMenu('vertnav'); 
/* } */
function SetFocus() {
  if (document.forms.length > 0) {
    isNotAdminLanguage:
    for (f=0; f<document.forms.length; f++) {
      if (document.forms[f].name != "adminlanguage") {
        var field = document.forms[f];

        for (i=0; i<field.length; i++) {
          if ( (field.elements[i].type != "image") &&
               (field.elements[i].type != "hidden") &&
               (field.elements[i].type != "reset") &&
               (field.elements[i].type != "submit") ) {

            document.forms[f].elements[i].focus();

            if ( (field.elements[i].type == "text") ||
                 (field.elements[i].type == "password") )
              document.forms[f].elements[i].select();

            break isNotAdminLanguage;
          }
        }
      }
    }
  }
}

function rowOverEffect(object) {
  if (object.className == 'dataTableRow') object.className = 'dataTableRowOver';
}

function rowOutEffect(object) {
  if (object.className == 'dataTableRowOver') object.className = 'dataTableRow';
}
function valida_envia() { 
    //valido el nombre 
    if (document.fvalida.nombre.value.length == 0) { 
       alert("Tiene que escribir su nombre") 
       document.fvalida.nombre.focus() 
       return 0; 
    } 
    //valido la edad. tiene que ser entero mayor que 18 
    edad = document.fvalida.edad.value 
    edad = validarEntero(edad) 
    document.fvalida.edad.value = edad 
    if (edad == "") { 
       alert("Tiene que introducir un número entero en su edad.") 
       document.fvalida.edad.focus() 
       return 0; 
    } else { 
       if (edad < 18) { 
          alert("Debe ser mayor de 18 años.") 
          document.fvalida.edad.focus() 
          return 0; 
       } 
    } 
    //valido el interés 
    if (document.fvalida.interes.selectedIndex==0){ 
       alert("Debe seleccionar un motivo de su contacto.") 
       document.fvalida.interes.focus() 
       return 0; 
    } 
    //el formulario se envia 
    alert("Muchas gracias por enviar el formulario"); 
    document.fvalida.submit();
	return true;
} 
/***************************************
	Required Functions
***************************************/
function check_values()	{
	var cpass = document.forms.registration.cpass.value;
	if(cpass.length < 8) {
		alert("8 caracteres minimo");
		return (false);
	}
	if (document.forms.registration.cterms.checked) {
		return true;
	} else {
		alert("Disculpe, debe aceptar los terminos y condiciones para poder registrarse.");
		return false;
	}
}
function modalDialogShow_IE(url,width,height) //IE
	{
	return window.showModalDialog(url,window,
		"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Raised;center:Yes;help:No;Resizable:Yes;Maximize:Yes");
	}
function modalDialogShow_Moz(url,width,height) //Moz
    {
    var left = screen.availWidth/2 - width/2;
    var top = screen.availHeight/2 - height/2;
    activeModalWin = window.open(url, "", "width="+width+"px,height="+height+",left="+left+",top="+top);
    window.onfocus = function(){if (activeModalWin.closed == false){activeModalWin.focus();};};
    }
var sActiveAssetInput;
function setAssetValue(v) //required by the asset manager
    {
    document.getElementById(sActiveAssetInput).value = v;
    }
function openAsset(s)
	{
	sActiveAssetInput = s
	if(navigator.appName.indexOf('Microsoft')!=-1)
		document.getElementById(sActiveAssetInput).value=modalDialogShow_IE("../inc/htmlarea/assetmanager/assetmanager.php",640,465); //IE	
	else
		modalDialogShow_Moz("../inc/htmlarea/assetmanager/assetmanager.php",640,465); //Moz	
	}
/*****************************************/
function MM_Nombre(Ncampo){
	if (Ncampo == 'wsuserstableclave')(Ncampo = 'Password');
	if (Ncampo == 'wsuserstableclave2')(Ncampo = 'Password Check');
	if (Ncampo == 'wsuserstableusuario')(Ncampo = 'User Name');
	if (Ncampo == 'wsuserstablenombre')(Ncampo = 'First Name');
	if (Ncampo == 'wsuserstableapellido')(Ncampo = 'Last Name');
	if (Ncampo == 'wsuserstableemail')(Ncampo = 'E-Mail');
	if (Ncampo == 'wsuserstabletel_A')(Ncampo = 'Phone');
	if (Ncampo == 'wsuserstabletel2_A')(Ncampo = 'Cell');
	if (Ncampo == 'wsuserstabletelfax_A')(Ncampo = 'Fax');
	if (Ncampo == 'wsuserstableempresa')(Ncampo = 'Company');
	if (Ncampo == 'wsuserstableRESALENUM')(Ncampo = 'Resale #');
	if (Ncampo == 'wsuserstabledireccion_1')(Ncampo = 'Address 1');
	if (Ncampo == 'wsuserstabledireccion_2')(Ncampo = 'Address 2');
	if (Ncampo == 'wsuserstablelocalidad')(Ncampo = 'City');
	if (Ncampo == 'wsuserstablecodpos')(Ncampo = 'Zip');
	if (Ncampo == 'wsuserstablepais')(Ncampo = 'Country');
	if (Ncampo == 'wsuserstabletel_Alternat_A')(Ncampo = 'Shipping - Phone');
	if (Ncampo == 'wsuserstableemail_Alternat')(Ncampo = 'Shipping - E-Mail');
	if (Ncampo == 'wsuserstabledireccion_Alternat_1')(Ncampo = 'Shipping - Address 1');
	if (Ncampo == 'wsuserstabledireccion_Alternat_2')(Ncampo = 'Shipping - Address 2');
	if (Ncampo == 'wsuserstablelocalidad_Alternat')(Ncampo = 'Shipping - City');
	if (Ncampo == 'wsuserstablecodpos_Alternat')(Ncampo = 'Shipping - Zip');
	if (Ncampo == 'wsuserstablepais_Alternat')(Ncampo = 'Shipping - Country');
	return Ncampo;
} 
function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { 
  	test=args[i+2]; 
	val=MM_findObj(args[i]);
    if (val) { 
		nm=val.name; 
		if ((val=val.value)!="") {
      		if (test.indexOf('isEmail')!=-1) { 
				p=val.indexOf('@');
        		if (p<1 || p==(val.length-1)) errors+='- '+MM_Nombre(nm)+' must contain an e-mail address.\n';
      			} else if (test!='R') { 
					num = parseFloat(val);
        			if (isNaN(val)) errors+='- '+MM_Nombre(nm)+' must contain a number.\n';
        			if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          			min=test.substring(8,p); max=test.substring(p+1);
          			if (num<min || max<num) errors+='- '+MM_Nombre(nm)+' must contain a number between '+min+' and '+max+'.\n';
    			} 
			}
		} else if (test.charAt(0) == 'R') errors += '- '+MM_Nombre(nm)+' is required.\n'; }
	} 
	if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}
function autotab(thisval,fname, flen){
	var fieldname = eval("document.dataUs." + fname);
	if(thisval != 9 && thisval != 16){
	if(fieldname.value.length + 1 <= flen){
	fieldname.focus();
	}else{
	for(x=0; x<document.TheForm.elements.length; x++){
		if(fieldname.name == document.TheForm.elements[x].name){
			var nextfield = x + 1;}
  		}document.TheForm.elements[nextfield].focus();}}
}
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
	input.value = input.value.slice(0, len);
	input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
	found = true;
	else
	index++;
	return found;
}
function getIndex(input) {
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	if (input.form[i] == input)index = i;
	else i++;
	return index;
}
return true;
}
function sh(_d)
{
  var _x = document.getElementById(_d);
  _x.style.visibility=_x.style.visibility=="hidden"?"visible":"hidden";
  _x.style.overflow=_x.style.overflow=="hidden"?"visible":"hidden";
}
function noenter() {
  return !(window.event && window.event.keyCode == 13); }
//validador

function validate_date_list(el, ev, warn_timeout)
{
   var warn_text = ' : you must specify a comma or space separated list of dates, like 1,16,31 or 1 16 31';
   var min_match_list    = [ /^[1-9]\d?([ ,]([1-9]\d?)?)*$/ ];
   var min_no_match_list = [ /,,/, /  /, /, ,/, /[4-9]\d/, /3[2-9]/ ];
   return validate_field(el, ev, warn_timeout, min_match_list, min_no_match_list, warn_text);
}

function validate_email(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in an email address';
    return validate_field(el, ev, warn_timeout, [ /^([a-zA-Z])[-\.\w]*(@(((\w[-\w]*)\.?)*)?)?$/ ], [], warn_text);
}

function validate_identifier(el, ev, warn_timeout)
{
    var warn_text = ' este valor no se permite aquí';
    return validate_field(el, ev, warn_timeout, [ /^\w+$/ ], [ ], warn_text);
}

function validate_integer(el, ev, warn_timeout)
{
    var warn_text = ' no se permite';
    return validate_field(el, ev, warn_timeout, [ /^\d+$/ ], [ /^0\d/ ], warn_text);
}

function validate_minute_list(el, ev, warn_timeout)
{
   var warn_text = ' : you must specify a comma or space separated list of minutes, like 15,23,45 or 15 23 45';
   var min_match_list    = [ /^[0-9]\d?([ ,]([1-9]\d?)?)*$/ ];
   var min_no_match_list = [ /,,/, /  /, /, ,/, /[6-9]\d/ ];
   return validate_field(el, ev, warn_timeout, min_match_list, min_no_match_list, warn_text);
}

function validate_name(el, ev, warn_timeout)
{
    var warn_text = ' No esta permitido aqui en el campo de Nombre';
    return validate_field(el, ev, warn_timeout, [ /^[a-zA-Z][-a-zA-Z ]*$/ ], [ /--/ ], warn_text);
}

function validate_price(el, ev, warn_timeout)
{
    var warn_text = ' No es un valor para un precio valido';
    return validate_field(el, ev, warn_timeout, [ /^\d+(\.(\d{0,2})?)?$/ ], [], warn_text);
}

function validate_Doble(el, ev, warn_timeout)
{
    var warn_text = ' No es un valor valido';
    return validate_field(el, ev, warn_timeout, [ /^\d+(\.(\d{0,2})?)?$/ ], [], warn_text);
}



function validate_signed_integer(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a signed whole number';
    return validate_field(el, ev, warn_timeout, [ /^[+-]?(\d+)?$/ ], [ /^0\d/, /^[+-]0/ ], warn_text);
}

function validate_telno(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a telephone number';
    return validate_field(el, ev, warn_timeout, [ /^\d[\d ]*$/, /^\+?(\d+( \((\d\)?)?)?)?(\d[\d ]*)?$/ ], [ /  /, /\(\d\d/ ], warn_text);
}

function validate_title(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a title field';
    return validate_field(el, ev, warn_timeout, [ /^[a-zA-Z][-a-zA-Z ]*$/ ], [], warn_text);
}

function validate_UK_postcode(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a UK postcode field';
    return validate_field(el, ev, warn_timeout, [ /^[A-Z][A-Z\d ]*$/ ], [ /  / ], warn_text);
}

function validate_USA_state_abbrev(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a state abbreviation';
    var match_re = /^(AK?|AL?|AR?|AZ?|CA?|CO?|CT?|DC?|DE?|FL?|GA?|HI?|IA?|ID?|IL?|IN?|KS?|KY?|LA?|MA?|MD?|ME?|MI?|MN?|MO?|MS?|MT?|NC?|ND?|NE?|NH?|NJ?|NM?|NV?|NY?|OH?|OK?|OR?|PA?|RI?|SC?|SD?|TN?|TX?|UT?|VA?|VT?|WA?|WI?|WV?|WY?)$/;
    return validate_field(el, ev, warn_timeout, [ match_re ], [ ], warn_text);
}

// finalizers

function id_finalize_email(id)
{
    return finalize_email(document.getElementById(id));
}

function finalize_email(el, domain_finalizer)
{
    var value = el.value;
    var tlds = '[^a-zA-Z](af|al|dz|as|ad|ao|ai|aq|ag|ar|am|aw|ac|au|at|az|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|bn|bg|bf|bi|kh|cm|ca|cv|cf|td|gg|je|cl|cn|cx|cc|co|km|cg|cd|ck|cr|ci|hr|cu|cy|cz|dk|dj|dm|do|tp|ec|eg|sv|gq|er|ee|et|fk|fo|fj|fi|fr|gf|pf|tf|fx|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt|gn|gw|gy|ht|hm|hn|hk|hu|is|in|id|ir|iq|ie|im|il|it|jm|jp|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|mu|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|na|nr|np|nl|an|nc|nz|ni|ne|ng|nu|nf|mp|no|om|pk|pw|pa|pg|py|pe|ph|pn|pl|pt|pr|qa|re|ro|ru|rw|kn|lc|vc|ws|sm|st|sa|sn|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sh|pm|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|bs|ky|tg|tk|to|tt|tn|tr|tm|tc|tv|ug|ua|ae|uk|us|um|uy|uz|vu|va|ve|vn|vg|vi|wf|eh|ye|yu|zm|zw|aero|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro)';

    var tlds_re = RegExp(tlds + '\.?$');

    if (value.match(/^[-\.\w]+$/))
    {
        el.value += '@domain' + '.' + domain_finalizer;
    }
    else if (value.match(/^[-\.\w]+@$/))
    {
        el.value += 'domain' + '.' + domain_finalizer;
    }
    else if (value.match(/^[-\.\w]+@([-\w]+\.)*[-\w]+$/))
    {
        if (! value.match(tlds_re)) el.value += '.' + domain_finalizer;
    }
    else if (value.match(/^[-\.\w]+@([-\w]+\.)+$/))
    {
        if (! value.match(tlds_re)) el.value += domain_finalizer;
    }
}

function id_finalize_price(id)
{
    return finalize_price(document.getElementById(id));
}

function finalize_price(el)
{
    var value = el.value;

    if (value.match(/^\d+$/))
    {
        el.value += '.00';
    }
    else if (value.match(/^\d+.$/))
    {
        el.value += '00';
    }
    else if (value.match(/^\d+.\d$/))
    {
        el.value += '0';
    }
}

function finalize_ucfirst(el) {
    el.value = el.value.toLowerCase();
    el.value = el.value.replace(/\b(\w)/g, 
		function(word) { 
			return word.substring(0,1).toUpperCase() + word.substring(1); 
		} 
    );
}

// implementation functions

function validate_field(el, ev, warn_timeout, match_list, no_match_list, warn_text) {
    if (!ev) ev = window.event;

    // preserve the start value for replacement in IE if the
    // user enters an invalid character

    var start_text = el.value;

    // allow backspace, deletion and arrow keys

    var keycode = get_keycode(ev);
    if (keycode == 8 || keycode == 9) {
        return true;
    }

    // the following unusual code correctly distinguises Mozilla 
    // char key presses from non-char keypresses (and also detects
    // when we get an IE keypress) which allows us to process chars
    // locally, but allow the browser to handle arrow/delete keys etc
    // (For some reason, trying to refer to ev.keyCode in the test
    // below breaks the Moz test, so we use document.selection instead
    // which is IE only)

    if (ev.which) {
        // it's a Mozilla keypress - process it here

        ;
    } else if (document.selection) {
        // it's an IE keypress - process it here

        ;
    } else {
        return true;
    }
 
    var key = String.fromCharCode(keycode);
    var cur_pos = cursor_pos(el);

    var new_value = insert_at_cursor(el, key);

    // does the new string match one of the 'must match' list ?

    var no_match = true;
    for (var i = 0; i < match_list.length; i++) {
        var regex = match_list[i];

        if (new_value.match(regex)) {
            no_match = false;
            break;
        }
    }
    
    if (no_match) {
        if (ev.keyCode) {
            // IE support - replace original value to erase illegal char
            // and reset cursor position
    
            el.value = start_text;
            set_cursor_pos(el, cur_pos);
    
            ev.returnValue = false;
        }
    
        // illegal character - show the user a warning and prevent the
        // character from being shown
    
        display_warning(el, warn_timeout, key + warn_text);
    
        return false;
    }

    // does the new string fail to match the 'must not match' list ?

    for (var i = 0; i < no_match_list.length; i++) {
        var regex = no_match_list[i];

        if (new_value.match(regex)) {
            if (ev.keyCode) {
                // IE support - replace original value to erase illegal char
                // and reset cursor position
    
                el.value = start_text;
                set_cursor_pos(el, cur_pos);
    
                ev.returnValue = false;
            }
    
            // illegal character - show the user a warning and prevent the
            // character from being shown
    
            display_warning(el, warn_timeout, key + warn_text);
    
            return false;
        }
    }

    if (ev.keyCode) {
        // IE support - ensure we don't insert the valid character again

        ev.returnValue = false;
    } else {
        // Mozilla - just let the browser insert the valid character

        return true;
    }
    return true;
}

function get_keycode(ev) {
    if (ev.keyCode) {
        return ev.keyCode;
    } else {
        return ev.which;
    }
}

// insert_at_cursor is based on code released under the GPL in the
// PHPMySQLAdmin project.

function insert_at_cursor(el, str) {

    // IE support

    var new_value;
    if (document.selection) 
    {
        el.focus();
        var sel = document.selection.createRange();
        sel.text = str;
        new_value = el.value;
    }

    // Mozilla/Netscape support
 
    else if (el.selectionStart || el.selectionStart == '0') 
    {
        var start_pos = el.selectionStart;
        var end_pos = el.selectionEnd;
        new_value = el.value.substring(0, start_pos)
                        + str
                        + el.value.substring(end_pos, el.value.length);
    } 
    else 
    {
        new_value += str;
    }

    return new_value;
}

function set_cursor_pos(el, cur_pos)
{
    if (cur_pos == -1) return;
    el.focus();
    var rng = el.createTextRange();
    rng.move("Character", cur_pos - 1)
    rng.select();
}

function cursor_pos(el)
{
    var i = el.value.length + 1;

    if (el.createTextRange)
    {
        var cursor = document.selection.createRange().duplicate();
        while (cursor.parentElement() == el
               && cursor.move("character", 1) == 1)
        {
             --i; 
        }
    } 
    return (i == el.value.length+1) ? -1 : i;
}

function display_warning(el, timeout, text)
{
    var geom_obj = getGeom(el);

    var warning_box_HTML = get_warning_box_HTML(text);

    var warning_box = document.getElementById('warning_box');
    if (! warning_box)
    {
        add_warning_box();
    }

    warning_box.innerHTML = warning_box_HTML;

    warning_box.style.left = geom_obj.x;
    warning_box.style.top  = geom_obj.y - 65;
    warning_box.style.display = 'inline';

    setTimeout("remove_warning()", (1000 * timeout));
}

function add_warning_box()
{
    var warning_box_HTML = get_warning_box_HTML('dummy');

    document.body.innerHTML += 
        '<span id="warning_box" style="position:absolute; display: none;">' +
         warning_box_HTML                                                   +
        '</span>';
}

function get_warning_box_HTML(text)
{
    return '<table class="Warning_table" id="info_table_1" cellspacing="2" width="350px">' +
           '<tr class="Warning_table_row">'                                                +
           '<td class="Warning_table_data">'                                               +
           text                                                                            +
           '</td>'                                                                         +
           '</tr>'                                                                         +
           '</table>'; 
}

function remove_warning()
{
    var warning_box = document.getElementById('warning_box');
    warning_box.style.display = 'none';
}

function getGeom(el)
{
    var object   = new Object();
    object.x     = el.offsetLeft;
    object.y     = el.offsetTop;
    var parent    = el.offsetParent;
    object.width  = el.offsetWidth;
    object.height = el.offsetHeight;
    while(parent != null)
    {
        object.x += parent.offsetLeft;
        object.y += parent.offsetTop;
        parent   = parent.offsetParent;
    }
    return object;
}
function fjsDynamicTracker(sid, cid, url, dir, ckexp) {
	var date = new Date();
	var expiration = new Date(date.valueOf() + (ckexp));
	var nu = 0;
	var res = 0;
	var col = 0;
	if(document.cookie.indexOf("xtrk", 0) < 0) {
		nu = 1;
	}
	document.cookie = "xtrk=" + sid + "; expires=" + expiration.toGMTString();
	var ec = document.cookie.length;
	var java = navigator.javaEnabled();
	var cpu = navigator.cpuClass;
	var browser = navigator.appName;
	var version = escape(navigator.appVersion);
	var tag = 1;
	if(typeof(screen) == "object") {
		res = screen.width + "X" + screen.height;
		if (browser != "Netscape") {
			col = screen.colorDepth;
		} else {
			col = screen.pixelDepth;
		}
	}
	var a = "<img src=\"" + url + dir + "/?cmod=trk&";
	var b = "cid=" + cid;
	var d = "&referer=" + escape(parent.document.referrer);
	var e = "&time=" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
	var f = "&tag=" + tag;
	var g = "&lb=" + (browser == "Netscape" ? navigator.language : navigator.userLanguage);
	var h = "&hjava=" + (java == 0 ? 0 : 1);
	var i = "&hjs=1";
	var j = "&res=" + res;
	var k = "&col=" + col;
	var l = "&ec=" + (ec == 0 ? 0 : 1);
	var m = "&nu=" + nu;
	var n = "&sl=" + (browser == "Netscape" ? 0 : navigator.systemLanguage);
	var o = "&expiration=" + escape(expiration.toGMTString());
	var p = "&cpu=" + cpu;
	var q = "&browser=" + browser;
	var r = "&version=" + version;
	var s = "&sid=" + sid;
	var z = "\" width=1 height=1 border=0 />";
	document.writeln(a + b + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + z);
	return true;
}
function fjsAddToBookmarks(url, title) {
	if (document.all) {
		window.external.AddFavorite(url, title); 
	} else if ((typeof(window.sidebar) == "object") && (typeof(window.sidebar.addPanel) == "function")) {
		window.sidebar.addPanel(title, url, "");
	} else {
		alert ("Presione Ctrl+D para agregar " + title + " en sus Favoritos");
	}
	return true;
}
function fjsSetHomePage(url, title) {
	if (document.all) {
		document.write('<img align="middle" alt="Establecer ' + title + ' como Página de Inicio!" border="0" id="addbookmarkico" onclick="this.setHomePage(\'' + url + '\');" name="addbookmarkico" src="/img/icohomepage.png" style="color:blue;cursor:pointer;behavior:url(#default#homepage);" title="Establecer ' + title + ' como Página de Inicio!" />');
	}
	return true;
}
function fjsSelectSearch(cfield) {
	cfield.value = "";
}
function fjsDeSelectSearch(cfield, cmsg) {
	if (cfield.value == "") {
		cfield.value = (typeof(cmsg) == "undefined" ? "Buscar" : cmsg);
	}
}
function fjsSearchSubmit(f, c, cmsg, clej) {
	if (f.type == "button") {
		var fs = document.forms;
		if (fs.length > 0) {
			for (var i = 0; i < fs.length; i++) {
				var fi = document.forms[i];
				for (var j = 0; j < fi.length; j++) {
					var e = fi.elements[j];
					if (e === f) {
						var n = $(fi.name);
					}
				}
			}
		}
	} else {
		var n = $(f);
	}
	var t = $((typeof(c) == "undefined" ? "csearch" : c));
	if(t.value != "" && t.value != (typeof(cmsg) == "undefined" ? "Buscar" : cmsg)) {
		n.submit();
	} else {
		alert((typeof(clej) == "undefined" ? "Ingrese el texto a buscar por favor. (Más de 2 letras)." : clej));
	}
}
function fjsGetAppropiateValues(w) {
	var jsw = window.getWidth();
	var icos;
	var phpwm;
	var phpwc;
	var phpwe;
	var r;
	if (jsw >= 1600) {
		icos = 48;
		phpwm = 18;
		phpwc = 82;
		phpwe = 0;
	} else if (jsw >= 1280 && jsw < 1600) {
		icos = 32;
		phpwm = 20;
		phpwc = 80;
		phpwe = 0;
	} else if (jsw >= 1020 && jsw < 1280) {
		icos = 24;
		phpwm = 22;
		phpwc = 78;
		phpwe = 0;
	} else if (jsw >= 800 && jsw < 1024) {
		icos = 16;
		phpwm = 24;
		phpwc = 76;
		phpwe = 0;
	} else if (jsw >= 640 && jsw < 800) {
		icos = 16;
		phpwm = 26;
		phpwc = 74;
		phpwe = 0;
	} else if (jsw < 640) {
		icos = 16;
		phpwm = 28;
		phpwc = 72;
		phpwe = 0;
	} else {
		icos = 24;
		phpwm = 22;
		phpwc = 78;
		phpwe = 0;
	}
	if (w == 1) {
		r = phpwm;
	} else if (w == 2) {
		r = phpwc;
	} else if (w == 3) {
		r = phpwe;
	} else if (w == 4) {
		r = icos;
	} else {
		r = icos;
	}
	return (r);
}
function fjsUpdateDisplayParams(title, isys) {
	window.defaultStatus = title;
	window.status = title;
	var widthbabor = fjsGetAppropiateValues(1);
	var widthcubierta = fjsGetAppropiateValues(2);
	var widthestribor = fjsGetAppropiateValues(3);
	var icosize = fjsGetAppropiateValues(4);
	widthbabor = widthbabor.toString() + "%";
	widthcubierta = widthcubierta.toString() + "%";
	widthestribor = widthestribor.toString() + "%";
	icosize = icosize.toString() + "x" + icosize.toString();
	var ojsonCMSDisplayParams = new Hash.Cookie('cjsonCMSDisplayParams', {autoSave: false, duration: (7 * 365)});
	if (ojsonCMSDisplayParams.get('widthbabor') == '') {
		ojsonCMSDisplayParams.empty();
		ojsonCMSDisplayParams.extend({
			'widthbabor': widthbabor,
			'widthcubierta': widthcubierta,
			'widthestribor': widthestribor,
			'icosize': icosize
		});
	} else {
		if (ojsonCMSDisplayParams.get('widthbabor') != widthbabor) {
			if (isys == 1) {
				$$('tdbabor').setStyle('width', widthbabor);
			}
			ojsonCMSDisplayParams.set('widthbabor', widthbabor);
		}
		if (ojsonCMSDisplayParams.get('widthcubierta') != widthcubierta) {
			if (isys == 1) {
				$$('tdcubierta').setStyle('width', widthcubierta);
			}
			ojsonCMSDisplayParams.set('widthcubierta', widthcubierta);
		}
		if (ojsonCMSDisplayParams.get('widthestribor') != widthestribor) {
			if (isys == 1) {
				$$('tdestribor').setStyle('width', widthestribor);
			}
			ojsonCMSDisplayParams.set('widthestribor', widthestribor);
		}
		if (ojsonCMSDisplayParams.get('icosize') != icosize) {
			ojsonCMSDisplayParams.set('icosize', icosize);
		}
	}
	
	return ojsonCMSDisplayParams.save();
}
function check_registrations_main_values() {
	var cpass = document.forms.registration.cpass.value;
	if(cpass.length < 3) {
    	alert("3 caracteres mínimo!");
   		return (false);
	}
	if (document.forms.registration.cterms.checked) {
		return true;
	} else {
		alert("Disculpe, debe aceptar los terminos y condiciones para poder registrarse.");
		return false;
	}
}
function checkearedit()	{
	var cemail = document.forms.useredit.cemail.value;
	var cname = document.forms.useredit.cname.value;
	var clastname = document.forms.useredit.clastname.value;
	var icountry = document.forms.useredit.icountry.value;
	var submitOk = "True";
	var mensaje = "Por favor, complete los siguientes datos:\n";
//	var ctel = document.forms.useredit.ctel.value;
//	var caddress = document.forms.useredit.caddress.value;
//	var ccity = document.forms.useredit.ccity.value;
//	var czip = document.forms.useredit.czip.value;
//  document.forms.useredit.czip.focus();
	if(cemail == "") {
		mensaje = mensaje + "Email\n";
		submitOk = "False";
	}
	if(cname == "") {
		mensaje = mensaje + "Nombre\n";
		submitOk = "False";
	}
	if(clastname == "") {
		mensaje = mensaje + "Apellido\n";
		submitOk = "False";
	}
	if(icountry == "") {
		mensaje = mensaje + "Pais\n";
		submitOk = "False";
	}
	if (submitOk == "False") {
		alert(mensaje);
		return false;
	} else {
		return true;
	}
}

/*
fjsChangeImageOnLoad()
	Function to Change de header image on load and unload. Based on MooTools J,
			'widthcubierta': widthcubierta,
			'widthestribor': widthestribor,
			'icosize': icosize
		});
	} else {
		if (ojsonCMSDisplayParams.get('widthbabor') != widthbabor) {
			if (isys == 1) {
				$$('tdbabor').setStyle('width', widthbabor);
			}
			ojsonCMSDisplayParams.set('widthbabor', widthbabor);
		}
		if (ojsonCMSDisplayParams.get('widthcubierta') != widthcubierta) {
			if (isys == 1) {
				$$('tdcubierta').setStyle('width', widthcubierta);
			}
			ojsonCMSDisplayParams.set('widthcubierta', widthcubierta);
		}
		if (ojsonCMSDisplayParams.get('widthestribor') != widthestribor) {
			if (isys == 1) {
				$$('tdestribor').setStyle('width', widthestribor);
			}
			ojsonCMSDisplayParams.set('widthestribor', widthestribor);
		}
		if (ojsonCMSDisplayParams.get('icosize') != icosize) {
			ojsonCMSDisplayParams.set('icosize', icosize);
		}
	}
	
	return ojsonCMSDisplayParams.save();
}
function check_registrations_main_values() {
	var cpass = document.forms.registration.cpass.value;
	if(cpass.length < 3) {
    	alert("3 caracteres mínimo!");
   		return (false);
	}
	if (document.forms.registration.cterms.checked) {
		return true;
	} else {
		alert("Disculpe, debe aceptar los terminos y condiciones para poder registrarse.");
		return false;
	}
}
function checkearedit()	{
	var cemail = document.forms.useredit.cemail.value;
	var cname = document.forms.useredit.cname.value;
	var clastname = document.forms.useredit.clastname.value;
	var icountry = document.forms.useredit.icountry.value;
	var submitOk = "True";
	var mensaje = "Por favor, complete los siguientes datos:\n";
//	var ctel = document.forms.useredit.ctel.value;
//	var caddress = document.forms.useredit.caddress.value;
//	var ccity = document.forms.useredit.ccity.value;
//	var czip = document.forms.useredit.czip.value;
//  document.forms.useredit.czip.focus();
	if(cemail == "") {
		mensaje = mensaje + "Email\n";
		submitOk = "False";
	}
	if(cname == "") {
		mensaje = mensaje + "Nombre\n";
		submitOk = "False";
	}
	if(clastname == "") {
		mensaje = mensaje + "Apellido\n";
		submitOk = "False";
	}
	if(icountry == "") {
		mensaje = mensaje + "Pais\n";
		submitOk = "False";
	}
	if (submitOk == "False") {
		alert(mensaje);
		return false;
	} else {
		return true;
	}
}
/*
fjsChangeImageOnLoad()
	Function to Change de header image on load and unload. Based on MooTools JSon.js.

License:
	NOMELOCOPIESOTECAGOABOLLOS-style license.
*/

function fjsChangeImageOnLoad() {
	new DynaSlideShow($$('#headerproa img)')).play(true);
	window.addEvent("beforeunload", function() {
		$('allwindow').fade('out');
	});
}
// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	var links = $$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	});
	$$(links).slimbox({'loop': true, 'overlayOpacity': 0.8, 'resizeDuration': 512, 'resizeTransition': Fx.Transitions.Expo.easeInOut, 'initialWidth': 160, 'initialHeight': 160, 'animateCaption': true, 'showCounter': true, 'counterText': 'Imagen {x} de {y}'}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
window.addEvent("domready", Slimbox.scanPage);
