function trim(st)
{
  var m = st.match(/^\s*(\S+(\s+\S+)*)\s*$/);
  return((m == null) ? "" : m[1]);
}
function isEmpty(fld, msg)
{
  var empty = (trim(fld.value) == "");
  if (empty)
  {
    alert(msg);
	fld.focus();
  }
  return empty;
}
function isEmptyAndEmpty(fld1, fld2, msg)
{
  var empty1 = (trim(fld1.value) == "");
  var empty2 = (trim(fld2.value) == "");
  var empty  = empty1 && empty2;
  if (empty)
  {
    alert(msg);
    fld1.focus();
  }
  return empty;
}
function isEmptySelect(fld, msg)
{
  var opc = fld.options[fld.selectedIndex];
  var empty = (trim(opc.value) == "");
  if (empty)
  {
    alert(msg);
    fld.focus();
  }
  return empty;
}
function isEmptyEmail(fld, msg)
{
  var email;
  var parts;
  var empty = (isEmpty(fld, msg));
  var esOk = !empty;
  if (esOk)
  {
    email = fld.value;
    var m = email.match(/^\s*(\S+(\s+\S+)*)\s*$/);
	parts = email.split(/@/);
	esOk = ((m[2] == null) || (m[2] == ""));
	esOk &= (parts.length == 2);
	if (esOk)
	{
	  var dot = parts[1].split(/\./);
	  esOk = (dot.length > 1);
	}
	if (!esOk)
	{
          alert(msg);
	  fld.focus();
	}
  }
  return !esOk;
}
function valueChecked(fldName)
{
  var value;
  var listFlds = document.getElementsByName(fldName);
  if (listFlds == null) return null;
  var pos = 0;
  var exist = false;
  while (!exist && pos < listFlds.length)
  {
    exist = listFlds[pos++].checked;
  }
  if (exist)
  {
    value = listFlds[--pos].value;
  } else
  {
    value = null;
  }
  return value;
}
function existOneRadioChecked(fldName, msg)
{
  var exist = (valueChecked(fldName) != null);
  if (!exist)
  {
	alert(msg);
    var listFlds = document.getElementsByName(fldName);
    if (listFlds != null) listFlds[0].focus();
  }
  return exist;
}
function existOneChecked(arrFldName, msg)
{
  var fld;
  var pos = 0;
  var exist = false;
  while (!exist && pos < arrFldName.length)
  {
    fld = document.getElementById(arrFldName[pos++]);
    exist = fld.checked;
  }
  if (!exist && arrFldName.length > 0)
  {
    fld = document.getElementById(arrFldName[0]);
    alert(msg);
    fld.focus();
  }
  return exist;
}
function isEqual(fld, val, msg)
{
  var value;
  var empty = (isEmpty(fld, msg));
  var esOk = !empty;
  if (esOk)
  {
    value = trim(fld.value);
    esOk = (value == val);
    if (esOk)
    {
      alert(msg);
      fld.focus();
    }
  }
  return esOk;
}
function isNumber(fld, digits, msg)
{
  var value;
  var empty = (isEmpty(fld, msg));
  var esOk = !empty;
  if (esOk)
  {
    value = trim(fld.value);
    if (!isNaN(value))
      esOk = (value.length == digits);
    else
      esOk = false;
    if (!esOk)
    {
      alert(msg);
      fld.focus();
    }
  }
  return !esOk;
}
function getXMLHttp()
{
  var C;
  try
  {
    C=new ActiveXObject("Msxml2.XMLHTTP")
  } catch(e)
  {
    try
    {
      C=new ActiveXObject("Microsoft.XMLHTTP")
    } catch(sc) { C=null }
  }
  if(!C&&typeof XMLHttpRequest!="undefined") { C=new XMLHttpRequest() }
  return C
}
function doAjaxRequest(method, action, qryStr, fnDone, extraFnData)
{
  var httpCli = getXMLHttp();
  var contentBody;

  //showDlg(true);
  if (method == "GET")
  {
    httpCli.open(method, action + "?" + qryStr, true);
    contentBody = null;
  } else
  {
    httpCli.open(method, action, true);
    httpCli.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    contentBody = qryStr;
  }
  httpCli.onreadystatechange=
        function()
        {
          if(httpCli.readyState==4)
          {
            //checkRedirect(httpCli);
            //renderLayers(httpCli);
            if (fnDone != null)
              fnDone(httpCli, extraFnData);
            //showDlg(false);
          }
        }
  httpCli.send(contentBody);
} //-- doAjaxRequest
//-- Renderitza les options que venen en el document XML-AJAX
function renderOptions(httpCli, idSelect)
{
  var valueOption, textOption, optionNode;
  var newopc, selectTag;
  var loptions, option;
  var lerrors = httpCli.responseXML.getElementsByTagName("parsererror");
  if (lerrors.length == 0)
  {
    var selectTag = document.getElementById(idSelect);
    while (selectTag.firstChild) selectTag.removeChild(selectTag.firstChild);

    if (selectTag != null)
    {
      loptions = httpCli.responseXML.getElementsByTagName("option");
      for (ind=0; ind < loptions.length; ind++)
      {
        option = loptions[ind];
        valueOption = option.getAttribute("value");
        textOption = option.childNodes[0];

        newopc = document.createElement("option");
        newopc.setAttribute("value", valueOption);
        optionNode = document.createTextNode(textOption.nodeValue)
        newopc.appendChild(optionNode);
        selectTag.appendChild(newopc);
      }
    } else
      alert("No existe Content: " + id);
      //contentDiv.className = node.getAttribute("class");
  } else
  {
    var nameTextNode = lerrors[0].childNodes[0];
    var htmlvalue = nameTextNode.nodeValue;
    alert("Parsing Error.\n" + error.length + " Errors\n" + htmlvalue);
    alert(httpCli.responseText);
  }
} //-- renderOptions
function setFocus(fldId)
{
  var fld = document.getElementById(fldId);
  if (fld.disabled == false && fld.readOnly == false) fld.focus();
}
function rangDateValid(fldIni, fldFin, msg)
{
  var dIni, dFin;
  var inRang = false;
  dIni = obtenirDate(fldIni, "dd/mm/yyyy");
  dFin = obtenirDate(fldFin, "dd/mm/yyyy");
  if (dIni != null && dFin != null)
    inRang = (dFin > dIni);
  if (!inRang)
  {
    alert(msg);
    fldFin.focus();
  }
  return inRang;
}
function obtenirDate(fld, mask)
{
  var v = fld.value, m = mask;
  var a, e, mm, dd, yy, x, s;

  // split mask into array, to see position of each day, month & year
  a = m.split(/[^mdy]+/);
  // split mask into array, to get delimiters
  s = m.split(/[mdy]+/);
  // convert the string into an array in which digits are together
  e = v.split(/[^0-9]/);

  if( s[0].length == 0 ) s.splice(0, 1);
  for( var i=0; i < a.length; i++ ){
          x = a[i].charAt(0).toLowerCase();
          if( x == "m" ) mm = parseInt(e[i], 10)-1;
          else if( x == "d" ) dd = parseInt(e[i], 10);
          else if( x == "y" ) yy = parseInt(e[i], 10);
  }
  // if year is abbreviated, guess at the year
  if( String(yy).length < 3 ){
          ////yy = 2000 + yy;
          ////if( (new Date()).getFullYear()+20 < yy ) yy = yy - 100;
          //// Si solo ponen dos cifras del a?o, ponemos automaticamente 1900
          yy = 1900 + yy;
  }
  // create date object
  var d = new Date(yy, mm, dd);
  if( d == null || d.getDate() != dd )
    d = null;
  else if( d.getMonth() != mm )
    d = null;
  else if ( d.getFullYear() != yy )
    d = null;
  return d;
}
//-- Nova validacio de dates
function getFieldDate(fld, mask)
{
	var v = fld.value, m = mask;
	var a, e, mm, dd, yy, x, s;

	// split mask into array, to see position of each day, month & year
	a = m.split(/[^mdy]+/);
	// split mask into array, to get delimiters
	s = m.split(/[mdy]+/);
	// convert the string into an array in which digits are together
	e = v.split(/[^0-9]/);

	if( s[0].length == 0 ) s.splice(0, 1);
	for( var i=0; i < a.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
		if( x == "m" ) mm = parseInt(e[i], 10)-1;
		else if( x == "d" ) dd = parseInt(e[i], 10);
		else if( x == "y" ) yy = parseInt(e[i], 10);
	}
	// if year is abbreviated, guess at the year
	if( String(yy).length < 3 ){
		////yy = 2000 + yy;
		////if( (new Date()).getFullYear()+20 < yy ) yy = yy - 100;
		//// Si solo ponen dos cifras del a?o, ponemos automaticamente 1900
		yy = 1900 + yy;
	}
	// create date object
	var d = new Date(yy, mm, dd);
	if( d == null || d.getDate() != dd )
		return "";
	else if( d.getMonth() != mm )
		return "";
	else if ( d.getFullYear() != yy )
		return "";

        var nv = "";
	for( i=0; i < a.length; i++ ){
		x = a[i].charAt(0).toLowerCase();
		if( x == "m" ){
			mm++;
			if( a[i].length == 2 ){
				mm = "0" + mm;
				mm = mm.substring(mm.length-2);
			}
			nv += mm;
		} else if( x == "d" ){
			if( a[i].length == 2 ){
				dd = "0" + dd;
				dd = dd.substring(dd.length-2);
			}
			nv += dd;
		} else if( x == "y" ){
			if( a[i].length == 2 ) nv += d.getYear();
			else nv += d.getFullYear();
		}

		if( i < a.length-1 ) nv += s[i];
	}
	return nv;
}
function isValidDate(fld, msg)
{
  var sdate = getFieldDate(fld, "dd/mm/yyyy");
  var empty = (trim(sdate) == "");
  if (empty)
  {
    alert(msg);
	fld.focus();
  }
  return empty;
}
// Validación de la letra final del NIF
function valida_nif(numero, letra)
{
  letras = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
  if(isNaN(numero))
    return false;
  num = Number(numero);
  if(num<23)
    indice = num;
  else
    indice = numero-(parseInt(num/23)*23);
  return (letra.toUpperCase() == letras[indice]);
}
function isDocIdeValid(fldDocId, fldNumDocId)
{
  var esok = false;
  if(!isEmptySelect(fldDocId, 'Debe introducir documento de identidad'))
   if(!isEmpty(fldNumDocId, 'Debe introducir documento de identidad'))
   {
     var opc = fldDocId.options[fldDocId.selectedIndex];
     if (trim(opc.value) == "1") //-- NIF
     {
       var nif = trim(fldNumDocId.value);
       var dni = nif.substring(0, nif.length-1);
       var letra = nif.substring(nif.length-1, nif.length);
       esok = valida_nif(dni, letra);
       if (!esok)
       {
         alert("Revise el NIF");
         fldNumDocId.focus();
       } else
       { //-- 9 dígitos + letra
         var dnitemp = trim(dni);
         dnitemp = "000000000" + dnitemp + letra;
         dnitemp = dnitemp.substring(dnitemp.length-9, dnitemp.length);
         fldNumDocId.value = dnitemp;
       }
     } else
     {
       esok = true;
     }
   }
  return esok;
}
//-- Recollim options dinàmiques
function dinamicSelectProv(event, field, capaId)
{
  var method, action, qrystr;
  method = "GET";
  action = "ajaxrequest";
  qrystr = "ipt=dom&dom=prov&id=";
  if(field.value.length > 0)
  {
    qrystr += field.value;
  }
  doAjaxRequest(method, action, qrystr, renderOptions, capaId);
}
//-- canvi de pagina dins el CV
function gocvpage(sec)
{
  var frm = document.getElementById("curriculo");
  var fldsec = document.getElementById("sec");

  if (validarCv(frm))
  {
    fldsec.value = sec;
    frm.submit();
  }
}
function gocvnextpage()
{
  var frm = document.getElementById("curriculo");
  if (validarCv(frm))
  {
    frm.submit();
  }
}
function gocvprevpage()
{
  var frm = document.getElementById("curriculo");
  var fldsec = document.getElementById("sec");
  var fldpresec = document.getElementById("presec");

  if (validarCv(frm))
  {
    fldsec.value = fldpresec.value;
    frm.submit();
  }
}
function habilitarCampsExp(fld, enable)
{
  var frm = fld.form;
  var lflds, fld;
  lflds = frm.getElementsByTagName("input");
  for(var ind = 0; ind < lflds.length; ind++)
  {
    fld = lflds[ind];
	fldType = fld.getAttribute("type");
    if ((fldType == "text") || (fldType == "checkbox"))
	{
	  fld.disabled = !enable;
	}
  }
  lflds = frm.getElementsByTagName("select");
  for(var ind = 0; ind < lflds.length; ind++)
  {
    fld = lflds[ind];
	fld.disabled = !enable;
  }
  if (enable)
    frm.date_ini_exp.focus();
}
function validarCvIde(frm)
{
  var esok = false;
  if(!isEmpty(frm.trato, 'Debe introducir el trato'))
   if(!isEmpty(frm.nom, 'Debe introducir el nombre'))
    if(!isEmpty(frm.ape1, 'Debe introducir el primer apellido'))
     if(!isValidDate(frm.date_nac, 'Debe introducir una fecha de nacimiento correcta'))
      if(!isEmptySelect(frm.pais_nac, 'Debe introducir pais de nacimiento'))
       if(!isEmptySelect(frm.nacionalidad, 'Debe introducir nacionalidad'))
        if(!isEmptySelect(frm.prov_nac, 'Debe introducir provincia de nacimiento'))
         if(!isEmpty(frm.city_nac, 'Debe introducir ciudad de nacimiento'))
          if(isDocIdeValid(frm.doc_id, frm.num_doc_id))
	       if(!isEmpty(frm.tvia, 'Debe introducir tipo de via'))
	        if(!isEmpty(frm.direccion, 'Debe introducir dirección'))
	         if(!isEmpty(frm.postal_code, 'Debe introducir código postal'))
	          if(!isEmptySelect(frm.pais_resi, 'Debe introducir pais de residencia'))
	           if(!isEmptySelect(frm.provi_resi, 'Debe introducir provincia de residencia'))
	            if(!isEmpty(frm.city_resi, 'Debe introducir ciudad de residencia'))
	             if(!isEmptyAndEmpty(frm.telf_part, frm.telf_mov, 'Debe introducir un teléfono'))
                  if(!isEmptyEmail(frm.email, 'Debe introducir un email'))
                   esok = true;
  return esok;
}
function validarCvEst(frm)
{
  var esok = false;
  if(!isEmptySelect(frm.estudi_level, 'Debe introducir nivel de estudios'))
   if(!isEmpty(frm.estudi_tit, 'Debe introducir título máximo oficial obtenido'))
    esok = true;
  if (esok)
  { //-- habilitar enables
    var fldIdi, nomFldIdi, numIdi;
    for (numIdi=1; numIdi <= 6; numIdi++)
    {
      nomFldIdi = "idioma" + numIdi;
      fldIdi = document.getElementById(nomFldIdi);
      fldIdi.disabled = false;
      nomFldIdi = "idi_level" + numIdi;
      fldIdi = document.getElementById(nomFldIdi);
      fldIdi.disabled = false;
      nomFldIdi = "idi_tit" + numIdi;
      fldIdi = document.getElementById(nomFldIdi);
      fldIdi.disabled = false;
    }
  }
  return esok;
}
function validarCvExp(frm)
{
  var esok = false;
  var numExpe;
  var sNumExpe = frm.num_expe.value;
  if (trim(sNumExpe) == "")
	numExpe = 0;
  else
	numExpe = parseInt(sNumExpe, 10);
  //-- valueChecked : Retorna null tant si no hi na clicats com si no existeixen radios
  var valUltExp = valueChecked('ultima_experiencia');
  var esSi;
  if (valUltExp == null)
    esSi = true;
  else
   esSi = (trim(valUltExp) == "1");
  //var esSi = true;
  if (esSi) //-- sí vol registrar l'última experiencia
  {
    if(!isValidDate(frm.date_ini_exp, 'Debe introducir fecha de inicio'))
     if(!isValidDate(frm.date_fin_exp, 'Debe introducir fecha de fin'))
      if(rangDateValid(frm.date_ini_exp, frm.date_fin_exp, 'La fecha inicial ha de ser inferior a la final'))
      if(!isEmpty(frm.empresa_exp, 'Debe introducir la empresa'))
       if(!isEmptySelect(frm.sec_exp, 'Debe introducir sector'))
        if(!isEmpty(frm.city_exp, 'Debe introducir la ciudad'))
         if(!isEmptySelect(frm.pais_exp, 'Debe introducir el pais'))
          if(!isEmpty(frm.contrato_exp, 'Debe introducir tipo de contrato'))
          {
            var arrFldName = ['finanz_exp', 'si_exp', 'ventas_exp', 'mkt_exp',
                              'rrhh_exp', 'logistic_exp', 'comun_exp',
                              'tecnic_exp', 'assis_exp'];
            if (existOneChecked(arrFldName, 'Debe indicar área de la empresa'))
			{
              if (valueChecked('otra_experiencia') == null && numExpe < 3)
			  {
				var fld = document.getElementById("otra_experiencia_si");
				alert("Indique si desea registrar otra experiencia laboral");
			    fld.focus();
			  } else
			     esok = true;
			}
          }
  } else
    esok = true;
  if (esok && esSi)
  { //-- següent pàgina
	var otraExp;
    var valOtraExp = valueChecked('otra_experiencia');
	if (valOtraExp != null)
	  otraExp = (valueChecked('otra_experiencia') == "1");
	else
	  otraExp = false;
    if (otraExp && numExpe < 4)
	  frm.sec.value = "exp"
	else
	  frm.sec.value = "vac"
  }
  return esok;
}
function enableValidRef(fld)
{
  var opc = fld.options[fld.selectedIndex];
  if (trim(opc.value) != "")
    fld.disabled = false;
}
function validarCvVac(frm)
{
  var esok = false;
  if(existOneRadioChecked('viajar', 'Debe indicar la disponibilidad para viajar'))
   if(existOneRadioChecked('cambio_resi', 'Debe indicar la disponibilidad para cambiar de residencia'))
    if(existOneRadioChecked('automoc_exp', 'Debe indicar experiencia en automoción'))
     if(!isEmptySelect(frm.inf_level, 'Debe indicar su nivel de ofimática'))
     {
       var arrFldName = ['finanz_int', 'si_int', 'ventas_int', 'mkt_int',
                         'rrhh_int', 'logistic_int', 'comun_int',
                         'tecnic_int', 'assis_int'];
       if (existOneChecked(arrFldName, 'Debe indicar áreas de interes'))
         esok = true;
	 }
  if (esok)
  {
	enableValidRef(frm.ref_vac1);
	enableValidRef(frm.ref_vac2);
	enableValidRef(frm.ref_vac3);
	enableValidRef(frm.ref_vac4);
  }
  return esok;
}
function validarCvPre(frm)
{
  var vexts = [ "doc", "pdf" ];
  var val = frm.doc_adjunt.value;
  var empty = (trim(val) == "");
  if (!empty)
  {
    var m = val.split(/\./);
    var ext = m[m.length-1].toLowerCase();
    var trobat = false;
    var idx = 0;
    while (!trobat && idx < vexts.length)
    {
      trobat = (vexts[idx++] == ext);
    }
    if (!trobat)
    {
      alert("Debe adjuntar un documento DOC o PDF");
      frm.doc_adjunt.value = "";
    }
    esOk = trobat;
  } else
    esOk = true;

  return esOk;
}
function ValidarCvCnf(frm)
{
  var esok = frm.lopd.checked;
  if (esok)
    frm.ipt.value = "sve";
  else
  {
    alert("Debe aceptar las normas legales para confirmar el proceso");
	frm.lopd.focus();
  }
  return esok;
}
function validarCv(frm)
{
  var esok;
  var secdta = frm.secdta.value;
  if (secdta == "ide") esok = validarCvIde(frm);
  else if (secdta == "est") esok = validarCvEst(frm);
  else if (secdta == "exp") esok = validarCvExp(frm);
  else if (secdta == "vac") esok = validarCvVac(frm);
  else if (secdta == "pre") esok = validarCvPre(frm);
  else if (secdta == "cnf") esok = true;
  else esok = false;
  return esok;
}
function initPageIde()
{
  var oStringMask = new Mask("dd/mm/yyyy","date");
  oStringMask.attach(document.getElementById("date_nac"));
  var phoneMask = new Mask("?##.###.###");
  phoneMask.attach(document.getElementById("telf_part"));
  phoneMask.attach(document.getElementById("fax"));
  phoneMask.attach(document.getElementById("telf_ofi"));
  var mobileMask = new Mask("&##.###.###");
  mobileMask.attach(document.getElementById("telf_mov"));
  var cpostalMask = new Mask("#####");
  cpostalMask.attach(document.getElementById("postal_code"));
//  var dniMask = new Mask("########-@");
//  dniMask.attach(document.getElementById("dni"));
  var fldnom = document.getElementById("nom");
  fldnom.focus();
}
function initPageEst()
{
  var fldnom = document.getElementById("estudi_level");
  fldnom.focus();
}
function initPageExp()
{
  var oStringMask = new Mask("dd/mm/yyyy","date");
  oStringMask.attach(document.getElementById("date_ini_exp"));
  oStringMask.attach(document.getElementById("date_fin_exp"));
  var fldnom = document.getElementById("date_ini_exp");
  fldnom.focus();
}
function initPageVac()
{
  var nomfld, fld, opc, empty;
  var prefix = "ref_vac";
  var pos = 1;
  var trobat = false;
  while (!trobat && pos < 5)
  {
    nomfld = prefix + pos;
    fld = document.getElementById(nomfld);
    opc = fld.options[fld.selectedIndex];
    trobat = (trim(opc.value) == "");
    pos++;
  }
  fld.disabled = false;
}
function activardoc(fldsel, flddocId)
{
  var flddoc = document.getElementById(flddocId);
  var opc = fldsel.options[fldsel.selectedIndex];
  var empty = (trim(opc.value) == "");
  flddoc.disabled = empty;
  if (!empty)
    flddoc.focus();
}
function addIdioma(frmId)
{ //-- afegim un nou idioma a la llista (dividi* --> capa a mostrar)
  //-- (idioma*, idi_level*, idi_tit* --> camps a fer readonly)
  var frm = document.getElementById(frmId);
  var numIdi = parseInt(frm.num_idioma.value) + 1;
  var nomFldIdi, fldIdi, nomDivIdi, divIdi;

  if (numIdi < 6)
  { //-- validar entrada idioma (idioma* != 0)
    nomFldIdi = "idioma" + numIdi;
    fldIdi = document.getElementById(nomFldIdi);
    var opc = fldIdi.options[fldIdi.selectedIndex];
    if (trim(opc.value) != "0")
    {
      frm.num_idioma.value = numIdi;
      nomDivIdi = "dividi" + (numIdi+1);
      divIdi = document.getElementById(nomDivIdi);
      divIdi.className = "fila_idioma";
      fldIdi.disabled = true;
      nomFldIdi = "idi_level" + numIdi;
      fldIdi = document.getElementById(nomFldIdi);
      fldIdi.disabled = true;
      nomFldIdi = "idi_tit" + numIdi;
      fldIdi = document.getElementById(nomFldIdi);
      fldIdi.disabled = true;
    } else
    {
      alert("Debe introducir idioma");
      fldIdi.focus();
    }
  } else
  {
    alert("No se pueden añadir más idiomas");
  }
}
function changeRef(fld, nextFldName, prevFldName)
{
  var opc = fld.options[fld.selectedIndex];
  var empty = (trim(opc.value) == "");
  if (empty)
  { //-- passa de ple a buit
	if (prevFldName != null)
	{
	  var prevFld = document.getElementById(prevFldName);
	  fld.disabled = true;
	  prevFld.disabled = false;
	}
  } else
  { //-- passa de vuit a ple o de ple a ple
	if (nextFldName != null)
	{
	  var nextFld = document.getElementById(nextFldName);
	  fld.disabled = true;
	  nextFld.disabled = false;
	}
  }
}
