if (typeof COMP == "undefined") {
    var COMP = {};
}

COMP.openWin = function (page){
  document.location.href=page;
}

COMP.js = function JS(str){
  return encodeHtml(unquote(str));
}

COMP.encodeHtml = function (str) {
  str = str.replace(/\"/g, "&quot;"); // Non rispetta gli spazi tra le parole ma permette il wordwrap nelle colonne
  str = str.replace(/</g, "&lt;");
  return str.replace(/>/g, "&gt;");
}

COMP.unquote = function (str) {
  var res = str.replace(/\\/g, "\\\\");
  res = res.replace(/\'/g, "\\\'");
  return res;
}

COMP.controllaLunghezza = function (obj, len, label) {
	var s = obj.value;
	var righe = s.split('\r\n');
	for(i=0; i < righe.length; i++) {
		if (righe[i].length != 0 && righe[i].length != len) {
			alert( "Il valore '" + righe[i] + "'" + (righe.length > 1 ? " (riga " + (i+1) + ") " : " ") + (label == undefined ? " " : " del campo '" + label + "' ") + "ha una lunghezza non valida: " + righe[i].length + " caratteri invece di " + len + " caratteri");
			obj.focus();
			break;
		}
	}
}

COMP.checkKeyPress = function (ev, controllo) {
	var whichASC = ev.keyCode || ev.charCode || 0;
	var whichKey = String.fromCharCode(whichASC);
	var res = false;
	if (controllo=="lett") {
		if (((whichKey>="a") && (whichKey<="z")) || ((whichKey>="A") && (whichKey<="Z")) || (whichKey=="\u0008") || (whichKey=="\u000D")) {
			res = true;
		}
	} else if (controllo=="num") {
		if (((whichKey>="0") && (whichKey<="9")) || (whichKey=="\u0008") || (whichKey=="\u000D")) {
			res = true;
		}
	} else if (controllo=="decimal") {
		if (((whichKey>="0") && (whichKey<="9")) || (whichKey=="\u0008") || (whichKey=="\u000D") || (whichKey==".")) {
			res = true;
		}
	} else if (controllo=="alfnum") {
		if (((whichKey>="a") && (whichKey<="z")) || ((whichKey>="A") && (whichKey<="Z")) || ((whichKey>="0") && (whichKey<="9")) || (whichKey=="\u0008") || (whichKey=="\u000D")) {
			res = true;
		}
	} else if (controllo=="date") {
		if (((whichKey>="0") && (whichKey<="9")) || (whichKey=="/") || (whichKey==" ") || (whichKey==":") || (whichKey=="\u0008") || (whichKey=="\u000D")) {
			res = true;
		}
	}
	if (!res) {
    COMP.preventDeault(ev);
  }
}

COMP.preventDeault = function (ev){
  if (ev.preventDefault) {
    ev.preventDefault();
  } else {
    ev.returnValue = false;
  }
}

COMP.disableEvent = function () {
  event.returnValue = false
}

//controlla i numeri decimali
COMP.checkKeyPressDecimal = function (ev, separator) {
	var whichASC = ev.keyCode || ev.charCode || 0;
	var whichKey = String.fromCharCode(whichASC);
	var res = false;
	if (((whichKey>="0") && (whichKey<="9")) || (whichKey=="\u0008") || (whichKey=="\u000D") || (whichKey==separator)) {
		res = true;
	}
	if (!res) {
    COMP.preventDeault(ev);
  }
}
//Controllo per vedere se è stato premuto il tasto ESC
COMP.keyhandler = function (e) {
  if (document.layers)
    Key = e.which;
  else
    Key = window.event.keyCode;
  if (Key == 27){
    return false;
  }
  return true;
}

//controlla il numero di caratteri premuti
COMP.textContatore = function (campo, limitemassimo) {
  if (campo.value.length > limitemassimo)
    campo.value = campo.value.substring(0, limitemassimo);
}

//controlla se è stata inserita la data correttamente
COMP.validateData = function (campo, focus) {
  if (arguments.length < 2) {
    campo = event.srcElement;
    focus = true;
  }
  if (campo.value=="") {
    return true;
  }
  /*prende in input la data inserita e un booleano che indica se
  la data è obbligatoria o meno*/
  var d = campo.value;
  var gg;
  var mm;
  var anno;
  var data;

  if (d.indexOf('-') >= 0) {
	data = d.split('-');
  	gg = data[0] * 1;
  	mm = data[1] - 1;
  	anno = data[2] * 1;
  } else if (d.indexOf('/') >= 0) {
	data = d.split('/');
  	gg = data[0] * 1;
  	mm = data[1] - 1;
  	anno = data[2] * 1;
  } else if (d.length == 8) {
  	gg = d.substr(0,2) * 1;
  	mm = d.substr(2,2) - 1;
  	anno = d.substr(4) * 1;
  } else {
    alert("ATTENZIONE!\n Data non valida.\n Esempio 01/01/1970");
    if (focus)
    	campo.focus();
    return false;
  }
  /*Accetta solo stringhe di 10 caratteri gg/mm/aaaa*/
  if (d.length > 10 || anno < 1800) {
    alert("ATTENZIONE!\n Data non valida.\n Esempio 01/01/1970");
    if (focus)
    	campo.focus();
    return false;
  }
  var oDate = new Date(anno, mm, gg)
  if (oDate.getFullYear() != anno || oDate.getMonth() != mm || oDate.getDate() != gg) {
    alert("ATTENZIONE!\n Data non valida.\n Esempio 01/01/1970");
    if (focus)
		campo.focus();
    return false;
  }
  gg = (gg < 10) ? ("0" + gg) : gg;
  mm++;
  mm = (mm < 10) ? ("0" + mm) : mm;
  campo.value = gg + "/" + mm + "/" + anno;
  return true;
}

COMP.validateDecimal = function (val,sep,block){
  if (!val.style.originalColor) {
    val.style.originalColor = val.style.color;
  } 
  val.style.color = val.style.originalColor;
  errore = false;
  with(val.value){
    for(i=0;i<length;i++){
      chr = val.value.charAt(i)
      if (!(((chr>="0") && (chr<="9")) || (chr==sep))) {
        errore = true;
      }
    }
    var num = substring(indexOf(sep)+1,length)
    if(num.indexOf(sep)>0){
      errore = true;
    } else if(num.length==0) {
      val.value = substring(0,length-1)
    } else if(num.length+1==length) {
      val.value = '0' + val.value
    }
    if(errore) {
      val.style.color='red';
      if(block) {
        alert("ATTENZIONE!\n Numero non valido!");
        val.focus()
        return false;
      }
    }
  }
}

COMP.objNull = function (allObj) {
  var rit = true;
  if ( allObj.length > 0 ) {
    for ( i=0;i<allObj.length;i++ ) {
      with(allObj.elements[i]){
        if (tagName!="FIELDSET" && (type=="password" || type=="text" || type=="textarea"|| type=="select-one")){
          if ((value == ''&& allObj.elements[i].isnull == "false") ) {
            style.oldBackgroundColor = style.backgroundColor;
            style.backgroundColor ="#FF9595";
            rit = false;
          } else {
            style.backgroundColor = style.oldBackgroundColor;
          }
        }
      }
    }
  }
  if(!rit)
    alert("Valorizzare i campi in rosso !")
  return rit;
}

COMP.debug = function (s) {
  var debugTextArea;
  var debugWin = window.open("", "debugWin", "toolbar=no,menubar=no,resizable=yes,scrollbars=yes,width=600,height=400");
  if (!debugWin.document.getElementById("debugTextArea"))
    debugWin.document.write("<html><body><textarea id=\"debugTextArea\" cols=\"60\" rows=\"30\"></textarea></body></html>");
  debugTextArea = debugWin.document.getElementById("debugTextArea");
  debugTextArea.innerText += "\n" + s;
}

COMP.validateDatetime = function (obj, focus){
  //return true;
  if (event) {
    obj = event.srcElement;
  }
  if (arguments.length < 2) {
    focus = true;
  }
  if (obj.value=="") {
    obj.hh = 0;
    obj.mi = 0;
    obj.ss = 0;
    obj.oDate = new Date().valueOf();
    return true;
  }
  
  var re = simpleDateFormatToRegExp(obj.pattern);
  
  var exampleDate = new Date();
  var exampleStr = obj.pattern.replace(/d+/, exampleDate.getDate()).replace(/M+/, exampleDate.getMonth() + 1).replace(/y+/, exampleDate.getFullYear()).replace(/H+/, exampleDate.getHours()).replace(/m+/, exampleDate.getMinutes()).replace(/s+/, exampleDate.getSeconds());
  var dateArray = re.regExp.exec(obj.value);
  if (dateArray == null) {
    if (focus) {
      alert("ATTENZIONE!\n Data-ora non valida.\n Esempio " + exampleStr);
      obj.select();
      obj.focus();
    }
    return false
  }
  var dd = dateArray[re.patternArray['d']] * 1;
  var mm = dateArray[re.patternArray['M']] * 1;
  var yyyy = dateArray[re.patternArray['y']] * 1;
  var hh = dateArray[re.patternArray['H']] * 1;
  var mi = dateArray[re.patternArray['m']] * 1;
  var ss = dateArray[re.patternArray['s']] * 1;
  dd = dd ? dd : 0;
  mm = mm ? mm : 0;
  yyyy = yyyy ? yyyy : 0;
  hh = hh ? hh : 0;
  mi = mi ? mi : 0;
  ss = ss ? ss : 0;
  
  var oDate = new Date(yyyy, mm - 1, dd, hh, mi, ss);
  
  if(oDate.getDate()!=dd||
    oDate.getMonth()!=mm - 1||
    oDate.getFullYear()!=yyyy||
    oDate.getHours()!=hh||
    oDate.getMinutes()!=mi||
    oDate.getSeconds()!=ss) {
    if (focus) {
      alert("ATTENZIONE!\n Data-ora non valida.\n Esempio " + exampleStr);
      obj.select();
      obj.focus();
    }
    return false
  }
  obj.hh = hh;
  obj.mi = mi;
  obj.ss = ss;
  obj.oDate = oDate.valueOf();
	return true;
}

COMP.simpleDateFormatToRegExp = function (pattern) {
  pattern = pattern.replace(/d+/, "d").replace(/M+/, "M").replace(/y+/, "y").replace(/H+/, "H").replace(/m+/, "m").replace(/s+/, "s");
  var splitted = pattern.split(/[^dMyHms]/);
  var patternArray = [];
  for (k = 0; k < splitted.length; ++k) {
    patternArray[splitted[k]] = k + 1;
  }
  
  var escPattern = "";
  for (k = 0; k < pattern.length; ++k) {
    var c = pattern.charAt(k);
    if (c == "[" || c == "]" || c == "(" ||
    c == ")" || c == "^" || c == "." ||
    c == "*" || c == "+" || c == "|" ||
    c == "?" || c == "{" || c == "}" ||
    c == "," || c == "$" || c == "\\" ||
    c == "-") {
      c = "\\" + c;
    }
    escPattern += c;
  }
  var reDateTime = new RegExp(escPattern.replace(/d|M|y|H|m|s/g, "(\\d+)"));
  var o = [];
  o.regExp = reDateTime;
  o.patternArray = patternArray;
  return o;
}

COMP.regExpToDate = function (regExp, patternArray, dateStr) {
  var dateArray = regExp.exec(dateStr);
  if (dateArray == null) {
     return null;
  }
  var dd = dateArray[patternArray['d']] * 1;
  var mm = dateArray[patternArray['M']] * 1;
  var yyyy = dateArray[patternArray['y']] * 1;
  var hh = dateArray[patternArray['H']] * 1;
  var mi = dateArray[patternArray['m']] * 1;
  var ss = dateArray[patternArray['s']] * 1;
  dd = dd ? dd : 0;
  mm = mm ? mm : 0;
  yyyy = yyyy ? yyyy : 0;
  hh = hh ? hh : 0;
  mi = mi ? mi : 0;
  ss = ss ? ss : 0;
  return new Date(yyyy, mm - 1, dd, hh, mi, ss);
}

//esempio: <input type="text" onkeypress="checkKeyPress('0-3, 5-7, ab', this.value);">
COMP.checkKeyPressReg = function (ev, regexp, text) {
	if (typeof(regexp) == 'string')
		re = new RegExp("^[" + regexp + "]*$");
	else
		re = regexp;
	var whichASC = ev.keyCode || ev.charCode || 0;;
	text += String.fromCharCode(whichASC);
	var res = false;
	if (re.exec(text) != null)
		res = true;
	if (!res) {
    COMP.preventDeault(ev);
  }
}

// funzione utilizzata per le date
COMP.cal = function (id, format) {
  var input = $(id)[0];
  var pos = $.datepicker._findPos(input);
  pos[1] += input.offsetHeight; // add the height
  $.datepicker.dialogDatepicker (
        $(id).val(), 
        function(date) {
          $(id).val(date);
        }, 
        {dateFormat: format},
        pos
  );
}


