var dPos = 0;
var mPos = 1;
var yPos = 2;
var daysPerMonth = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
var arrayLen  = new Array(2, 2, 4, 2);

var VK_ZERO     = 48;
var VK_NOVE     = 57;
var VK_ZERO_PAD = 96;
var VK_NOVE_PAD = 105;
//   9 => TAB; 20 => CAPS LOCK; 45 => INSERT; 46 => DELETE; 33 => PG UP; 34 => PG DOWN;
//  35 => END; 36 => HOME; 19 => PAUSE; 145 => SCROLL LOCK; 37 => LEFT; 38 => UP; 39 => RIGHT; 
//  40 => DOWN; 27 => ESC; 112-123 => F1-F12; 8 => BACKSPACE; 13 => ENTER; 
// 144 => NUM LOCK; 16 => SHIFT; 17 => CTRL; 18 => ALT
var VK_ESCAPE_KEYS = new Array( 8, 9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 145 );

var CENTURY_DEFAULT = 2000;
var LAST_CENTURY_DEFAULT = 1900;
var ANO_MEDIO = Math.floor(100/2);


//-------------------------------------------------------------------
// This function accepts a string variable and verifies if it is in
// the proper format for an e-mail address or not.
// The function returns true if the format is valid, false if not.
//-------------------------------------------------------------------

function isEmail(email) {
    invalidChars = " ~\'^\`\"*+=\\|][(){}<>$&!#%?/:,;áÁàÀâÂäÄãÃéÉèÈêÊëËíÍìÌîÎïÏóÓòÒôÔöÖõÕúÚùÙûÛüÜçÇ";

    // Check for null
    if (email == "") {
        return false;
    }

    // Check for invalid characters as defined above
    for (i=0; i<invalidChars.length; i++) {
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1) {
            return false;
        }
    }
    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
        return false;
    }
    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".") {
        return false;
    }
    while ((Pos < lengthOfEmail) && ( Pos != -1)) {
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
        if (Pos != -1) {
            Pos++;
        }
    }

    // There must be at least one @ symbol
    atPos = email.indexOf("@",1);
    if (atPos == -1) {
        return false;
    }

    // But only ONE @ symbol
    if (email.indexOf("@",atPos+1) != -1) {
        return false;
    }

    // Also check for at least one period after the @ symbol
    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) {
        return false;
    }
    if (periodPos+3 > email.length) {
        return false;
    }
    return true;
}


//-------------------------------------------------------------------
// Verify if the string passed is a valid time (HH:MM:SS)
//   Returns true or false
//-------------------------------------------------------------------
function isTime(timeStr) {
  if(timeStr.length == 8) {
    for(var i=0; i<timeStr.length; i++) {
      if((i==2 || i==5) && (timeStr.charAt(i)!=":")) return false;
      if((i!=2 && i!=5) && !isDigit(timeStr.charAt(i))) return false;
    }
    var hour = timeStr.charAt(0) + timeStr.charAt(1);
    var minute = timeStr.charAt(3) + timeStr.charAt(4);
    var second = timeStr.charAt(6) + timeStr.charAt(7);
    if(((hour >=0) && (hour <= 24)) &&
       ((minute >= 0) && (minute <= 59)) &&
       ((second >= 0) && (second <= 59))) {
      return true;
    }
    else {
      return false;
    }
  }

  return false;
}


//-------------------------------------------------------------------
// Verify if the string passed is a valid date (DD/MM/YYYY)
//   Returns true or false
//-------------------------------------------------------------------
function isDate(dateStr) {
  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = dateStr.match(datePat); // is the format ok?
  if (matchArray == null) {
    //alert("Entre uma data válida, no formato (dd/mm/yyyy).");
    return false;
  }
  month = matchArray[3]; // parse date into variables
  day   = matchArray[1];
  year  = matchArray[5];
  if (month < 1 || month > 12) { // check month range
    //alert("O mês deve estar entre 1 e 12.");
    return false;
  }
  if (day < 1 || day > 31) {
    //alert("O dia deve estar entre 1 e 31.");
    return false;
  }
  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    //alert("O mês "+month+" não tem 31 dias!")
    return false;
  }
  if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
      //alert("Fevereiro de " + year + " não tem " + day + " dias!");
      return false;
    }
  }
  return true; // date is valid
}


//-------------------------------------------------------------------
// Verify if the string passed is a valid date (DD/MM/YYYY)
//   Returns an array (adjusted value of date and true or false)
//-------------------------------------------------------------------
function isDateReal(dateStr) {
  var dateValue = dateStr;
  var retArray = new Array();

  if (dateValue == null | dateValue == '' | dateValue == ' ') return false; 

  var vLength = dateValue.length;
  var vStr = new Array(' ',' ',' ');
  var temp = new Array('','','');
  var vIndex=0;
  var vChar='';
  var vDelims = "/";
  var ret = true;
  var tamPadrao = new Array(null,null, null);
  var existDelim = ( dateValue.indexOf(vDelims) >= 0 );
  
  if (existDelim) {
    tamPadrao[0] = 10;
    tamPadrao[1] = 8;
    tamPadrao[2] = 6;
    if (vLength != tamPadrao[0] && vLength != tamPadrao[1] && vLength != tamPadrao[2]) ret = false;
  }
  else {
    tamPadrao[0] = 8;
    tamPadrao[1] = 6;
    if (vLength != tamPadrao[0] && vLength != tamPadrao[1]) ret = false;
  }
  
  
  if (existDelim) {

    for( var count=0; count < vLength; ++count ) {
      vChar = dateValue.charAt(count);
      if (vChar.search(vDelims)==0) {
        vIndex = vIndex + 1;
      }
      else { temp[vIndex] += vChar;
      }  
    }
  }  // if existDelim
  else {
    if (vLength == tamPadrao[0]) {  //full
      temp[0] = dateValue.substring(0, arrayLen[0]);
      temp[1] = dateValue.substring(arrayLen[0], arrayLen[0]+arrayLen[1]);
      temp[2] = dateValue.substring(arrayLen[0]+arrayLen[1], arrayLen[0]+arrayLen[1]+arrayLen[2]);
    }
    else if (vLength == tamPadrao[1]) {  //abreviado
      temp[0] = dateValue.substring(0, arrayLen[0]);
      temp[1] = dateValue.substring(arrayLen[0], arrayLen[0]+arrayLen[1]);
      temp[2] = dateValue.substring(arrayLen[0]+arrayLen[1], arrayLen[0]+arrayLen[1]+arrayLen[3]);
    }
  
  } // else existDelim
  
  vStr[0]=temp[0];
  vStr[1]=temp[1];
  vStr[2]=temp[2];

  ret = (temp[0]!='' && temp[1]!='' && temp[2]!='');

  if ( isNaN(vStr[0]) ) ret = false;
  if ( isNaN(vStr[1]) ) ret = false;
  if ( isNaN(vStr[2]) ) ret = false;

    
  var strip = ""
  for (i=0; i<vStr[0].length; i++) { 
    if (!isNaN(vStr[0].charAt(i))) strip += vStr[0].charAt(i); 
  }
  if (strip.length > 0) vStr[0] = parseFloat(vStr[0],10) + '';
  if (trim(vStr[0]) != '' && (vStr[0] > 31 || vStr[0] < 1)) ret = false;

  strip = ""
  for (i=0; i<vStr[1].length; i++) { 
    if (!isNaN(vStr[1].charAt(i))) strip += vStr[1].charAt(i); 
  }
  if (strip.length > 0) vStr[1] = parseFloat(vStr[1],10) + '';
  if (trim(vStr[1]) != '' && (vStr[1] > 12 || vStr[1] < 1) ) ret = false;


  //zero fills the day if less than defined length and truncates if more
  if (vStr[0].length > arrayLen[0]) {
    vStr[0] = vStr[0].substr(0,arrayLen[0]);
  }
  else {
    while (vStr[0].length < arrayLen[0]) {
      vStr[0] = '0'+vStr[0];
    }
  }


//If the year isn't numeric, fill with ? and treat as unrecognizable, otherwise, convert to integer before
//filling to correct length.

  if (isNaN(vStr[2]) || vStr[2] == ' ') vStr[2] = "????";
//  else vStr[2] = parseFloat(vStr[2], 10) + '';

  if (vStr[2].length != arrayLen[2] && vStr[2].length != arrayLen[3]) {
    ret = false;
  }
  if ( vStr[2].length == arrayLen[2] && parseFloat(vStr[2], 10) <= 0 ) ret = false;


  //ano com 2 digitos
  if (vStr[2].length == arrayLen[3]) {
    if ( vStr[2] >= ANO_MEDIO ) { // arredondar para 1900
      vStr[2] = parseFloat(vStr[2], 10) + LAST_CENTURY_DEFAULT + '';
    }
    else {
      vStr[2] = parseFloat(vStr[2], 10) + CENTURY_DEFAULT + '';
    }
    
  }


//Check if day of month is valid for month in year (check leapyear too)
  if (!isNaN(vStr[2]) && !isNaN(vStr[1])) {
      if (((vStr[2] % 4 == 0) && (vStr[2] % 100 != 0)) || (vStr[2] % 400 == 0)) {
         daysPerMonth[1] = 29;
      } 
      else {
         daysPerMonth[1] = 28;
      }
  }
  else {
    daysPerMonth[1] = 29;
  }

  if (vStr[0] > daysPerMonth[vStr[1]-1]) ret = false;

//If length of month < 2, zero fill it
  //meses
  if (vStr[1].length > arrayLen[1]) {
    vStr[1] = vStr[1].substr(0,arrayLen[1]);
  }
  else {
    while (vStr[1].length < arrayLen[1]) {
      vStr[1] = '0'+vStr[1];
    }
  }

  
//Finally, swap items around into output format and add delimiters
  temp[0] = vStr[0]; 
  temp[1] = vStr[1]; 
  temp[2] = vStr[2]; 
  
  if (ret) {
    retArray[0] = temp[0];
    if (temp[1] != '')
      retArray[0] += vDelims+temp[1];
    if (temp[2] != '')
      retArray[0] += vDelims+temp[2];
    retArray[1] = ret;
  }
  else {
    retArray[0] = dateStr;
    retArray[1] = ret;
  }
  
  return retArray;

}



//-------------------------------------------------------------------
// Trim functions
//   Returns string with whitespace trimmed
//-------------------------------------------------------------------
function trimL(str) {
var n=0;
var i=0;

  if (str=='') return '';

  for (i=0; i<str.length; i++) {
   n = str.charCodeAt(i);   
   if (n>32) break;   	
  }

  if (i<=str.length)
  	return str.substring(i,str.length);
  else return str;
}

function trimR(str) {
var n=0;
var i=0;

  if (str=='') return '';

  for (i=str.length-1; i>=0; i--) {
   n = str.charCodeAt(i);

   if (n>32) break;   	
  }

  if (i>=0)
  	return str.substring(0,i+1);
  else return str;
}


// verifica se a data <dt> é maior que a data corrente
function isDateGreaterThanNow(dt) {
	
	if (!isDate(dt))	{
		return false;
 	}
	
	var today = new Date();
	var dtParts = dt.split('/');
	var day=0, month=0, year=0;
	var dtTarget,dif=0;
	
	day   = parseInt(dtParts[0],10);
	month = parseInt(dtParts[1],10);
	year  = parseInt(dtParts[2],10);
	
	dtTarget = new Date(year, month-1, day);
	//alert('today, date='+today.getDate()+', month='+today.getMonth()+', year='+today.getFullYear());
	
	dif = today.getTime() - dtTarget.getTime();
	
	return (dif<0);
}


// verifica se a data <dt> é maior ou igual que a data corrente
function isDateGreaterThanOrEqualNow(dt) {
	var res= isDate(dt);
	
	//var todayAux = new Date();
	var today = new Date();
	
	//alert(dt);
	var dtParts = dt.split('/');
	var day=0, month=0, year=0;
	var dtTarget,dif=0;
	
	day   = parseInt(dtParts[0],10);
	month = parseInt(dtParts[1],10);
	year  = parseInt(dtParts[2],10);
	
	dtTarget = new Date(year, month-1, day);
	//alert('today, date='+today.getDate()+', month='+today.getMonth()+', year='+today.getFullYear());
	
	dif = today.getTime() - dtTarget.getTime();
	
	return (dif<=0);
}


function trim(str) { 
  var r = trimR(str);
  var l= trimL(r);
  return l;
}

//-------------------------------------------------------------------
// isNull(value)
//   Returns true if value is null
//-------------------------------------------------------------------
function isNull(val) {
  if (val == null) { return true; }
  return false;
}

//-------------------------------------------------------------------
// isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
function isBlank(val) {
  if (val == null) { return true; }
  for (var i=0; i < val.length; i++) {
    if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n")) { return false; }
  }
  return true;
}

//-------------------------------------------------------------------
// isAlphanumeric(value)
//   Returns true if value contains alphanumeric digits
//-------------------------------------------------------------------
function isAlphanumeric(val) {
  var str ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for( var i=0; i < val.length; i++ ) {
    if( str.indexOf(val.charAt(i)) < 0 ) {
      return false;
    }
  }
  return true;
}

//-------------------------------------------------------------------
// isAlphanumeric2(value)
//   Returns true if value contains alphanumeric digits (inclui o caractere '/')
//-------------------------------------------------------------------
function isAlphanumeric2(val) {
  var str ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/";
  for( var i=0; i < val.length; i++ ) {
    if( str.indexOf(val.charAt(i)) < 0 ) {
      return false;
    }
  }
  return true;
}

//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(val) {
  for (var i=0; i < val.length; i++) {
    if (!isDigit(val.charAt(i))) { return false; }
  }
  return true;
}

//-------------------------------------------------------------------
// isNumeric(value)
//   Returns true if value contains a positive float value
//-------------------------------------------------------------------
function isNumeric(val) {
  var dp = false;
  for (var i=0; i < val.length; i++) {
    if (!isDigit(val.charAt(i))) {
      if (val.charAt(i) == ',') { // padrão brasileiro...
        if (dp == true) { return false; } // already saw a decimal point
        else { dp = true; }
      }
      else if (val.charAt(i) == '.') {
      }
      else {
        return false;
      }
    }
  }
  return true;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
  var string="1234567890";
  if (string.indexOf(num) != -1) {
    return true;
  }
  return false;
}

//-------------------------------------------------------------------
// isLetter(value)
//   Returns true if value is a alphabet letter
//-------------------------------------------------------------------
function isLetter(num) {
  var string="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if (string.indexOf(num) != -1) {
    return true;
  }
  return false;
}

//-------------------------------------------------------------------
// isMonth(string)
//   Returns true if string is either a full month name or a month
//   abbreviation.
//-------------------------------------------------------------------
function isMonth(val) {
  val = val+"";
  val = val.toLowerCase();
  if((val=="jan") || (val=="feb") || (val=="mar") || (val=="apr") || (val=="may") || (val=="jun") ||
     (val=="jul") || (val=="aug") || (val=="sep") || (val=="oct") || (val=="nov") || (val=="dec")) {
    return true;
  }
  if((val=="january") || (val=="february") || (val=="march") || (val=="april") || (val=="may") ||
     (val=="june") || (val=="july") || (val=="august") || (val=="september") || (val=="october") ||
     (val=="november") || (val=="december")) {
    return true;
  }
  return false;
}

//-------------------------------------------------------------------
// setNullIfBlank(input_object)
//   Sets a form field to "" if it isBlank()
//-------------------------------------------------------------------
function setNullIfBlank(obj) {
  if (isBlank(obj.value)) {
    obj.value = "";
  }
}

//-------------------------------------------------------------------
// setFieldsToUpperCase(input_object)
//   Sets value of form field toUpperCase() for all fields passed
//-------------------------------------------------------------------
function setFieldsToUpperCase() {
  for (var i=0; i<arguments.length; i++) {
    var obj = arguments[i];
    obj.value = obj.value.toUpperCase();
  }
}

//-------------------------------------------------------------------
// disallowBlank(input_object[,message[,true]])
//   Checks a form field for a blank value. Optionally alerts if
//   blank and focuses
//-------------------------------------------------------------------
function disallowBlank(obj) {
  var msg;
  var dofocus;
  if (arguments.length>1) { msg = arguments[1]; }
  if (arguments.length>2) { dofocus = arguments[2]; } else { dofocus=false; }
  if (isBlank(obj.value)) {
    if (!isBlank(msg)) {
      alert(msg);
    }
    if (dofocus) {
      obj.select();
      obj.focus();
    }
    return true;
  }
  return false;
}

//-------------------------------------------------------------------
// disallowModify(input_object[,message[,true]])
//   Checks a form field for a value different than defaultValue.
//   Optionally alerts and focuses
//-------------------------------------------------------------------
function disallowModify(obj) {
  var msg;
  var dofocus;
  if (arguments.length>1) { msg = arguments[1]; }
  if (arguments.length>2) { dofocus = arguments[2]; } else { dofocus=false; }
  if (getInputValue(obj) != getInputDefaultValue(obj)) {
    if (!isBlank(msg)) {
      alert(msg);
    }
    if (dofocus) {
      obj.select();
      obj.focus();
    }
    setInputValue(obj,getInputDefaultValue(obj));
    return true;
  }
  return false;
}

//-------------------------------------------------------------------
// isChanged(input_object)
//   Returns true if input object's state has changed since it was
//   created.
//-------------------------------------------------------------------
function isChanged(obj) {
    if ((typeof obj.type != "string") && (obj.length > 0) && (obj[0] != null) && (obj[0].type=="radio")) {
        for (var i=0; i<obj.length; i++) {
            if (obj[i].checked != obj[i].defaultChecked) { return true; }
            }
        return false;
        }
    if ((obj.type=="text") || (obj.type=="hidden") || (obj.type=="textarea"))
        { return (obj.value != obj.defaultValue); }
    if (obj.type=="checkbox") {
        return (obj.checked != obj.defaultChecked);
        }
    if (obj.type=="select-one") {
        if (obj.options.length > 0) {
            var x=0;
            for (var i=0; i<obj.options.length; i++) {
                if (obj.options[i].defaultSelected) { x++; }
                }
            if (x==0 && obj.selectedIndex==0) { return false; }
            for (var i=0; i<obj.options.length; i++) {
                if (obj.options[i].selected != obj.options[i].defaultSelected) {
                    return true;
                    }
                }
            }
        return false;
        }
    if (obj.type=="select-multiple") {
        if (obj.options.length > 0) {
            for (var i=0; i<obj.options.length; i++) {
                if (obj.options[i].selected != obj.options[i].defaultSelected) {
                    return true;
                    }
                }
            }
        return false;
        }
    // return false for all other input types (button, image, etc)
    return false;
}

//-------------------------------------------------------------------
// getInputValue(input_object)
//   Get the value of any form input field
//   Multiple-select fields are returned as comma-separated values
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function getRadioValue(obj) {
	var objLength = obj.length;
		
	if (objLength == undefined)		{
		if (obj.checked)	{
			return obj.value;
		}
	}
	
    for (var i=0; i<obj.length; i++) {
      	if (obj[i].checked == true) { return obj[i].value; }
    }
    return "";
}

function getInputValue(obj) {
  // para radio utilize a funcao acima
  if ((obj.type=="radio")) {
    // obj = eval("obj.form."+obj.name);
    for (var i=0; i<obj.length; i++) {
      if (obj[i].checked == true) { return obj[i].value; }
    }
    return "";
  }
  if (obj.type=="text" || obj.type=="password") { return obj.value; }
  if (obj.type=="hidden") { return obj.value; }
  if (obj.type=="textarea") { return obj.value; }
  if (obj.type=="checkbox") {
    if (obj.checked == true) { return obj.value; }
    return "";
  }
  if (obj.type=="select-one") {
    if (obj.options.length > 0) {
      return obj.options[obj.selectedIndex].value;
    } else {
      return "";
    }
  }
  if (obj.type=="select-multiple") {
    var val = "";
    for (var i=0; i<obj.options.length; i++) {
      if (obj.options[i].selected) {
        val = val + "" + obj.options[i].value + ",";
      }
    }
    if (val.length > 0) {
      val = val.substring(0,val.length-1); // remove trailing comma
    }
    return val;
  }
  return "";
}

//-------------------------------------------------------------------
// getInputDefaultValue(input_object)
//   Get the default value of any form input field when it was created
//   Multiple-select fields are returned as comma-separated values
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function getInputDefaultValue(obj) {
    if ((typeof obj.type != "string") && (obj.length > 0) && (obj[0] != null) && (obj[0].type=="radio")) {
        for (var i=0; i<obj.length; i++) {
            if (obj[i].defaultChecked == true) { return obj[i].value; }
            }
        return "";
        }
    if (obj.type=="text" || obj.type=="password") { return obj.defaultValue; }
    if (obj.type=="hidden") { return obj.defaultValue; }
    if (obj.type=="textarea") { return obj.defaultValue; }
    if (obj.type=="checkbox") {
        if (obj.defaultChecked == true) {
            return obj.value;
            }
        return "";
        }
    if (obj.type=="select-one") {
        if (obj.options.length > 0) {
            for (var i=0; i<obj.options.length; i++) {
                if (obj.options[i].defaultSelected) {
                    return obj.options[i].value;
                    }
                }
            }
        return "";
        }
    if (obj.type=="select-multiple") {
        var val = "";
        for (var i=0; i<obj.options.length; i++) {
            if (obj.options[i].defaultSelected) {
                val = val + "" + obj.options[i].value + ",";
                }
            }
        if (val.length > 0) {
            val = val.substring(0,val.length-1); // remove trailing comma
            }
        return val;
        }
    return "";
}

//-------------------------------------------------------------------
// setInputValue()
//   Set the value of any form field. In cases where no matching value
//   is available (select, radio, etc) then no option will be selected
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function setInputValue(obj,val) {
    if ((typeof obj.type != "string") && (obj.length > 0) && (obj[0] != null) && (obj[0].type=="radio")) {
        for (var i=0; i<obj.length; i++) {
            if (obj[i].value == val) {
                obj[i].checked = true;
                }
            else {
                obj[i].checked = false;
                }
            }
        }
    if (obj.type=="text" || obj.type=="password")
        { obj.value = val; }
    if (obj.type=="hidden")
        { obj.value = val; }
    if (obj.type=="textarea")
        { obj.value = val; }
    if (obj.type=="checkbox") {
        if (obj.value == val) { obj.checked = true; }
        else { obj.checked = false; }
        }
    if ((obj.type=="select-one") || (obj.type=="select-multiple")) {
        for (var i=0; i<obj.options.length; i++) {
            if (obj.options[i].value == val) {
                obj.options[i].selected = true;
                }
            else {
                obj.options[i].selected = false;
                }
            }
        }
}

//-------------------------------------------------------------------
// isFormModified(form_object,hidden_fields,ignore_fields)
//   Check to see if anything in a form has been changed. By default
//   it will check all visible form elements and ignore all hidden
//   fields.
//   You can pass a comma-separated list of field names to check in
//   addition to visible fields (for hiddens, etc).
//   You can also pass a comma-separated list of field names to be
//   ignored in the check.
//-------------------------------------------------------------------
function isFormModified(theform, hidden_fields, ignore_fields) {
    if (hidden_fields == null) { hidden_fields = ""; }
    if (ignore_fields == null) { ignore_fields = ""; }

    var hiddenFields = new Object();
    var ignoreFields = new Object();
    var i,field;

    var hidden_fields_array = hidden_fields.split(',');
    for (i=0; i<hidden_fields_array.length; i++) {
        hiddenFields[Trim(hidden_fields_array[i])] = true;
        }
    var ignore_fields_array = ignore_fields.split(',');
    for (i=0; i<ignore_fields_array.length; i++) {
        ignoreFields[Trim(ignore_fields_array[i])] = true;
        }
    for (i=0; i<theform.elements.length; i++) {
        var changed = false;
        var name = theform.elements[i].name;
        if (!isBlank(name)) {
            var type = theform[name].type;
            if (!ignoreFields[name]) {
                if (type=="hidden" && hiddenFields[name]) {
                    changed = isChanged(theform[name]);
                    }
                else if (type=="hidden") {
                    changed = false;
                    }
                else {
                    changed = isChanged(theform[name]);
                    }
                }
            }
        if (changed) {
            return true;
            }
        }
        return false;
}


//-------------------------------------------------------------------
// mascaraDiaMesAno( campo_data )
// Mascara o campo para a digitacao de dia, mes e ano (dia/mes/ano)
//-------------------------------------------------------------------
function mascaraDiaMesAno( data ) {
  var mydata = data.value;
  if (mydata.length == 2){
    if (mydata.charAt(1) == "/") {
      data.value = "0" + mydata;
    } else {
      data.value += "/";
    }
  }
  if (mydata.length == 5) {
    if (mydata.charAt(4) == "/") {
      var lastChar = mydata.charAt(3);
      var mydata = mydata.substring(0, 3);
      data.value = mydata + "0" + lastChar + "/";
    } else {
      data.value += "/";
    }
  }
}






//-------------------------------------------------------------------
// Daqui pra baixo, foi o Eduardo Gouvea que fez. Se precisar mudar de
// arquivo para um lugar melhor, tudo bem.
//-------------------------------------------------------------------


//-------------------------------------------------------------------
// mascaraMesAno( campo_data )
// Mascara o campo para a digitacao de mes e ano (mes/ano)
//-------------------------------------------------------------------
function mascaraMesAno( data ) {
  var mydata = data.value;
  if (mydata.length == 2){
    if (mydata.charAt(1) == "/") {
      data.value = "0" + mydata;
    } else {
      data.value += "/";
    }
  }
}

//-------------------------------------------------------------------
//  Conta o número de checkboxes selecionadas
//-------------------------------------------------------------------
function countSelected(umaCheckBox) {
  var contador = 0;

  if (umaCheckBox != null) {
    if (umaCheckBox.length != null) {
      for (var i = 0; i < umaCheckBox.length && contador < 2; i++) {
        if(umaCheckBox[i].checked) {
          contador++;
        }
      }
    } else {
      if(umaCheckBox.checked) {
        contador++;
      }
    }
  }
  return contador;
}


//------------------------------------------------------------------------------
//  Conta o número de itens selecionados em um array de option
//------------------------------------------------------------------------------
function countSelectedOption(arrayOption) {
  var contador = 0;

  if (arrayOption != null) {
    if (arrayOption.length != null) {
      for (var i = 0; i < arrayOption.length && contador < 2; i++) {
        if(arrayOption[i].selected) {
          contador++;
        }
      }
    } else {
      if(arrayOption.checked) {
        contador++;
      }
    }
  }
  return contador;
}


//-------------------------------------------------------------------
//  Retorna true se mais de uma checkbox estiver selecionada
//-------------------------------------------------------------------
function maisDeUmaSelecionada(umaCheckBox) {
  return (countSelected(umaCheckBox) > 1);
}


//------------------------------------------------------------------------------
//  Retorna true se mais de um item estiver selecionado no array de option
//  ou checkbox
//------------------------------------------------------------------------------
function maisDeUmItemSelecionado(arrayOption) {
  return (countSelectedOption(arrayOption) > 1);
}


//-------------------------------------------------------------------
//  Retorna true se nenhuma checkbox estiver selecionada
//-------------------------------------------------------------------
function nenhumaSelecionada(umaCheckBox) {
  return (countSelected(umaCheckBox) == 0);
}


//-------------------------------------------------------------------
//  Pega o "value" da primeira checkbox selecionada
//
//  @deprecated
//  Deverá ser substituída por <code>getFirstSelectedCheckbox(umaCheckBox)</code>
//-------------------------------------------------------------------
function getSelected(umaCheckBox) {
  var valor = "";

  if (umaCheckBox != null) {
    if (umaCheckBox.length != null) {
      for (var i = 0; i < umaCheckBox.length; i++) {
        if(umaCheckBox[i].checked) {
          valor = umaCheckBox[i].value;
          break;
        }
      }
    } else {
      valor = umaCheckBox.value;
    }
  }
  return valor;
}


//------------------------------------------------------------------------------
//  Retorna a única ou a primeira check box selecionada
//------------------------------------------------------------------------------
function getFirstSelectedCheckbox(umaCheckbox) {
  var checkboxSel = null;

  if (umaCheckbox != null) {
    if (umaCheckbox.length != null) {
      for (var i = 0; i < umaCheckbox.length; i++) {
        if(umaCheckbox[i].checked) {
          checkboxSel = umaCheckbox[i];
          break;
        }
      }
    } else {
      checkboxSel = umaCheckbox;
    }
  }
  return checkboxSel;
}


//------------------------------------------------------------------------------
//  Retorna todas as checkboxes selecionadas.
//  Mesmo que haja apenas 1 checkbox selecionada, sempre retorna um array.
//------------------------------------------------------------------------------
function getAllSelectedCheckboxes(umArrayCheckbox) {
    var subArray = null;

    if (umArrayCheckbox != null) {
        if (umArrayCheckbox.length != null) {
            for (var i = 0; i < umArrayCheckbox.length; i++) {
                if(umArrayCheckbox[i].checked) {
                    if (subArray == null) {
                        subArray = new Array();
                    }
                    subArray[subArray.length] = umArrayCheckbox[i];
                }
            }
        } else {
            if (subArray == null) {
                subArray = new Array();
            }
            subArray[subArray.length] = umArrayCheckbox;
        }
    }
    return subArray;
}


//------------------------------------------------------------------------------
//  Retorna o primeiro <option> selecionado de um <select>
//------------------------------------------------------------------------------
function getSelectedOption(umSelect) {
  var optionSel = null;

  if (umSelect != null) {
    for (var i = 0; i < umSelect.length; i++) {
      if(umSelect[i].selected) {
        optionSel = umSelect[i];
        break;
      }
    }
  }
  return optionSel;
}


//------------------------------------------------------------------------------
//  Retorna o primeiro radio selecionado de um <input type=radio>
//------------------------------------------------------------------------------
function getSelectedRadio(umRadio) {
  var radioSel = null;

  if (umRadio != null) {
      if (umRadio.length != null && umRadio.length > 0) {
          for (var i = 0; i < umRadio.length; i++) {
              if(umRadio[i].checked) {
                  radioSel = umRadio[i];
                  break;
              }
          }
      } else {
          if(umRadio.checked) {
              radioSel = umRadio;
          }
      }
  }
  return radioSel;
}


//------------------------------------------------------------------------------
// Verifica se o valor inteiro está contido no conjunto (array) de valores
//------------------------------------------------------------------------------
function estahContido(valor, valores) {
  var encontrou = false;

  if (valores != null) {
    if (valores.length != null) {
      for (var i = 0; i < valores.length && !encontrou; i++) {
        if (parseInt(valor, 10) == parseInt(valores[i])) {
          encontrou = true;
        }
      }
    }
  }
  return encontrou;
}

//-----------------------------------------------------------
// Functions acrescentadas por emurai

function getOptionIndex(comp, pkey) {
  var i;

  for (i=0; i<comp.options.length; i++) 
  	if (comp.options[i].value==pkey) 
		return i;

  return -1;
}


function extrairMascaraCPF(cpf) {
  var tam = cpf.length;
  var cpfNumerico = "";
  for (var idx = 0; idx < tam; idx++) {
    ch = cpf.substring(idx, idx+1);
    if (ch != '.' && ch != '-')
      cpfNumerico += ch;
  }

  return fillLeftChars(cpfNumerico,11,'0'); 
}

function validarMascaraCPF(cpf) {
  var posDot1 = cpf.indexOf('.', 0);
  var posDot2 = cpf.indexOf('.', posDot1+1);
  var posBar = cpf.indexOf('-');

  if (posDot1 > -1 || posDot2 > -1 || posBar > -1) {
    if (posDot1 != 3 || posDot2 != 7 || posBar != 11) {
      return false;
    }
  }
  return true;
}


function extrairMascaraCGC(cgc) {
  var tam = cgc.length;
  var cgcNumerico = "";
  for (var idx = 0; idx < tam; idx++) {
    ch = cgc.charAt(idx);
    if (ch != '.' && ch != '-' && ch != '/')
      cgcNumerico += ch;
  }

// return fillLeftChars(cgcNumerico,14,'0');
 return cgcNumerico;
}

function validarMascaraCGC(cgc) {
  var posDot1 = cgc.indexOf('.', 0);
  var posDot2 = cgc.indexOf('.', posDot1+1);
  var posSlash = cgc.indexOf('/');
  var posBar = cgc.indexOf('-');

  if (posDot1 > -1 || posDot2 > -1 || posSlash > -1 || posBar > -1) {
    if (posDot1 != 2 || posDot2 != 6 || posSlash != 10 || posBar != 15) {
      return false;
    }
  }
  return true;
}

function verificarCGC(CGCValue) {
  var dig1 = 0;
  var dig2 = 0;
  var i;
  var fator;
  
  CGCValue = extrairMascaraCGC(CGCValue);


    // Controle contra digitação de dados do tipo 111111111111, 222222222222, etc
    var temp = '';
    var ctr = 0;
    for (i=0; i<CGCValue.length; i++)
    {
      if(temp == CGCValue.charAt(i))
      {
        ctr++;
      }
      temp = CGCValue.charAt(i);
    }
    if (ctr >= 12)
      return false;


  if (CGCValue ==null || trim(CGCValue).length != 14) 
       return false;
      
  // primeiro digito
  fator=14;
  for (i=12; i>=1; i--){ 
	if (i==4) 
	  fator= 6;
    
      dig1= dig1 + parseInt(CGCValue.substring(i-1,i),10)*(fator-i);
     }

  dig1= dig1%11;
  if (dig1==0 || dig1==1) dig1=0;
  else dig1= 11-dig1;

  // alert("digito 1: " + parseInt(dig1,10));
  // alert("subs: " + CGCValue.substring(12,13));

  if (parseInt(dig1,10) != CGCValue.substring(12,13) ) return false;

  // segundo digito
  fator=15;
  for (i=13; i>=1; i--){
	  if (i==5) fator= 7;
	  
      dig2= dig2 + parseInt(CGCValue.substring(i-1,i),10)*(fator-i);
     }

  dig2= dig2%11;
  if (dig2==0 || dig2==1) dig2=0;
  else dig2= 11-dig2;

  // alert("digito 2: " + dig2);
  // alert("subs: " + CGCValue.substring(13,14));

  if( parseInt(dig2,10) != (CGCValue.substring(13,14)) ){
    return false;
  }
  else{
    return true;
  }
  
}

function fillLeftChars(v,size,ch) {
 var i=0;
 var dif=0;
 var buf='';
 
 if (v=='' || v==null) return '';
 if (v.length>=size) return v;
 
 dif = size - v.length;
 
 for (i=0; i<dif; i++) {
   buf+= ch; 
  }
  
 buf += v;
 return buf;
}

function verificarCPF(CPFValue) {
    var i;
    var dig1 = 0;
    var dig2 = 0;
    
    CPFValue = extrairMascaraCPF(CPFValue);


    // Controle contra digitação de dados do tipo 111111111111, 222222222222, etc
    var temp = '';
    var ctr = 0;
    for (i=0; i<CPFValue.length; i++)
    {
      if(temp == CPFValue.charAt(i))
      {
        ctr++;
      }
      temp = CPFValue.charAt(i);
    }
    if (ctr >= 9)
      return false;


    if (trim(CPFValue) == null || trim(CPFValue).length != 11) 
       return false;       
      
    for (i=1; i<=9; i++){
      dig1= dig1 + parseInt(CPFValue.substring(i-1,i),10) *i;
    }

    dig1= dig1%11;
    
    if (dig1==10) dig1=0;

    if (dig1 != CPFValue.substring(9,10)) return false;

    for (i=2; i<=10; i++){
       dig2= dig2 + parseInt(CPFValue.substring(i-1,i),10)*(i-1); 
    }

    dig2= dig2%11;

    if (dig2==10) dig2=0;

    if(dig2 != CPFValue.substring(10,11)){
      return false;
    }
    else{
      return true;
    }

}



function toCpf(cpf) {

    if(trim(cpf.value)!="" && cpf.value.length == 11) {

      cpf = cpf.value.substring(0,3) + "." + cpf.value.substring(3,6) +
            "." + cpf.value.substring(6,9) + "-" + cpf.value.substring(9,11);

    }

    return cpf;
}

function toCnpj(cnpj) {
    if(trim(cnpj.value)!="" && cnpj.value.length < 14 ) {
      cnpj.value = lPad(cnpj.value, '0', 14);
    }
    if(trim(cnpj.value)!="" && cnpj.value.length == 14) {
      cnpj.value = cnpj.value.substring(0,2) + "." + cnpj.value.substring(2,5) + "." 
             + cnpj.value.substring(5,8) + "/" + cnpj.value.substring(8,12) 
             + "-" + cnpj.value.substring(12,14);

    }
    return cnpj;
}

function getSelectedRadioCheckbox(umaCheckBox) {
  var valor = "";

  if (umaCheckBox != null) {
    if (umaCheckBox.length != null) {
      for (var i = 0; i < umaCheckBox.length; i++) {
        if(umaCheckBox[i].checked) {
          valor = umaCheckBox[i].value;
          break;
        }
      }
    } else {
      valor = umaCheckBox.value;
    }
  }
  return valor;
}



function filtrarDados(obj, grouping) {
  var keyDecimal = [190, 194];
  if (grouping == '.') keyDecimal = [190, 194];
  else if (grouping == ',') keyDecimal = [188, 110];

  if (event.keyCode != 9 && event.keyCode != 16 && event.keyCode != 8 && event.KeyCode != 13 &&
      event.keyCode != 35 && event.keyCode != 36) {
    if (event.keyCode == keyDecimal[0] || event.keyCode == keyDecimal[1]) {
      obj.value = obj.value.substring(0, obj.value.length-1);
    }
  }
}

// Aplica máscara decimal, indicando o tamanho máximo da parte inteira
// Ex: passando 3 como tamMax. Ao se digitar no campo o valor: 12345
// teremos como resultado 123,00
// Ex: passando 3 como tamMax. Ao se digitar no campo o valor: 123,45
// teremos como resultado 123,00
function applyLimitedMask(obj, tamMax) {

  var valor = obj.value;

  // Retira os pontos
  while(valor.indexOf(".")>0) {
     valor = valor.replace(".", "");
  }
  // Retira as vírgulas
  while(valor.indexOf(",")>0) {
     valor = valor.replace(",", "");
  }

  if (valor.length > tamMax) {

     valor = valor.substr(0, tamMax);
  }

  obj.value = valor;

  // Aplica a mascara de de decimais
  valueToMaskDec(obj, 2, '.', ',');

  return obj.value;

}

function valueToMaskDec(obj, numDecimal, grouping, decimal) {
//if ( isNaN(numDecimal) || trim(numDecimal) == "") numDecimal = 2;
//numDecimal = parseInt(''+numDecimal, 10);
//if (event.keyCode != 9 && event.keyCode != 16) {

    var menor = false;
    var dp = false;
    var dec = false;
    var tamOrig;
    
    if(obj.value.indexOf(decimal) >= 0) {
      dec = true;
      var indexPos = obj.value.indexOf(decimal);
      var subAux = obj.value.substring(indexPos+1);
      if (subAux.length < numDecimal) {
        obj.value += lPad('', '0', (numDecimal - subAux.length)); //'00';
      }
      else if (subAux.length > numDecimal) {

        obj.value = setDecimalDec(obj.value, numDecimal, grouping, decimal);

        indexPos = obj.value.indexOf(decimal);
        subAux = obj.value.substring(indexPos+1);
        if (subAux.length < numDecimal) {
          obj.value += lPad('', '0', (numDecimal - subAux.length)); //'00';
        }
      }

    }
    while(obj.value.match(/\D/)) {
      obj.value = obj.value.replace(/\D/,'');
      dp = true;
    }
    while(obj.value.substr(0,1)=='0') {
      obj.value = obj.value.substr(1);
    }

    if (obj.value.length == 0) tamOrig = 1;
    else tamOrig = obj.value.length;
    while(obj.value.length<(numDecimal+1)) {
      if (dec)
        obj.value = '' + 0 + obj.value;        
      else {
        var strAux='';
        for (var x=0; x<tamOrig; x++) {
          strAux += '0';
        }
        obj.value = obj.value + strAux + '';
      }

      menor = true;
    }
    
    var valor = "";
    var tam;
    if (menor) tam = obj.value.length-(numDecimal+1);
    else if (dp) {
      tam = obj.value.length-numDecimal;
    }
    else tam = obj.value.length;

    for (var idx = tam; idx > 0; idx-=3) {
      valor = obj.value.substring(idx, idx - 3) + grouping + valor;
    }
    if (valor.charAt(valor.length-1) == grouping) valor = valor.substring(0, valor.length-1);

    if (!menor && dp) obj.value = valor + obj.value.substr(obj.value.length-numDecimal);
    else if (!menor && !dp) obj.value = valor + lPad('', '0', numDecimal);
    obj.value = obj.value.substr(0,obj.value.length-numDecimal)+decimal+obj.value.substr(obj.value.length-numDecimal);

	if (obj.value == "0,00") {
    	obj.value = "";
    }

 // }
}

function maskToValue(obj) {
  var valor = obj.value;
  // Esse loop é necessário porque o replace só substitui a primeira ocorrencia do "."
  while(valor.indexOf(".")>0) {
    valor = valor.replace(".", "");
  }
  valor = valor.replace(",", ".");
  obj.value = valor;
}

function maskFloatToValue(obj) {
  var valor = obj.value;
  valor = valor.replace(",", "");
  valor = valor.replace(".", ",");
  obj.value = valor;
}

function setDecimalDec(parametro, numCasas, grouping, decimal){
  pos = parametro.indexOf(decimal);
  var pDecAux = '';
  if (pos > 0) {
     pInt = parametro.substring(0, pos);
     pDec = parametro.substring(pos + 1, parametro.length);
     if (pDec.length > numCasas) {
        ind = pDec.substring(numCasas, (numCasas+1));

        
        if (Math.abs(ind) >= 5) {
           if (pDec.substring(0,1) == '0') pDecAux = '0';
           pDec = Math.abs(pDec.substring(0,numCasas)) + 1;
           if (pDec < 10) pDec = pDecAux + '' + pDec;
           if ( pDec == eval('1'+lPad('', '0', numCasas)) ) {
              pInt++;
              pDec = lPad('', '0', numCasas);
           }
           else if (pDec == 1)
             pDec = lPad('', '0', (numCasas-1)) + "1";
        }
        else 

        

           pDec = pDec.substring(0,numCasas);
        return (pInt + decimal + pDec);
        
     }
     else {
        if (pDec.length < (numCasas -1))
           pDec = pDec + lPad('', '0', (numCasas-pDec.length));
           return (pInt + decimal + pDec);
     }
  }
  else {
     return (trim(parametro) != "" ) ? parametro+decimal+lPad('', '0', numCasas) : parametro;
  }
}


//-------------------------------------------------------------------
// LPad e RPad functions
//   Retorna uma string ajustada um numero definido do caracter de preenchimento
//-------------------------------------------------------------------
function lPad(str, charac, length) {
  var strAux = str;
  for (var i=strAux.length; strAux.length<length; i++) strAux = charac + strAux;
  return strAux;
}

function rPad(str, charac, length) {
  var strAux = str;
  for (var i=strAux.length; strAux.length<length; i++) strAux += charac;
  return strAux;
}


function isEscapeKey(key) {
  for (var idx=0; idx<VK_ESCAPE_KEYS.length; idx++) {
    if ( key == VK_ESCAPE_KEYS[idx] ) return true;
  }
  return false;
}

function filtrarAlfaDigit(obj) {
  var kCode = event.keyCode;
  var value = obj.value;
  var aux = "";
  var i;
  if (kCode < 33 || kCode >46)
  {
    for (i=0;i<=value.length;i++)
    {

      if (   value.substr(i,1) == "0" 
          || value.substr(i,1) == "1" 
          || value.substr(i,1) == "2" 
          || value.substr(i,1) == "3" 
          || value.substr(i,1) == "4" 
          || value.substr(i,1) == "5" 
          || value.substr(i,1) == "6" 
          || value.substr(i,1) == "7" 
          || value.substr(i,1) == "8" 
          || value.substr(i,1) == "9"  )
       {  
         aux = aux + obj.value.substr(i,1);
       }
    }
    obj.value = aux;
  }
/*  
  if (!event.altKey && !event.ctrlKey) {
    if ( !isEscapeKey(kCode) || event.shiftKey ) {
      if ( (kCode > VK_NOVE || kCode < VK_ZERO) && (kCode > VK_NOVE_PAD || kCode < VK_ZERO_PAD) ) {
        obj.value = obj.value.substring(0, obj.value.length-1);
      }
      else if (event.shiftKey) {
        obj.value = obj.value.substring(0, obj.value.length-1);
      }
    }
  }
*/
}





  function truncar(num, numDec, decSeparator)
  {

      var newValue = "";
      var ctr = 0;
      var flagCtr = false;

      for (y=0;y<num.length;y++) {

          newValue += num.charAt(y);
          if (num.charAt(y) == decSeparator) {
             flagCtr = true;
          }
          if (flagCtr) {
             ctr++;
          }
          if (ctr > numDec) {
             break;
          }
          
      }

      return newValue;
  }


/*
 * Retorna os indices selecionados de um select multiplo
 */
function getSelectedIndexes(obj) {
  if (obj.type=="select-multiple") {
    var val = "";
    for (var i=0; i<obj.options.length; i++) {
      if (obj.options[i].selected) {
        val = val + "" + i + ",";
      }
    }
    if (val.length > 0) {
      val = val.substring(0,val.length-1); // remove trailing comma
    }
    return val;
  }
  return "";
}

/*
 * Valida CEP
 */
function isCEP(cep) {
   if (!isNumeric(cep)) return false;
   if (cep.length != 8) return false;
   return true;
}

/*
* Valida Telefone
*/
function isTelefone(string)		{
	if (trim(string).length<8)	{
		return false;
	}
	
	if (!isInteger(string))	{
		return false;
	}
	
	return true;
}

function isValidPercent(obj) {

    if (!obj.value || trim(obj.value) == "") {
    	return true;
    }
    
    var s = trim(obj.value);

    if (!isNumeric(s)) {
	obj.value = '';
	obj.focus();
	alert('Digite um % valido!');
	return false;	   
    }

    // Retira os pontos
    while(s.indexOf(".")>0) {
    	s = s.replace(".", "");
    }
    
    // Retira as virgulas
    while(s.indexOf(",")>0) {
    	s = s.replace(",", ".");
    }
    
    if(parseFloat(s, 10) < 0 
       || parseFloat(s, 10) > 100) {
	obj.value = '';
	obj.focus();
	alert('Digite um % valido!');
	return false;	   
    }

    return true;	
}

function abrirGlossario() {
  window.open("../html/glossario.htm", "", "menubar=no,toolbar=no,location=no,scrollbars=yes,status=no,resizable=yes");
}

function formatarCep( campo ) {
  var valor = removerCaracteresEspeciais(trim(campo.value));
  if( valor != "" ) {
    if( valor.length > 3 ) {
      valor = valor.substring(0,valor.length-3) + "-" + valor.substring(valor.length-3)
    }
  }
  campo.value = valor;
}
/**
 * Remove todos os caracteres que não sejam um digito de 0 a 9
 * removendo também ',' e '.'. O novo valor vem no retorno do método.
 */
function removerNaoNumericos( valor ) {
  var numeros = "0123456789";
  valor = trim(valor);
  var ret = "";
  for(var i=0; i<valor.length; i++) {
    if (numeros.indexOf(valor.charAt(i)) >= 0) {
      ret += valor.charAt(i);
    }
  }
  return ret;
}


/**
 * Remove caracteres especiais da String informada.
 * Passa o valor a ser editado. O novo valor vem no retorno do método.
 */
function removerCaracteresEspeciais( valor ) {
  var especiais = ".,;:-_#%&*!@|\\/[]{}+=<>()";
  valor = trim(valor);
  var ret = "";
  for(var i=0; i<valor.length; i++) {
    if( especiais.indexOf(valor.charAt(i)) < 0 ) {
      ret += valor.charAt(i);
    }
  }
  return ret;
}

function formatarTelefone( campo ) {
  var valor = removerCaracteresEspeciais(trim(campo.value));
  if( valor != "" ) {
    if( valor.length > 4 ) {
    	valor.substring(0,valor.length-4)
      valor = valor.substring(0,valor.length-4) + "-" + valor.substring(valor.length-4)
    }
  }
  campo.value = valor;
}


function formatarMoeda( campo ) {
  var valor = removerNaoNumericos(trim(campo.value));
  if( valor != "" ) {
    if( valor.length == 1 ) {
      valor = "0,0" + valor;
    }
    else if( valor.length == 2 ) {
      valor = "0," + valor;
    }
    else {
      var casaDecimal = valor.substring(valor.length-2);
      var inteiro = valor.substring(0,valor.length-2);
      var novo = "";
      var idxPonto = 0;
      for(var i=inteiro.length-1; i>=0; i--) {
        if( idxPonto == 3 ) {
          novo = "." + novo;
          idxPonto = 0;
        }
        novo = inteiro.charAt(i) + novo;
        idxPonto++;
      }
      valor = novo + "," + casaDecimal;
    for(var i=0; i<valor.length; i++) {
      if( valor.charAt(i) == '0' ) {
        valor = valor.substring(1,valor.length);
      } else {
        break;
      }
    }
    }
  }
  campo.value = valor;
}

function removerMascaraMoedaSemDecimal( campo ) {
  var valor = removerCaracteresEspeciais(trim(campo.value));
  campo.value = valor.substring(0,valor.length-2);
}

// Verifica se é uma data valida e se esta no formato DD/MM/AAAA
function validarData(value, obj) {

      if (validaParametro(trim(value))) {

	  ultDia = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	  pos1 = value.indexOf("/");
	  pos2 = value.substring(pos1+1, value.length).indexOf("/") + pos1+1;
	  if ((pos1 < 1 || pos2 < pos1 + 2) || (value.length >10)) {
	    if(obj.value != "") {
	    	alert("Data deve estar no formato dd/mm/aaaa");
	    }
	    obj.value = "";
	    return false;
	  }
	  else {
	  dia = value.substring(0,pos1);
	  mes = value.substring(pos1+1, pos2);
	  ano = value.substring(pos2+1, value.length);

	  if (dia.length == 1)
	 dia = "0" + dia;

	  if (mes.length == 1)
	 mes = "0" + mes;

	  obj.value= dia + "/" + mes + "/" + ano;

	  if (ano.length != 4) {
	    alert("Ano inválido!");
	    obj.value = "";
	    return false;
	  }
	  else if (dia.length > 2 || dia.length < 1) {
	    alert("Dia inválido!");
	    obj.value = "";
	    return false;
	  }
	  else if (mes.length > 2 || mes.length < 1) {
	    alert("Mês inválido!");
	    obj.value = "";
	    return false;
	  }
	  else { //else tudo
	       dia = Math.abs(dia);
	       mes = Math.abs(mes);
	       ano = Math.abs(ano);
	    if (mes == 2 && !isLeapYear(ano)) {
	      if (dia > ultDia[mes-1]) {
		alert("Dia inválido!");
		obj.value = "";
	     return false;
		 } //dia > ultDia
	    } //mes == 2...
	    else if (isLeapYear(ano) && mes == 2) {
	      if (dia > ultDia[mes-1] + 1) {
	       alert("Dia inválido!");
	       obj.value = "";
	       return false;
	      } //dia > ultDia
	    }  //else if
	   else if (mes > 12 || mes < 1) {
		 alert("Mês inválido!");
		 obj.value = "";
		 return false;
	      }
	   else if (dia > 31 || dia > ultDia[mes-1] || dia < 1) {
	      alert("Dia inválido!");
		 obj.value = "";
		 return false;
	      }
	    }  //else tudo
	 } //else
      } //primeiro if
      else {
	alert("Campo só aceita número e '/' !");
	obj.value = "" ;
	return false;
      }
      return true;
}

function validaParametro(parametro) {
     tam = parametro.length;
     for (i=0; i<tam; i++) {
       var ch = parametro.substring(i, i+1);
       if ((ch < "0" || ch > "9") && ch!="/") return false;
     }
     return true;
}

function isLeapYear(ano) {
     div = ano/4;
     if (div - Math.floor(div) == 0)
	return true;
     else return false;
}


//valor = true -> mostra do div
function mostra_div(lista, valor) {
	for (var x in lista) {
		var e = document.getElementById(lista[x]);
		e.style.display = valor ? "" : "none";
                //se for para esconder o elemento, apaga a resposta selecionada...
		if(!valor){
            apagaRespostasQuadro (e);
		}
	}

}
// Preencher Respostas VC SA
function responde() {
	var elementos = document.getElementsByTagName("input");
	for (var i=0; i < elementos.length; i++ ) {
		preencheInput(elementos[i]);
	}
	elementos = document.getElementsByTagName("select");
	for (var i=0; i < elementos.length; i++ ) {
		preencheInput(elementos[i]);
	}
	elementos = document.getElementsByTagName("textarea");
	for (var i=0; i < elementos.length; i++ ) {
		preencheInput(elementos[i]);
	}
}

function preencheInput(elemento) {
	if (elemento.type == "text" || elemento.type == "textarea") {
		//Para não sobrescrever o onkeypress do input se ele ja existir
		if (elemento.onkeypress == undefined) {
			elemento.onkeypress=filtrarAspasSimplesBarra;
		}
	}
	var valor = null;
	try {
		if (elemento.type != "hidden") {
			valor = eval(elemento.name);
		}
	} catch (e){	
		//alert("Faltando resposta \"" + elemento.name + "\" erro: " + e);
	}
	if (valor != null) {
		if (elemento.type == "text" || elemento.type == "textarea") {
			elemento.value = valor;
		} else if (elemento.type == "checkbox" || elemento.type == "radio") {
			for (var i=0;i<valor.length;i++) {
				if (elemento.value == valor[i]) {
					elemento.checked = true;
				}
			}
		} else if (elemento.type == "select-one") {
			for (var i=0;i<elemento.length;i++) {
				if (elemento.options[i].value == valor[0]) {
					elemento.options[i].selected = true;
				}
			}
		}
	}
}
function filtrarAspasSimplesBarra(evt) {
	if (navigator.appName == "Microsoft Internet Explorer") {
		var evt = window.event;
	}
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode == 39 || charCode == 92) {
		return false;
	}
	return true;
}

function filtrarFloat(evt) {
	if (navigator.appName == "Microsoft Internet Explorer") {
		var evt = window.event;
	}
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (!evt.witch) {
		if (evt.keyCode == 8 || evt.keyCode == 46 || ( evt.keyCode >=37 && evt.keyCode <=40)) {
			return true;
		}
	}
	if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 44 && charCode != 46) {
		return false;
	}
	
	if (charCode == 44 || charCode == 46) {
		if (this.value.indexOf('.') == -1) {
			this.value += '.';
		}
		return false;
	}

	if (this.value.indexOf('.') != -1 && (this.value.length - this.value.indexOf('.') > 1)) {
		return false;
	}
	/*if (this.value.length this.value.indexOf('.')) {
		return false;
	}*/
	return true;
}

function desmarcaCheckBox (lista, nome) {
	elementos = document.getElementsByName(nome);
	for (var i = 0; i < elementos.length; i++) {
		for (var x in lista) {
			if (elementos[i].value == lista[x]) {
				elementos[i].checked = false;
			}
		}
	}
}
function mostraOculto (lista, nome, valor) {
	elementos = document.getElementsByName(nome);
	for (var i = 0; i < elementos.length; i++) {
		if (elementos[i].value == valor) {
			mostra_div(lista, elementos[i].checked);
			return elementos[i].checked;
		}
	}
	return false;
}

function mostraOculto2 (lista, nome, valor) {
	elementos = document.getElementsByName(nome);
	for (var i = 0; i < elementos.length; i++) {
		if (elementos[i].value == valor) {
			mostra_div(lista, !elementos[i].checked);
			return !elementos[i].checked;
		}
	}
	return false;
}

function apagaRespostasQuadro (elemento) {
	if (elemento.type == "text" || elemento.type == "textarea" || elemento.type == "password") {
			elemento.value = "";
	} else if (elemento.type == "checkbox" || elemento.type == "radio") {
		elemento.checked = false;
	} else if (elemento.type == "select-one") {
		elemento.selectedIndex = -1
		for (var i=0;i<elemento.length;i++) {
			if (elemento.options[i].value == "") {
				elemento.options[i].selected = true;
			}
		}
	}
	if (!elemento.hasChildNodes){
		return;
	}
	for (var i=0; i < elemento.childNodes.length; i++) {
		apagaRespostasQuadro (elemento.childNodes[i]);
	}
}
function apagaRespostas(perguntas, condicao) {
	var pergunta = null;
	if (condicao) {
		for (var x in perguntas) {
			pergunta = eval('document.formQuest.' + perguntas[x]);
			pergunta.selectedIndex = 0;
		}
	}
}

function geraRespostaEmail(codPergunta) {
	
	if (codPergunta == "1133") {
		p = document.getElementsByName("P" + codPergunta)[1];
		if (p.checked) {
			document.getElementById('RespEnvioEmail').innerHTML += '<input type="hidden" name="R' + codPergunta + '" value="Sim">';
		}
		return;
	}
	
	var p = document.getElementsByName("P" + codPergunta)[0];
	
	if (codPergunta == "2582" && p.options[p.selectedIndex].value == "2636") {
		return;
	}
	
	if (codPergunta == "1358") {
		var resp1358 = document.getElementsByName("P1358")[0].value;
		if (resp1358 == "2718" || // Coleção A Grande Cozinha
			resp1358 == "2719" || //Coleção Atlas National Geografic
			resp1358 == "2720" || //Veja Rio
			resp1358 == "2721" || //Veja SP
			resp1358 == "1389" || //Almanaque Abril
			resp1358 == "1390" || //Ana Maria
			resp1358 == "1393" || //Bizz
			resp1358 == "1406" || //Faça e Venda
			resp1358 == "1407" || //Fadas
			resp1358 == "1408" || //Flashback
			resp1358 == "1409" || //Guia do Estudante
			resp1358 == "1411" || //Info Canal
			resp1358 == "2460" || //Loveteen
			resp1358 == "1415" || //Minha Novela
			resp1358 == "1416" || //MTV
			resp1358 == "1423" || //Princesas
			resp1358 == "1426" || //Religiões
			resp1358 == "1428" || //RSVP
			resp1358 == "2461" || //Sou+eu!
			resp1358 == "1431" || //Super Surf
			resp1358 == "1432" || //Tititi
			resp1358 == "1433" || //Toda Teen
			resp1358 == "1437" || //Viva Mais
			resp1358 == "1440")   //Witch
			return;
	}
	if (codPergunta == "2566" || codPergunta == "2567" || codPergunta == "2568" || codPergunta == "2569") {
		if (p.options[p.selectedIndex].text == "1") p.options[p.selectedIndex].text = "Janeiro";
		if (p.options[p.selectedIndex].text == "2") p.options[p.selectedIndex].text = "Fevereiro";
		if (p.options[p.selectedIndex].text == "3") p.options[p.selectedIndex].text = "Março";
		if (p.options[p.selectedIndex].text == "4") p.options[p.selectedIndex].text = "Abril";
		if (p.options[p.selectedIndex].text == "5") p.options[p.selectedIndex].text = "Maio";
		if (p.options[p.selectedIndex].text == "6") p.options[p.selectedIndex].text = "Junho";
		if (p.options[p.selectedIndex].text == "7") p.options[p.selectedIndex].text = "Julho";
		if (p.options[p.selectedIndex].text == "8") p.options[p.selectedIndex].text = "Agosto";
		if (p.options[p.selectedIndex].text == "9") p.options[p.selectedIndex].text = "Setembro";
		if (p.options[p.selectedIndex].text == "10") p.options[p.selectedIndex].text = "Outubro";
		if (p.options[p.selectedIndex].text == "11") p.options[p.selectedIndex].text = "Novembro";
		if (p.options[p.selectedIndex].text == "12") p.options[p.selectedIndex].text = "Dezembro";
	}
	if (p.options[p.selectedIndex].value != "") {
		document.getElementById('RespEnvioEmail').innerHTML += '<input type="hidden" name="R' + codPergunta + '" value="' + p.options[p.selectedIndex].text + '">';
	}
}


function Apenas_Numeros(caracter)
{
  var nTecla = 0;
  if (document.all) {
      nTecla = caracter.keyCode;
  } else {
      nTecla = caracter.which;
  }
  if ((nTecla> 47 && nTecla <58)
  || nTecla == 8 || nTecla == 127
  || nTecla == 0 || nTecla == 9  // 0 == Tab
  || nTecla == 13) { // 13 == Enter
      return true;
  } else {
      return false;
  }
}