﻿	/*
	  Form Validation v1.1
	  Written by Sharky, quasimodo
	  Last Updated  21-Dec-2001  by  quasimodo
	*/
	
	//implementing a trim function for strings in javascript Added for PRNJ3.8 15-Oct-09
		String.prototype.trim = function () {
	    return this.replace(/^\s*/, "").replace(/\s*$/, "");
	    }
	    
	    //Added function echeck for email validation for PRNJ3.8 15-Oct-09
		var bugchars = '!#$^&*()+|}{[]?><~%:;/,=`"\'\\';
		function CharsInBag(s)
		{
		var i;
		var lchar="";
		// Search through string's characters one by one.
		// If character is not in bag.
		for (i = 0; i < s.length; i++)
		{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if(i>0)lchar=s.charAt(i-1)
		if (bugchars.indexOf(c) != -1 || (lchar=="." && c==".")) return false;
		}
		return true;
		}

		function isInteger(s)
		{ var i;
		for (i = 0; i < s.length; i++)
		{
		//Check that current character is not a number.
		var c = s.charAt(i);
		if ((c >= "0") && (c <= "9") && (c != ".")) return false;
		}
		//All characters are numbers.
		return true;
		}

		function echeck(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		var lastdot=str.lastIndexOf(dot);
		if (str.indexOf(at)==-1){		   
		   return false;
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){		   
		   return false;
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr || str.substring(lastdot+1)==""){		    
		    return false;
		}		 
		if (str.indexOf(at,(lat+1))!=-1){		    
		    return false;
		 }
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){		    
		    return false;
		 }
		 if (str.indexOf(dot,(lat+2))==-1){		    
		    return false;
		 }		
		 if (str.indexOf(" ")!=-1){		    
		    return false;
		 }
		if(CharsInBag(str)==false){		    
		    return false;
		 }
		 var arrEmail=str.split("@")
		 var ldot=arrEmail[1].indexOf(".")
		 if(isInteger(arrEmail[1].substring(ldot+1))==false){		    
		    return false;
		 }
 		 return true;					
	}

	//Funcrion echeck ends PRNJ3.8 15-Oct-09
	
	//PRNJ3.8 Starts 07-Sep-09
	function getDateStr() {
				// format = YYYY-MM-DD	
				var dd = new Date()
				var da = "" + dd.getFullYear() + "-" + eval(dd.getMonth() +1) + "-" + dd.getDate();
				return da;
			}
	//PRNJ3.8 Ends 07-Sep-09 
	
	function check() {
		if ( chktext(0,3) && chkbox() && chktext(4,4) && chkstate() && chktext(5,5) && chkemailtel() && chkbox2() && chktext(6,8) ) {
		//PRNJ3.8 Starts 07-Sep-09
		var s=s_gi(s_account); 
			s.linkTrackVars='prop14,prop15'; 
			s.prop14=document.forms['inputform'].email.value; 
			s.prop15=getDateStr(); 
			s.tl(this,'o','Registration'); 
			var s_code=s.t();if(s_code)document.write(s_code);
		//PRNJ3.8 Ends 07-Sep-09 
			return true;
		} else return false;
	}

        function chkstate() {
            country = document.forms['inputform'].working_country.value;
            if (country == '131' || country == '222') {
                if (document.forms['inputform'].state.value =='*') {
                    message("No ha seleccionado un estado");
                    return false;
                }
                else {
                    return true;
                }
            }
            else {
                    return true;
            }
        }

	function info_chk() {
		if ( chktext(0,3) && chkbox() && chktext(4,4) && chkstate() && chktext(5,5) && chkemailtel() && chkbox2() ) {
			return true;
		} else return false;
	}

	function message(msg) {
		alert(msg);
	}

	function chkbox() {
		items = document.forms['inputform'].org_type.length;
		items--;
		orgflag = 0;
		for ( i=0; i<=items; i++ ) {
			if (document.forms['inputform'].org_type[i].checked == true) {	orgflag = 1; } 
		}
		if ( orgflag == 0 ) {
			message("No ha marcado un tipo de organización");
			return false;
		} else {
			return true;
		}
    }
	function chkbox2() {

		items = document.forms['inputform'].coverage.length;
		items--;
		checkflag = 0;
		for ( i=0; i<=items; i++ ) {
			if (document.forms['inputform'].coverage[i].checked == true) {	checkflag = 1; } 
		}
		if ( checkflag == 0 ) {
			message("No ha marcado un ??rea de cobertura");
			return false;
		} else {
			return true;
		}
	}

	function chkemailtel() {
		if ( !txt("email")) {
			message("No ha escrito una dirección de correo electrónico");
			return false;
		}
                else {
                    itm = eval("document.forms['inputform'].email.value");
                    if ( !emailCheck (itm) ) {
                        return false;
                    }
                }
		if ( !txt("tel") ) {
			message("No ha escrito un número de teléfono");
			return false;
		} 
		return true;
	}			


	function email_chk() {
		if ( !txt("Email")) {
			message("No ha escrito una dirección de correo electrónico");
			return false;
		}
                else {
                    itm = eval("document.forms['inputform'].Email.value");
                    if ( !emailCheck (itm) ) {
                        return false;
                    }
                }
		return true;
	}


	function chktext(startnum,endnum) {
		textArray = new Array("No ha escrito un nombre de pila","No ha escrito un apellido","No ha escrito un cargo","No ha escrito una organización de noticias","No ha escrito una dirección postal","No ha escrito un código postal","No ha escrito un nombre de usuario","No ha escrito una contraseña","No ha escrito una contraseña confirmada");
		nameArray = new Array("first_name","surname","job_title","news_organization","address1","post_code","username","password","confirm");
		textflag = 0;
		forloop: for ( i=startnum; i<=endnum; i++ ) {
			if ( !txt(nameArray[i],textArray[i]) ) {
				msg = "" + textArray[i];
				message(msg);
				textflag = 1;
				break forloop;
			}
		}
		if ( textflag == 1 ) { return false; } else { return true; }
	}
	
	function txt(nm) {
		itm = eval("document.forms['inputform']." + nm + ".value");
                itm = trimWhitespace(itm);
		if ( itm == "" || itm == null ) { return false; } else { return true; }
	}



	
        function trimWhitespace(inputString) {
          // Removes leading and trailing spaces from the passed string. Also
          // removes consecutive spaces and replaces it with one space.
          
	  var retValue = inputString;
	  var tmpValue = "";
	  
          // Check for spaces at the beginning of the string
          var ch = retValue.substring(0, 1);
          while (ch == " ") { 
             retValue = retValue.substring(1, retValue.length);
             ch = retValue.substring(0, 1);
          }
          
          // Check for spaces at the end of the string
          ch = retValue.substring(retValue.length-1, retValue.length);
          while (ch == " ") { 
             retValue = retValue.substring(0, retValue.length-1);
             ch = retValue.substring(retValue.length-1, retValue.length);
          }
          
          // Note that there are two spaces in the string - look for multiple spaces within the string
          while (retValue.indexOf("  ") != -1) { 
             retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
          }
                   
	  // Strip other white-space characters
	  tmpValue = retValue;
	  retValue = "";
	  len = tmpValue.length;
	  
	  for (var i=0; i < len; i++) 
	  {
	    if(tmpValue.charAt(i) >= ' ')
	    {
	      retValue = retValue + tmpValue.charAt(i);	    
	    }
	  }    

          // Return the trimmed string
          return retValue; 
          
       } // Ends the "trim" function
	

	function validateProfileName(formName, textValue){
	  var isOK = true;
	  
	  isOK = checkForWhiteSpaceOnly(formName, textValue);
	  
          if(!isOK){
            alert('Debe escribir al menos un carácter que no esté en blanco.');
            return isOK;
          }
	  
	  // Any more checks down here...

	  return isOK;
	
	}

        function checkForWhiteSpaceOnly(formName, textName){
          var isOK = true;
          itm = eval("document.forms['" + formName + "']." + textName + ".value");
          if ( itm == "" || itm == null ) { 
            isOK = false; 
          } 
          
          if(isOK){
            ctr = 0;            
            len = itm.length;
            for (var i=0; i < len; i++) {
              if(itm.charAt(i) > ' '){
                ctr ++;
              }
            }
            
            if(ctr == 0){
              isOK = false;
            }
          }
          return isOK;
        }
	
	
	function checkNullSpaces(nm){
          var isOK = true;
          itm = eval("document.forms['inputform']." + nm + ".value");
          if ( itm == "" || itm == null ) { 
            isOK = false; 
          } 
          
          if(isOK){
            ctr = 0;            
            len = itm.length;
            for (var i=0; i < len; i++) {
              if(itm.charAt(i) > ' '){
                ctr ++;
              }
            }
            
            if(ctr == 0){
              isOK = false;
            }
          }
          return isOK;
        }
	
	
        function checkAndDisplayError(nm){             
          var isOK = checkNullSpaces(nm);         
          if(!isOK){
            alert('Debe escribir al menos un carácter que no esté en blanco');
          }
          return isOK
        }

	function changetype(formname) {
		values = document.forms['inputform'].elements['working_country'].options[formname].value;
		var idx = formname;
		document.forms['inputform'].country_address.selectedIndex = idx;
		document.forms['inputform'].working_country.selectedIndex = idx;
		document.forms['inputform'].state.length = 0;
		document.forms['inputform'].state.length = 1;
		document.forms['inputform'].state.options[0].value = '*';
		if ((values == "222" || values == "131")) {
                    document.forms['inputform'].state.options[0].text = '- Seleccionar -';
                } else {
                    document.forms['inputform'].state.options[0].text = '--- Innecesario  ---';
                }
		document.forms['inputform'].state.options[0].selected = true;
		if (values == "131") {
			for (i=0; i<db1.length; i++) {
                                var arrayOfStrings = db1[i].split("|");
				document.forms['inputform'].state.options[i+1] = new Option(arrayOfStrings[1],arrayOfStrings[0],"","");
			}
		}
		if (values == "222") {
			for (i=0; i<db2.length; i++) {
                                var arrayOfStrings2 = db2[i].split("|");
				document.forms['inputform'].state.options[i+1] = new Option(arrayOfStrings2[1],arrayOfStrings2[0],"","");
			}
		}
	}

	
	function chk_year() {
		si_fy = document.forms['inputform'].elements['yearStart'].selectedIndex;
		values_fy = document.forms['inputform'].yearStart.options[si_fy].value;
		si_ty = document.forms['inputform'].yearEnd.selectedIndex;
		values_ty = document.forms['inputform'].yearEnd.options[si_ty].value;
		if (values_fy > values_ty) {
			alert("No puede establecer una fecha 'Desde' posterior a la fecha 'Hasta'");
			document.forms['inputform'].yearEnd.selectedIndex = document.forms['inputform'].elements['yearStart'].selectedIndex;
		}
	}

	function chkpasswd() {
		if ( document.forms['inputform'].password.value == document.forms['inputform'].confirm.value ) {
			return true;
		} else { 
			alert("Las contraseñas no coinciden - Vuélvalo a intentar");
			document.forms['inputform'].password.value = "";
			document.forms['inputform'].confirm.value = "";
			return false;
		}
	}
	
	
        // --UK-- is the date valid?
        function IsDateValid(year, month, day)
        {
          correct = false;
          bi = (year%400==0 || (year%4==0 && year%100!=0));
          if ( ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) && day >= 1 && day <= 31)
            { correct = true;}
            else
            {
                  if ( ( month == 4 || month == 6 || month == 9 || month == 11 ) && day >= 1 && day <= 30)
                  { correct = true;}
                  else
                  {
                        if (bi)
                        { correct = ( day >= 1 && day <= 29 && month == 2);}
                        else
                        { correct = ( day >= 1 && day <= 28 && month == 2);}
                  }
                }
          return correct;  
        }

        // --UK-- is the date valid?
        function DatesAreValid(syear, smonth, sday, eyear, emonth, eday)
        {
          correct = false;
		  // first of all check for invalid leap years etc.
          if ( IsDateValid(syear, smonth, sday) && IsDateValid(eyear,emonth,eday) ) {
			if ( parseInt(syear) <= parseInt(eyear) )
			{
				if ( parseInt(syear) < parseInt(eyear) ) {
					correct = true; // simply return as we are before the end year!
				}
				else { // the syear must equal the eyear so check the rest
					if ( parseInt(smonth) < parseInt(emonth) ) {
						correct = true; // simply return as we are before the end month!
					}
					else { // the smonth must equal the emonth so check the days
						if ( parseInt(smonth) == parseInt(emonth) )
						{
							if ( parseInt(sday) <= parseInt(eday) ) {
								correct = true;
							}
							else {
								correct = false;
							}
						}
						else {
							correct = false;
							// Invalid month!
						}
					}
			    } // do we have a valid set of years!
			}
			else {
				// invalid year as syear is before eyear
				correct = false;
			}
		  }
          return correct;  
        }


	function chkDates() {
		si_fy = document.forms['inputform'].elements['yearStart'].selectedIndex;
		values_fy = document.forms['inputform'].yearStart.options[si_fy].value;
		si_fm = document.forms['inputform'].elements['monthStart'].selectedIndex;
		values_fm = document.forms['inputform'].monthStart.options[si_fm].value;
		si_fd = document.forms['inputform'].elements['dayStart'].selectedIndex;
		values_fd = parseInt(document.forms['inputform'].dayStart.options[si_fd].value);

        if ( IsDateValid( values_fy, values_fm, values_fd) == false ) {
			alert("Ha seleccionado una fecha no válida como fecha 'Desde'");
        }
        else {
            si_ty = document.forms['inputform'].elements['yearEnd'].selectedIndex;
            values_ty = document.forms['inputform'].yearEnd.options[si_ty].value;
            si_tm = document.forms['inputform'].elements['monthEnd'].selectedIndex;
            values_tm = document.forms['inputform'].monthEnd.options[si_tm].value;
            si_td = document.forms['inputform'].elements['dayEnd'].selectedIndex;
            values_td = parseInt(document.forms['inputform'].dayEnd.options[si_td].value);

            if ( IsDateValid( values_ty, values_tm, values_td) == false ) {
                alert("Ha seleccionado una fecha no válida como fecha 'Hasta'");
            }
            else {
                if ( DatesAreValid(values_fy, values_fm, values_fd, values_ty, values_tm, values_td) == false ) {
                    alert("Ha escrito una fecha 'Desde' posterior a la fecha 'Hasta'");
                }
            }
        }
	}


	function chkDate() {
		si_fy = document.forms['inputform'].elements['year'].selectedIndex;
		values_fy = document.forms['inputform'].year.options[si_fy].value;
		si_fm = document.forms['inputform'].elements['month'].selectedIndex;
		values_fm = document.forms['inputform'].month.options[si_fm].value;
		si_fd = document.forms['inputform'].elements['day'].selectedIndex;
		values_fd = parseInt(document.forms['inputform'].day.options[si_fd].value);

        if ( IsDateValid( values_fy, values_fm, values_fd) == false ) {
			alert("Ha seleccionado una fecha no válida");
        }
	} 

	/*PRNJ3.8 16th September 2009 -- begins */
	
	
	function validateChangePasswordForm(old_pswd,new_pswd,conf_pswd,errorField){
	
	var errfld = document.getElementById? document.getElementById(errorField): document.all[errorField];
	
		if(checkNullOrBlank(old_pswd) || checkNullOrBlank(new_pswd) || checkNullOrBlank(conf_pswd)){
		errfld.innerHTML = "Introduzca información en todos los campos obligatorios";
		return false;
		}
		
		if(compareTwoFields(new_pswd,conf_pswd)==false){
		errfld.innerHTML = "Las contraseñas no coinciden";
		return false;
		}
		
		else
		return true;
	
	}
	
	
	function checkNullOrBlank(field){
	if (document.getElementById || document.all) {
      var fld = document.getElementById? document.getElementById(field): document.all[field];
      
      if(fld==null || fld.value=="")
      return true;
      else
      return false;
	}
	}
	
	function compareTwoFields(field1,field2){
	if (document.getElementById || document.all) {
      var fld1 = document.getElementById? document.getElementById(field1): document.all[field1];
      var fld2 = document.getElementById? document.getElementById(field2): document.all[field2];
      
      	if(fld1.value==fld2.value)
      	return true;
      	else
      	return false;
      }
	}
	
//The following function is added for the feedback form requirement in PRNJ3.8 release.
//This function limits the number of characters in a textArea to the maximum extent of the maxLimit size.
var isContentCleared = false;

function limitCharacters(event,txtField,counterField,maxLimit){

if (! event)
event = window.event;

//Ignore the non-printable keys like arrow keys,pageUp,pageDown etc. for Internet Explorer
if(event.keyCode >= 33 && event.keyCode <= 40)
return true;

var messageVal = txtField.value;

//workaround for Internet Explorer
//A single enter line on Internet Explorer is interpreted as a combination of \r and \n (\r\n) ---- so calculate no. of \r's and subtract from actual length.
var cr="";
var cr_length =cr.length;
//count \r's
if(cr = messageVal.match(/\r/g)){
cr_length = cr.length;
}

//workaround for safari browser
// A single enter line on safari browser is interpreted as two \n's (\n\n) --- so calculate no. of \n\n's and subtract from actual length.
var nn="";
var nn_length = nn.length;
//count \n\n's
if(nn = messageVal.match(/\n\n/g)){
nn_length = nn.length;
}

var extraSplChars=0;
extraSplChars = (cr_length) + (nn_length);

//if the user directly paste the content instead of typing in the textbox , then clear the extra content.
// keycode '17' is for 'ctrl' key
if(event.keyCode == 17)
clearExtraContent(event,txtField,maxLimit,extraSplChars);

var remainingChars;
var currLen = (messageVal.length) - extraSplChars;
remainingChars = maxLimit - currLen;

//If the input keys are either backspace or delete button then allow those keys
	if(event.keyCode != 8 && event.keyCode != 46){
		if(currLen>=maxLimit){
		remainingChars = 0;
		setRemainingChars(counterField,remainingChars);
		return false;
		}
	}

	
setRemainingChars(counterField,remainingChars); 

} //end of limitCharacters

function setRemainingChars(counterField,val){

	if (document.getElementById || document.all) {
      var el = document.getElementById? document.getElementById(counterField): document.all[counterField];
	  if (el && typeof el.innerHTML != "undefined") el.innerHTML = val;
	} 
}

//if the user directly paste the content instead of typing in the textbox , then clear the extra content.
//the 'enter' key has special character representation in some browsers , so while taking the substrng of actual value take into consideration these special characters also.
function clearExtraContent(e,field,maxLimit,splChars){
if(!e)
e = window.event;

if (document.getElementById || document.all) {
      var el = document.getElementById? document.getElementById(field.id): document.all[field.id];
	  el.value = el.value.substring(0,maxLimit+splChars);
	} 

}

function clearContentForTheFirstTime(field){
if(isContentCleared == false){
	if (document.getElementById || document.all) {
      var el = document.getElementById? document.getElementById(field.id): document.all[field.id];
	  el.value = "";
	  isContentCleared = true;
	  el.style.color = "black";
	  el.focus();
	} 
	} 
}

	
	
	/*PRNJ3.8 16th September 2009 -- ends */
	