/*
*	Lista de navegadores malnacidos
*/
var ie52mac = (
	navigator.userAgent.indexOf('MSIE 5.2') != -1 &&
	navigator.userAgent.indexOf('Mac') != -1
);
/*
*	Funciones DHTML compatibles con el estándar DOM
*/
// Función para obtener el valor de un estilo dado el id del elemento
function getStyleById(id, style)
{
	var elm = document.getElementById(id);
	return getStyle(elm, style);
}
// Función para obtener el valor de un estilo dado el elemento
function getStyle(elm, style)
{
	if(typeof(document.defaultView) == 'object') return document.defaultView.getComputedStyle(elm, null).getPropertyValue(style);
	else if(elm.currentStyle) return elm.currentStyle[style];
}
// Función para establecer el valor de un estilo dado el id del elemento
function setStyleById(id, style, value)
{
	var elm = document.getElementById(id);
	setStyle(elm, style, value);
}
// Función para establecer el valor de un estilo dado el elemento
function setStyle(elm, style, value)
{
	elm.style[style] = value;
}
/*
*	Función para inicializar diferentes módulos
*/
var window_onload = [];
window.onload = function()
{
	for(var i in window_onload) {
		eval(window_onload[i]);
	}
}
/*
*	Activar el boton del menú
*/
function MenuInit()
{
	if(typeof(activar) != 'undefined') {
		var elm = document.getElementById('menu' + activar + 'bot');
		elm.className = 'on';
	}
}
window_onload[window_onload.length] = 'MenuInit()';
/*
*	Funciones para Rollovers
*/
// Función para inicializar los rollovers
function RollInit()
{
	var imgs = document.getElementsByTagName('IMG');
	for(var i = 0; i != imgs.length; ++i) {
		if(/(\w+)ROLL$/.test(imgs[i].id)) {
			var roll_id = RegExp.$1;
			if(/(\w+)FOTO$/.test(roll_id)) {
				// ...
			} else {
				var elm = imgs[i];
				elm.img_over = new Image();
				elm.img_over.src = elm.src.replace(/(.gif|.jpg|.png)$/, '_over$1');
				elm.img_orig = new Image();
				elm.img_orig.src = elm.src;
				if(/(\w+)MENU$/.test(roll_id)) {
					elm.MyRollOver = RollOver;
					elm.MyRollOut = RollOut;
				} else {
					elm.onmouseover = RollOver;
					elm.onmouseout = RollOut;
				}
			}
		}
	}
}
window_onload[window_onload.length] = 'RollInit()';

// Función para hacer rollover de una imagen
function RollOver()
{
	this.src = this.img_over.src;
}
// Función para restaurar una imagen
function RollOut()
{
	this.src = this.img_orig.src;
}
function setOpacityById(id, alfa)
{
	var elm = document.getElementById(id);
	return setOpacity(elm, alfa);
};
function setOpacity(elm, alfa)
{
	if(alfa == 0) {
		elm.style.visibility = 'hidden';
	} else if(elm.style.visibility == 'hidden') {
		elm.style.visibility = 'inherit';
	}
	if(typeof(elm.style.opacity) != 'undefined') elm.style.opacity = (alfa == 1) ? '0.999' : alfa;
	else if(typeof(elm.style.MozOpacity) != 'undefined') elm.style.MozOpacity = (alfa == 1) ? '0.999' : alfa;
	else if(typeof(elm.style.KhtmlOpacity) != 'undefined') elm.style.KhtmlOpacity = alfa;
	else if(!ie52mac && typeof(elm.style.filter) != 'undefined') elm.style.filter = (alfa == 1) ? '' : 'alpha(opacity=' + (alfa*100) + ')';
};
function BlendById(id, alfa0, alfa1)
{
	var elm = document.getElementById(id);
	return Blend(elm, alfa0, alfa1);
};
var blend_elm = null;
var blend_alfa1 = 0;
var blend_tmr = null;
var blend_t = 50;
function Blend(elm, alfa0, alfa1)
{
	if(blend_tmr) {
		clearTimeout(blend_tmr);
		blend_tmr = null;
	}
	if(blend_elm) {
		setOpacity(blend_elm, blend_alfa1);
	}
	blend_elm = elm;
	blend_alfa1 = alfa1;
	blend_tmr = setTimeout('cicloBlend(' + alfa0 + ')', blend_t);
};
function cicloBlend(alfa0)
{
	blend_tmr = null;
	if(blend_elm) {
		setOpacity(blend_elm, alfa0);
		var tmp = 0.333 * (blend_alfa1 - alfa0);
		if(Math.abs(tmp) <= 0.01) {
			setOpacity(blend_elm, blend_alfa1);
			blend_elm = null;
		} else {
			alfa0 += tmp;
			blend_tmr = setTimeout('cicloBlend(' + alfa0 + ')', blend_t);
		}
	}
};
/*
	Función para abrir una ventana. Puede recibir los siguientes parámetros:

	url	-> Página web que mostrará la ventana. Por defecto página en blanco. Ejemplo: 'aviso.phpl'.
	target	-> Ventana en la que se abrirá la url. Por defecto en una nueva ventana cada vez. Ejemplo: '_blank'.
	width	-> Ancho en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 300
	height	-> Alto en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 125
	left	-> Distancia en píxeles al borde izquierdo de la pantalla. Por defecto centrada horizontalmente. Ejemplo: 100
	top	-> Distancia en píxeles al borde superior de la pantalla. Por defecto centrada verticalmente. Ejemplo: 100
	resizable	-> Indica si el usuario puede modificar el tamaño de la ventana. Por defecto no. Ejemplo: 'yes' o true
		Valores posibles: 'yes', 'no', '1', '0', true, false.
	scrollbars	-> Indica si la ventana tendrá barras de scroll. Por defecto no. Ejemplo: 'no' o false
		Valores posibles: 'yes', 'no', '1', '0', true, false.

	Poner un parámetro a null o no pasarlo es lo mismo.

	Ejemplo:

	// Abrir aviso.phpl en una nueva ventana, con tamaño 250x125, centrada horizontalmente
	// pero a 100 píxeles del borde superior.

	AbrirVentana('aviso.php', '_blank', 250, 125, null, 100);
*/
function AbrirVentana(url, target, width, height, left, top, resizable, scrollbars)
{
	if(typeof(url) == 'undefined' || url == null) url = '';
	if(typeof(target) == 'undefined' || target == null) target = '';

	if(typeof(width) == 'undefined' || width == null) width = 275;
	if(typeof(height) == 'undefined' || height == null) height = 275;

	if(typeof(window.screen) == 'undefined') {
		var sw = 800;
		var sh = 600;
	} else {
		var sw = window.screen.width;
		var sh = window.screen.height;
	}

	if(typeof(left) == 'undefined' || left == null) left = Math.round(0.5 * (sw - width));
	if(typeof(top) == 'undefined' || top == null) top = Math.round(0.5 * (sh - height));

	if(typeof(resizable) == 'undefined' || resizable == 'no' || !resizable) resizable = 0;
	else resizable = 1;

	if(typeof(scrollbars) == 'undefined' || scrollbars == 'no' || !scrollbars) scrollbars = 0;
	else scrollbars = 1;

	var win = window.open(url, target, 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',directories=0,location=0,menubar=0,resizable=' + resizable +',scrollbars=' + scrollbars + ',status=0,toolbar=0');
	win.focus();
}
/*
*	Funciones auxiliares comúnmente usadas
*/
// Función para mostrar un elemento
function Muestra(id)
{
	setStyleById(id, 'visibility', 'inherit');
}
// Función para ocultar un elemento
function Oculta(id)
{
	setStyleById(id, 'visibility', 'hidden');
}
// Función para ir a una url
function IrA(url)
{
	location.href = url;
};
// Función para los combos que saltan a urls
function Saltar(elm)
{
	var url = elm[elm.selectedIndex].value;
	if(url == '') elm.selectedIndex = 0;
	else location.href = url;
}
/*
*	Funciones para chequear formularios
*/
var errores = '';
function ValidarRequerido(campo, titulo, formulario)
{
	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);

	if(form[campo].value == '') {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#dae6fa');
		setStyle(form[campo], 'color', '#000');

	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};
function ValidarEmail(campo, titulo, formulario)
{
	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);
	if(form[campo].value == '' || !isEmail(form[campo].value)) {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#dae6fa');
		setStyle(form[campo], 'color', '#000');
	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};
// Función para comprobar el formato de una dirección de correo
function isEmail(str) {
	// are regular expressions supported?
	var supported = 0;
	if(window.RegExp) {
		var tempStr = 'a';
		var tempReg = new RegExp(tempStr);
		if(tempReg.test(tempStr)) supported = 1;
	}
	if(!supported) return (str.indexOf('.') > 2) && (str.indexOf('@') > 0);
	var r1 = new RegExp('(@.*@)|(\\.\\.)|(@\\.)|(^\\.)');
	var r2 = new RegExp('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
	return (!r1.test(str) && r2.test(str));
};
// Función para comprobar el formato de la fecha: dia/mes/año (año >= 1970)
function CheckDate(fecha){
	if(fecha == '' || fecha == null) return(2);
	fecha_date = fecha.match(/^(\d+)\/(\d+)\/(\d+)$/);
	if(fecha_date == '' || fecha_date == null ) return(0);
	fecha_dia = Number(fecha_date[1]);
	fecha_mes = Number(fecha_date[2]);
	fecha_ano = Number(fecha_date[3]);
	if(isNaN(fecha_dia) || isNaN(fecha_mes) || isNaN(fecha_ano)) return(0);
	if(fecha_ano > 70 && fecha_ano <= 99 ) fecha_ano = fecha_ano + 1900
	if(fecha_ano < 1970 || fecha_ano > 9999) return(0);
	if(fecha_ano % 4 == 0) bisiesto = true; // año bisiesto
	else bisiesto = false;
	if(fecha_mes == 2) {
		if(!bisiesto) {
			if(fecha_dia > 28 || fecha_dia < 1) return (0);
		} else {
			if(fecha_dia > 29 || fecha_dia < 1) return (0);
		}
	} else if(fecha_mes==1 || fecha_mes==3 || fecha_mes==5 || fecha_mes==7 || fecha_mes==8 || fecha_mes==10 || fecha_mes==12) {
		if(fecha_dia > 31 || fecha_dia < 1) return (0);
	} else if(fecha_mes==9 || fecha_mes==4 || fecha_mes==6 || fecha_mes==11) {
		if(fecha_dia > 30 || fecha_dia < 1) return (0);
	} else return (0);
	return(1);
};

function CheckTime(str)
{
	hora = str;
	if (hora=='') return(0);
	if (hora.length > 5) return(0);
	a = hora.charAt(0); //<=2
	b = hora.charAt(1); //<4
	c = hora.charAt(2); //:
	d = hora.charAt(3); //<=5
	if ((a==2 && b>3) || (a>2)) return(0);
	if (d>5) return(0);
	if (c!=':') return(0);
	return(1);
}

function replaceAll( str, from, to ) {
    var idx = str.indexOf( from );

    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }

    return str;
}

function filtrar_proceso_seleccion(pag,cada_entidad)
{
	var provincia;
	var perfil;
	var entidad;
	var area;
	entidad = document.forms["frm_procesos_seleccion"].entidad.value;
	provincia = document.forms["frm_procesos_seleccion"].provincia.value;
	perfil = document.forms["frm_procesos_seleccion"].perfil.value;
	area = document.forms["frm_procesos_seleccion"].area.value;

	$('#capa_procesos_seleccion').load('capa_procesos_seleccion.php', {cada_entidad:cada_entidad, entidad_sel: entidad, provincia_sel: provincia, area_sel: area, perfil_sel: perfil, p:pag});
}

function filtrar_proceso_seleccion_nacional(pag)
{
	var entidad;
	var perfil;
	var provincia;
	var area;
	pais=-10;//Esto es para que pueda usar lo mismo tanto para nacional como para intern

	entidad = document.forms["frm_procesos_nacional"].entidad.value;
	perfil = document.forms["frm_procesos_nacional"].perfil.value;
	provincia = document.forms["frm_procesos_nacional"].provincia.value;
	area = document.forms["frm_procesos_nacional"].area.value;
//	alert('entidad:'+entidad+'\nPerfil:'+perfil+'\nProvincia:'+provincia);

	$('#capa_procesos_trabajo_nacional').load('capa_procesos_nacional.php', { entidad_sel: entidad, perfil_sel: perfil, provincia_sel: provincia, p: pag, pais_sel: pais,area_sel:area});

}

function filtrar_proceso_seleccion_internacional(pag)
{
	var entidad;
	var perfil;
	var pais;
	provincia=-10;

	entidad = document.forms["frm_procesos_internacional"].entidad.value;
	perfil = document.forms["frm_procesos_internacional"].perfil.value;
	pais = document.forms["frm_procesos_internacional"].pais.value;
	area = document.forms["frm_procesos_internacional"].area.value;

	$('#capa_procesos_trabajo_internacional').load('capa_procesos_internacional.php', { entidad_sel: entidad, perfil_sel: perfil, pais_sel: pais, p: pag, provincia_sel: provincia,area_sel:area});
}

function filtrar_sector_bancario_provincias()
{
	var entidad;
	var perfil;
	var provincia;
	var area;
	entidad = document.forms["sector_bancario_provincias"].entidad.value;
	perfil = document.forms["sector_bancario_provincias"].perfil.value;
	provincia = document.forms["sector_bancario_provincias"].provincia.value;
	area = document.forms["sector_bancario_provincias"].area.value;
	$('#capa_sector_bancario_provincias').load('capa_sector_bancario_provincias.php', { entidad_sel: entidad, perfil_sel: perfil, provincia_sel: provincia,area_sel:area});
}


function mensaje_votar_correcto()
{
	var id_encuesta;
	var respuesta;
	for(i=0;i<document.encuesta.encuesta.length;i++)
        if(document.encuesta.encuesta[i].checked)
        respuesta=document.encuesta.encuesta[i].value;

	id_encuesta = document.forms["encuesta"].numero_encuesta.value;
//alert('Id_Respuesta: '+respuesta);
	$('#capa_encuesta').load('resultados_encuestas.php', { numero_encuesta: id_encuesta, encuesta:respuesta});
}

function filtrar_provincia(pag)
{
//alert(pag);
//document.getElementById("bloque2").style.display= " none";
	$('#bloque2').load('capa_provincias.php', { banco: pag});

}






// Impresionante sprintf en js
  sprintfWrapper = {

      init : function () {

          if (typeof arguments == "undefined") { return null; }
          if (arguments.length < 1) { return null; }
          if (typeof arguments[0] != "string") { return null; }
          if (typeof RegExp == "undefined") { return null; }

          var string = arguments[0];
          var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
          var matches = new Array();
          var strings = new Array();
          var convCount = 0;
          var stringPosStart = 0;
          var stringPosEnd = 0;
          var matchPosEnd = 0;
          var newString = '';
          var match = null;

          while (match = exp.exec(string)) {
              if (match[9]) { convCount += 1; }

              stringPosStart = matchPosEnd;
              stringPosEnd = exp.lastIndex - match[0].length;
              strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

              matchPosEnd = exp.lastIndex;
              matches[matches.length] = {
                  match: match[0],
                  left: match[3] ? true : false,
                  sign: match[4] || '',
                  pad: match[5] || ' ',
                  min: match[6] || 0,
                  precision: match[8],
                  code: match[9] || '%',
                  negative: parseInt(arguments[convCount]) < 0 ? true : false,
                  argument: String(arguments[convCount])
              };
          }
          strings[strings.length] = string.substring(matchPosEnd);

          if (matches.length == 0) { return string; }
          if ((arguments.length - 1) < convCount) { return null; }

          var code = null;
          var match = null;
          var i = null;

          for (i=0; i<matches.length; i++) {

              if (matches[i].code == '%') { substitution = '%' }
              else if (matches[i].code == 'b') {
                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
                  substitution = sprintfWrapper.convert(matches[i], true);
              }
              else if (matches[i].code == 'c') {
                  matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
                  substitution = sprintfWrapper.convert(matches[i], true);
              }
              else if (matches[i].code == 'd') {
                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
                  substitution = sprintfWrapper.convert(matches[i]);
              }
              else if (matches[i].code == 'f') {
                  matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
                  substitution = sprintfWrapper.convert(matches[i]);
              }
              else if (matches[i].code == 'o') {
                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
                  substitution = sprintfWrapper.convert(matches[i]);
              }
              else if (matches[i].code == 's') {
                  matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
                  substitution = sprintfWrapper.convert(matches[i], true);
              }
              else if (matches[i].code == 'x') {
                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                  substitution = sprintfWrapper.convert(matches[i]);
              }
              else if (matches[i].code == 'X') {
                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                  substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
              }
              else {
                  substitution = matches[i].match;
              }

              newString += strings[i];
              newString += substitution;

          }
          newString += strings[i];

          return newString;

      },

      convert : function(match, nosign){
          if (nosign) {
              match.sign = '';
          } else {
              match.sign = match.negative ? '-' : match.sign;
          }
          var l = match.min - match.argument.length + 1 - match.sign.length;
          var pad = new Array(l < 0 ? 0 : l).join(match.pad);
          if (!match.left) {
              if (match.pad == "0" || nosign) {
                  return match.sign + pad + match.argument;
              } else {
                  return pad + match.sign + match.argument;
              }
          } else {
              if (match.pad == "0" || nosign) {
                  return match.sign + match.argument + pad.replace(/0/g, ' ');
              } else {
                  return match.sign + match.argument + pad;
              }
          }
      }
  }

  sprintf = sprintfWrapper.init;

   function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
 }



 /******************Comprobar compra para La casa del libro*********************************/

 function comprobar_compra (cantidad)
{
	if (cantidad=="")
	{
		alert("Debes de añadir algún libro a la cesta de la compra para poder continuar");
	}
	else
		document.location.href=cantidad;


}









function filtrar_area2(area_sel,perfil_sel,contador)
{

	//alert(contador);
	/*if(area_sel=="")
		area_sel=-5;
	if(perfil_sel=="")
		perfil_sel=-5;
*/
	$('#myDiv_line_'+contador).load('capa_area_alerta_exp.php', {area:area_sel, perfil: perfil_sel, contador_sel: contador});
}



function filtrar_perfil2(area_sel,perfil_sel,contador)
{
/*	if(area_sel=="")
		area_sel=-5;
	if(perfil_sel=="")
		perfil_sel=-5;*/

	$('#myDiv_line_'+contador).load('capa_perfil_alerta_exp.php', {area:area_sel, perfil: perfil_sel, contador_sel: contador});
}



/***********************************************************************/


function AbrePrivacidad()
{
	AbrirVentana("privacidad.php", "privacidad", 640, 490);
};



// Variable de Conteo de lineas
var lineCount = new Array();

/**
 * Agrega una linea de datos a un formulario
 * @param string div El ID del div objetivo donde se agrega una linea
 * @param string line El ID del div que contiene la linea a agregar
 * @param string f Funcion extra para pasarle a los eventos
 */
function addFormLine(div, line, f)
{



	var f = (f == null) ? "" : f;
	lineCount[div] = lineCount[div] == null ? 1 : lineCount[div] + 1;
	var mySelf = div + "_line_" + lineCount[div];
//	var mySelf ="myLine_" + lineCount[div];
	var myNum = lineCount[div];
	var divTarget = document.getElementById(div);
	var divLine = document.getElementById(line).innerHTML;
	var divTitle = document.getElementById(line).getAttribute('title');
	var newDiv = document.createElement('div');
	newDiv.className = 'row';
	newDiv.setAttribute('id', mySelf);
	divLine = divLine.replace(/mySelf/g, mySelf);
	newDiv.innerHTML = divLine;
	newDiv.innerHTML += "<td><div class=\"cell\"><img title='Eliminar experiencia' style=\"cursor: pointer;\" src=\"images/remove.gif\" border=\"0\" onclick=\"removeFormLine(\'" + mySelf + "\'); " + f + "\"></div></td>";

	/*if (divTitle != null && divTarget.hasChildNodes() == false){
		var titles = divTitle.split(",");
		var newTitle = document.createElement('div');
		newTitle.className = 'row';
		for (i = 0; i < titles.length; ++i){
			var titleSize = titles[i].match(/\(\w+\)/,'');
			titleSize = titleSize[0].replace(/[\(\)]/g,'');
			var titleName = titles[i].replace(/\(\w+\)/,'');
			newTitle.innerHTML += "<div class=\"title\" style=\"width: " + titleSize + "px;\">" + titleName + "</div>";
		}
		divTarget.appendChild(newTitle);
		divTarget.setAttribute('cab', '1');
	}*/
	divTarget.appendChild(newDiv);

	}

/**
 * Elimina una linea de un formulario
 * @param string div El ID del div que se quiere eliminar
 */
function removeFormLine(div)
{
	//alert(div);
	var parentName = div.replace(/_line_\w+/g, '');
	var divParent = document.getElementById(parentName);
	var divTarget = document.getElementById(div);
	var hasTitle = divParent.getAttribute('cab');
	divParent.removeChild(divTarget);
	if (hasTitle != null && divParent.childNodes.length == 1){
		divParent.innerHTML = "";
	}
}
  //-->


 function mostrar_experiencia(experiencia)
 {


 	if(experiencia==1)
 	{

		setStyleById('capa_experiencia', 'display', 'block');

			addFormLine('myDiv', 'myLine');

 	}

 	else

 	{
		setStyleById('capa_experiencia', 'display', 'none');
 	}



 }


// Funcion para establecer el valor de un estilo a una clase
function setStyleByClass(t,c,p,v){
  var elements;
  if(t == '*') {
    // '*' not supported by IE/Win 5.5 and below
    elements = (ie) ? document.all : document.getElementsByTagName('*');
  } else {
    elements = document.getElementsByTagName(t);
  }
  for(var i = 0; i < elements.length; i++){
    var node = elements.item(i);
    for(var j = 0; j < node.attributes.length; j++) {
      if(node.attributes.item(j).nodeName == 'class') {
        if(node.attributes.item(j).nodeValue == c) {
          eval('node.style.' + p + " = '" +v + "'");
        }
      }
    }
  }
}