//Abre janela central
b_versao = parseInt(navigator.appVersion);

var win = null;
function NewWindow(mypage,myname,w,h,scroll,size)
{
if (b_versao >= 4)
	{
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	}
else
	{
	LeftPosition = 100
	TopPosition = 100
	}
settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable='+size+''
win = window.open(mypage,myname,settings)
if(win.window.focus){win.window.focus();}
}



var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var blanks = " \t\n\r";  // aka whitespace chars

// decimal point character differs by language and culture
var decimalPointDelimiter = "."


// Returns true if string s is empty

function isEmpty(s)
  {
  return ((s == null) || (s.length == 0));
  }


// Returns true if string s is empty or all blank chars

function isBlank(s)
  {
  var i;

  // Is s empty?
  if (isEmpty(s))
    return true;

  // Search through string's chars one by one until we find first
  // non-blank char, then return false; if we don't, return true
  for (i=0; i<s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (blanks.indexOf(c) == -1) 
      return false;
    }
  // All characters are blank
  return true;
  }

// Removes all characters which appear in string bag from string s

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 blank
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all characters which do NOT appear in string bag from string s

function stripCharsNotInBag (s, bag)
  {
  var i;
  var returnString = "";

  // Search through string's characters one by one;
  // if character is in bag, append to returnString
  for (i = 0; i < s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (bag.indexOf(c) != -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all blank chars (as defined by blanks) from s

function stripBlanks(s)
  {
  return stripCharsInBag(s, blanks)
  }


// Removes leading blank chars (as defined by blanks) from s

function stripLeadingBlanks(s)
  { 
  var i = 0;
  while ((i < s.length) && (blanks.indexOf(s.charAt(i)) != -1))
     i++;
  return s.substring(i, s.length);
  }


// Removes trailing blank chars (as defined by blanks) from s

function stripTrailingBlanks(s)
  { 
  var i = s.length - 1;
  while ((i >= 0) && (blanks.indexOf(s.charAt(i)) != -1))
     i--;
  return s.substring(0, i+1);
  }


// Removes leading+trailing blank chars (as defined by blanks) from s

function stripLeadingTrailingBlanks(s)
  { 
  s = stripLeadingBlanks(s);
  s = stripTrailingBlanks(s);
  return s;
  }


// Returns true if character c is an English letter (A .. Z, a..z)

function isLetter(c)
  {
  return (((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")));
  }


// Returns true if character c is a digit (0 .. 9)

function isDigit(c)
  {
  return ((c >= "0") && (c <= "9"));
  }


// Returns true if all chars in string s are numbers;
// first character is allowed to be + or -; does not 
// accept floating point, exponential notation, etc.

function isInteger(s)
  {
  if (isBlank(s))
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true
  for (i; i<s.length; i++)
    {   
    // Check that current character is number
    var c = s.charAt(i);
    if (!isDigit(c)) 
      return false;
    }
  // All characters are numbers
  return true;
  }


// True if string s is an unsigned floating point (real) number; 
// first character is allowed to be + or -; no exponential notation.

function isFloat(s)
  { 
  var seenDecimalPoint = false;

  if (isBlank(s)) 
    return false;
  if (s == decimalPointDelimiter) 
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true

  for (i; i<s.length; i++)
    {   
    // Check that current character is number
    var c = s.charAt(i);

    if ((c == decimalPointDelimiter) && !seenDecimalPoint) 
      seenDecimalPoint = true;
    else if (!isDigit(c)) 
      return false;
    }
  // All characters are numbers
  return seenDecimalPoint;
  }


// Returns true if string s is English letters (A .. Z, a..z) only

function isAlphabetic(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphabetic char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
  {   
  // Check that current character is letter
  var c = s.charAt(i);

  if (!isLetter(c))
    return false;
  }

  // All characters are letters
  return true;
  }


// Returns true if string s is English letters (A .. Z, a..z) and numbers only

function isAlphanumeric(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphanumeric char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
    {   
    // Check that current character is number or letter
    var c = s.charAt(i);

    if (! (isLetter(c) || isDigit(c) ) )
    return false;
    }

  // All characters are numbers or letters
  return true;
  }


// reformatString(targetStr [, str1, int1, str2, int2, ... strN, intN])       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within targetString.
//
// reformatString() takes one required string argument, targetStr, 
// and 0-N optional string/integer-pair arguments. These optional 
// arguments specify how targetStr is to be reformatted and how/where 
// other strings are to be inserted in it.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123)456-7890" make this function call:
//   reformatString("1234567890", "(", 3, ")", 3, "-", 4)

function reformatString(targetString)
  { 
  var arg;
  var sPos = 0;
  var resultString = "";

  for (var i=1; i<reformatString.arguments.length; i++)
    {
    arg = reformatString.arguments[i];
    if (i%2 == 1) 
      {
      resultString += arg;
      }
    else
      {
      resultString += targetString.substring(sPos, sPos + arg);
      sPos += arg;
      }
    }
  return resultString;
  }

// Returns true if string s is an integer such that a <= s <= b
function isIntegerInRange (s, a, b)
  { 
  if (isBlank(s)) 
    return false;
  if (!isInteger(s)) 
    return false;
  var num = parseInt(s);
  return ((num >= a) && (num <= b));
  }

// Returns index of checked radio button in radio set,
// or -1 if no radio buttons are checked

function getCheckedRadioButton(radioSet)
  { 
  for (var i=0; i<radioSet.length; i++)
    if (radioSet[i].checked)
      return i;
  return -1;
  }


// Returns array containing index(es) of checked checkbox(es) 
// in checkbox set, or -1 if no checkboxes are checked

function getCheckedCheckboxes(checkboxSet)
  {
  var arr = new Array();
  for (var i=0,j=0; i<checkboxSet.length; i++)
    if (checkboxSet[i].checked)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }


// Returns array containing index(es) of checked option(s) 
// in select box, or -1 if no options are selected

function getCheckedSelectOptions(select)
  {
  var arr = new Array();
  for (var i=0,j=0; i<select.length; i++)
    if (select.options[i].selected)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }

//Valida o CPF 
function val_CPF(numero)
{
//return true;

	dig_1 = 0;
	dig_2 = 0;
	controle_1 = 10;
	controle_2 = 11;
	lsucesso = 1;
	if (numero.length != 11)
	{
		return false;
	}
	else
	{
		for ( i=0 ; i < 9 ; i++)
		{
			dig_1 = dig_1 + parseInt(numero.substring(i, i+1) * controle_1);
			controle_1 = controle_1 - 1;
		}
		resto = dig_1 % 11;
		dig_1 = 11 - resto;
		if ((resto == 0) || (resto == 1))
		{
			dig_1 = 0;
		}
		for ( i=0 ; i < 9 ; i++)
		{
			dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
			controle_2 = controle_2 - 1;
		}
		dig_2 = dig_2 + 2 * dig_1;
		resto = dig_2 % 11;
		dig_2 = 11 - resto;
		if ((resto == 0) || (resto == 1))
		{
			dig_2 = 0;
		}
		dig_ver = (dig_1 * 10) + dig_2;
		if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length)))
		{
			return false;
		}
	}
	return true;
}

meses = new Array(12);
meses = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];	

function eh_bissexto(ano){
	if ( ((ano - 1996) % 4) == 0) return true;
	return false;
}	
	
function validaData(data){
	// Recebe a data no formato dd/mm/aaaa
	var	aux = data;
	var	barras = 0;
	var	erro = 0;
	var	dia = 0;
	var	mes = 0;
	var	ano = 0;
	var	eh_barra = 1;							
	if (data=="" || data.length !=10)
		erro = 1
	else {
		for (var i=0; (i<aux.length) && (erro==0); i++) {
			if (aux.charAt(i)=='/') {
				if (eh_barra==0) {
					barras++;
					eh_barra = 1;
				}
				else erro = 1;
			}
			else {
				a = parseInt(aux.charAt(i), 10);
				if (isNaN(a)) erro = 1;
				eh_barra = 0;
			}
		}
		if (barras != 2) erro = 1;
				
		if (erro==0) {
			pos = aux.indexOf("/");
			pos2 = aux.indexOf("/", pos+1);
			dia = parseInt(aux.substring(0, pos), 10);
			mes = parseInt(aux.substring(pos+1, pos2), 10);
			ano = parseInt(aux.substring(pos2+1, aux.length), 10);

			if (ano<1900 || ano>2050) erro = 1;
			else {
				if (eh_bissexto(ano)) meses[1] = 29;
				else meses[1] = 28;
				if (mes<1 || mes>12) erro = 1;
				else if (dia<1 || dia>meses[mes-1]) erro = 1;
			}
		}
		if (erro==1)
			return false;
		else return true;
	}
}

function validaHora(hora)
{
	// Recebe a hora no formato hh:mm
	if (hora.length < 5)
	{
		return false;
	}

	if ((isIntegerInRange (hora.substring(0, 2), 0, 23)) && (isIntegerInRange (hora.substring(3, 2), 0, 59)))
		return true;
	else
		return false;
}

// Função de auto-tabulação
// Parâmetros:
// input - o elemento de formulário que está sendo utilizado 
// len - o tamanho do campo antes do tab automático (normalmente o maxlength)
// e - ? Sempre passar event
//
// Forma de utilização no HTML:
// <input onKeyUp="return autoTab(this, 3, event);">
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}

	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
			if(arr[index] == ele)
				found = true;
			else
				index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
	}
	return true;
}

// Função de preenchimento de listas de seleção <SELECT> através de um array 
// e da seleção de valores de outro <SELECT>
// Modo de utilização - no select principal, digite
// onChange="fillSelectFromArray(NOMEDOSELECTDESTINO, ((this.selectedIndex == -1) ? null : NOMEDOVETOR[this.selectedIndex-1]));"
// OBS: a página deve criar o array NOMEDOVETOR antes de referenciá-lo
// Exemplo de vetor:
//regioesEstado = new Array(
//	new Array(
//		new Array("Capital", 1),
//		new Array("Interior", 2)
//	),
//	new Array(
//		new Array("Capital", 1),
//		new Array("Região Serrana", 2),
//		new Array("Norte Fluminense", 3),
//		new Array("Região dos Lagos", 4),
//		new Array("Baixada Fluminense", 5)
//	)
//);
// OBS2: Para mudar o comportamento do select a ser populado, alterar a expressão condicional
// ((this.selectedIndex == -1) ? null : NOMEDOVETOR[this.selectedIndex-1])
// para outra que atenda às necessidades
function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {
	var i, j;
	var prompt;
	// empty existing items
	for (i = selectCtrl.options.length; i >= 0; i--) {
		selectCtrl.options[i] = null; 
	}
	prompt = (itemArray != null) ? goodPrompt : badPrompt;
	if (prompt == null) {
		j = 0;
	}
	else {
		selectCtrl.options[0] = new Option(prompt);
	j = 1;
	}
	if (itemArray != null) {
		// add new items
		for (i = 0; i < itemArray.length; i++) {
			selectCtrl.options[j] = new Option(itemArray[i][0]);
			if (itemArray[i][1] != null) {
				selectCtrl.options[j].value = itemArray[i][1]; 
			}
			j++;
		}
	// select first item (prompt) for sub list
	selectCtrl.options[0].selected = true;
   }
}

// Função de validação de emails
function isEmail(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("Email address seems incorrect (check @ and .'s)")
		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("The username doesn't seem to be valid.")
		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("Destination IP address is invalid!")
			return false
			}
		}
		return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
//		alert("The domain name doesn't seem to be valid.")
		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>3) {
	   // the address must end in a two letter or three letter word.
	//   alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	//   var errStr="This address is missing a hostname!"
	//   alert(errStr)
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}
