/**
*	Generic javscript to include in all of the new infojobs jsp pages.
*	This js gets automatically included in jsps using the ij:header tag 
*	This js joins this old js files in one:
*	 - func_longitud_01.js
*	 - func_mensajes.js
*	 - func_setcookie_01.js
*	 - func_trim_01.js
*	 - func_banner.js 
*
*	Once compresseed using yuicompressor.jar this file weights 6k
*/

/** func_logintud_01.js */
function longitud(input, nombre, minima, maxima, bMostraMissatge)
{
	/* bMostraMissatge és un paràmetre optatiu que fa que s'inclogui o no el nou missatge d'error a la pàgina. Per defecte es true */
	if (typeof(bMostraMissatge) == 'undefined')
		bMostraMissatge = true;
		
	var length = longitudReal(input.value);
	if (length < minima) {
		if (minima > 1) {
			addGlobalErrorMessage(input,bMostraMissatge?"MIN_CHARS":"",nombre,minima);
		} else {
			addGlobalErrorMessage(input,bMostraMissatge?"NO_VACIO":"",nombre);
		}
		return false;
	}

	if (length > maxima) {
		diferencia = length - maxima;
		addGlobalErrorMessage(input,bMostraMissatge?"MAX_CHARS":"",nombre,maxima,diferencia);
		return false;
	}
	return true;
}

function isLongitudOK(input, minima, maxima){
	/* bMostraMissatge és un paràmetre optatiu que fa que s'inclogui o no el nou missatge d'error a la pàgina. Per defecte es true */
	var length = longitudReal(input.value);
	if (length < minima) {
		return false;
	}
	if (length > maxima) {
		return false;
	}
	return true;
}

function longitudReal(text) {
	var length = 0;
	for (var i = 0; i < text.length; ++i) {
		// If the browser interprets carriage return as character 10, instead of the pair 13 + 10, increment length.
		// This is necessary because Java will interpret carriage return as two characters anyway; at least in Windows.
		if (text.charCodeAt(i) == 10 /* carriage return */ && (i == 0 || text.charCodeAt(i - 1) != 13 /* line feed */)) {
			++length; // The extra \r some browsers don't count.
		}
		++length;
	}
	return length;
}

function sinPunto(nombreArchivo){
	for(var i=0; i < nombreArchivo.value.length; i++){
		if(nombreArchivo.value.charAt(i)=="."){
			addGlobalErrorMessage(nombreArchivo,"SIN_PUNTO");
			return false;
		}
	}
	return true;
}

function sinCaracteresEspeciales (nombreArchivo){
	var codCaracter=0;
	var caracter='';

	for (var i=0;i< nombreArchivo.value.length;i++){
		codCaracter=nombreArchivo.value.charCodeAt(i);
		caracter=nombreArchivo.value.charAt(i);
		if((codCaracter<48 || codCaracter>122 || (codCaracter>90 && codCaracter<97)||(codCaracter>57 && codCaracter<65)) && caracter!='_' && caracter!='-'){
			addGlobalErrorMessage(nombreArchivo,"CHARS_INVALIDOS");
			return false;
		}
	}
	return true;
}
function sinCaracteresEspeciales_bis (input,nombre){
	var caracter='';
	
	for (var i=0;i< input.value.length;i++){
		caracter=input.value.charAt(i);
		if((caracter == "\"" || caracter == "'" || caracter == "<" || caracter == ">")){
			addGlobalErrorMessage(input,"CHARS_INVALIDOS_2",nombre);
			return false;
		}
	}
	return true;
}
function primerCaracterNoBlanco (input,tipo){
	if (input.value.charCodeAt(0) == 32 ){
		addGlobalErrorMessage(input,tipo);
		return true;
	}
}

/** func_mensajes.js
var alertaMsg=new Object();
alertaMsg["CAMPOS_DISTINTOS"]=getIJMessage("campos_distintos");
alertaMsg["MIN_CHARS"]=getIJMessage("min_chars");
alertaMsg["NO_VACIO"]=getIJMessage("no_vacio");
alertaMsg["MAX_CHARS"]=getIJMessage("max_chars");
alertaMsg["EMAIL_INVALIDO_@"]=getIJMessage("email_invalido_@");
alertaMsg["EMAIL_USUARIO_CHARS_INVALIDOS"]=getIJMessage("email_usuarios_chars_invalidados");
alertaMsg["EMAIL_DOMINIO_INVALIDO"]=getIJMessage("email_dominio_invalido");
alertaMsg["EMAIL_"]=getIJMessage("email_");
alertaMsg["EMAIL_USUARIO_INVALIDO"]=getIJMessage("email_usuario_invalido");
alertaMsg["EMAIL_IP_INVALIDO"]=getIJMessage("email_ip_invalido");
alertaMsg["DOMINIO_INVALIDO"]=getIJMessage("dominio_invalido");
alertaMsg["EMAIL_DOMINIO_CORTO"]=getIJMessage("email_dominio_corto");
alertaMsg["EMAIL_DOMINIO_FALTA"]=getIJMessage("email_dominio_falta");
alertaMsg["EMAIL_INVALIDO"]=getIJMessage("email_invalido");
alertaMsg["FALTA_SPEC_EN_CAMPO"]=getIJMessage("falta_spec_en_campo");
alertaMsg["SEL_VALOR_EN_CAMPO"]=getIJMessage("set_valor_en_campo");
alertaMsg["OPCION_INVALIDA_SALARIOS"]=getIJMessage("opcion_invalida_salarios");
alertaMsg["SALARIOS_TIPOS_DIFERENTES"]=getIJMessage("salarios_tipos_diferentes");
alertaMsg["SALARIO_MAX_MENOR"]=getIJMessage("salario_max_menor");
alertaMsg["CV_DATOS_PERSONALES_NOM"]=getIJMessage("cv_datos_personales_nom");
alertaMsg["CV_DATOS_PERSONALES_TEL"]=getIJMessage("cv_datos_personales_tel");
alertaMsg["CV_DATOS_PERSONALES_MAIL"]=getIJMessage("cv_datos_personales_mail");
alertaMsg["SOLO_NUMEROS"]=getIJMessage("solo_numeros");
alertaMsg["FALTA_OPCION"]=getIJMessage("falta_opcion");
alertaMsg["SEL_ELEMENTOS_MAX"]=getIJMessage("sel_elementos_max");
alertaMsg["URL_SIN_HTTP"]=getIJMessage("url_sin_http");
alertaMsg["PRIV_NORMAL_NO_OCULTAR"]=getIJMessage("priv_normal_no_ocultar");
alertaMsg["PRIV_MAX_NO_VISIBLE"]=getIJMessage("priv_max_no_visible");
alertaMsg[""]="";*/

// The parameter id identifies one of the String from alertaMsg-object.
// The function accepts a variable number of parameters. Extra passed parameter-values are
// used to replace [param_x] in alerta-Strings
function addGlobalErrorMessage(input,id) {
	var theMsg=getMessageString(id);
	if (theMsg) {
		// for each parameter passed, replace [param_x]
		for(var i=2;i<arguments.length;i++) {
			var regExpParam=new RegExp("\\[param_"+(i-1)+"]");
			theMsg=theMsg.replace(regExpParam,arguments[i]);
		}
	
		addErrorMessage(input,theMsg);
	}
}
/** Se podria hacer un metodo especifico para xhtml, descomentar alertaMsg
 *  y así mantener la compatibilidad con coldFusion*/
// returns alerta message identified by messageId
function getMessageString(messageId) {
	return getIJMessage(messageId);
}


/** func_setcookie_01  only used in 15 page so may be we can remove from here */
/**
 * writes a cookie
 * paramters:
 * - nombre
 * - valor
 * - expirationDate (optional)
 * - path (optional)
 * - domain (optional
 * - secure (optional)
 */
function SetCookie(nombre, valor) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = nombre + "=" + escape (valor) +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path == null) ? "" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
} 

/** func_trim_01.js */
function trim(input){
	var string=input.value;
	var expresion=/^\s*(\w*)/gi;
	string = string.replace(expresion,"$1");
	expresion=/(\w*)\s*$/gi;
	string = string.replace(expresion,"$1");
	input.value=string;
}

String.prototype.trim = function () {		
	var string = this;
	var expresion=/^\s*(\w*)/gi;
	string = string.replace(expresion,"$1");
	expresion=/(\w*)\s*$/gi;
	string = string.replace(expresion,"$1");
	return string;
}
 
 
 /** func_banner.js */
 
 var document_write_buffer = '';

function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")? false: true;
}

function override() {
		//Trokola ya que la función getBanner llama a un javascript que printa el banner, pero printa el
		//el codigo html delbaner con un http:// harcodeado por lo que si la navegación es bajo https
		//saltaria el error de que existen elementos no seguros en la página 
		var DummyDocumentWriteVariable = '';
		document_write_buffer = '';
		document.writeOLD = document.write;
		document.write= function(x){
				document_write_buffer += x;
			}
}

function desOverride() {
	document.write = document.writeOLD;
}


//para que el parametro tile funcion bien en DART
//y no se repitan los banners de una posicion 
//tanto tile como transactionID deben unicos en la pagina
var now = new Date();
var millis = now.getTime();
var ad_rand=Math.floor(Math.random()*1000000);
var transId = ""+ (millis+ ad_rand);


function getBanner(atts) {
	//return;
 var creativeServerURL = "//level.infojobs.com";
 var attString = getAttributeString(atts);
 var noCache =getDgv();
 //Si hay session de usuario añadimos el parametro SSL=1
 if (customGetCookie("ENC_RND_STR") != null) {
 	attString += "&SSL=1";
 }else{
 	//Si no existe la session de usuario puede que tambien estemos navegando bajo ssl, por lo tanto comprobamos la URL actual a ver si es https
 	var loc = window.location;
 	if (window.location.href.substring(0, 5).toLowerCase() == "https"){
 		attString += "&SSL=1";
 	}
 }
 document.write(' <scr' + 'ipt language="JavaScript1.1" src="' + creativeServerURL + '/js.ng/Params.richmedia=no&amp;transactionID=' + transId + attString + '&amp;dgv=' + noCache + '" type="text/javascript">');
 document.write(' </scr' + 'ipt>');
 document.write(' <noscr' + 'ipt>');
 document.write(' <a href="' + creativeServerURL + '/click.ng/transactionID=' + transId + attString + '&amp;dgv=' + noCache +  '">');
 document.write('  <img src="' + creativeServerURL + '/image.ng/transactionID=' + transId + attString + '&amp;dgv=' + noCache +  '" alt="Banner">');
 document.write(' </a>');
 document.write(' </noscr' + 'ipt>');
}

function getBannerLogoHome(atts) {
	//return;
 	var creativeServerURL = "//level.infojobs.com";
 	var attString = getAttributeString(atts);
 	var noCache =getDgv();
	//Si hay session de usuario añadimos el parametro SSL=1
	if (customGetCookie("ENC_RND_STR") != null) {
	 	attString += "&SSL=1";
	}else{
		var loc = window.location;
 		//Si no existe la session de usuario puede que tambien estemos navegando bajo ssl, por lo tanto comprobamos la URL actual a ver si es https
	 	if (window.location.href.substring(0, 5).toLowerCase() == "https"){
	 		attString += "&SSL=1";
	 	}
	 }
 	document.write('	<a href="' + creativeServerURL + '/click.ng/transactionID=' + transId + attString + '&amp;dgv=' + noCache + '">');
 	document.write('		<img src="' + creativeServerURL + '/image.ng/transactionID=' + transId + attString + '&amp;dgv=' + noCache + '" alt="' + getIJMessage('VER_OFERTAS') + '">');
 	document.write('	</a>');
} 


//parametro para salvar el proxy
function getDgv(){
	var now = new Date();
 	var millis = now.getTime();
 	var ad_rand=Math.floor(Math.random()*1000000);
 	var dgv = ""+ (millis+ ad_rand);
	return dgv;
}

function getAttributeString(atts) {
 var alphaNum = /^[A-Za-z0-9*_\\-]+$/
 var result = "";
 
 //En caso de que no llegue el parametro directamente
 //se mira a ver si existe en una variable javascript.
 //Esto se usa tan solo en la HOME, que al ser cacheada
 //no permite un parametro dinamico desde el servidor.

 if( typeof(tile) != 'undefined' ){
	if( !atts.tile ){
 		atts.tile = tile;
	}
 }
 for (att in atts) {
  if (alphaNum.test(att) && alphaNum.test(atts[att])) {
   result += "&amp;" + att + "=" + atts[att];
  }
 }
 return result;
}

//HF 29-04-2008, Se duplican estas funciones aqui para eliiminar el error js del menu 
//de candidatos de forma rápida. La forma adecuada de arreglarlo es buscar todos los sitios 
//de la web donde func_getcookie_01.js no este incluido e incluirlo. Despues ya podremos 
//llamar directamente al metodo GetCookie en luger de customGetCookie  
function customGetCookie (nombre) {
	var arg = nombre + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return customGetCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) {
			break;
		}
	}
	return null;
}

function customGetCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) {
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
} 

/**
 * Adds a 'dgv' random parameter to the given URL, 
 * to prevent bad proxies from caching pages.
 * @param url The url
 * @return Encoded url with the dgv param.
 */
function encodeURL(url) {
	var now = new Date();
 	var millis = now.getTime();
 	var ad_rand=Math.floor(Math.random()*1000000);
 	var dgv = ""+ (millis+ ad_rand);
 	if (url.indexOf('?')> -1) {
 		url += "&";
 	} else {
 		url += "?";
 	}
	return url = url + "dgv=" + dgv;
}
 
/**
 *  Returns a localized message for the given key. For messages with params like "has borrado {0} cvs"
 * @param key The key
 * @param param can be an array or a simple object like a String, number, ...
 * @return The localized message
 */
function getIJMessageWithParams(key, param) {
	//check if exists JSMensajes
	if (JSMensajes == null || typeof JSMensajes == 'undefined') {
		return "";
	}
	
	//check if key is valid
	if (key == null || typeof key == 'undefined') {
		return "";
	}
	
	var mensaje = getIJMessage(key);
	//check if param has 1 argument or multiple arguments
	if (typeof param == 'object') {		
		for (var i=0; i<param.length; i++) {
			mensaje = mensaje.replace("\{" + i + "\}", param[i]);
		}			
	} else {		
		mensaje = mensaje.replace("\{0\}", param);
	}
	
	return mensaje;	
}
		
	
/**
* Returns a localized message for the given key.
* @param key The key
* @return The localized message
*/
function getIJMessage(key) {
	//check if exists JSMensajes
	if (typeof JSMensajes == 'undefined' || JSMensajes == null) {
		return "";
	}
	
	//check if key is valid
	if (key == null || typeof key == 'undefined') {
		return "";
	}
	
	return JSMensajes[key];		
}

function getCurrentLocale(){
	return _currentLocale;
}

/**
 * @return the base path of images
 */
function getIJImgPath() {
	return _portalImgPath;
}

/**
 * open a new pop-up window
 * @param theURL
 * @param theName
 * @param theWidth
 * @param theHeight
 * @return
 */
function entrar(theURL,theName,theWidth,theHeight) {
	window.open(theURL, theName, "width="+theWidth+",height="+theHeight+",scrollbars=yes,alwaysRaised=yes,dependent=no,location=no,screenX=0,screenY=0,resizable=no");
}
 

/**
 * valida que en input contenga un valor numérico, sin guiones. Sólo caracteres del 0 al 9. 
 * @param input     input del formulario
 * @param nombre    nombre en pantalla, para el mensaje de error
 * @param bMostraMissatge
 * @return
 */

function esnumero(input, nombre, bMostraMissatge) {

	/* bMostraMissatge ?s un par?metre optatiu que fa que s'inclogui o no el nou missatge d'error a la p?gina. Per defecte es true */
	if (typeof(bMostraMissatge) == 'undefined')
		bMostraMissatge = true;

	if (bMostraMissatge) {
		var sText = "SOLO_NUMEROS";
	}
	else {
		var sText = "";
	}
   	var numericExpression = /^[0-9]+$/;
   	if(input.value.match(numericExpression)) return true;
   	addGlobalErrorMessage(input,sText,nombre);
   	return false;
}




/*
 * importado desde: func_format_price.js
 * 
function numFormat(dec, miles)	
   dec  : int       num. posiciones decimales
   miles: boolean   <true> si hay que marcar los miles. 

Ejemplo de uso: 
var numero = new oNumero(12345678.1266);
document.write("El número: " + numero.valor+'<br>');
document.write("Formateado queda: ");
document.write(numero.formato(2, true));

*/ 
// Formato precio: 123.456.789,00
function formatPrice(valor) {
	return numFormat(valor, 2, true);
}

/*
 * importado desde: func_format_price.js
 * 
 */
// Formato libre. 
// dec:   int   num. de posiciones decimales deseadas. 
// miles: bool  si se desea separador de miles o no.  
function numFormat(valor, dec, miles) {
		var num = valor; 
		var signo=3;
		var expr;
		var cad = ""+valor;
		var ceros = "";
		var pos;
		var pdec;
		var  i;
		for (i=0; i < dec; i++){
			ceros += '0';
		}
		pos = cad.indexOf('.');
		if (pos < 0){
		    cad = cad+"."+ceros;
		} else {
		    pdec = cad.length - pos -1;
		    if (pdec <= dec){
		        for (i=0; i< (dec-pdec); i++) {
		            cad += '0';
		        }
		    } else {
		        num = num*Math.pow(10, dec);
		        num = Math.round(num);
		        num = num/Math.pow(10, dec);
		        cad = new String(num);
		    }
		}
		pos = cad.indexOf('.'); 
		if (pos < 0){
		 	pos = cad.lentgh;
		}
		if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+'){
			signo = 4;
		}
		if (miles && pos > signo) {
		    do {
		        expr = /([+-]?\d)(\d{3}[\.\,]\d*)/ ;
		        cad.match(expr);
		        cad=cad.replace(expr, RegExp.$1+','+RegExp.$2);
		       } while (cad.indexOf(',') > signo);
		}
		/// Nos aseguramos de que tenga las posiciones decimales indicadas. 
		if (dec > 0 ) {
		    pos = cad.indexOf('.');
			if (pos < 0){
			    cad = cad+".";
			    pos = cad.indexOf('.');
			} 
			pdec = cad.length - pos -1;
			if (pdec <= dec){
			    for (i=0; i< (dec-pdec); i++) {
			        cad += '0';
			    }
			}
		}
		if (dec<0) {
			cad = cad.replace(/\./,'');
		}

		/// Cambiamos las ',' por puntos y el punto por coma... 
		cad = cad.replace('.','_');	
		cad = cad.replace(',','.');	
		cad = cad.replace('_',',');	
		
	    return cad;
}

function saveError(err, msg, url, line){
	var imgSrc = '/js/pix.xhtml?e=' + err + '&msg=' + msg + '&t=' + (new Date()).getTime();
	(new Image()).src = imgSrc;
}

var _loadedCSS = {};
/**
 * Loads the specified CSS if not already loaded by this function.
 * @param url The URL of the CSS to load
 */
function loadCSS(url) {
	if (typeof _loadedCSS[url] == 'undefined') {
		$("head").append("<link>");
		var css = $("head").children("link:last");
		var href = staticUrl + url + "?" + staticV;
		css.attr({
		      rel:  "stylesheet",
		      type: "text/css",
		      href: href
		    });
		_loadedCSS[url] = true;
	}
}

/**
 * Changes all selects in a form with class="form1" (and .global-search) to JQuery UI selectmenu except:
 * - Multiple selects (multiple="xxx" or size > 1)
 * - Hidden selects (as their size cannot be computed)
 * @param selector [optional] The elements to update, defaults to all selectmenus.
 */
function styleSelects(selector) {
	if(!selector) { //If the optional argument is not there, create a new variable with that name.
		var selector = ".form1 select, .global-search select";
	}
	if (jQuery && jQuery().selectmenu) {
		var styled = false;
		jQuery(selector).each(function(index) {
			if (jQuery(this).attr("size")<2 && jQuery(this).attr("multiple")=="" && jQuery(this).is(":visible")) {
				if (!styled) {
					styled = true;
				}
				jQuery(this).selectmenu();
				jQuery(this).addClass("selectmenu");
			}
		});
	}
}

/**
 * Updates all the selectmenus in the page to match the underlying select
 * element's conent and selected value
 * @param selector [optional] The elements to update, defaults to all selectmenus.
 */
function updateStyledSelects(selector) {
	if(!selector) { //If the optional argument is not there, create a new variable with that name.
		var selector = ".selectmenu";
	}
	jQuery(selector).each(function(index) {
		var t = jQuery(this);
		if (t.hasClass("selectmenu")) {
			try {
				t.selectmenu("enable");
				t.selectmenu();
				t.selectmenu("value", jQuery(this).val());
				if (t.is(":disabled")) {
					t.selectmenu("disable");
				} else {
					t.selectmenu("enable");
				}
			} catch (exception) {}
		}
	});
}

jQuery(document).load(function() {
	setTimeout("updateStyledSelects()", 300);
});

/**
 * Add a class on the text and password fields inside a form with class "form1"
 * that have the focus.
 */
function focusColor(selector) {
	jQuery(selector).focus(function() {
		jQuery(this).addClass("focus");
    });
    jQuery(selector).blur(function() {
    	jQuery(this).removeClass("focus");
    });
}

jQuery(document).ready(function() {
	var selector = '.form1 input[type="text"],.form1 input[type="password"],.form1 textarea,' +
				   '.acces-login input[type="text"],.acces-login input[type="password"],.acces-login textarea,' +
				   '#buscar-ofertas input[type="text"],#buscar-ofertas input[type="password"],#buscar-ofertas textarea,' +
				   '#footer .global-search input[type="text"],#footer .global-search input[type="password"],#footer .global-search textarea,' +
				   '#search-engine input[type="text"],#search-engine input[type="password"],#search-engine textarea,' +
				   '.social input[type="text"],.social input[type="password"],.social textarea';
	focusColor(selector);
});

/**
 * Initialize jQuery Tools default tooltips
 */
jQuery(document).ready(function() {
	var selector = '.tooltip-trigger';
	jQuery(selector).tooltip({position: 'bottom right', offset: [14,-31], relative:true, effect:'slide'});
});

/**
 * Looks for "Publicidad Vacia" inside the innerHTML of the element with the
 * given Id and hides the container if found.
 * 
 * @param containerID
 *            The Id of the HTML element containing the banner
 */
function hideEmptyBannerContainer(containerID) {
	bannerCandidateMenu = document.getElementById(containerID);
	if (bannerCandidateMenu) {
		if (bannerCandidateMenu.innerHTML.indexOf("Publicidad Vacia") != -1) {
			bannerCandidateMenu.style.display = "none";
		}
	}
}

