
var shcuts_on = true;

function ChangeClass(item, newClass) { 
if (document.getElementById) { 
	var stritem=item;
	var numitem=stritem.substring(6,4); //---número submenú
 	document.getElementById(item).className = newClass;
	}
} 

var registre;

function registre_on(registre){
var idregistre=registre;
if (document.getElementById) { 
 	document.getElementById(idregistre).className = "registreon";
	}
}

function registre_off(registre){
if (document.getElementById) { 
 	document.getElementById(registre).className = "registreoff";
	}
}

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=1020,height=600');");
//	return id;
}

function popUpComplete(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=1020,height=600');");
}

//--------------------

function nl2br(str) {
   return str.replace(/\n/g,"<br>");
}

function gotoKey(the_key, the_path) {
	
	if (shcuts_on) {
		switch (the_key) {
	
			case 72: document.location = the_path + 'index.php/syn.home_index';
				break; // 'H'
			case 82: document.location = the_path + 'index.php/syn.resumes_list';
				break; // 'R'
			case 65: document.location = the_path + 'index.php/syn.job/do.jobAdd.1';
				break; // 'A'
			case 69: document.location = the_path + 'index.php/syn.jobsl_search_results';
				break; // 'E'
			case 83: document.location = the_path + 'index.php/syn.resumes_search';
				break; // 'S'
				
		}
	}
	
}

function disable_shortcuts() {
	shcuts_on = false;
}

function enable_shortcuts() {
	shcuts_on = true;
}


function trim(s) {
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function function_exists(function_name) {
    if (typeof function_name == 'string'){
        return (typeof window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}
function replaceNonAcceptChars(str) {
	return str.replace(/(.)\1\1\1/g, '');
}
function displayCss(idDiv, onOff, howToDisplay) {
	if(onOff) {
		document.getElementById(idDiv).style.display = howToDisplay;
	} else {
		document.getElementById(idDiv).style.display = 'none';
	}
}

function display(idDiv, onOff) {
	displayCss(idDiv, onOff, 'block');
}

function valbutton(radioName) {
	// place any other field validations that you require here
	// validate myradiobuttons
	myOption = -1;
	for (i=radioName.length-1; i > -1; i--) {
		if (radioName[i].checked) {
			myOption = i; i = -1;
		}
	}
	if (myOption == -1) {
		return "";
	} else {
		return radioName[myOption].value;
	}
}
//--------------------
function removeAllChilds(element) {
	if (element && element.childNodes) {
		for (var i = element.childNodes.length -1; i >= 0; i--) {
			element.removeChild(element.childNodes[i]);
		}
	}
}
var msgAlert = null;
function Alert (text) {
  var body = document.getElementsByTagName("body")[0];
  this.all = document.createElement("div");
  this.all.className = "transparencia";
  this.win = document.createElement("div");
  this.win.className = "Alert";
  this.closer = document.createElement("a");
  this.closer.href = "javascript:hideAlert();";
  typeof(this.closer.style.cssFloat) != "undefined" ? this.closer.style.cssFloat = "right": this.closer.style.styleFloat = "right";
  this.closer.top = "0";
  this.closer.appendChild(document.createTextNode("X"));
  this.p = document.createElement("h2");
  //this.p.appendChild(document.createTextNode(text));
  this.p.innerHTML = text;
  this.win.appendChild(this.closer);
  this.win.appendChild(this.p);
  this.all.style.display = "none";
  this.win.style.display = "none";
  body.appendChild(this.all);
  body.appendChild(this.win);
}
Alert.prototype.show = function (text, options) {
  if (text) {
    removeAllChilds(this.p);
    this.p.innerHTML = text;
    if(typeof(options) != 'undefined') {
    	for(var i = 0; i < options.length; i++) {
        	this.p.innerHTML += "<input type='button' value='" + options[i].text + "' id='showAlertOption_"+i+"' />";
    		$(document.getElementById('showAlertOption_' + i)).click(options[i].whatToDo);
    	}
    }
  }
  this.all.style.display = "block";
  this.win.style.display = "block";
  if (document.all) {
  	this.win.style.top = Math.max(document.body.scrollTop, document.documentElement.scrollTop) + document.body.clientHeight/4 - this.win.offsetHeight + "px";
  } else {
    this.win.style.top = window.pageYOffset + window.innerHeight/2 - this.win.offsetHeight + "px";
  }
}
Alert.prototype.hide = function () {
  this.all.style.display = "none";
  this.win.style.display = "none";
}

Alert.prototype.close = function () {

}

function AlertOption(txt, fn) {
	this.text = txt;
	this.whatToDo = fn;
}

function showAlert(text, options) {
  try {
     if (!msgAlert) {
        msgAlert = new Alert(text);
     }
     msgAlert.show(text, options);
  } catch(err) {
     alert(text);
  }
}

function hideAlert() {
  if (msgAlert) {
    msgAlert.hide();
  }
}

function isPressedEnter(evt) {
	var e = evt ? evt : window.event;
	if(!e) return false;
	var key = 0;
	if (e.keyCode) { key = e.keyCode; }
	else if (typeof(e.which) != 'undefined') { key = e.which; }
	if (key == 13) {
		return true;
	} else {
		return false;
	}
}
//field: object input type. op:' hide' or 'show' text. txt: Text valid to show inside the input
function showHideTextInInput(field, op, txt){
	var text  = field.value;
	if(op == 'hide' && text == txt){
		field.style.color = 'black';
		field.value = '';
	}else if(op == 'show' && text == ''){
		field.style.color = '#8F8F8F';
		field.value = txt;
	}
}
//Ajusta el tamaño de un iframe al de su contenido interior para evitar scroll
function autofitIframe(id){
	if (!window.opera && document.all && document.getElementById){
		id.style.height=id.contentWindow.document.body.scrollHeight;
	} else if(document.getElementById) {
		id.style.height=id.contentDocument.body.scrollHeight+"px";
	}
}

// Comprueba si el código postal es válido
function checkPostalCode(postalCode) {
	var regPostalCode = /^(5[0-2]|[0-4][0-9])[0-9]{3}$/;
	
	if(regPostalCode.test(postalCode)) {
		return true;
	}
	
	return false;
}

function setMaxSalary(salaryMin, salaryMax){
	
	if(salaryMax.value == "" || parseInt(salaryMax.value) < parseInt(salaryMin.value)){
		salaryMax.value = salaryMin.value;
	}
}

function checkIdentification(id) {
	//Returns: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF bad, -2 = CIF bad, -3 = NIE bad, 0 = ??? bad
	var id = id.toUpperCase();
	var num = new Array();
	var abc = "TRWAGMYFPDXBNJZSQVHLCKE";
	var format = new RegExp('(([A-Z0-9]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)');
	var formatNIF = new RegExp('(^[0-9]{8}[A-Z]{1}$)');
	var formatSpecialNIF = new RegExp('^[KLM]{1}');
	var formatCIF = new RegExp('^[ABCDEFGHJNPQRSUVW]{1}');
	var formatTNIE = new RegExp('^[T]{1}');
	var formatXYZNIE = new RegExp('^[XYZ]{1}');
	var endFormatTNIE = new RegExp('^[T]{1}[A-Z0-9]{8}$');
	
	for (var i = 0; i < 9; i ++) {
		num[i] = substr(id, i, 1);
	}
	
	//If havent valid format, KO
	if (!format.test(id)) {
		return 0; //KO
	}

	//Standard NIFs Validation
	if (formatNIF.test(id)) {
		if (num[8] == substr(abc, substr(id, 0, 8) % 23, 1)) {
			return 1; //OK
		} else {
			return -1; //KO
		}
	}
	
	//Algorithm to check CIF 
	var suma = num[2] + num[4] + num[6];
	for (var i = 1; i < 8; i += 2)
		suma += substr((2 * num[i]),0,1) + substr((2 * num[i]),1,1);
	var n = 10 - substr(suma, suma.length - 1, 1);
	
	//Special NIFs (calculated as CIFs) Validation
	if (formatSpecialNIF.test(id)) {
		if (num[8] == String.fromCharCode(64 + n)) {
			return 1; //OK
		} else {
			return -1; //KO
		}
	}
	
	//CIFs Validation
	if (formatCIF.test(id)) {
		if (num[8] == String.fromCharCode(64 + n) || num[8] == substr(n, n.length - 1, 1)) {
			return 2; //OK
		} else {
			return -2; //KO
		}
	}
	
	//NIEs Validation
	if (formatTNIE.test(id)) { //T
		if (num[8] == endFormatTNIE.test(id)) {
			return 3; //OK
		} else {
			return -3; //KO
		}
	}
	
	if (formatXYZNIE.test(id)) { //XYZ
		if (num[8] == substr(abc, substr(str_replace(new Array('X','Y','Z'), new Array('0','1','2'), id), 0, 8) % 23, 1)) {
			return 3; //OK
		} else {
			return -3; //KO
		}
	}
	
	//if isnt yet check it, return 0 (KO)
	return 0;
}

/*** Hash Javascript Functions (to see examples search new Hash js) ***/
function Hash() {
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}
	   
		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}

// Method to add all options from a hash in a selectbox
function addHashInCombo (hashFrom, comboTo) {
	removeAllOptions(comboTo);
	var i = 0;

	for (var hVal in hashFrom.items) {
		comboTo.options[i] = new Option(hashFrom.getItem(hVal), hVal);
		i++;
	}
}

//Method to add all options from a hash in a selectbox
function addHashInComboOnlyParent (hashFrom, hashParent, comboTo, parent, preselected) {
	removeAllOptions(comboTo);
	var i = 0;

	for (var hVal in hashParent.items) {
		if (parent == hashFrom.getItem(hVal)) {
			comboTo.options[i] = new Option(hashParent.getItem(hVal), hVal);
			if (preselected == hVal) {
				comboTo.options[i].selected = 'selected';
			}
			i++;
		}
	}
}

// Method to remove all options from a selectbox
function removeAllOptions (selectbox) {
    var z;  
    if (selectbox != null) {
		if (selectbox.length > 0) {
			for (var z=(selectbox.length-1); z>=0; z--) {
		    	selectbox.remove (z);
		    }
	    }
    }
}

// Valida si un select ha sido rellenado o no
function validaSelect(nomSelect) {
	var indice = eval("document.getElementById('"+nomSelect+"').selectedIndex");
	if (indice == 0) {
		return false;
	} 
	return true;
}

// Method to show an alert getting the message
// from AlertMessages (array for testing)
function showAlertCode(code) {
	try {
		var text = AlertMessages[code];
		if (!msgAlert) {
			msgAlert = new Alert(text);
			msgAlert.show();
		} else {
			msgAlert.show(text);
		}
	} catch(err) {
		alert(text);
	}
}

function showInfoBubble() {
  $('.bubbleInfo').each(function () {
    // optionssrc="path/to/jQuery.js"
    var distance = 5;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.triggerAccordion', this);
    var bubble = $('.bubble', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), bubble.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the bubble element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        //top: -90,
        //left: -3,

// reset position of bubble box
/*
        bubble.css({
          top: -120,
          bottom: 0,
          left: 90,
          display: 'block' // brings the bubble back in to view
        })
        */
        bubble.css({
          bottom: (trigger[0].offsetTop - trigger[0].offsetWidth*3) + 'px',
          right: (trigger[0].offsetLeft - 200) + 'px',
          display: 'block' // brings the bubble back in to view
        })
        // (we're using chaining on the bubble) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });       
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        bubble.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the bubble entirely after the effect (opacity alone doesn't do the job)
          bubble.css('display', 'none');
        });
      }, hideDelay);
    });
  });
}

function changeNameCompanyInJobForm(oCompanyName, oHiddenCompany, company) {
	if (oHiddenCompany.checked == true) {
		oCompanyName.readOnly = false;
		oCompanyName.style.color = "black";
	}
	else {
		oCompanyName.readOnly = true;
		oCompanyName.style.color = "gray";	
		oCompanyName.value = company;
	}
}
//PHP substr in javascript
function substr( f_string, f_start, f_length ) { 
    f_string = f_string+'';
    
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}
//PHP str_replace in javascript
function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    
    
    var _is_array = function(mixed_var) {
        return (mixed_var instanceof Array);
    };
    
    var f = search, r = replace, s = subject;
    var ra = _is_array(r), sa = _is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
     
    return sa ? s : s[0];
}

function selectAllCheckBoxes(selectList, magicSelect) {
	if (selectList && magicSelect) {
		if (selectList.length > 0) { 
			for (i=0; i<selectList.length; i++) {
				selectList[i].checked = magicSelect.checked;
			}
		} else {
			selectList.checked = magicSelect.checked;
		}
	}
}

function allChecked(selectsName, magicSelect) {
	var selects = document.getElementsByName(selectsName);
	if(!selects || !magicSelect) {
		return;
	}
	var areAllChecked = true;
	var end = false;
	var i = 0;
	var selectNum = selects.length;
	
	while(!end) {
		if(i == selectNum) {
			end = true;
		} else if(!selects[i].checked) {
			areAllChecked = false;
			end = true;
		} else {
			i++;
		}
	}
	
	if(areAllChecked) {
		magicSelect.checked = true;
	} else {
		magicSelect.checked = false;
	}
}

//Method to repaint a table
function repaintTable(selectorString, oddClass) {
	if(!oddClass) {
		var oddClass = "odd";
	}
	var elements = $(selectorString);
	for (var i = 0; i < elements.length; i++) {
		if(i % 2 == 0) {
			$(elements[i]).addClass(oddClass);
		} else {
			$(elements[i]).removeClass(oddClass);
		}
	}
}

// Translate a text and disable buttons
undoTranslationBuffer = [];
function translate(inputName, buttonsName, langValue) {
	var input = document.getElementById(inputName);
  	$.post(brand + "index.php/syn.job/do.translateJob", {input: input.value, lang: langValue}, function(data){
  		undoTranslationBuffer[inputName] = input.value;
  		input.value = data;
  	});
	var buttons = $('img[name='+buttonsName+']');
	for(var i = 0; i < buttons.length; i++) {
		buttons[i].style.display = 'none';
	}
	var buttonUndo = $('img[id=undo'+buttonsName+']');
	buttonUndo = buttonUndo[0];
	buttonUndo.style.display = 'inline';
}

function undoTranslation(inputName, buttonsName) {
	var oldText = undoTranslationBuffer[inputName];
	var input = document.getElementById(inputName);
	if(oldText) {
		input.value = oldText;
	}
	var buttons = $('img[name='+buttonsName+']');
	for(var i = 0; i < buttons.length; i++) {
		buttons[i].style.display = 'inline';
	}
	var buttonUndo = $('img[id=undo'+buttonsName+']');
	buttonUndo = buttonUndo[0];
	buttonUndo.style.display = 'none';
}

function loadXML(xml) {
	if (typeof ActiveXObject !== undefined) {
		try {
			var dom = new ActiveXObject("Microsoft.XMLDOM");
			dom.async = "false";
			dom.loadXML(xml);
			return dom;
		} catch(ex) {
			alert(ex);
		} 
	} else {
		try {
			var parser = new DOMParser();
			return parser.parseFromString(xml, "text/xml");
		} catch(ex) {
			alert(ex);
		}
	}
	return null;
}