function MM_findObj(n, d) { //v4.0
  var p,i,x;  
  if(!d) d=document; 
    if((p=n.indexOf("?"))>0&&parent.frames.length) 
      {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
        if(!(x=d[n])&&d.all) x=d.all[n]; 
        for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
          for(i=0;!x&&d.layers&&i<d.layers.length;i++) {
            x=MM_findObj(n,d.layers[i].document);
      }
    if(!x && document.getElementById) 
      x=document.getElementById(n);
   
    return x;
}

function confirmDelete(form)
{
   if (!form)
   {
      alert("No se ha introducido formulario para el cual relizar confirmación");
   }
   else
   {
	if (confirm("¿Seguro que desea borrar los objetos elegidos?"))
        {
	    var formobject = MM_findObj(form);
	    formobject.submit();
        }
   }
}

function submitForm(form)
{
   if (!form)
   {
       alert("No se ha introducido formulario para el cual relizar submit");
   }
   else
   {
       var formobject = MM_findObj(form);
       formobject.submit();
   }
}

function submitFormToUrl(form,url)
{
   if (!form)
   {
       alert("No se ha introducido formulario para el cual relizar submit");
   }
   else
   {
       var formobject = MM_findObj(form);
       formobject.action=url;
       formobject.submit();
   }
}

// Checks if "string" contain the string "allowed" 
// on a position between start and end.
// If start and end are 0 the all string will be checked.
function hasValidChar(string,allowed,start,end) {
    if ((start==0) && (end==-1))
    {	
   	end = string.length;
    }
    var pos = false;
    for (var i=start; i< end; i++) {
       if (allowed.indexOf(string.charAt(i)) == -1)
	{       
	  pos = false;
	}
       else
       {
          pos = i;
	  return pos;
       }
    }
    return pos;
}

// Checks if "string" contain the string "allowed" 
// several times.
function hasValidCharMoreThanOnce(string,allowed,start,end) {
    if ((start==0) && (end==-1))
    {	
   	end = string.length;
    }
    var one = false;
    for (var i=start; i< end; i++) {
       if (allowed.indexOf(string.charAt(i)) != -1)
       {
	  if (one)
          {
		return true;	  
          }
	  one = true;
       }
    }
    return false;
}

function validateMail(mailString){
    var invalid;
    var invalidCharList = '`~!#$%^&*()+={}[]|;\':,/<>? ';
    
    //Private Const INVALIDPAIRSLIST = ".-;-.;--;..;@@;._;-_;_.;_-;__;"


    var arrobaPos = hasValidChar(mailString,'@',0,mailString.length);
    var dotPos = hasValidChar(mailString,'.',arrobaPos,mailString.length);
  
    invalid = (mailString.length-dotPos<=1);

    if (!invalid)
        invalid = (hasValidChar(mailString,invalidCharList,0,mailString.length));

    if (!invalid)
        invalid = (hasValidCharMoreThanOnce(mailString,'.',arrobaPos,mailString.length));

    if (!invalid)
        invalid = hasValidChar(mailString,invalid,0,mailString.legth);
  
    if (!invalid)
        invalid = (hasValidCharMoreThanOnce(mailString,'@',0,mailString.length));

    return !invalid;
}


function validateRegistryDomainName(domainName)
{
    var invalid;
    var invalidCharList = '`~!#$%^&*()+={}[]|;\':,/<>? ';	
    var dotPos = hasValidChar(domainName,'.',0,domainName.length);

    if (dotPos>2)
    {
        invalid = hasValidChar(domainName,invalidCharList,0,domainName.length); 

        if (!invalid)
           var substring = domainName.substring(0,4);
	if (substring.toString()=='www.')
	   invalid = 1; 

        if (!invalid)
           var substring = domainName.substring((domainName.length-4),domainName.length);
	if ((substring.toString()!='.com') && (substring.toString()!='.net') && (substring.toString()!='.org'))
 	   invalid = 1; 

    }
    else
    { 
        invalid=1;
    }	
    return !invalid;
}
function validatePostalCode(postalCode)
{
    var allowed= '0123456789';	
    var start=0;
    var end=postalCode.length;

    if (postalCode.length!=5)
	{
		return false;
	}

    var one = true;
    for (var i=start; i< end; i++) {
       if (allowed.indexOf(postalCode.charAt(i)) == -1)
       {
	      	return false;
       }
    }

    return true;
    
}

function openRecoveryPassword() 
{
   ventana = window.open("/layout/set/recoverpassword/solucionesi/passwordrecovery/recoverlogin?currentlayout=/layout/set/recoverpassword","Recuperación","top=70,left=70,width=240,height=150,resizable=no,scrollbars=no");
}

function changeStateAllcheckboxes(formname,checkboxname)
{
   var checked = formname.all.checked;
   with( formname )
   {
       	for( var i=0; i<elements.length; i++ )
        {
             if( elements[i].type == 'checkbox' && elements[i].name == checkboxname && elements[i].disabled == "" )
             {
                 if( checked==false )
                 {
                     elements[i].checked = false;
                 }
                 else
                 {
                     elements[i].checked = true;
                 }
             }
        }
   }
}

function changeStateFormcheckboxes(formname,checkboxname,allcheck)
{
   var checked = allcheck.checked;
   with( formname )
   {
       	for( var i=0; i<elements.length; i++ )
        {
             if( elements[i].type == 'checkbox' && elements[i].name == checkboxname && elements[i].disabled == "" )
             {
                 if( checked==false )
                 {
                     elements[i].checked = false;
                 }
                 else
                 {
                     elements[i].checked = true;
                 }
             }
        }
   }
}

function validateUid(uid)
{
	var regex = /^[0-9a-zA-Z.\:_\-]*$/;
	return regex.test(uid);
}


function isValidEmail(email) {

  var validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  var strEmail = email;

  // search email text for regular exp matches
  if (strEmail.search(validRegExp) == -1) 
  {
     return false;
  } 

  return true; 

}



function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address.
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
        alert("La dirección de correo es incorrecta (verifique @ y ')")
        return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid
if (user.match(userPat)==null) {
    // user is not valid
    alert("El nombre del usuario de correo no es válido.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
          for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                alert(" La IP de destino no es válida !")
                return false
            }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
        alert("El nombre de dominio no es válido")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>4) {
   // the address must end in a two letter or three letter word.
   alert("La dirección debe finalizar con un sufijo de entre cuatro y dos letras")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="Falta el nombre del servidor en la direccin de correo"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

//Funciones para verificar el nmero de fax

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 9;

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

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateFaxNumber(Phone){

        if ((Phone==null)||(Phone=="")){
                alert("Introduzca el número de fax")
                return false
        }
        if (checkInternationalPhone(Phone)==false){
                alert("El número de fax es incorrecto")
                return false
        }
        return true
}

