//SCA - Scripts Gerais

//******************************************************************************
//TRATAMENTO DE EVENTOS
//******************************************************************************
//Remove caracteres invalidos de um campo do form
//evt: evento que disparou este metodo, de onde sera obtido o elemento que
//o capturou.
//validChars: string contendo os caracteres validos
//doUpperCase: coloca os caracteres minusculos dos campos em maiusculos.
function removeInvalidChars(evt, validChars, doUpperCase) {
  var vKeyCode;
  if (evt.target) {
    sourceElement = evt.target;
    vKeyCode = evt.which;
  }
  else { //IE
    sourceElement =  event.srcElement;
    vKeyCode = event.keyCode;
  }

  //Para não "engolir" a navegaçao pela tecla "tab":
  if (vKeyCode != 9) {
      removeInvalidCharsFromField(sourceElement, validChars, doUpperCase);
  }
}//function removeInvalidChars(evt, validChars, doUpperCase)


//******************************************************************************
//MANIPULACAO DE STRINGS e FORMATACAO DE CAMPOS
//******************************************************************************

function removeInvalidCharsFromField(formField, validChars, doUpperCase) {
    var vFieldValue = formField.value;

    if (trim(doUpperCase).toUpperCase() == "TRUE") {
            vFieldValue = vFieldValue.toUpperCase();
    }

    var vNewValue = "";
    for (vIdx=0; vIdx < vFieldValue.length; vIdx++) {
          if (validChars.indexOf(vFieldValue.substr(vIdx, 1)) != -1) {
             vNewValue = vNewValue + vFieldValue.substr(vIdx, 1);
          }
    }

    formField.value = vNewValue;
}

//Remove espaços em branco do inicio e do fim das Strings.
//Remove tambem espaços dublos do meio das strings.
function trim(vValue) {
	var vNewValue = "";
	saParts = vValue.split(" ");

	for (index = 0; index < saParts.length; index++) {
        if(saParts[index] != "") {
			if (vNewValue == "") {
				vNewValue = saParts[index];
			}
			else {
				vNewValue = vNewValue + " " + saParts[index];
			}
		}
	}//for

	return vNewValue;
}//function trim(vValue)

//Coloca vChar a esquerda de vField em quantidade suficiente para que vField
//deixe de ser menor que o valor numérico vLength.
function padLeftWithChar(vFieldValue, vLength, vChar) {
    vFieldValue = trim(vFieldValue);
    while (vFieldValue.length < parseInt(vLength, 10)) {
        vFieldValue = vChar+vFieldValue;
    }
    return vFieldValue;
}//function padLeftWithChar(vField, vLength, vChar)

function areOnlyZeroes(vString) {
    vString = trim(vString);
    var vZeroes = padLeftWithChar("", vString.length, "0");

    return (vZeroes == vString);
}

function isNumber(vString) {
    var vResult = true;
    vString = trim(vString);
    for(idx = 0; idx < vString.length;  idx++) {
        if ("0123456789".indexOf(vString.substr(idx, 1)) <= -1) {
            vResult = false;
        }
    }
    return vResult;
}

//******************************************************************************
//OPERACOES SOBRE DATA E HORA
//******************************************************************************

function isValidDate(day, month, year) {
    day = parseInt(day, 10);
    month = parseInt(month, 10);
    year = parseInt(year, 10);

    if (year < 1900) {
      return false;
    }
    else if (month < 1 || month > 12) {
      return false;
    }
    else if (day < 1 || day > 31) {
      return false;
    }
    else if (day > getNumberOfDaysInMonth(month, year)) {
      return false;
    }
    else {
      return true;
    }
}//function isValidDate(day, month, year)


//--Verifica se a primeira data é posterior à segunda.
//Retorna < 0 se a primeira data é posterior à segunda
//Retorna 0 se for igual
//Retorna > 0 se a primeira data for anterior à segunda
function compareDates(firstDay, firstMonth, firstYear, secondDay, secondMonth, secondYear) {
        return (calculateDateInDays(secondDay, secondMonth, secondYear, 1900)
            - calculateDateInDays(firstDay, firstMonth, firstYear, 1900));
}//compareDates


//Retorna true se o ano informado for bissexto
function isLeapYear(year) {
  if ((year % 400)==0) {
    return true;
  }
  else if ((year % 4) == 0 && (year % 100) != 0) {
    return true;
  }
  else {
    return false;
  }
}//isLeapYear

//Calcula a quantidade de dias decorridos desde 01/01/referenceYear ate
//day/month/year
function calculateDateInDays(day, month, year, referenceYear) {
    var vDay = parseInt(day, 10);
    var vMonth = parseInt(month, 10);
    var vYear = parseInt(year, 10);
    var vReferenceYear = parseInt(referenceYear, 10);

    var vDifference = 0;

    for (i = vReferenceYear; i < vYear; i++) {
        if (isLeapYear(i)) {
            vDifference = vDifference + 366;
        }//if (isLeapYear(i))
        else {
            vDifference = vDifference + 365;
        }//else
    }//for

    for (i = 1; i < vMonth; i++) {
        vDifference = vDifference + getNumberOfDaysInMonth(i, vYear);
    }

    vDifference = vDifference + vDay;

    return vDifference;
}//function calculateDateInDays

//Retorna o numero de dias do mes month no ano year.
function getNumberOfDaysInMonth(month, year) {
    var vMonth = parseInt(month, 10);
    var vYear = parseInt(year, 10);

if (vMonth == 1 || vMonth == 3 || vMonth == 5 || vMonth == 7 || vMonth == 8
            || vMonth == 10 || vMonth == 12) {
        return 31;
    }//if (vMonth == 1 || vMonth == 3 || vMonth == 5 || vMonth == 7 || vMonth == 8
    else if (vMonth == 4 || vMonth == 6 || vMonth == 9 || vMonth == 11) {
        return 30;
    }//else if (vMonth == 4 || vMonth == 6 || vMonth == 9 || vMonth == 11)
    else if (vMonth == 2) {
        if (isLeapYear(vYear)) {
            return 29;
        }//if (isLeapYear(vYear))
        else {
            return 28;
        }//else [if (isLeapYear(vYear))]
    }//else if (vMonth == 2)
    else {
        return 0;
    }//else
}//function getNumberOfDaysInMonth(month, year)

/******************************************************************************
* OUTRAS FUNCOES
*******************************************************************************/
function pausecomp(timeInMillis){
    dtBegin = new Date();
    while (1){
      dtNow=new Date();
      diff = dtNow-dtBegin;
      if( diff >= timeInMillis){
          break;
      }
    }//while
}


//Recebe o radio como parametro, retorna o valor do que estiver selecionado ou
//"" caso nenhum esteja selecionado.
function getRadioValue(radioButton) {
  var vValue = "";
    if (radioButton && radioButton.length) {
      for (iRadioIdx = 0; iRadioIdx < radioButton.length; iRadioIdx++) {
        if(radioButton[iRadioIdx].checked) {
          vValue = radioButton[iRadioIdx].value;
        }
      }
    }
    else if (radioButton) {
      if (radioButton.checked) {
        vValue = radioButton.value;
    }
  }
  return vValue;
}

function getCheckBoxValue(checkBox) {
  var vArray = new Array(0);

  if (checkBox && checkBox.length) {
    for (iCBidx = 0; iCBidx < checkBox.length; iCBidx++) {
      if (checkBox[iCBidx].checked) {
          vArray.push(checkBox[iCBidx].value);
      }
    }
  }
  else if (checkBox) {
    if (checkBox.checked) {
      vArray.push(checkBox.value);
    }
  }
  return vArray;
}
