/**
 * @author icabello & dbea
 */

/**
* S'utilitza per obtenir prefixos de controls. Trenquem l'id pel separador i
* obtenim un array d'strings. Seguidament concatenem les cadenes de l'array amb
* separadors fins al nombre de vegades indicades com a paràmetre i ho retornem.
* @param {Object} AId Id de l'element.
* @param {Object} ADelimitador Separador de subelements normalment '_'.
* @param {Object} ANumItems Nombre d'elements a inclore en el resultat.
*/
function getFirstIndexOf(AId, ADelimitador, ANumItems){
   var lvNames, lStr;
   var i;
   
   lStr = '';
   // Trenquem el id pels separadors i ens retorna una collection d'strings
   lvNames = String(AId).split(ADelimitador);
   // Concatenem les cadenes de la collection amb separadors fins al nombre de vegades indicades com a paràmetre
   for (i = 0; i <= ANumItems - 1; i ++ ){
      lStr += lvNames[i] + ADelimitador;
   }
   return lStr;
}

/**
* S'utilitza per obtenir id de controls.
* Retorna l'últim id de control basant - se en 2 separadors.
* Dividim id per la primera cadena de separació ('_') i l'últim
* element de dividir id per la primera cadena el dividim per
* la segona cadena de separació ('|'). Finalment retornem el
* primer element d'aquesta última divisió.
* @param {Object} id
* @param {Object} sep1
* @param {Object} sep2
*/
function getLastIndexOf(id, sep1, sep2){
   var vname, vid, chkid;
   
   vname = String(id).split(sep1);
   chkid = vname[vname.length - 1];
   vid = String(chkid).split(sep2);
   return vid[0];
}

/**
* Aparentment s'utilitza per donar format de tipus moneda separat per comes i punts.
* isNaN = Is Not a Number.
* @param {Object} num
*/
function formatCurrency(num) {
   // treu punts, euros, i comes
   num = num.toString().replace(/\./g, '');
   if(isNaN(num)) { num = "0"; }
      var sign = (num == (num = Math.abs(num)));
   num = Math.floor(num * 100 + 0.50000000001);
   // cents = num % 100;
   num = Math.floor(num / 100).toString();
   // if(cents < 10) cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3);
   i ++ )
   {
      num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
   }
   return (((sign) ? '' : '-') + num);
   // + ',' + cents
}

/**
* Retorna si un element és buit o no.
* @param {Object} field Element a comprovar.
*/
function isEmpty(field){
   if ((field.value === null) || (field.value === '')){
      if ( ! field.disabled){
         field.focus();
      }
      return true;
   }
   else{
      return false;
   }
}

/**
* Comprova si en una DropDownList o listbox hi ha algun element seleccionat. L'element 0 es considera buit.
* @param {Object} field
* @param {Object} isFocus
*/
function isSelectedValue(field, isFocus){
   if (field.selectedIndex === 0){
      if (( ! field.disabled) && (isFocus)){
         field.focus();
      }
      return false;
   }
   else{
      return true;
   }
}

/**
* Valida el format d'un telèfon.
* @param {Object} tel
*/
function isTel (tel) {
   var i, num, cont, error;
   cont = 0;
   error = - 1;
   for(i = 0; i < tel.length; i ++ ){
      num = tel.charAt(i);
      if(num == " "){
      }
      else if( ! isNaN(num)){
         cont ++ ;
      }
      else{
         error = 'El telèfon només pot contenir xifres';
      }
      if(error != - 1){
         break;
      }
   }
   if ((cont != 9) && error == - 1){
      if(tel.length > 0){
         error = 'El telèfon ha de contenir 9 dígits';
      }
   }
   return error;
}

/**
* Valida el format del correu electrònic amb una regular expression.
* @param {Object} email
*/
function isEmail (email) {
   var goodEmail = email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.cat)|(\..{2,2}))$)\b/gi);
   
   if (goodEmail){
      return true;
   }
   else {
      return false;
   }
}

/**
* Valida el format del correu electrònic.
* @param {Object} obj
*/
function isValidEmail(obj) {
   var str = obj.value;
   var at = "@";
   var dot = ".";
   var lat = str.indexOf(at);
   var lstr = str.length;
   var ldot = str.indexOf(dot);
   
   if ( ! isEmpty(obj)){
      if (str.indexOf(at) == - 1){
         return false;
      }
      if (str.indexOf(at) == - 1 || str.indexOf(at) === 0 || str.indexOf(at) == lstr){
         obj.focus();
         return false;
      }
      if (str.indexOf(dot) == - 1 || str.indexOf(dot) === 0 || str.indexOf(dot) == lstr){
         obj.focus();
         return false;
      }
      if (str.indexOf(at, (lat + 1)) != - 1){
         obj.focus();
         return false;
      }
      if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot){
         obj.focus();
         return false;
      }
      if (str.indexOf(dot, (lat + 2)) == - 1){
         obj.focus();
         return false;
      }
      if (str.indexOf(" ") != - 1){
         obj.focus();
         return false;
      }
      return true;
   }
   else{
      return true;
   }
}

/**
* Habilita o deshabilita un checkbox. En cas de deshabilitar-lo el deschequeja.
* @param {Object} me El checkbox
* @param {Object} type El tipus
* @param {Object} enable Habilitar/deshabilitar
*/
function changeInputState(me, type, enable){
   if (me.type == type){
      if ( ! enable){
         me.checked = false;
      }
      me.disabled = ( ! enable);
   }
}

/**
* Agafa els fills a partir del nom del pare.
* @param {Object} id
*/

function getByNameChildrenObjects(id){
   var vaux, str;
   var i;
   str = '';
   vaux = String(id).split('_');
   // li resto 2 per treure el identificador concret del control
   for (i = 0; i <= vaux.length - 2; i ++ ){
      if (str !== ''){
         str = str + '_' + vaux[i];
      }
      else{
         str = vaux[i];
      }
   }
   return str;
}

/**
* Localitza els fills d'un checkbox i habilita o deshabilita els seus fills.
* @param {Object} me
* @param {Object} type
* @param {Boolean} AEnable
*/
function locateAndChangeInputState(me, type, AEnable /*{Boolean}*/){
   var lstr, lenabled;
   var i;
   var lElem, lParentNode;
   lstr = getByNameChildrenObjects(me.id);
   if (AEnable !== undefined)
   {
      lenabled = AEnable;
   }
   else
   {
      lenabled = document.getElementById(me.id).checked;
   }
   for (i = 0; i <= document.forms[0].length - 1; i ++ ){
      lElem = document.forms[0].elements[i];
      if ((String(lElem.id).indexOf(lstr) === 0) && (lElem.type == type) && (lElem.id !== me.id))
      {
         // En cas de que el check sigui de tipus chekanidat no s'habilita. Això s'utilitza en els
         // usercontrols de checklistgrid d'àrea geogràfica del detall d'ofertes de treball per no
         // habilitar les comarques de Barcelona.
         lParentNode = document.forms[0].elements[i].parentNode;
         if ((AEnable !== undefined) && (lParentNode !== undefined) &&
         (lParentNode.className == 'checkanidat'))
         {
            changeInputState(document.forms[0].elements[i], type, false);
         }
         else
         {
            changeInputState(document.forms[0].elements[i], type, lenabled);
         }
         
      }
   }
}

/**
*
* @param {Object} me Un dels checkboxes del usercontrol.
* @param {Object} type Tipus dels chekboxes (suposo que sempre val checkbox)
* @param {Object} checked Aparentment deprecated.
*/

function locateAndGetInputState(me, type, checked){
   var str;
   var i;
   var bool = true;
   // agafa el nom més generic e identificatiu del control per poder agafar tots els fills (TOTS)
   str = getFirstIndexOf(me.id, '_', 2);
   // alert(str);
   for (i = 0; i <= document.forms[0].length - 1; i ++ ){
      if (((String(document.forms[0].elements[i].id).indexOf(str) === 0) &&
         (document.forms[0].elements[i].id != me.id)) && (document.forms[0].elements[i].type == type)) {
         // if (checked){
            // per si al tenir - les totes chequejades es vol mostrar indiferent
            // bool = (bool && document.forms[0].elements[i].checked && me.checked);
            // }else{
            bool = ! ( ! bool || document.forms[0].elements[i].checked || me.checked);
         // }
      }
   }
   return bool;
}

/**
* Força la selecció exclusiva de checkbox en els usercontrols de tipus checklistgrid.
* @param {Object} me
* @param {Object} type
*/
function locateAndSetExclusiveState(me, type)
{
   var str;
   var i;
   // pone en falso todos los hermanos cdo es de seleccion exclusiva
   str = getFirstIndexOf(me.id, '_', 2);
   for (i = 0; i <= document.forms[0].length - 1; i ++ ){
      if (((String(document.forms[0].elements[i].id).indexOf(str) === 0) &&
         (document.forms[0].elements[i].id != me.id)) &&
         (document.forms[0].elements[i].id.indexOf("cbxAltresNou")<0) &&
      (document.forms[0].elements[i].type == type))
      {
         // if (document.forms[0].elements[i].id != me.id){
            document.forms[0].elements[i].checked = false;
         // }
      }
   }
}

/**
* Retorna si hi ha un element a un array.
* (Nota: MSM. Com sempre reinventem la roda perqué desconeixem que existeix indexOf en els arrays.)
* @param {Object} elem
* @param {Object} array
*/
function elementInArray(elem, array){
   var k;
   for (k = 0; k <= array.length - 1; k ++ ){
      if (elem == array[k]){
         return true;
      }
   }
   return false;
}


/**
* Deshabilita els fills d'un checkbox a partir del seu nom (pare).
* @param {Object} arguments
*/
function disableChildObjects(){
   var j, i;
   var name, id, obj, auxid;
   // MSM. Canvi de notació per compatibilitat i millora d'eficiència
   //var vchecked = new Array;
   var vchecked = [];

   // disable children
   //window.console.info('disableChildObjects');
   // window.console.info('arguments.length='+String(arguments.length));
  //    for (i = 0; i <= arguments.length - 1; i ++ )
 // {
   // window.console.info('arguments['+String(i)+'] = ' + arguments[i]); 
  //}
   // argument[0] resetejar ?
   // argument[1] part del form a resetejar
   // argument[2..n] controls a deshabilitar fills
   
   for (i = 2; i <= arguments.length - 1; i ++ ){
      name = arguments[i];
      //window.console.info('name=' + name);
      for (j = 0; j <= document.forms[0].length - 1; j ++ ){
         if ((String(document.forms[0].elements[j].id).indexOf(name) === 0)){
            id = document.getElementById(document.forms[0].elements[j].id).parentElement.parentElement.parentElement.parentElement.parentElement.id;
            obj = document.getElementById(document.forms[0].elements[j].id);
            //window.console.info('id=' + id + 'obj.id=' + obj.id);
            //window.console.info('obj.parentElement.id=' + obj.parentElement.id);
            //window.console.info('obj.parentElement.parentElement.id=' + obj.parentElement.parentElement.id);
            //window.console.info('obj.parentElement.parentElement.parentElement.id=' + obj.parentElement.parentElement.parentElement.id);
            //window.console.info('obj.parentElement.parentElement.parentElement.parentElement.id=' + obj.parentElement.parentElement.parentElement.parentElement.id);
            //window.console.info('obj.parentElement.parentElement.parentElement.parentElement.parentElement.id=' + obj.parentElement.parentElement.parentElement.parentElement.parentElement.id);
            auxid = getLastIndexOf(obj.id, '$', '|');
            
            //window.console.info('auxid=' + auxid);
            if ((String(id).indexOf(name + '$CheckboxGrid$') === 0) && ( ! elementInArray(auxid, vchecked))){
               //window.console.info(obj.id + ' disabled.');
               changeInputState(obj, 'checkbox', false);
            }
            else{
               if (obj.checked){
                  vchecked.push(getLastIndexOf(obj.id, '$', '|'));
               }
            }
         }
      }
   }
}

/**
* Mira si tots els germans i/o fills estan chequejats.
* @param {checkbox} obj Checkbox que estem processant.
* @param {boolean} exclusive Fa que la selecció sigui exclusiva per als checkboxes.
*/
function groupItemsState(obj/*:checkbox*/, exclusive/*:boolean*/){
   var vVector;
   if (locateAndGetInputState(obj, 'checkbox', obj.checked)){
      if (String(document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML).indexOf(' (Indiferent)') > 0){
         vVector = String(document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML).split(' (Indiferent)');
         document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML = vVector[0];
         document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML += ' (Indiferent)';
      }
      else{
         document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML += ' (Indiferent)';
      }
   }
   else{
      vVector = String(document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML).split(' (Indiferent)');
      document.getElementById(getFirstIndexOf(obj.id, '$', 2) + 'lblHeader').innerHTML = vVector[0];
      // alert('exclusive :' + exclusive);
      if (exclusive && obj.checked) {
         // alert('locateAndSetExclusiveState');
         locateAndSetExclusiveState(obj, 'checkbox');
      }
   }
}

// mira si tots els germans i / o fills estan chequejats (deprecated)
/*
function groupItemsState(obj){
   var vVector;
   if (locateAndGetInputState(obj, 'checkbox', obj.checked)){
      if (String(document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML).indexOf(' (Indiferent)') > 0){
         vVector = String(document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML).split(' (Indiferent)');
         document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML = vVector[0];
         document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML += ' (Indiferent)';
         }else{
         document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML += ' (Indiferent)';
      }
      }else{
      vVector = String(document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML).split(' (Indiferent)');
      document.getElementById(getFirstIndexOf(obj.id, '_', 2) + 'lblHeader').innerHTML = vVector[0];
   }
}
*/


/**
* Posa el valor a un tipus de control en concret (MSM. Descripció de funcionament lapidària.).
* @param {Object} me
* @param {Object} type
* @param {Object} checked
* @param {Object} enabled
* @param {Object} checkItems
*/
function resetInputValue(me, type, checked, enabled, checkItems){
   var i, nombre1, nombre2;
   for (i = 0; i <= document.forms[0].length - 1; i ++ ){
      if (String(document.forms[0].elements[i].id).indexOf(me) > - 1){
         if (document.forms[0].elements[i].type == type){
            if (checked !== null){
               document.forms[0].elements[i].checked = checked;
            }
            if (enabled !== null){
               document.forms[0].elements[i].disabled = ( ! enabled);
            }
         }
      }
   }
   
   if (checkItems){
      nombre1 = '';
      for (i = 0; i <= document.forms[0].length - 1; i ++ ){
         nombre2 = getFirstIndexOf(document.forms[0].elements[i].id, '_', 2);
         if (String(document.forms[0].elements[i].id).indexOf(me) > - 1){
            if (document.forms[0].elements[i].type == type){
               if ((nombre1 != nombre2)){
                  groupItemsState(document.getElementById(document.forms[0].elements[i].id));
               }
               nombre1 = nombre2;
            }
         }
      }
   }
}

/**
* Funcions del formulari d'inscripció a l'acte A prop teu 2005.
*/
function validateForm(){
   
   var nom = document.wciform.txtNom.value;
   var cognoms = document.wciform.txtCognoms.value;
   var telefon = document.wciform.txtTelefon.value;
   // var numero = document.wciform.txtNumCol.value;
   var email = document.wciform.txtemail.value;
   var assitents = document.wciform.txtAssistents.value;
   
   if (nom === ""){
      alert('El camp nom és obligatori');
      document.wciform.txtNom.focus();
   }
   else if(cognoms === ""){
      alert('El camp cognoms és obligatori');
      document.wciform.txtCognoms.focus();
   }
   else if(isTel(telefon) != - 1){
      alert(isTel(telefon));
      document.wciform.txtTelefon.focus();
   }
   else
      /*
   else if (document.wciform.rdbNoucolSi.checked){
      if((isNaN(numero)) || (numero == '')){
         alert('El número de col·legiat ha de ser un número');
         document.wciform.txtNumCol.focus();
      }
   }
   */
   
   if( ! isEmail(email) && ! email === ""){
      alert('El correu electrònic no es correcte');
      document.wciform.txtemail.focus();
   }
   else if(telefon.length === 0 && email.length === 0){
      alert('El camp telèfon o correu electrònic son necessaris');
   }
   else if(assitents === ""){
      alert('El número total d\'assistents és obligatori');
      document.wciform.txtAssistents.focus();
   }
   else if(isNaN(assitents)){
      alert('El número total d\'assistents ha de ser un número');
      document.wciform.txtAssistents.focus();
   }
   else if(assitents <= 0){
      alert('El número total d\'assistents ha de ser més gran que zero');
      document.wciform.txtAssistents.focus();
   }
   else{
      document.wciform.submit();
   }
}

/**
* Funcions del formulari d'inscripció a l'acte A prop teu 2005.
*/
function enviar(){
   validateForm();
}

/**
*
* @param {Object} impresio
*/
function restaurarVisualitzacio(impresio){
   if (document.wciform.rdbAutoSi.checked){
      document.getElementById("tdlblPoblacio").style.display = 'block';
      document.getElementById("tdcmbPoblacio").style.display = 'block';
      document.getElementById("tdlblRecorregut").style.display = 'block';
      document.getElementById("tdcmbRecorregut").style.display = 'block';
      
   }
   if (impresio == "True"){
      this.focus();
      this.print();
      this.close();
   }
}

/**
*
*/
function amagarVisualitzacio(){
   
   if (document.wciform.rdbAutoNo.checked){
      document.getElementById("tdlblPoblacio").style.display = 'none';
      document.getElementById("tdcmbPoblacio").style.display = 'none';
      document.getElementById("tdlblRecorregut").style.display = 'none';
      document.getElementById("tdcmbRecorregut").style.display = 'none';
   }
}

/**
*
* @param {Object} check
*/
function mostrarLlistaAutocar(check){
   var llista = document.getElementById('autocar');
   llista.style.display = 'block';
   llista = document.getElementById('titolAutocar');
   llista.style.display = 'block';
   document.getElementById("tdlblRecorregut").style.display = 'block';
   document.getElementById("tdcmbRecorregut").style.display = 'block';
}

/**
*
*/
function amagaLlistaAutocar(){
   var llista = document.getElementById('autocar');
   llista.style.display = 'none';
   llista = document.getElementById('titolAutocar');
   llista.style.display = 'none';
   document.getElementById("tdlblRecorregut").style.display = 'none';
   document.getElementById("tdcmbRecorregut").style.display = 'none';
}

/**
*
*/
function amagaLlistaPoblacions(){
   var llista = document.getElementById('poblacio');
   llista.style.display = 'none';
   llista = document.getElementById('titolPoblacio');
   llista.style.display = 'none';
   document.getElementById("tdlblPoblacio").style.display = 'none';
   document.getElementById("tdcmbPoblacio").style.display = 'none';
}

/**
*
* @param {Object} check
*/
function mostrarLlistaPoblacions(check){
   var llista = document.getElementById('poblacio');
   llista.style.display = 'block';
   llista = document.getElementById('titolPoblacio');
   llista.style.display = 'block';
   document.getElementById("tdlblPoblacio").style.display = 'block';
   document.getElementById("tdcmbPoblacio").style.display = 'block';
}

/**
* Funcions per a la validació del formulari de Queixes, reclamacions i suggeriments
*/

function validarQueixa(fire_postback_code)
{
    var bool = true;
	var frm = document.wciform;	
	
	if (frm.template_rblMitja_1.checked)
	{
	    //correu		
		if (bool && isEmpty(frm.template_txtNom))
		{
		    alert('El camp NOM és necessari per poder enviar la resposta.');
			bool = false;
		}		
		if (bool && isEmpty(frm.template_txtCognom1))
		{
			alert('El camp PRIMER COGNOM és necessari per poder enviar la resposta.');
			bool = false;
		}		
		if (bool && isEmpty(frm.template_txtAdresa))
		{
			alert('El camp ADREÇA és necessari per poder enviar la resposta.');
			bool = false;
		}
		//template_frmPoblacions_lbxPoblacio
		if (bool && isEmpty(frm.listPoblacions))
		{
			alert('El camp POBLACIÓ és necessari per poder enviar la resposta.');
			bool = false;
		}				
		if (bool && isEmpty(frm.template_txtCodiPostal))
		{
			alert('El camp CODI POSTAL és necessari per poder enviar la resposta.');
			bool = false;
		}
	}
	else
	{
	    if (frm.template_rblMitja_3.checked)
	    {
		    //email
			if (bool && isEmpty(frm.template_txtNom))
			{
				alert('El camp NOM és necessari per poder enviar la resposta.');
				bool = false;
			}			
			if (bool && isEmpty(frm.template_txtCognom1))
			{
				alert('El camp PRIMER COGNOM és necessari per poder enviar la resposta.');
				bool = false;
			}							
			if ((bool) && isEmpty(frm.template_txtCorreuElectronic))
			{
				alert('El camp CORREU ELECTRÒNIC és necessari per poder enviar la resposta.');
				bool = false;
			}			
			if (bool && !isEmpty(frm.template_txtCorreuElectronic))
			{
			    if (!isEmail(frm.template_txtCorreuElectronic.value))
			    {
				    alert('El CORREU ELECTRÒNIC introduït no és correcte.');
					bool = false;
				}
			}
		}
		else
		{
		    if (frm.template_rblMitja_2.checked)
		    {
			    //fax
				if (bool && isEmpty(frm.template_txtNom))
				{
					alert('El camp NOM és necessari per poder enviar la resposta.');
					bool = false;
				}				
				if (bool && isEmpty(frm.template_txtCognom1))
				{
					alert('El camp PRIMER COGNOM és necessari per poder enviar la resposta.');
					bool = false;
				}				
				if (bool && isEmpty(frm.template_txtFax))
				{
					alert('El camp FAX és necessari per poder enviar la resposta.');
					bool = false;
				}
			}
			else
			{
			    if (frm.template_rblMitja_0.checked)
			    {
				    //no en vull rebre
					if (bool && isEmpty(frm.template_txtNom))
					{
						alert('El camp NOM és necessari per poder enviar la resposta.');
						bool = false;
					}				
					if (bool && isEmpty(frm.template_txtCognom1))
					{
						alert('El camp PRIMER COGNOM és necessari per poder enviar la resposta.');
						bool = false;
					}
				}
				else
				{
				    if (frm.template_rblMitja_4.checked)
			        {
				        //teléfon
					    if (bool && isEmpty(frm.template_txtNom))
					    {
						    alert('El camp NOM és necessari per poder enviar la resposta.');
						    bool = false;
					    }				
					    if (bool && isEmpty(frm.template_txtCognom1))
					    {
						    alert('El camp PRIMER COGNOM és necessari per poder enviar la resposta.');
						    bool = false;
					    }
					    if (bool && (isEmpty(frm.template_txtTelefon) && isEmpty(frm.template_txtTelefonMobil)))
					    {
						    alert('És necessari algun TELÈFON de contacte per poder respondre telefònicament.');
						    bool = false;
					    }					
    				}
    			}
			}
		}
	}
	
	if (bool && !isEmpty(frm.template_txtCorreuElectronic)){
		if (!isEmail(frm.template_txtCorreuElectronic.value)){
			alert('El CORREU ELECTRÒNIC introduït no és correcte.');
			bool = false;
		}
	}
	
	if (bool && isEmpty(frm.template_txtComentaris)){
		alert('El camp COMENTARIS és necessari per poder enviar la queixa, reclamació o suggeriment.');
		bool = false;
	}

	if (bool && frm.template_chMailConfirmacio.checked && isEmpty(frm.template_txtCorreuElectronic)) {
	    alert("Si desitja rebre confirmació del suggeriment, ha d'introduïr un CORREU ELECTRÒNIC");
	    bool = false;
	}
	
	if (bool){
		eval(fire_postback_code);
	}
}

/*
  Funcions per a la validació del formulari de Deixen's les teves dades
*/
function validarDeixansLesTevesDades(fire_postback_code){
	var bool = true;
	var frm = document.wciform;
	
	
	if (bool && isEmpty(frm.template_txtNom))
	{
	    alert('El camp NOM és necessari per poder rebre el mailing');
	    bool = false;
	}
		
	if (bool && isEmpty(frm.template_txtCognom1))
	{
	    alert('El camp PRIMER COGNOM és necessari per poder rebre el mailing');
		bool = false;
	}
		
	if (bool && isEmpty(frm.template_txtCognom2)){
	    alert('El camp SEGON COGNOM és necessari per poder rebre el mailing.');
		bool = false;
	}
	
	if (bool && isEmpty(frm.template_txtCorreuElectronic)){
		alert('El camp CORREU ELECTRÒNIC és necessari per poder rebre el mailing.');
		bool = false;
	}
		
	if (bool && !isEmpty(frm.template_txtCorreuElectronic))
	{
	    if (!isEmail(frm.template_txtCorreuElectronic.value))
	    {
		    alert('El CORREU ELECTRÒNIC introduït no és correcte.');
			bool = false;
		}
	}
	
	if (bool)
	{
		eval(fire_postback_code);
	}
}


function validarCessioDades(fire_postback_code) {
    var bool = true;
    var frm = document.wciform;


    if (bool && isEmpty(frm.template_txtNumCol)) {
        alert('El NÚMERO DE COL·LEGIAT és obligatori.');
        bool = false;
    }

    if (bool && isEmpty(frm.template_txtNom)) {
        alert('El camp NOM és obligatori.');
        bool = false;
    }

    if (bool && isEmpty(frm.template_txtCognom1)) {
        alert('El camp PRIMER COGNOM és obligatori.');
        bool = false;
    }

    if (bool && isEmpty(frm.template_txtCognom2)) {
        alert('El camp SEGON COGNOM és obligatori.');
        bool = false;
    }

    if (bool && isEmpty(frm.template_txtTelefon)) {
        alert('El camp TELÈFON és obligatori.');
        bool = false;
    }

    if (bool) {
        eval(fire_postback_code);
    }
}

/**
* extreu un string d'un altre i retorna el restant al camp
*/

function popChar(strfield,str){
	var vaux;
	var field;
	
	field = document.getElementById(strfield);
	
	if (field.innerHTML.indexOf(str) > 0){
		vaux = field.innerHTML.split(str);	
		field.innerHTML = vaux[0];
	}
}

/**
* neteja les labels obligatories
*/

function netejarOblFormQueixes(){	
	popChar('template_lblAdresa',' *');	
	popChar('template_frmPoblacions_lblProvincia',' *');
	popChar('template_frmPoblacions_lblPoblacio',' *');
	popChar('template_lblCodiPostal',' *');
	popChar('template_lblCorreu',' *');
	popChar('template_lblFax',' *');
	popChar('template_lblTelefon',' *');
}

/**
* Canvia el caption de les labels en funció de la opció escollida per dir quins camps són obligatoris.
*/

function marcarObligatoris()
{
	var frm = document.wciform;
		
	if (frm.template_rblMitja_0.checked)
	{
	    //no resposta
		netejarOblFormQueixes();
	}
	else
	{
	    if (frm.template_rblMitja_1.checked)
	    {
		    //correu
			netejarOblFormQueixes();						
    		document.getElementById('template_lblAdresa').innerHTML += ' *';
	    	document.getElementById('template_frmPoblacions_lblProvincia').innerHTML += ' *';
		    document.getElementById('template_frmPoblacions_lblPoblacio').innerHTML += ' *';
			document.getElementById('template_lblCodiPostal').innerHTML += ' *';
		}
		else
		{
		    if (frm.template_rblMitja_3.checked)
			{
			    //email
				netejarOblFormQueixes();												
        		document.getElementById('template_lblCorreu').innerHTML += ' *';
			}
			else
			{
			    if (frm.template_rblMitja_2.checked)
				{
				    //fax
					netejarOblFormQueixes();									
					document.getElementById('template_lblFax').innerHTML += ' *';	
				}
				else
				{
				    if (frm.template_rblMitja_4.checked)
				    {
				        //telèfon
					    netejarOblFormQueixes();
            			document.getElementById('template_lblTelefon').innerHTML += ' *';	
            		}
            	}
		    }
        }
    }
}

/**
* Suposo que deu de rebre un array de checkboxes i comprova si algun està checked.
* (Nota: En la condició del for podria incloure's la validació de bool per millorar eficiència.)
*/

function isSelectedOption(){
   var bool;
   var i;
   bool = false;
   
   for (i = 0; i <= arguments.length - 1; i ++ ){
      bool = (bool || arguments[i].checked);
   }
   
   return bool;
}

/**
* Comprova que la longitud del valor d'un element sigui vàlida.
* @param {Object} field
* @param {Object} longitud
*/
function isValidLength(field, longitud){
   if (Number(field.value.length) >= Number(longitud)){
      return true;
   }
   else{
      if ( ! field.disabled){
         field.focus();
      }
      return false;
   }
}

/**
* Comprova que dos valors de dos elements siguin iguals i si no ho son intenta donar el focus al segon.
* S'utilitza en la validació de canvi de contrasenya.
* @param {Object} field1 Primer element.
* @param {Object} field2 Segon element.
*/
function equalValues(field1, field2){
   if (field1.value == field2.value){
      return true;
   }
   else{
      if ( ! field2.disabled){
         field2.focus();
      }
      return false;
   }
}

/**
* Nomesnumeros
* @param {Object} evt
*/
function nomesnumeros_onkeypress(evt) {
   
   var e = (window.event) ? window.event : evt ;
   var keycode;
   if (document.all) { keycode = e.keyCode ; }
   else if (document.getElementById) {keycode = e.which ; }
   if (keycode > 32 && (keycode < 48 || keycode > 57)) {
      if (e && e.preventDefault) {
         e.preventDefault() ;
         e.returnValue = false ;
      }
      else {e.returnValue = false ;}
         return false ;
   }
   else { return true ;}
   }

/**
* Valida un formulari. (Quin???).
* @param {Object} fire_postback_code - Si val true fa postback, sinó no???.
* @author MSM.
*/
function validForm(fire_postback_code){
   var bool;
   bool = true;

   if (bool){
      if ( ! isEmpty(document.wciform.template_txtEmail)){
         if ( ! (isValidEmail(document.wciform.template_txtEmail))){
            alert('El format del correu electrònic és incorrecte.');
            bool = false;
         }
      }
      else{
         alert('El camp correu electrònic ha d\'estar informat.');
         bool = false;
      }
   }
   
   if (bool){
      if ( ! isSelectedValue(document.wciform.template_ddlTipusProblema)){
         alert('Ha de seleccionar un valor per al camp tipus de problema.');
         bool = false;
      }
   }
   
   if (bool){
      if (isEmpty(document.wciform.comentaris)){
         alert('El camp comentaris ha d\'estar informat.');
         bool = false;
      }
   }
   
   if (bool){
      if ( ! isSelectedValue(document.wciform.template_ddlFrecuencia)){
         alert('Ha de seleccionar un valor per al camp freqüència.');
         bool = false;
      }
   }
   
   if (bool){
      if ( ! isSelectedOption(document.wciform.template_rblConnexio_0, document.wciform.template_rblConnexio_1)){
         alert('Ha de seleccionar un valor per al camp tipus de connexió.');
         bool = false;
      }
   }

   if (bool) {
       if ((document.wciform.template_ddlTipusProblema.selectedIndex === 5) && (document.wciform.template_txtEmail.value === document.wciform.template_txtEmailWebCOIB.value)) {
           alert("Si no pot entrar al correu, ha d'indicar una adreça de correu alternativa per poder ser atesa.");
           bool = false;
       }
   }


   if (bool) {
       if ((document.wciform.template_ddlTipusProblema.selectedIndex === 6) && (document.wciform.template_txtEmail.value === document.wciform.template_txtEmailWebCOIB.value)) {
           var answer = confirm ("Si el problema que té implica que no pot llegir correus electrònics, si us plau, canviï l'adreça de correu on vol rebre la resposta.\n\n" +
                                 "Desitja enviar igualment la seva incidència i ser atesa a l'adreça " + document.wciform.template_txtEmail.value + "?")
           if (!(answer))
           bool = false;
       }
   }
   
   if (bool){
      eval(fire_postback_code);
   }
}

/**
* Valida el formulari d'enviar a un amic.
* @param {Object} fire_postback_code
*/
function validateFormAmic(fire_postback_code){
   var bool;
   bool = true;
   
   if (bool){
      if (isEmpty(document.wciform.template_Remitent)){
         alert('El camp Remitent ha d\'estar informat.');
         bool = false;
      }
   }
   
   if (bool){
      if ( ! isEmpty(document.wciform.template_adresa)){
         if ( ! (isValidEmail(document.wciform.template_adresa))){
            alert('El format del correu electrònic és incorrecte.');
            bool = false;
         }
      }
      else{
         alert('El camp Adreça ha d\'estar informat.');
         bool = false;
      }
   }
   
   if (bool){
      document.wciform.iframecontents.value = Frameaenviar.document.body.innerHTML;
      eval(fire_postback_code);
   }
}

/**
* Validació del formulari de canvi de contrassenya.
* @param {Object} fire_postback_code
*/
function VFCanviPass(fire_postback_code){
   var bool;
   bool = true;
   
   
   if (bool){
      if (isEmpty(document.wciform.tbnovacontrasenya)){
         alert('El camp nova paraula clau ha d\'estar informat.');
         bool = false;
      }
      else{
         if ( ! isValidLength(document.wciform.tbnovacontrasenya, 6)){
            alert('La paraula clau ha de tenir un mínim de 6 caràcters.');
            bool = false;
         }
      }
   }
   
   if (bool){
      if (isEmpty(document.wciform.tbconfirmaciocontrasenya)){
         alert('El camp confirmació de paraula clau ha d\'estar informat.');
         bool = false;
      }
      else{
         if ( ! equalValues(document.wciform.tbnovacontrasenya, document.wciform.tbconfirmaciocontrasenya)){
            alert('La confirmació ha de ser igual que la paraula clau.');
            bool = false;
         }
      }
   }
   
   if (bool){
      eval(fire_postback_code);
   }
}

/**
* Validació e-mail.
* @param {Object} fire_postback_code
*/
function VFEmail(fire_postback_code){
   var bool;
   bool = true;
   
   if (bool){
      if ( ! isEmpty(document.wciform.template_txtEmail)){
         if ( ! (isValidEmail(document.wciform.template_txtEmail))){
            alert('El format del correu electrònic és incorrecte.');
            bool = false;
         }
      }
      else{
         alert('El camp correu electrònic ha d\'estar informat.');
         bool = false;
      }
   }
   
   if (bool){
      eval(fire_postback_code);
   }
}

/**
* Validació usuari.
* @param {Object} fire_postback_code
*/
function VFValidUser(fire_postback_code){
   var bool;
   bool = true;
   
   if (bool){
      if ( ! isEmpty(document.wciform.user)){
         bool = true;
      }
      else{
         alert('Has d\'escriure el teu nom d\'usuari per a poder identificar-te.');
         bool = false;
      }
   }
   
   if (bool){
      document.wciform.submit();
   }
}

/**
* Validació del formulari de resposta.
* @param {Object} fire_postback_code
*/
function VFResposta(fire_postback_code){
   var bool;
   bool = true;
   
   if (bool){
      if ( ! isEmpty(document.wciform.resposta)){
         bool = true;
      }
      else{
         alert('Has d\'escriure el text corresponent a la resposta.');
         bool = false;
      }
   }
   
   if (bool){
      eval(fire_postback_code);
   }
}

/**
* Validació del text del cercador.
* @param {Object} fire_postback_code
*/
function ValidarTextoCercador(fire_postback_code) {
   var txtCer = document.getElementById('template_tCercador') ;
   if(txtCer){
      if( ! isValidLength(txtCer, 3)){
         alert('La cadena de cerca ha de tenir més de 2 caràcteres');
      }
      else{
         eval(fire_postback_code);
      }
   }
}

/**
* Validació formulari de suport.
* @param {Object} fire_postback_code
*/
function validFormSupportExchange(fire_postback_code) {
   var txtMem = document.getElementById('template_memResposta');
   if(txtMem){
      if(isEmpty(txtMem)){
         alert('Per poder enviar el formulari has d\'escriure algun comentari.');
      }
      else{
         eval(fire_postback_code);
      }
   }
}

/**
* Validació formulari enquesta.
* @param {Object} fire_postback_code
*/
function validFormEnquesta(fire_postback_code){
   var bool;
   bool = true;
   if ( ! isSelectedOption(document.wciform.template_resp1RadioButton13, document.wciform.template_resp1RadioButton1, document.wciform.template_resp1RadioButton2, document.wciform.template_resp1RadioButton3 )){
      // alert('Ha de seleccionar un valor per la primer respuesta');
      bool = false;
   }
   if ( bool && ! isSelectedOption(document.wciform.template_resp2RadioButton4, document.wciform.template_resp2RadioButton5, document.wciform.template_resp2RadioButton6 )){
      // alert('Ha de seleccionar un valor per la Segunda respuesta');
      bool = false;
   }
   if (bool && ! isSelectedOption(document.wciform.template_resp3RadioButton7, document.wciform.template_resp3RadioButton8 )){
      // alert('Ha de seleccionar un valor per la tercerea respuesta');
      bool = false;
   }
   if ( bool && ! isSelectedOption(document.wciform.template_resp4RadioButton10, document.wciform.template_resp4RadioButton11, document.wciform.template_resp4RadioButton12 )){
      // alert('Ha de seleccionar un valor per la Cuarta respuesta');
      bool = false;
   }
   if(bool){
      eval(fire_postback_code);
   }
   else{
      alert("Si us plau respongui a totes les preguntes de l'enquesta");
   }
   
}

/**
* Validació del formulari subscripció d'alertes de treball.
* @param {Object} fire_postback_code
*/
function VFAlertes(fire_postback_code){
   var bool;
   bool = true;
   // situació laboral
   if (bool && ! isSelectedOption(document.wciform.template_rblSituacioLaboral_0, document.wciform.template_rblSituacioLaboral_1)){
      bool = false;
      alert("Has de seleccionar una situació laboral.");
   }
   
   // motiu de cerca
   if (bool && isSelectedOption(document.wciform.template_rblSituacioLaboral_1)){
      // si la situació laboral es actiu...
      if (bool && ! isSelectedValue(document.wciform.template_ddlMotiuCerca)){
         bool = false;
         alert("Has d\'informar el motiu de cerca.");
      }
   }
   
   // periodicitat
   if (bool && ! isSelectedOption(document.wciform.template_rblPeriodicitat_0, document.wciform.template_rblPeriodicitat_1)){
      bool = false;
      alert("Has de seleccionar una periodicitat.");
   }
   else{
      // si seleccionen setmanal cada
      if (bool && isSelectedOption(document.wciform.template_rblPeriodicitat_1)){
         // han de seleccionar el dia de la setmana
         if ( ! isSelectedValue(document.wciform.template_ddlDiaSetmana)){
            bool = false;
            alert("Has d\'informar el dia de la setmana en el que vols rebre les ofertes.");
         }
      }
   }
   // experiencia laboral 1
   if (bool && isSelectedValue(document.wciform.template_ddlExperiencia1, false)) {
      // si seleccionen experiència laboral han de dir si tenen més d'un any o no
      if (bool && ! isSelectedOption(document.wciform.template_rblExperiencia1_0, document.wciform.template_rblExperiencia1_1)){
         bool = false;
         alert("Has d\'informar si tens més d\'un any d\'experiencia en l\'ambit seleccionat.");
      }
   }
   
   // experiencia laboral 2
   if (bool && isSelectedValue(document.wciform.template_ddlExperiencia2, false)){
      // si seleccionen experiència laboral han de dir si tenen més d'un any o no
      if (bool && ! isSelectedOption(document.wciform.template_rblExperiencia2_0, document.wciform.template_rblExperiencia2_1)){
         bool = false;
         alert("Has d\'informar si tens més d\'un any d\'experiencia en l\'ambit seleccionat.");
      }
   }
   
   if(bool){
      eval(fire_postback_code);
   }
}

/**
* Habilita o deshabilita controls del formulari de subscripcio d'alertes en funció dels seus valors.
*/
function disableAlertesRelated()
{
   var vreq;
   
   if (document.wciform.template_ddlExperiencia1.selectedIndex === 0){
      document.wciform.template_rblExperiencia1_0.checked = false;
      document.wciform.template_rblExperiencia1_1.checked = false;
      document.wciform.template_rblExperiencia1_1.disabled = true;
      document.wciform.template_rblExperiencia1_0.disabled = true;
      
      document.wciform.template_ddlExperiencia2.selectedIndex = 0;
      document.wciform.template_ddlExperiencia2.disabled = true;
      document.wciform.template_rblExperiencia2_1.disabled = true;
      document.wciform.template_rblExperiencia2_0.disabled = true;
      
      vreq = String(document.getElementById('template_lblExperiencia1').innerHTML).split('(*)');
      document.getElementById('template_lblExperiencia1').innerHTML = vreq[0];
   }
   else{
      document.wciform.template_ddlExperiencia2.disabled = false;
      vreq = String(document.getElementById('template_lblExperiencia1').innerHTML).split('(*)');
      document.getElementById('template_lblExperiencia1').innerHTML = vreq[0];
      document.getElementById('template_lblExperiencia1').innerHTML += '(*)';
   }
   
   if (document.wciform.template_ddlExperiencia2.selectedIndex === 0){
      document.wciform.template_rblExperiencia2_0.checked = false;
      document.wciform.template_rblExperiencia2_1.checked = false;
      document.wciform.template_rblExperiencia2_1.disabled = true;
      document.wciform.template_rblExperiencia2_0.disabled = true;
      
      vreq = String(document.getElementById('template_lblExperiencia2').innerHTML).split('(*)');
      document.getElementById('template_lblExperiencia2').innerHTML = vreq[0];
   }
   else{
      vreq = String(document.getElementById('template_lblExperiencia2').innerHTML).split('(*)');
      document.getElementById('template_lblExperiencia2').innerHTML = vreq[0];
      document.getElementById('template_lblExperiencia2').innerHTML += '(*)';
   }
   
   document.wciform.template_rblExperiencia2_1.disabled = (document.wciform.template_ddlExperiencia2.selectedIndex === 0);
   document.wciform.template_rblExperiencia2_0.disabled = (document.wciform.template_ddlExperiencia2.selectedIndex === 0);
   
   document.wciform.template_rblExperiencia1_1.disabled = (document.wciform.template_ddlExperiencia1.selectedIndex === 0);
   document.wciform.template_rblExperiencia1_0.disabled = (document.wciform.template_ddlExperiencia1.selectedIndex === 0);
   
   document.wciform.template_ddlDiaSetmana.disabled = ( ! isSelectedOption(document.wciform.template_rblPeriodicitat_1));
   
   if (isSelectedOption(document.wciform.template_rblSituacioLaboral_1)){
      document.wciform.template_ddlMotiuCerca.disabled = false;
      vreq = String(document.getElementById('template_lblMotiuCerca').innerHTML).split('(*)');
      document.getElementById('template_lblMotiuCerca').innerHTML = vreq[0];
      document.getElementById('template_lblMotiuCerca').innerHTML += '(*)';
   }
   else{
      document.wciform.template_ddlMotiuCerca.disabled = true;
      vreq = String(document.getElementById('template_lblMotiuCerca').innerHTML).split('(*)');
      document.getElementById('template_lblMotiuCerca').innerHTML = vreq[0];
   }
   
   if (document.wciform.template_chkNoCorreu.checked) {
      document.wciform.template_rblPeriodicitat_0.disabled = true;
      document.wciform.template_rblPeriodicitat_1.disabled = true;
      document.wciform.template_ddlDiaSetmana.disabled = true;
      document.wciform.template_rblSelectorOfertes_0.disabled = true;
      document.wciform.template_rblSelectorOfertes_1.disabled = true;
      document.wciform.template_txtRetribucio.disabled = true;
   }
   else{
      document.wciform.template_rblPeriodicitat_0.disabled = false;
      document.wciform.template_rblPeriodicitat_1.disabled = false;
      document.wciform.template_ddlDiaSetmana.disabled = ( ! isSelectedOption(document.wciform.template_rblPeriodicitat_1));
      document.wciform.template_rblSelectorOfertes_0.disabled = false;
      document.wciform.template_rblSelectorOfertes_1.disabled = false;
      document.wciform.template_txtRetribucio.disabled = (document.wciform.template_rblSelectorOfertes_0.checked);
   }
}

/**
*
*/
function manageCheckedList()
{
   var enabled, correu;
   
   enabled = false;
   correu = false;
   
   if (document.wciform.template_rblSelectorOfertes_0 !== undefined){
      enabled = document.wciform.template_rblSelectorOfertes_0.checked;
   }
   
   if (document.wciform.template_chkNoCorreu !== undefined){
      correu = document.wciform.template_chkNoCorreu.checked;
   }
   if (enabled || correu){
      // chequeja tots els controls o no en funcio de la primera part del if
      
      if (enabled) {
         resetInputValue(arguments[1], 'checkbox', true, false, false);
      }
      else{
         resetInputValue(arguments[1], 'checkbox', null, false, false);
      }
      document.getElementById('btnNetejar').style.display = 'none';
      document.wciform.template_txtRetribucio.value = '';
      document.wciform.template_txtRetribucio.disabled = true;
   }
   else{
      if ( ! enabled) {
         document.getElementById('btnNetejar').style.display = 'block';
         document.wciform.template_txtRetribucio.disabled = false;
         resetInputValue(arguments[1], 'checkbox', null, true, true);
         disableChildObjects(arguments);
      }
   }
}

/**
*
*/
function IFAlertes(){
   // argument[0] resetejar ?
   // argument[1] part del form a resetejar
   // argument[2..n] controls a deshabilitar fills
   //window.console.info('IFAlertes');
   if (arguments[0]){
      // boto netejar
      resetInputValue(arguments[1], 'checkbox', false, true, true);
      document.wciform.template_txtRetribucio.value = '';
   }
   else{
      // inici formulari
      manageCheckedList(arguments[0], arguments[1], arguments[2]);
      // estem al formulari de subscripcio
      // alert(document.wciform.template_chkNoCorreu);
      if (document.wciform.template_chkNoCorreu !== undefined){
         disableAlertesRelated();
      }
   }
   //disableChildObjects(arguments);
   disableChildObjects(arguments[0], arguments[1], arguments[2]);
}

/**
*
*/
function amagarFiltres(){
   if (document.getElementById('template_pnlChecks').style.display == 'block'){
      document.getElementById('template_pnlChecks').style.display = 'none';
      document.getElementById('template_lblAmagarMostrar').innerText = 'Mostrar';
   }
   else{
      document.getElementById('template_pnlChecks').style.display = 'block';
      document.getElementById('template_lblAmagarMostrar').innerText = 'Amagar';
   }
}

//  ---------------------------------------
// Valida el formulari de salut mental
function validateSalutMental(fire_postback_code){
   var bool;
   bool = true;
   
   var telefon = isTel(document.wciform.template_txtTel.value);
   if (isEmpty(document.wciform.template_txtTel)){
      telefon = isTel(' ');
   }   
   // alert(isEmpty(document.wciform.template_txtTel));
   
   // alert(telefon);
   if ( isEmpty(document.wciform.template_txtNom) ){
      alert('El camp nom és obligatori');
      document.wciform.template_txtNom.focus();
      bool = false;
   }
   else if( isEmpty(document.wciform.template_txtCognoms)){
      alert('El camp cognoms és obligatori');
      document.wciform.template_txtCognoms.focus();
      bool = false;
   }
   else if( ! isEmail(document.wciform.template_txtEmail.value) || isEmpty(document.wciform.template_txtEmail) ){
      alert('El correu electrònic no es correcte');
      document.wciform.template_txtEmail.focus();
      bool = false;
   }
   else if(telefon != - 1){
      alert(telefon);
      document.wciform.template_txtTel.focus();
      bool = false;
      /*
      }else if (isEmpty(document.wciform.template_txtTallers)){
      alert('El camp Tallers és obligatori');
      document.wciform.template_txtTallers.focus();
      bool = false;
      */
   }
   else if(document.wciform.template_txtNumColegiado.value.length > 0){
      if((document.wciform.template_txtNumColegiado.value.length > 6) || (isNaN(document.wciform.template_txtNumColegiado.value)) ){
         alert('El Número Col·legial no es correcte');
         document.wciform.template_txtNumColegiado.focus();
         bool = false;
      }
   }
   
   if(bool){
      var cantCheck;
      cantCheck = 0;
      if (document.wciform.template_chkOpc1.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc2.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc3.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc4.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc5.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc6.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc7.checked){
         cantCheck += 1;
      }
      if (document.wciform.template_chkOpc8.checked){
         cantCheck += 1;
      }
      
      if (cantCheck > 2){
         alert("Només pots escollir 2 Tallers.");
         bool = false;
      }
      else if (cantCheck < 2){
         alert("Has d\'escollir 2 Tallers.");
         bool = false;
      }
      // alert(cantCheck);
   }
   
   // alert(document.wciform.template_rblDinar_0.checked);
   if(bool){
      if ( ! document.wciform.template_rblDinar_0.checked && ! document.wciform.template_rblDinar_1.checked ){
         // alert("Se queda a dinar ?");
         alert('El camp Dinar és obligatori');
         bool = false;
      }
   }
   
   if(bool){
      eval(fire_postback_code);
   }
}

//  ---------------------------------------
// Valida el formulari de ApropTeu2006
function validateApropTeu2006(fire_postback_code){
   var bool;
   bool = true;
   
   var telefon = isTel(document.wciform.template_txtTelefon.value);
   if (isEmpty(document.wciform.template_txtTelefon)){
      telefon = isTel(' ');
   }
   //alert(document.wciform.template_txtcolegiat.value);
   
   if ( isEmpty(document.wciform.template_txtNom) ){
      alert('El camp nom és obligatori');
      document.wciform.template_txtNom.focus();
      bool = false;
   }
   else if( isEmpty(document.wciform.template_txtCognoms)){
      alert('El camp cognoms és obligatori');
      document.wciform.template_txtCognoms.focus();
      bool = false;
   }else if((telefon != - 1) && ( !isEmail(document.wciform.template_txtemail.value)|| isEmpty(document.wciform.template_txtemail) )){
		//alert('document.wciform.template_txtTelefon.value.length  ' + document.wciform.template_txtTelefon.value.length )
		if ((document.wciform.template_txtemail.value.length == 0) && (document.wciform.template_txtTelefon.value.length == 0)){
			alert('S\'ha d\'informar el telèfon o el correu electrònic');
			document.wciform.template_txtemail.focus();			
			bool = false;
		}else
		if( (!isEmail(document.wciform.template_txtemail.value)|| isEmpty(document.wciform.template_txtemail) ) &&(document.wciform.template_txtTelefon.value.length == 0) ){
			//alert(2);
			alert('El correu electrònic no es correcte');
			document.wciform.template_txtemail.focus();			
			bool = false;
		}else
		if((telefon != - 1)){
			//alert(3);
			alert(telefon);
			document.wciform.template_txtTelefon.focus();			
			bool = false;
		}				
   }
   else if((!isEmail(document.wciform.template_txtemail.value) || isEmpty(document.wciform.template_txtemail)) && (!isEmpty(document.wciform.template_txtemail)) ){
	  //alert(4);		
      alert('El correu electrònic no es correcte');
      document.wciform.template_txtemail.focus();
      bool = false;
   }
   else if((telefon != - 1) && (document.wciform.template_txtTelefon.value.length > 0) ){
		//alert(5);
      alert(telefon);
      document.wciform.template_txtTelefon.focus();
      bool = false;
    }
    else if(isNaN(document.wciform.template_txtAssistents.value)){
		alert('El número total d\'assistents ha de ser un número');
		document.wciform.template_txtAssistents.focus();   
		bool = false;		
   }
    else if(document.wciform.template_txtAssistents.value < 1){
		alert('El número total d\'assistents ha de ser més gran que zero');
		document.wciform.template_txtAssistents.focus();   
		bool = false;		
   }
   else if(isNaN(document.wciform.template_txtLudotecaInfants.value) && (document.wciform.template_txtLudotecaInfants.style.display != 'none') ){
		alert('El número total d\'infants ha de ser un número');
		document.wciform.template_txtAssistents.focus();   
		bool = false;		
   }
    else if((document.wciform.template_txtLudotecaInfants.value < 1)  && (document.wciform.template_txtLudotecaInfants.style.display != 'none') ){
		alert('El número total d\'infants ha de ser més gran que zero');
		document.wciform.template_txtAssistents.focus();   
		bool = false;		
   }
   else if( (document.wciform.template_txtcolegiat.value.length > 0) || (document.wciform.template_txtcolegiat.style.display == 'block' )){
		//alert(document.wciform.template_txtcolegiat.style.display);
      if((document.wciform.template_txtcolegiat.value.length > 6) 
			|| (isNaN(document.wciform.template_txtcolegiat.value)) 
			 ){
         alert('El Número Col·legial no es correcte');
         document.wciform.template_txtcolegiat.focus();
         bool = false;
      }  
   }//template_lblPoblacioAnadaLugar
	else if( (document.wciform.template_cmbPoblacioAnada.style.display == 'block') ){
		//alert(document.wciform.template_cmbPoblacioAnada.style.display);
		//alert(document.wciform.template_cmbPoblacioAnada.value);
      if((document.wciform.template_cmbPoblacioAnada.value == 0)) {
         alert('Has de seleccionar la població de anada');
         document.wciform.template_cmbPoblacioAnada.focus();
         bool = false;
      }   
   }//template_lblPoblacioTornadalugar
   if((bool) && (document.wciform.template_cmbPoblacioTornada.style.display == 'block' )){
		//alert(document.wciform.template_cmbPoblacioTornada.value);
      if((document.wciform.template_cmbPoblacioTornada.value == 0)){
         alert('Has de seleccionar la població de tornada');
         document.wciform.template_cmbPoblacioTornada.focus();
         bool = false;
      }
   }
   
   //alert(document.wciform.template_cmbPoblacioTornada.style.display);
   if(bool){
      eval(fire_postback_code);
   }
}

function validateOsona(fire_postback_code){
	var bool;
	bool = true;
   
	var telefon = isTel(document.wciform.template_txtTelefon.value);
	if (isEmpty(document.wciform.template_txtTelefon)){
		telefon = isTel(' ');
	}
	//alert(document.wciform.template_txtcolegiat.value);
	   
	if ( isEmpty(document.wciform.template_txtNom) ){
		alert('El camp nom és obligatori');
		document.wciform.template_txtNom.focus();
		bool = false;
	}
	else if( isEmpty(document.wciform.template_txtCognoms)){
		alert('El camp cognoms és obligatori');
		document.wciform.template_txtCognoms.focus();
		bool = false;
	}else if((telefon != - 1) && ( !isEmail(document.wciform.template_txtemail.value)|| isEmpty(document.wciform.template_txtemail) )){
			//alert('document.wciform.template_txtTelefon.value.length  ' + document.wciform.template_txtTelefon.value.length )
			if ((document.wciform.template_txtemail.value.length == 0) && (document.wciform.template_txtTelefon.value.length == 0)){
				alert('S\'ha d\'informar el telèfon o el correu electrònic');
				document.wciform.template_txtemail.focus();			
				bool = false;
			}else
			if( (!isEmail(document.wciform.template_txtemail.value)|| isEmpty(document.wciform.template_txtemail) ) &&(document.wciform.template_txtTelefon.value.length == 0) ){
				//alert(2);
				alert('El correu electrònic no es correcte');
				document.wciform.template_txtemail.focus();			
				bool = false;
			}else
			if((telefon != - 1)){
				//alert(3);
				alert(telefon);
				document.wciform.template_txtTelefon.focus();			
				bool = false;
			}				
	}
	else if((!isEmail(document.wciform.template_txtemail.value) || isEmpty(document.wciform.template_txtemail)) && (!isEmpty(document.wciform.template_txtemail)) ){
		//alert(4);		
		alert('El correu electrònic no es correcte');
		document.wciform.template_txtemail.focus();
		bool = false;
	}
	else if((telefon != - 1) && (document.wciform.template_txtTelefon.value.length > 0) ){
			//alert(5);
		alert(telefon);
		document.wciform.template_txtTelefon.focus();
		bool = false;
	}
	
	if(bool){
		eval(fire_postback_code);
	}
}

function VFFiltresBiblio(fire_postback_code){
   var bool;
   var frm = document.wciform;
   bool = true;
   var lLlibreElectronic = getURLParam("SigTop");
   
   // situació laboral
   if (isEmpty(frm.template_txtAutor) && isEmpty(frm.template_txtEditorial) && isEmpty(frm.template_txtISBN) && isEmpty(frm.template_txtTitol) && isEmpty(frm.template_txtMateries) && (isEmpty(frm.template_txtTopografica) && (lLlibreElectronic != "ll-e"))){
      bool = false;      
      alert("Has d\'acurar el criteri de cerca per fer-lo més específic.");
   }
   
   if (bool){
		eval(fire_postback_code);
   }
} 

function VFParaulaBiblio(fire_postback_code){
   var bool;
   var frm = document.wciform;
   bool=true;
   
   if (isEmpty(frm.template_txtParaulaClau)){
      bool = false;      
      alert("Has d\'acurar el criteri de cerca per fer-lo més específic.");
   }
   
   if (!isEmpty(frm.template_txtParaulaClau)){
	  if (!isValidLength(frm.template_txtParaulaClau,3)){ 
		bool = false;
		alert("El camp QUALSEVOL PARAULA ha de tenir més de 3 caracters per poder obtenir un resultat òptim de la cerca.");
	  }
   }
   if (bool){
		eval(fire_postback_code);
   }
}  

function getURLParam(strParamName)
{
  var strReturn = "";
  var strHref = window.location.href;
  if (strHref.indexOf("?") > -1)
  {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
    {
        if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 )
        {
            var aParam = aQueryString[iParam].split("=");
            strReturn = aParam[1];
            break;
        }
    }
  }
  return unescape(strReturn);
}

function jugacapa(nomcapa) {
    var capa = document.getElementById(nomcapa);
    if (capa.style.display == 'block') {
        capa.style.display = 'none';
    } else {
        capa.style.display = 'block';
    }
}