// FUNCIONES ESENCIALES ----
// ---8<--------------------

function left(str,n){if(n<=0){return "";}else if(n>String(str).length){return str;}else{return String(str).substring(0,n);}}
function right(str,n){if(n<=0){return "";}else if(n>String(str).length){return str;}else{var iLen=String(str).length;return String(str).substring(iLen,iLen-n);}}

function teInteresaExt(pis){
	if(!pis || !pis.items) return;
	var teInteresaExt=document.getElementById("teInteresaExt");
	var code="";
	for (var i=0;i<pis.items.length;i++){
		var item=pis.items[i];
		var htmlUrl=item.origin.htmlUrl.replace(/\/$/,""); htmlUrl=htmlUrl.replace("http://","");var first4=String(htmlUrl).substring(0,4);if(first4=="www."){htmlUrl = htmlUrl.replace(first4,"");}
		var fecha = item.published; var theDate = new Date(fecha*1000); fecha = theDate.getDate()+'|'+(theDate.getMonth()+1)+'|'+theDate.getFullYear();

//		var snippet = ""; if(item.content!=undefined){snippet=item.content;}else if(item.summary!=undefined){snippet=item.summary;}else{snippet="";}

		var snippet = "";
		if(item.annotations[0]!=undefined && item.annotations[0].content!=undefined){snippet=""+item.annotations[0].content;}else{
		if(item.summary!=undefined){snippet=""+item.summary;}else if(item.content!=undefined){snippet=""+item.content;}else{snippet="";}}

		code+="<div class='rssItem'>";
		code+="<a href='"+item.alternate.href+"'>"+item.title+"</a>";
		code+="<div class='miniURL'><div class='fecha'>"+fecha+"</div><div class='medio'>"+htmlUrl+"</div><div class='clear'>&nbsp;</div></div>";
		code+="<div class='snippet'>"+snippet+"</div>";
		code+="<div class='clear'>&nbsp;</div>";
		code+="</div";
		}
	teInteresaExt.innerHTML=code;
	}

function refresh(){window.location.reload(false);}

function wordToUpper(str_sentence)
	{
	return str_sentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);
	function convertToUpper(){return arguments[0].toUpperCase();}
	}

function textCounter(field,cntfield,maxlimit)
	{
	if (field.value.length > maxlimit) // if too long...trim it!
	field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
	cntfield.value = maxlimit - field.value.length;
	}

function anyCheck(formName,fieldName,accion)
	{
	var total=0;
	if(document.forms[formName].elements[fieldName+"[]"].length){
	for (var i=0;i<document.forms[formName].elements[fieldName+"[]"].length;i++){if (eval("document.forms[formName].elements[fieldName][i].checked") == checked){total+=1;}}
	}else{alert("QQ");document.forms[formName].elements[fieldName].checked == checked;}
	if (total==0){alert(i+"No has seleccionado nada")}else{if (confirm("Confirma que quieres " + accion + " " + total + " elemento(s)")) {document.forms[formName].submit();}};
	}

checked = false;
function checkedAll(formName,fieldName)
	{
	if (checked==false){checked=true}else{checked=false}
	if (document.forms[formName].elements[fieldName].length)
		{
		for (var i=0;i<document.forms[formName].elements[fieldName].length;i++){document.forms[formName].elements[fieldName][i].checked=checked;}
		} else {document.forms[formName].elements[fieldName].checked=checked}
	}

// ---Convierte todos los elementos checkeados de un ckeckbox en un array separado por "|"--------
function sortNumbers(a,b){return a-b;}
function checkedtoArray(formName,fieldName)
	{
	var total=""; for(var i=0;i<document[formName].elements["_"+fieldName].length;i++)
		{if(document[formName].elements["_"+fieldName][i].checked){var data=document[formName].elements["_"+fieldName][i].value; data = data.split("|"); total+=data[0]+",";}}
	var arrayNumbers=total.split(','); var qq=arrayNumbers.sort(sortNumbers); qq=qq.join(","); qq=(qq.substring(1)); document[formName].elements[fieldName].value=qq;
	}

// ---Convierte todos los elementos checkeados de un ckeckbox en un array separado por ","--------
function checkedtoArrayB(formName,fieldName,mixto)
	{
	var totalA="";
	var totalB="";
	for(var i=0;i<document[formName].elements["_id"+wordToUpper(fieldName)].length;i++)
		{
		if(document[formName].elements["_id"+wordToUpper(fieldName)][i].checked)
			{
			dato = document[formName].elements["_id"+wordToUpper(fieldName)][i].value;
			dato = dato.split("|");
			totalA+=dato[0]+",";
			if(mixto==true){totalB+=dato[1]+", ";}
			}
		}
	document[formName].elements["id"+wordToUpper(fieldName)].value = totalA;
	if(mixto==true){document[formName].elements["nombre"+wordToUpper(fieldName)].value = totalB;}
	}

// ---Chequea campos obligatorios al enviar formulario--------
function formCheck(formobj,camposObligatorios,titCamposObligatorios,msg){
	// name of mandatory fields
	var fieldRequired = camposObligatorios.split("|");
	// field description to appear in the dialog box
	var fieldDescription = titCamposObligatorios.split("|");
	// dialog message
	var alertMsg = msg+":\n";
	var l_Msg = alertMsg.length;
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			if (obj.type == null)
				{
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){if (obj[j].checked){blnchecked=true;}}
				if (!blnchecked){alertMsg += " - " + fieldDescription[i] + "\n";}
				continue;
				}
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].value == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
		}
	}
	if (alertMsg.length == l_Msg){return true;}else{alert(alertMsg);return false;}
}

// Añade la hora a las fechas
function anadeHora(formName,fieldName)
	{
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds();
	var timeValue = " ";
	timeValue += ((hours<10)?"0":"")+hours;
	timeValue += ((minutes<10)?":0":":")+minutes;
	timeValue += ((seconds<10)?":0":":")+seconds;
	document[formName].elements[fieldName].value+= timeValue;
	}

// generate SEF url
function genSEF(from,to) {
	var str = from.value.toLowerCase();
	str = str.replace(/[\xc0-\xc5\xe0-\xe5\u0100-\u0105\u0386\u0391\u03ac\u03b1\u0410\u0430\u05d0]/g,'a');
	str = str.replace(/[\xc8-\xcb\xe8-\xeb\u0116-\u011b\u0112\u0113\u0388\u0395\u03ad\u03b5\u042d\u044d]/g,'e');
	str = str.replace(/[\xa1\xcc-\xcf\xec-\xef\u0128-\u012b\u012e-\u0132\u013a\u0389\u038a\u0390\u0397\u0399\u03aa\u03ae\u03af\u03b7\u03b9\u03ca\u0418\u0438]/g,'i');
	str = str.replace(/[\xd2-\xd6\xd8\xf0\xf2-\xf6\xf8\u014d\u014c\u0150\u0151\u038c\u038f\u039f\u03a9\u03bf\u03c9\u03cc\u03ce\u041e\u043e]/g,'o');
	str = str.replace(/[\xb5\xd9-\xdc\xf9-\xfc\u0171\u0173\u0168-\u0170\u0423\u0443]/g,'u');
	str = str.replace(/[\u0392\u03b2\u05d1]/g,'b');
	str = str.replace(/[\xc7\xe7\u0106-\u010d\u0147\u0148\u05da\u05db]/g,'c');
	str = str.replace(/[\xd0\u010e-\u0111\u0394\u03b4\u05d3]/g,'d');
	str = str.replace(/[\u03a6\u03c6]/g,'f');
	str = str.replace(/[\u011c-\u0123\u0393\u03b3\u05d2]/g,'g');
	str = str.replace(/[\u0124-\u0127\u05d4]/g,'h');
	str = str.replace(/[\u0134\u0135]/g,'j');
	str = str.replace(/[\u0136\u0137\u039a\u03ba\u05d7\u05e7]/g,'k');
	str = str.replace(/[\u0139-\u013e\u0141\u0142\u039b\u03bb\u05dc]/g,'l');
	str = str.replace(/[\u039c\u03bc\u05dd\u05de]/g,'m');
	str = str.replace(/[\xd1\xf1\u0143-\u0148\u039d\u03bd\u05df\u05e0]/g,'n');
	str = str.replace(/[\u0154-\u0159\u03a1\u03c1\u05e8]/g,'r');
	str = str.replace(/[\u03a0\u03c0\u05e3\u05e4]/g,'p');
	str = str.replace(/[\x8a\x9a\xdf\u015a-\u0161\u03a3\u03c2\u03c3\u05e1]/g,'s');
	str = str.replace(/[\u0162-\u0167\u021a\u021b\u03a4\u03c4\u05d8\u05ea]/g,'t');
	str = str.replace(/[\u05d5]/g,'v');
	str = str.replace(/[\u03be\u039e]/g,'x');
	str = str.replace(/[\x9f\xdd\xfd\xff\u038e\u03a5\u03ab\u03b0\u03c5\u03cb\u03cd\u05d9]/g,'y');
	str = str.replace(/[\x9e\u0179-\u017e\u0396\u03b6\u05d6]/g,'z');
	str = str.replace(/[\u05e2]/g,'aa');
	str = str.replace(/[\xc6\xe6]/g,'ae');
	str = str.replace(/[\u03a7\u03c7]/g,'ch');
	str = str.replace(/[\u039e\u03be\u0152\u0153]/g,'oe');
	str = str.replace(/[\xde\xfe\u0398\u03b8]/g,'th');
	str = str.replace(/[\u05e5\u05e6]/g,'ts');
	str = str.replace(/[\u03c8\u03a8\u0398\u03b8]/g,'ps');
	str = str.replace(/[\u05e9]/g,'sh');
	str = str.replace(/[\xdf]/g,'sz');
	str = str.replace(/[^a-z 0-9]+/g,'');
	str = str.replace(/\s+/g, "_");
	to.value = str;
	}

// ---Ancho de la ventana--------
function browserWidth()
	{
	var w = 0;
	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
		}
	}
	//W3C
	else
	{
		w = window.innerWidth;
	}
	return (w);
}

// ---Ancho y Alto de la ventana--------
function browserWidthHeight()
	{
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//W3C
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return (w+"|"+h);
}

// ---Estás seguro/a--------
function areYouSure(destino,genero) {
	if (confirm("¿Estás segur"+genero+"?")) {
		document.location.href=destino;
		}
	}

// ---Estás bien seguro/a--------
function areYouPrettySure(destino,genero) {
	if (confirm("----------\nATENCIÓN\n----------\nEliminando una ficha eliminarás también\nTODOS LOS COMENTARIOS Y ETIQUETAS\nque se hayan hecho en ella\n\n¿Estás segur"+genero+"?")) {
		document.location.href=destino;
		}
	}

// ---Estás realmente seguro/a--------
function areYouReallySure(destino,genero) {
	if (confirm("---------------------------------\nESTO ES UNA DECISIÓN IMPORTANTE\n---------------------------------\nEliminando una categoría eliminarás\nTODAS LAS FICHAS, COMENTARIOS,\nANOTACIONES Y ETIQUETAS\nque se hayan hecho en esa categoría\n\n¿Estás completamente segur"+genero+"?")) {
		document.location.href=destino;
		}
	}

// ---abre-CierraBloques----
function toggle(div) {
		if (document.getElementById(div).style.display=='') {
			document.getElementById(div).style.display = 'none';
			return
		} document.getElementById(div).style.display = ''; 
	}	

// ---marcaHoy--------------
function marcarHoy(dia,mes,ano) {
	diaHoy(dia); mesHoy(mes); anoHoy(ano);
}

// ---hoy(dia)--------------
function diaHoy(SelectName) {
	var today=new Date()
	var Value=today.getDate()
	eval('SelectObject = document.' + 
	SelectName + ';');
	for(index = 0; 
		index < SelectObject.length; 
		index++) {
	if(SelectObject[index].value == Value)
	SelectObject.selectedIndex = index;
	}
}

// ---hoy(mes)--------------
function mesHoy(SelectName) {
	var today=new Date()
	var Value=today.getMonth()+1
	eval('SelectObject = document.' + 
	SelectName + ';');
	for(index = 0; 
		index < SelectObject.length; 
		index++) {
	if(SelectObject[index].value == Value)
	SelectObject.selectedIndex = index;
	}
}

// ---hoy(año)--------------
function anoHoy(SelectName) {
	var today=new Date()
	var Value=today.getFullYear()
	eval('SelectObject = document.' + 
	SelectName + ';');
	for(index = 0; 
		index < SelectObject.length; 
		index++) {
	if(SelectObject[index].value == Value)
	SelectObject.selectedIndex = index;
	}
}

function refrescaParent() {
	window.parent.location.reload(true);
	self.parent.tb_remove();return false;
//	window.opener.location.reload();
}

/*
DepSelectOne: Dependen Select Lists V1.0
copyright 2003 Richard Cornford

constructor parameters for DepSelectOne(masterSelect)
masterSelect = a reference to the select element that is the
first select box in the chain of dependent select boxes.
If more than one instance of the DepSelectOne is required
the name attribute of the masteSelect element for each should
be unique (as the names are used to reference instances of the
Class)

The constructor should additionally be passed one or more
string that contain the same names as the names of the select
elements that are intended to be dependent on the master select
element, in the order in which each shall be dependent on the previous.
The names should be unique within a form.

Example:
&lt;body onload="new DepSelectOne(document.forms['formName'].elements['level_1'], 'level_2', 'level_3', ... , 'level_n');"&gt;

The maximum number of dependent select boxes is not defined in, or
limited by, this code and will probably depend on the JavaScript
implementation. It will be bigger than will ever actually be needed
and performance will drop off if the list gets big, at least in part
because the HTML will become impracticably large.
*/
function DepSelectOne(masterSelect){
	var frm = masterSelect.form;
	this.selectedBlock = 0;
	this.selBoxes = new Array(masterSelect);
	if((frm)&&(typeof Option != 'undefined')){
		for(var c = 1;c < arguments.length;c++){
			var selObj = frm[arguments[c]];
			if((selObj)&&(selObj.type.indexOf('select') == 0)&&(selObj.type.indexOf('mult') < 0)&&(selObj.options.length > 2)){
				this.selBoxes[this.selBoxes.length] = frm[arguments[c]];
			}
		}
		if((this.selBoxes.length >1)&&(this.selBoxes.length == arguments.length)){
			this.selectElement = this.selBoxes[0];
			DepSelectOne.inst[this.index = this.selectElement.name] = this;	//keep global record of this object instance.
			this.selBoxes[0] = this;
			this.optionBlock = new OptionBlock(0, this.selectElement, this.selectElement.options[0].value, this, 0);
			this.next = new DepSelectOneNext(this.selBoxes, 1);
			this.next.setSelection(this.optionBlock.getSelection());
			this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.index+'\'].handleChange(0)');
		}else{
			//alert('DepSelectOne constructor could not find\nsufficient properly configured SELECT elements\nto initialise.');
		}
	}
}
DepSelectOne.inst = {};	//Globally accessible object to hold instances of the DepSelectOne Class.
//call chain terminating functions.
DepSelectOne.prototype.validateNext = DepSelectOne.prototype.reset = DepSelectOne.prototype.setSelection = DepSelectOne.prototype.setSelectedFromChild = function(){return true;}
DepSelectOne.prototype.validate = function(){
	return ((this.optionBlock.lastSelection < 0)?false:this.next.validateNext());
}
DepSelectOne.prototype.init = function(selectedBlock){
	if(selectedBlock >= 0){
		this.optionBlock.lastSelection = selectedBlock;
	}
	if(this.optionBlock.lastSelection >= 0){
		this.optionBlock.doElement();
		if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
	}
}
DepSelectOne.prototype.handleChange = function(ind){
	this.selBoxes[ind].changed();
	if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
}
DepSelectOne.prototype.refresh = function(){
	this.selectElement.selectedIndex = this.optionBlock.lastSelection;
	this.next.reset();
}
DepSelectOne.prototype.changed = function(){
	this.optionBlock.readState();
	this.next.setSelection(this.optionBlock.getSelection());
}

function DepSelectOneNext(selBoxes, selBoxIndex){
	this.selectedBlock = -1;
	this.classObj = selBoxes[0];
	this.previous = selBoxes[(selBoxIndex-1)]
	this.selectElement = selBoxes[selBoxIndex];
	selBoxes[selBoxIndex] = this;
	this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.classObj.index+'\'].handleChange('+selBoxIndex+')');
	this.seperatorOption = new DepOption(this.selectElement.options[0]);
	this.optionBlocks = [];
	var startIndex = 1;
	while(startIndex < this.selectElement.options.length){
		var nextIndex = this.optionBlocks.length;
		this.optionBlocks[nextIndex] = new OptionBlock(startIndex, this.selectElement, this.selectElement.options[0].value, this, nextIndex);
		startIndex += this.optionBlocks[nextIndex].getOptionsTotal();
	}
	for(var cnt = 0,c = 0;c < this.optionBlocks.length;c++){
		this.optionBlocks[c].blockStart = cnt;
		cnt += this.optionBlocks[c].getItems();
	}
	if(++selBoxIndex < selBoxes.length){
		this.next = new DepSelectOneNext(selBoxes, selBoxIndex);
	}else{
		this.next = this.classObj;
		this.previous.init(this.selectedBlock);
	}
}
DepSelectOneNext.prototype.reset = function(){
	if((this.selectedBlock >= 0)&&(this.optionBlocks[this.selectedBlock].lastSelection >= 0)){
		this.selectElement.selectedIndex = this.optionBlocks[this.selectedBlock].lastSelection;
		this.next.reset();
	}
}
DepSelectOneNext.prototype.setSelection = function(selBlock){
	this.selectedBlock = selBlock;
	if(this.selectedBlock < 0){
		var opt = this.selectElement.options;
		opt.length = 0; //clear options
		opt[0] = this.seperatorOption.getOption();
		this.selectElement.selectedIndex = 0;
		this.next.setSelection(-1);
	}else{
		var blk = this.optionBlocks[this.selectedBlock];
		blk.doElement();
		this.next.setSelection(blk.getSelection());
	}
}
DepSelectOneNext.prototype.changed = function(){
	if(this.selectedBlock >= 0){
		var blk = this.optionBlocks[this.selectedBlock];
		blk.readState();
		this.next.setSelection(blk.getSelection());
	}
}
DepSelectOneNext.prototype.setSelectedFromChild = function(blockIndex){
	if(this.selectedBlock < 0){	//only set from OptonBlock on the first attempt.
		this.selectedBlock = blockIndex;
	}
}
DepSelectOneNext.prototype.init = function(selBlock){
	if(selBlock >= 0){
		var blockIndex = 0;
		while(!this.optionBlocks[blockIndex++].nextBlockTest(selBlock));
	}
	this.previous.init(this.selectedBlock);
}
DepSelectOneNext.prototype.validateNext = function(){
	return (((this.selectedBlock < 0)||(this.optionBlocks[this.selectedBlock].lastSelection < 0))?false:this.next.validateNext());
}

function DepOption(optEl){
	this.value = optEl.value;
	this.text = optEl.text;
}
DepOption.prototype.getOption = function(){
	return new Option(this.text, this.value);
}

function OptionBlock(startIndex, selectElement, seperatorValue, owner, blockIndex){
	this.blockStart = 0;
	this.owner = owner;
	this.index = blockIndex;
	this.selectElement = selectElement;
	this.seperators = [];
	this.optionBlock = [];
	this.lastSelection = -1;
	var opts = this.selectElement.options;
	while((startIndex < opts.length)&&(opts[startIndex].value == seperatorValue)){
		this.seperators[this.seperators.length] = new DepOption(opts[startIndex++]);
	}
	while((startIndex < opts.length)&&(opts[startIndex].value != seperatorValue)){
		if((this.lastSelection < 0)&&(opts[startIndex].selected == true)){
			this.lastSelection = this.optionBlock.length; //record first item selected, if any.
		}
		this.optionBlock[this.optionBlock.length] = new DepOption(opts[startIndex++]);
	}
	if(this.lastSelection >= 0)this.owner.setSelectedFromChild(this.index)
}
OptionBlock.prototype.getOptionsTotal = function(){
	return (this.seperators.length + this.optionBlock.length);
}
OptionBlock.prototype.getItems = function(){
	return this.optionBlock.length;
}
OptionBlock.prototype.nextBlockTest = function(selBlock){
	if((selBlock >= this.blockStart)&&(selBlock < this.blockStart+this.optionBlock.length)){
		this.lastSelection = selBlock - this.blockStart;
		this.owner.selectedBlock = this.index;
		return true;
	}
	return false;
}
OptionBlock.prototype.getSelection = function(){
	return ((this.lastSelection < 0)?-1:(this.blockStart+this.lastSelection));
}
OptionBlock.prototype.doElement = function(){
	var opt = this.selectElement.options;
	opt.length = 0; //clear options
	if((this.lastSelection < 0)&&(this.seperators.length > 0)){
		opt[opt.length] = this.seperators[(this.seperators.length-1)].getOption();
	}
	for(var c = 0;c < this.optionBlock.length;c++){
		opt[opt.length] = this.optionBlock[c].getOption();
	}
	this.selectElement.selectedIndex = ((this.lastSelection < 0)?0:this.lastSelection);
}
OptionBlock.prototype.readState = function(){
	if(this.lastSelection < 0){
		this.lastSelection = (this.selectElement.selectedIndex - 1);
		this.doElement();
	}else{
		this.lastSelection = this.selectElement.selectedIndex;
	}
}


/*
demonstration use of validate function of DepSelectOne Class
*/
function testSel(){
	if(  DepSelectOne.inst['level_1'].validate()  ){ //note the use of the name of the first SELECT Element in the chain to reference the object instance.
		alert('Selection is complete and valid');
	}else{
		alert('Selection is in-complete and NOT valid');
	}
}