﻿//   by Vlad Pitaru
//
//   --------------------------------------------------------------------------------------------------|
//  | FUNCTION NAME	  	 | HOW TO USE                                                                  |
//  |--------------------------------------------------------------------------------------------------|
//  | Maiuscolo()		     | onkeypress="Maiuscolo(event)"	                                           |
//  |--------------------------------------------------------------------------------------------------|
//  | OnlyDouble()		   | onkeypress="OnlyDouble(event)"                                              |
//  |--------------------------------------------------------------------------------------------------|
//  | OnlyInteger()	  	 | onkeypress="OnlyInteger(event)"                                             |
//  |--------------------------------------------------------------------------------------------------|
//  | DateFormat()	  	 | onkeypress="AddSlash(event)" onblur="DateFormat(event)"                     |
//  |--------------------------------------------------------------------------------------------------|
//  | DoubleToString()	 | str = DoubleToString(3100.99)  -- 2 decimals (requires NumberFormat154.js)  |
//  |--------------------------------------------------------------------------------------------------|
//  | DoubleToString3()	 | str = DoubleToString3(3100.998) -- 3 decimals  (requires NumberFormat154.js)|
//   --------------------------------------------------------------------------------------------------|
//  | DoubleToStringDec()| str = DoubleToStringDec(nr, nrDecimals)        (requires NumberFormat154.js)|
//   ---------------------------------------------------------------------------------------------------
//  | FormatNumber()     | str = FormatNumber(controlName, nrDecimals)    (requires NumberFormat154.js)|
//   ---------------------------------------------------------------------------------------------------

function StopPropagation(e) {
  if (!(e.stopPropagation == null)) {
    e.stopPropagation();
    e.preventDefault();
  }
  else {
    e.cancelBubble = true;
    e.returnValue = false;
  }
}

function Maiuscolo(e) {
  // cross-browser compatibility
  if (!e) var e = window.event;
  var srcElement = (e.target) ? e.target : e.srcElement;
  var keyCode = (e.which) ? e.which : e.keyCode;

  if ((keyCode >= 97) && (keyCode <= 122)) {
    ChangeFiredKeyCode(e, String.fromCharCode(keyCode - 32));
  }

  if (keyCode == 13)
    StopPropagation(e);
}

function MaiuscoloEnter(e) {
  // cross-browser compatibility
  if (!e) var e = window.event;
  var srcElement = (e.target) ? e.target : e.srcElement;
  var keyCode = (e.which) ? e.which : e.keyCode;

  if ((keyCode >= 97) && (keyCode <= 122)) {
    ChangeFiredKeyCode(e, String.fromCharCode(keyCode - 32));
  }
}

function ChangeFiredKeyCode(e, newChar) {
  // cross-browser compatibility
  if (e.which) {
    var newEvent = document.createEvent("KeyEvents")
    newEvent.initKeyEvent("keypress", true, true, document.defaultView,
							e.ctrlKey, e.altKey, e.shiftKey,
							e.metaKey, 0, newChar.charCodeAt(0))

    e.preventDefault()
    e.target.dispatchEvent(newEvent)
  }
  else {
    e.keyCode = newChar.charCodeAt(0);
  }
}

function DoubleToString(importo) {
  // debugger;

  var str = "";
  if (importo.toString() != "NaN") {
    var num = new NumberFormat();
    num.setInputDecimal('.');
    num.setNumber(importo);
    num.setPlaces('2', false);
    num.setCurrencyValue('$');
    num.setCurrency(false);
    num.setCurrencyPosition(num.LEFT_OUTSIDE);
    num.setNegativeFormat(num.LEFT_DASH);
    num.setNegativeRed(false);
    num.setSeparators(false, '.', ',');
    str = num.toFormatted();
  }

  return str;
}

function DoubleToString3(importo) {
  // debugger;

  var str = "";
  if (importo.toString() != "NaN") {
    var num = new NumberFormat();
    num.setInputDecimal('.');
    num.setNumber(importo);
    num.setPlaces('3', false);
    num.setCurrencyValue('$');
    num.setCurrency(false);
    num.setCurrencyPosition(num.LEFT_OUTSIDE);
    num.setNegativeFormat(num.LEFT_DASH);
    num.setNegativeRed(false);
    num.setSeparators(false, '.', ',');
    str = num.toFormatted();
  }

  return str;
}

function DoubleToStringDec(importo, nrDecimals, thounsandSeparator) {
  var useThousands = thounsandSeparator;
  if (!useThousands) useThousands = false;

  var str = "";
  if (importo.toString() != "NaN") {
    var num = new NumberFormat();
    num.setInputDecimal('.');
    num.setNumber(importo);
    num.setPlaces(nrDecimals.toString(), false);
    num.setCurrencyValue('$');
    num.setCurrency(false);
    num.setCurrencyPosition(num.LEFT_OUTSIDE);
    num.setNegativeFormat(num.LEFT_DASH);
    num.setNegativeRed(false);
    num.setSeparators(useThousands, '.', ',');
    str = num.toFormatted();
  }

  return str;
}

function FormatDouble(e, nrDecimals) {
  if (!e) var e = window.event;
  var srcElement = (e.target) ? e.target : e.srcElement;
  dPU = parseFloat(srcElement.value.replace(".", "").replace(",", "."));
  if (!isNaN(dPU)) {
    srcElement.value = DoubleToStringDec(dPU, nrDecimals);
  }
  else {
    srcElement.value = "";
  }
}

function OnlyDouble(e) {
  if (!blockNonNumbers(e, true, true)) {
    StopPropagation(e);
    return;
  }
  return;
}

function OnlyInteger(e) {
  if (!blockNonNumbers(e, false, true)) {
    StopPropagation(e);
    return;
  }
  return;
}

function AddSlash(e) {
  // cross-browser compatibility
  if (!e) var e = window.event;
  var srcElement = (e.target) ? e.target : e.srcElement;
  var keyCode = (e.which) ? e.which : e.keyCode;

  if (!(((keyCode >= 48) && (keyCode <= 57)) ||    // number
		(keyCode == 9) || (keyCode == 8) || 	  	 // backspace, tab
		(srcElement.value.length >= 10))) {
    StopPropagation(e);
    return;
  }

  if ((srcElement.value.length == 2) || (srcElement.value.length == 5)) {
    srcElement.value = srcElement.value + "/";
  }
}

function DateFormat(e) {
  // cross-browser compatibility
  if (!e) var e = window.event;
  var srcElement = (e.target) ? e.target : e.srcElement;
  var keyCode = (e.which) ? e.which : e.keyCode;

  srcElement.value = ValidateDate(srcElement.value);
}

function ValidateDate(strDate) {
  var strDateArray;
  var strDay;
  var strMonth;
  var strYear;
  var intDay;
  var intMonth;
  var intYear;

  if (strDate.length < 1)
    return "";

  strDateArray = strDate.split("/");

  if (strDateArray.length != 3) {
    return "";
  }
  else {
    strDay = strDateArray[0];
    strMonth = strDateArray[1];
    strYear = strDateArray[2];
  }

  if (strYear.length == 1)
    strYear = "200" + strYear;

  if (strYear.length == 2) {
    if (strYear > "80")
      strYear = "19" + strYear;
    else
      strYear = "20" + strYear;
  }

  if (strYear.length == 3)
    strYear = "1" + strYear;

  intDay = parseInt(strDay, 10);
  if (isNaN(intDay))
    return "";

  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth))
    return "";

  intYear = parseInt(strYear, 10);
  if (isNaN(intYear))
    return "";

  if ((intYear < 1800) || (intYear > 2200))
    return "";

  if (intMonth > 12 || intMonth < 1)
    return "";

  if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1))
    return "";

  if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1))
    return "";

  if (intMonth == 2) {
    if (intDay < 1)
      return "";

    if (LeapYear(intYear) == true) {
      if (intDay > 29)
        return "";
    }
    else {
      if (intDay > 28)
        return "";
    }
  }

  if (strDay.length == 1) strDay = "0" + strDay;
  if (strMonth.length == 1) strMonth = "0" + strMonth;

  return strDay + "/" + strMonth + "/" + strYear;
}

function LeapYear(intYear) {
  if (intYear % 100 == 0) {
    if (intYear % 400 == 0)
      return true;
  }
  else {
    if ((intYear % 4) == 0)
      return true;
  }

  return false;
}

function FormatNumber(controlName, nrDecimals) {
  dPU = parseFloat(document.getElementById(controlName).value.replace(",", "."));

  if (!isNaN(dPU))
    document.getElementById(controlName).value = DoubleToStringDec(dPU, nrDecimals);
}

function blockNonNumbers(e, allowDecimal, allowNegative) {
  var key;
  var isCtrl = false;
  var keychar;
  var reg;

  if (window.event) {
    key = e.keyCode;
    isCtrl = window.event.ctrlKey
  }
  else if (e.which) {
    key = e.which;
    isCtrl = e.ctrlKey;
  }

  if (isNaN(key)) return true;

  keychar = String.fromCharCode(key);

  // check for backspace or delete, or if Ctrl was pressed
  if (key == 8 || isCtrl) {
    return true;
  }

  reg = /\d/;
  var obj = (e.target) ? e.target : e.srcElement;

  var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 && obj.value.length == 0 : false;
  var isFirstD = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;

  if (keychar == '.' && obj.value.indexOf(',') == -1) {
    isFirstD = false;
    obj.value = obj.value + ',';
  }

  return isFirstN || isFirstD || reg.test(keychar);
}
