//Prototipos
String.prototype.trim = function() {
  a = this.replace(/^\s+/, '');
  return a.replace(/\s+$/, '');
}
// No hace nada
function notdo(){}
//-------------------------------------------
// FUNCIONES CON VENTANAS
//-------------------------------------------
// Lanza una nueva ventana
function windowPopUp(href,prop) {
	popup=window.open(href,"popup",prop);
	popup.focus();
}
// Re-escala una ventana
function windowResize(ancho,alto){
	window.resizeTo(ancho,alto);
}
// Cierra la ventana activa
function windowClose(){
	self.close();
}
//-------------------------------------------
// A DESPRECIAR EN FUTURAS VERSIONES
//-------------------------------------------
// Lanza una nueva ventana
function popupwin(href,prop) {
	popup=window.open(href,"popup",prop);
	popup.focus();
}
//-------------------------------------------
// ARRAYS
//-------------------------------------------
// Rotacion de un array a la izquierda con indice basado en 1
function arrayRotateIzquierda_1(arr){
	len = arr.length;
	if ( len > 1 ) {
		// Guardo el primer elemento
		tmp = arr[1];
		// Realizo la rotacion
		for (i=2; i < len ; i++){
			arr[i-1] = arr[i];
		}
		// Coloco el primer elemento en su sitio
		arr[len-1] = tmp;
	}
	return arr;
}
// Rotacion de un array a la derecha con indice basado en 1
function arrayRotateDerecha_1(arr){
	len = arr.length;
	if ( len > 1 ) {
		// Guardo el ultimo elemento
		tmp = arr[len-1];
		// Realizo la rotacion
		for ( i=(len - 1); i > 1 ; i--){
			arr[i] = arr[i-1];
		}
		// Coloco el primer elemento en su sitio
		arr[1] = tmp;
	}
	return arr;
}
// OBJETOS
/* Recoger una unstacia de un OBJ DHTML con compatibilidad de navegadores */
function getObj(name) {
	obj = new Object();
    obj.obj = new Object();
    obj.style = new Object();
    obj.style.visibility = "";
    if (name != "") {
		if (document.all)  {
            obj.obj = document.all[name];
			if (obj.obj != "undefined" && obj.obj != null ) {
				obj.style = document.all[name].style;
			}
        }
        else if (document.getElementById) {
			obj.obj = document.getElementById(name);

			if (obj.obj != "undefined" && obj.obj != null ) {
				obj.style = document.getElementById(name).style;
			}
        }
        else if (document.layers) {
            obj.obj = document.layers[name];
			if (obj.obj != "undefined" && obj.obj != null ) {
				obj.style = document.layers[name];
			}
        }
    }
  return obj;
}
// Cambiar CONTENIDO
function alterContent(objeto, contenido){
	if (document.all)
		//dcontent.innerHTML=mycontent[i];
		document.all[objeto].innerHTML = contenido;
	else if (document.getElementById){
		rng = document.createRange();
		el = document.getElementById(objeto);
		rng.setStartBefore(el);
		htmlFrag = rng.createContextualFragment(contenido);
		while (el.hasChildNodes()) el.removeChild(el.lastChild);
		el.appendChild(htmlFrag);
	}
}
//-------------------------------------------
// MENUS - LISTA DE CAPAS -
//-------------------------------------------
var MenusJS = new Object();
var MenusTimerID = 0;
var MenusHideTime = 2; // en segundos
function addMenu(nombre) {
	MenusJS[nombre] = new Object();
	MenusJS[nombre]['timer'] = MenusHideTime;
}
function setMenuNumItems(nombre, num) {
	MenusJS[nombre]['num'] = num;
}
function getMenuNumItems(nombre) {
	return MenusJS[nombre]['num'];
}
function showMenuItem(nombre, item) {
	var objeto = new Object();
	MenusJS[nombre]['activo'] = true;
	MenusJS[nombre]['timer'] = MenusHideTime;
    objeto = getObj(item);
    objeto.style.visibility = 'visible';
    objeto.style.display = "";
}
function hideMenuItem(nombre, item){
	var objeto = new Object();
	//MenusJS[nombre]['activo'] = false;
    objeto = getObj(item);
    objeto.style.visibility = 'hidden';
    objeto.style.display = "none";
}
function hideAllMenu(nombre, item) {
	MenusJS[nombre]['activo'] = false;
	num = MenusJS[nombre]['num'];
	for (i=0; i < num; i++) {
		item_tmp = nombre + "_" + i;

		if (item == item_tmp ) { }
		else {
			hideMenuItem(nombre, item_tmp);
		}
	}
}
function activarMenu(nombre){
	MenusJS[nombre]['activo'] = true;
}
function desactivarMenu(nombre){
	MenusJS[nombre]['activo'] = false;
}
function compruebaMenus(){
	for (menu in MenusJS) {
		time	= MenusJS[menu]['timer'];
		activo	= MenusJS[menu]['activo'];
		if (activo == false) {
			time -= 1;
			MenusJS[menu]['timer'] = time;
			if ( time <= 0 ) {
				hideAllMenu(menu, "");
				MenusJS[menu]['timer'] = MenusHideTime;
				MenusJS[menu]['activo'] = true;
			}
		}
	}
	MenusTimerID = setTimeout("compruebaMenus()", 1000);
}

// Iniciar la comprobacion de menus
//compruebaMenus();

/* ENVIAR PAGINA A UN AMIGO */
 function enviarA( URLENC ) {
	win_prop = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=600,height=350";
	ventAmi = window.open('send_to.php?url=' + URLENC, 'enviarA', win_prop);
	ventAmi.focus();
}
/* IMPRIMIR PAGINA */
 function ImprimirPagina( URLIMP ) {
	win_prop = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=750,height=550";
	ventPrn = window.open( URLIMP , 'imprimirP', win_prop);
	ventPrn.focus();
}
/* AUMENTAR Y REDUCIR LETRAS */
// StyleSwitcher functions
function setActiveSS(title) {
	var i, a, main;
	for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true; if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
}
function getActiveSS() {
	var i, a; for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled ) return a.getAttribute("title");
	} return null;
}
function getPreferredSS() {
	var i, a; for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if (a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("rel").indexOf("alt") == -1 && a.getAttribute("title") ) return a.getAttribute("title");
	} return null;
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString();
	} else expires = ""; document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) {
	var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;
}
window.onload = function(e) {
	var cookie = readCookie("style"); var title = cookie ? cookie : getPreferredSS(); setActiveSS(title);
}
window.onunload = function(e) {
	var title = getActiveSS(); createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredSS();
setActiveSS(title);
/* -- Adobe GoLive JavaScript Library */
/* -- Global Functions */
function CSScriptInit() {
	if(typeof(skipPage) != "undefined") { if(skipPage) return; }
	idxArray = new Array;
	for(var i=0;i<CSInit.length;i++)
		idxArray[i] = i;
	CSAction2(CSInit, idxArray);
}
CSInit = new Array;
CSExit = new Array;
CSStopExecution=false;
function CSAction(array) {return CSAction2(CSAct, array);}
function CSAction2(fct, array) {
	var result;
	for (var i=0;i<array.length;i++) {
		if(CSStopExecution) return false;
		var aa = fct[array[i]];
		if (aa == null) return false;
		var ta = new Array;
		for(var j=1;j<aa.length;j++) {
			if((aa[j]!=null)&&(typeof(aa[j])=="object")&&(aa[j].length==2)){
				if(aa[j][0]=="VAR"){ta[j]=CSStateArray[aa[j][1]];}
				else{if(aa[j][0]=="ACT"){ta[j]=CSAction(new Array(new String(aa[j][1])));}
				else ta[j]=aa[j];}
			} else ta[j]=aa[j];
		}
		result=aa[0](ta);
	}
	return result;
}
CSAct = new Object;
function CSClickReturn () {
	var bAgent = window.navigator.userAgent;
	var bAppName = window.navigator.appName;
	if ((bAppName.indexOf("Explorer") >= 0) && (bAgent.indexOf("Mozilla/3") >= 0) && (bAgent.indexOf("Mac") >= 0))
		return true; /* dont follow link */
	else return false; /* dont follow link */
}
/* -- Action Functions */
// Version 1.1. A Michael Ahgren action.
function CSRemoveIEbox(){
if (document.images&&navigator.userAgent.indexOf("MSIE")!=-1){
	for(i=0;i<document.links.length;i++){
		target=eval("document.links[i]")
		target.onfocus=blurHandler
		}
	}
}
function blurHandler(){
	obj=window.event.srcElement
    if(obj.tagName == "A"||obj.tagName=="AREA") obj.blur()
}

/* FORMULARIOS */
function AccionOp(accionStr) {
	document.DATOS.op.value	= accionStr;
	document.DATOS.submit();
}

function ComentariosOp(accionStr,idStr) {
    document.COMENTARIOS.op.value=accionStr;
    document.COMENTARIOS.comentarioId.value=idStr;
    document.COMENTARIOS.submit();
}

/* Limitar numero de caracteres */
function checkInputSize(which, maxsize){
	which.value = which.value.substring(0, maxsize);
}
// FLASH
function makeFlashObj(file, name, width, height, bgcolor, flashVars) {
    msg = "";
    if (width == "") {
        widthStr = "";
    }
    else {
        widthStr = " width='" + width + "' ";
    }
    if (height == "" ) {
        heightStr = "";
    }
    else {
        heightStr = " height='" + height + "' ";
    }
    msg = '<OBJECT ';
    msg += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
    msg += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ';
    msg +=  widthStr + heightStr;
    msg += 'id="' + name + '" align="middle" >';
    msg += '\n<param name="allowFullScreen" value="true" />';
    msg += '\n<param name="bgcolor" value="' + bgcolor + '" />';
    msg += '\n<param name="allowScriptAccess" value="sameDomain" />';
    msg += '\n<param name="movie" value="' + file + '" />';
    msg += '\n<param name="quality" value="high" />';
	msg += '\n<param name="wmode" value="transparent" />';
    msg += '\n<param name="FlashVars" value="' + flashVars + '" />';
    msg += '\n<embed src="' + file + '" id="' + name + '" name="' + name + '"';
    msg += ' allowFullScreen="true" ';
    msg += ' quality="high" wmode="transparent" ';
    msg += widthStr + heightStr + 'bgcolor="' + bgcolor + '" align="middle" ';
    msg += 'allowScriptAccess="sameDomain" type="application/x-shockwave-flash" ';
    msg += 'FlashVars="' + flashVars + '" ';
    msg += 'pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    msg += '</OBJECT>';

    //ZZ alert(msg);
    document.write(msg);
}
/*
*
*/
function changeBackImage(id,imagen) {
    newImage = "url(" + imagen + ")";
    document.getElementById(id).style.backgroundImage = newImage;
}

/**
* MASCARA EN INPUTS PARA ENTRADA DE TEXTO
*
* MaskInput(field: HTMLInputElement, mask: String): void
*     		Adds the mask to a field.
*     field
*         field that will receive the mask
*     mask
*         mask that will be applied
* DEFAULT RULES
*     * 	a = A-Z and 0-9
*     * 	A = A-Z, accents and 0-9
*     * 	9 = 0-9
*     * 	C = A-Z and accents
*     * 	c = A-Z
*     * 	* = Any character
* Special rules
*     * 	E = (Except) exception
*     * 	O = (Only) only
*
* MASK CREATION
* 	Simple masks:
* 	In this kind of mask the user can't type more characters than the amount of
* 	characters in the mask.
*         Example:
*         telephone = (99)9999-9999
*         date = 99/99/9999
*
* 	Special mask "rule^exceptions":
* 	This kind of mask is composed ty two parts, separated by "^",
* 	the left side specified the rule and the right one, the exceptions for the selected rule.
*
*         Example:
*         9^abc = The rule is to accept only numbers "9" and the exception are the characters a, b and c
*         c^123 = Accepts only a-z characters and the exception are the numbers 1, 2 and 3
*
* 	Use of the special rules:
* 	it's similar to the special mask, but the left side has a different meaning,
* 	can be "E" (any character, except...) and "O" (only...)
*         Example:
*         E^abc: Accepts any character, except a, b and c
*         O^123: Only allows the characters 1, 2 e 3
*
* EXAMPLE
*     var f = document.forms[0];
*     MaskInput.apply(f.fone, "(99)9999-9999");
*     MaskInput.apply(f.data, "99/99/9999");
*     MaskInput.apply(f.etc, "Cc99-*C");
*     MaskInput.apply(f.except, "E^abc");
*     MaskInput.apply(f.only, "O^abc");
*     MaskInput.apply(f.letra, "C^");
*     MaskInput.apply(f.letra2, "C^ ");
*     MaskInput.apply(f.numero, "9^abc");
*/

aE = function( o, e, h ){ var x='addEventListener'; o[x] ? o[x]( e, h, false ) : o[x='attachEvent'] ? o[x]( 'on' + e, h ) : o[ 'on' + e ] = h; }

MaskedInput = {
    patterns: { '1': /[A-Z]/i, '2': /[0-9]/, 4: /[\xC0-\xFF]/i, '8': /./},
    rules: { 'a': 3, 'A': 7, '9': 2, 'C':5, 'c': 1, '*': 8 },

	check: function( e ){
		function validChar( c, rule ){
			var r = MaskedInput.rules[rule] || 0;
	  		for( var i = 1; i <= r; i<<=1 )
				if( r & i && MaskedInput.patterns[i].test( c ) )
					break;
			return i <= r || c == rule;
		}
		var f, k, mC, r, m = ( f = ( e.target || e.srcElement ) ).getAttribute( 'mask' ), c = String.fromCharCode( k = isNaN( e.which ) ? e.keyCode : e.which ), l = f.value.length;
		return Boolean( ( /^(0|8)$/.test( k ) ? true : ( r = /^(.)\^(.*)$/.exec( m ) ) && ( r[0] = r[2].indexOf( c ) + 1 ) + 1 ? r[1] == 'O' ? r[0] : r[1] == 'E' ? !r[0] : validChar( c, r[1] ) || r[0] : ( l = ( f.value += m.substr( l, ( r = /[A|9|C|\*]/i.exec( m.substr( l ) ) ) ? r.index : l ) ).length ) < m.length && validChar( c, m.charAt( l ) ) ) || ( ( e.returnValue = false ) || e.preventDefault && e.preventDefault() ) )
	},

	apply: function( field, mask ){
        if (field != undefined){
            field.setAttribute( 'mask', mask );
            for( var i in { keypress: 0, keyup: 1 } )
                aE( field, i, this.check );
        }
	}
}

/**
*
*/
function frmMarcaValidar(obj,bool){
    if (!bool){
        obj.className='notvalidated';
    }
    else {
        obj.className='validated';
    }
}

//
function validaFormElement(ele){
  obj = document.getElementById(ele);
  if (obj.value.trim() == '') {
    frmMarcaValidar(obj,false);
    res = false;
    obj.focus();
    return false;
  }
  else {
    frmMarcaValidar(obj,true);
    return true;
  }
}

/**
*
*/
function checkDniNieCif(a){
    //Entra un this desde el input (Ej: )
    var temp=a.value.toUpperCase();
    var cadenadni="TRWAGMYFPDXBNJZSQVHLCKET";
    var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
    var validated = false;

    if (temp!==''){
        /*No es un CIF ni un NIE, es un DNI*/
        if (!/^[ABCDEFGHKLMNPQSX]/.test(temp)){
            posicion = a.value % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
            letra = cadenadni.charAt(posicion);
            //Es menos de 9 dígitos, añadimos la letra
            if (!/^[A-Za-z0-9]{9}$/.test(temp)){
                //alert('Tienes menos de 9 dígitos en el DNI');
                //a.value=a.value+letra ;
                validated = false;
            }
            else {
                //Tiene los 9 dígitos, comprobamos si la letra esta bien
                posicion = a.value.substring(8,0) % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
                letra = cadenadni.charAt(posicion);
                var letradni=temp.charAt(8);
                validated = true;
                if (letra != letradni) {
                    //alert("La Letra del DNI no es correcta."+letradni+" es distinta de "+letra);
                    validated = false;
                }
            }
        }
        else {
            //Es un NIE o un CIF
            if (/^[X]/.test(temp)){
                //Es un NIE
                var temp1=temp.substr(1,8);
                posicion = temp1 % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
                letra = cadenadni.substring(posicion,posicion+1);
                if (!/^[A-Za-z0-9]{9}$/.test(temp)){
                    //Es menos de 9 dígitos, añadimos la letra
                    //alert('Tienes menos de 9 dígitos en el NIE');
                    //a.value=a.value+letra ;
                    validated = false;
                }
                else{
                    //Tiene los 9 dígitos, comprobamos si la letra esta bien
                    var temp1=temp.substr(1,7);
                    posicion = temp1 % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
                    letra = cadenadni.charAt(posicion);
                    var letranie=temp.charAt(8);
                    validated = true;
                    if (letra != letranie){
                        //alert("La Letra del NIE no es correcta."+letranie+" es distinta de "+letra);
                        validated = false;
                    }
                }
            }
            else{
                //Es un CIF
                var cifcontrol = 0;
                for( i = 2; i <= 6; i += 2 ){
                    cifcontrol = cifcontrol + v1[ parseInt(temp.substr(i-1,1)) ];
                    cifcontrol = cifcontrol + parseInt(temp.substr(i,1));
                };
                cifcontrol = cifcontrol + v1[ parseInt(temp.substr(7,1)) ];
                cifcontrol = (10 - ( cifcontrol % 10));
                if (!/^[A-Za-z0-9]{9}$/.test(temp)){
                    //Es menos de 9 dígitos, añadimos el dígito de control
                    //alert('Tienes menos de 9 dígitos en el CIF');
                    //a.value=a.value+cifcontrol;
                    validated = false;
                }
                else{
                    validated = true;
                    if (cifcontrol!=temp.substr(8,1)) {
                        //alert ('El dígito de control del CIF no es correcto.El correcto es '+cifcontrol);
                        validated = false;
                    }
                }
            }
        }
    }
    //
    frmMarcaValidar(a,validated);
    //
    a.value=a.value.toUpperCase();
    //

    if (validated) return true
    else return false;
}

/**
*
*/
function digitoControl(cadena){
   var cifras = new Array(1,2,4,8,5,10,9,7,3,6);
   var chequeo = 0;
   for (var i=0; i < cifras.length; i++){
    chequeo += parseInt(cadena.charAt(i)) * cifras[i];
   }
   chequeo = 11 - (chequeo % 11);
   if (chequeo == 11) {chequeo = 0;}
   if (chequeo == 10) {chequeo = 1;}
   return chequeo;
}

/**
*
*/
function checkCuentaBanco(obj){
    var validated = false;
    var temp = obj.value;
    // formato:
    // 0000 0000 00 0000000000
    // 4 dígitos: Código del Banco
    // 4 dígitos: Código de la sucursal
    // 2 dígitos: Dígito de control
    // 10 dígitos: número de cuenta del cliente.

    if (!/^[ 0-9]{23}$/.test(temp)){
    }
    else {
        banco = temp.substr(0,4);
        sucursal = temp.substr(5,4);
        dc = temp.substr(10,2);
        cuenta = temp.substr(13,10);
        if (banco.length == 4 && cuenta.length == 10 ){
            digit1 = digitoControl("00" + banco + sucursal);
            digit2 = digitoControl(cuenta);
            dcCal = digit1 +""+ digit2;
            cuentaCal = banco + " " + sucursal + " " + dcCal + " " + cuenta;
            if (cuentaCal == obj.value){
                validated = true;
            }
        }
    }
    //
    frmMarcaValidar(obj,validated);
}


/**
* Codigo de la seguridad social
*/
function calculaSSDC(){
    NumSS=document.formcalculadora.NC.value;
    if (NumSS=="") {
        //alert("Por favor, introduzca todos los datos.");
        return ('');
    }
    if ((NumSS.length == 9) || (NumSS.length == 10)) {
        if (NumSS.substr(2,1) == 0) {
          NumSS = NumSS.substr(0,2)+NumSS.substr(3, NumSS.length-3)
        }
        dc = parseInt(NumSS) % 97;
        if (dc <= 9) {
            document.formcalculadora.DC.value="0"+ dc
        }
        if (dc > 9) {
            document.formcalculadora.DC.value=dc
        }
    }
    else {
       //alert("Por favor, introduzca 9 o 10 dígitos.");
    }
    /*result=result*10+iTemp;
    return(result);*/
}

/**
*
*/
function inputTextDefault(input,text){
  if(input.value == text){
    input.value = "";
    input.style.color='#333333';
  }
}

/**
*
*/
function inputPassDefault(input,text){
  if(input.value == text){
    input.value = "";
    //input.type = "password";
    //input.setAttribute('type', 'password');
    input.style.color='#333333';
  }
}

/**
*
*/
function ajaxFunction(url,objName){
  var xmlHttp;
  if (url != ''){
    if(window.XMLHttpRequest){
      // Firefox, Opera 8.0+, Safari
      xmlHttp = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
      // Internet Explorer
      try{
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e){
        try{
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
          //alert("Tu navegador no soporta AJAX!");
          //return false;
        }
      }
    }
    else{
      return false;
    }
    xmlHttp.onreadystatechange = function(){
      var objRef = window[objName];
      //if ('object' == typeof objRef){}
      switch(xmlHttp.readyState){
        case 0: break;
        case 1: break;
        case 2: break;
        case 3: objRef.loading(); break;
        case 4:
          objRef.responseText = xmlHttp.responseText;
          objRef.complete();
        break;
      }
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
  }
}

/**
* Capas
*/
function twShow(id,mode){
  if (mode==null) mode ='block';
  obj = document.getElementById(id);
  obj.style.display = mode;
}

function twHide(id){
  obj = document.getElementById(id);
  obj.style.display = 'none';
}

