/*
* Input validation routines.
* Author: Claudio Carniato.
* Based on script found at The JavaScript Source!! http://javascript.internet.com
* Original by Torsten Frey (tf@tfrey.de) http://www.tfrey.de
*/


/*
* Check if all characters of "numString" are numbers.
*/
function onlyNumbers(numString) {
  for (var i = 0; i < numString.length; i++) {
    // Check that current character is number.
    var c = numString.charAt(i);
    if ((c < "0") || (c > "9"))
      return(false);
  }
  // All characters are numbers.
  return(true);
}

/*
* Returns the passed string without trailing and ending spaces.
*/
function trimSpaces(string) {
  var cnt;
  var s = string;
  var i;

  // Find the position of the first non blank character.
  cnt = -1;
  for (i=0; i < s.length; i++) {
    if (s.charAt(i) != ' ') {
      cnt = i;
      break;
    }
  }
  // If cnt = -1 the string is entirely composed of blanks.
  if (cnt == -1) {
    s = "";
    return(s);
  } else {
    if (cnt > 0) {
      s = s.substr(cnt);
    }
  }
  // Find the position of the last non blank character.
  cnt = s.length;
  for (i = s.length-1; i >= 0; i--) {
    if (s.charAt(i) != ' ') {
      cnt = i;
      break;
    }
  }
  if (cnt < s.length-1){
    s = s.substr(0, cnt+1);
  }

  return(s);
}

/*
* Checks if the string "dateString" represents a valid date.
* Parameters:
*   dateString: the string to be checked;
*   field: the field containing the date to check. If not null the function writes
*          back on it the formatted date.
* Returns:
*   0: if the string is a valid date;
*   1: if the string is empty or contains only whitespace characters;
*   >= 2: if the strings is not a valid data.
*/
function isValidDate(dateString, field) {
  var checkstr = "0123456789";
  var dateField = field;
  var dateValue = "";
  var sepChar = "/";
  var day = "";
  var month = "";
  var year = "";
  var leap = 0;
  var i;
  var pos1 = -1;
  var pos2 = -1;
  var zeroPad = "00";
  var yearPad = "2000";
  var today = new Date();

  dateValue = trimSpaces(dateString);
  if (dateValue.length == 0){
    return(1);
  }

  // Search the position of the first two non numbers chars.
  for (i = 0; i < dateValue.length; i++) {
    if (checkstr.indexOf(dateValue.substr(i,1)) == -1) {
      if (pos1 == -1) {
        pos1 = i
      } else {
        pos2 = i;
        break;
      }
    }
  }

  // Extract day, month and year from date.
  if (pos1 != -1) {
    day = dateValue.substr(0, pos1);
  }
  if ((pos1 != -1) && (pos2 != -1)) {
    month = dateValue.substr(pos1+1, pos2-pos1-1);
    year = dateValue.substr(pos2+1);
  } else {
    if ((pos1 != -1) && (pos2 == -1)) {
      month = dateValue.substr(pos1+1, 2);
    }
  }
  if ((pos1 == -1) && (pos2 == -1)) {
    switch (dateValue.length) {
      case 1:
        day = dateValue;
        break;
      case 2:
        day = dateValue;
        break;
      case 6:
        // Change date to 8 digits string. If year is entered as 2-digit, always assume 20xx.
        dateValue = dateValue.substr(0,4) + '20' + dateValue.substr(4,2);
      case 8:
        day = dateValue.substr(0,2);
        month = dateValue.substr(2,2);
        year = dateValue.substr(4,4);
        break;
      default:
        return(19);
    }
  }

  // If void, set month to the current month.
  if (month == "") {
    month = (today.getMonth() + 1).toString();
  }
  // If void, set year to the current year.
  if (year == "") {
    year = today.getFullYear();
  }

  // Pad day, month and year to their minimum length.
  if (day.length < 2) {
    day = zeroPad.substr(0, 2-day.length) + day;
  }
  if (month.length < 2) {
    month = zeroPad.substr(0, 2-month.length) + month;
  }
  if (year.length < 4) {
    year = yearPad.substr(0, 4-year.length) + year;
  }

  // Check if day, month and year are numbers.
  if (!onlyNumbers(day) || !onlyNumbers(month) || !onlyNumbers(year)) {
    return(20);
  }

  // Validation of month.
  if ((month < 1) || (month > 12)) {
     return(21);
  }
  // Validation of day.
  if (day < 1) {
    return(22);
  }
  // Validation leap-year - february - day.
  if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
     leap = 1;
  }
  if ((month == 2) && (leap == 1) && (day > 29)) {
     return(23);
  }
  if ((month == 2) && (leap != 1) && (day > 28)) {
     return(24);
  }
  // Validation of other months.
  if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
     return(25);
  }
  if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
     return(26);
  }

  // If no error, write the completed date to input-field.
  if (dateField != null) {
    dateField.value = day + sepChar + month + sepChar + year;
  }
  return(0);
}

/*
* Test if the value of the field passed as parameter is a valid date.
* Parameters:
*   field: the field to check;
*   allowEmpty: if true an empty value of the field is considered valid,
*               otherwise it's treated like an invalid date.
* If the value is not valid shows a message and puts focus on field.
* Return true if the value is ok, false otherwise.
*/
function check_date(field, allowEmpty) {
  var dateField = field;
  var date = dateField.value;
  var notOk = false;

  var err = isValidDate(date, dateField);
  if (allowEmpty) {
    notOk = err > 1;
  } else {
    notOk = err > 0;
  }

  if (notOk) {
    alert("La data inserita non e' corretta.");
    dateField.select();
    dateField.focus();
  }
  return(!notOk);
}

/*
* Checks if the string "numString" contains only numeric characters.
* Parameters:
*   numString: the string to be checked.
* Returns:
*   0: if the string contains only numeric characters;
*   1: if the string is empty or contains only whitespace characters;
*   2: if the strings is not a valid number (doesn't contains only numeric characters).
*/
function isValidInteger(numString) {
  var numberValue = trimSpaces(numString);
  if (numberValue.length == 0){
    return(1);
  }
  return(onlyNumbers(numberValue)? 0 : 2);
}

/*
* Test if the value of the field passed as parameter is a valid number.
* Parameters:
*   field: the field to check;
*   allowEmpty: if true an empty value of the field is considered valid,
*               otherwise it's treated like an invalid number.
* If the value is not valid shows a message and puts focus on field.
* Return true if the value is ok, false otherwise.
*/
function check_number(field, allowEmpty) {
  var numberField = field;
  var num = numberField.value;
  var notOk = false;
  
  var err = isValidInteger(num);
  if (allowEmpty) {
    notOk = err > 1;
  } else {
    notOk = err > 0;
  }
  
  if (notOk) {
    alert("Il valore inserito non e' corretto.");
    numberField.select();
    numberField.focus();
  }
  return(!notOk);
}

function check_form(form, allowEmpty) {
  var ok = true;
  
  for (var i = 0; i < form.length; i++) {
    var e = form.elements[i];
    var type = e.name.substr(e.name.length-2, 2);
    switch (type) {
      case '_d':
        ok = check_date(e, allowEmpty);
        if (!ok) {
          return(false);
        }
        break;
      case '_n':
        ok = check_number(e, allowEmpty);
        if (!ok) {
          return(false);
        }
        break;
    }
  }
  return(true);
}

function check_form_and_submit(formName, allowEmpty) {
  var form = document.getElementById(formName);
  if (check_form(form, allowEmpty)) {
    form.submit();
  }
}

// Inverte la selezione di tutte le checkboxes.
function invertAllCheckBoxes(fName, cName) {
  var f = document.forms[fName];
  for (c = 0; c<f.elements.length; c++) {
  	if (f.elements[c].name && f.elements[c].name==cName) {
  	  f.elements[c].checked = !f.elements[c].checked;
		}
  }
} // invertAllCheckBoxes()

function switchEdit(cbList, doubleEditFlag, divName, inputTemplate) {
	var ind = cbList.options[cbList.selectedIndex].value;
	if (doubleEditFlag[ind] == 1) {
		document.getElementById(divName).innerHTML = inputTemplate;
	} else {
		document.getElementById(divName).innerHTML = '';
	}
}

function applySorting(sorting) {
	if (sorting!="") {
		document.forms["frmPageBar"]["sorting"].value = sorting;
		document.forms["frmPageBar"]["pageNo"].value = 1;
		document.forms["frmPageBar"].submit();
	}
}

var LAYOUT = "default";
var query = window.location.search.substring(1);
var parameters = query.split('&');
for (var i = 0; i<parameters.length; i++) {
	var pos = parameters[i].indexOf('=');
	if (pos>0) {
		var key = parameters[i].substring(0, pos);
		if (key=="layout") {
			LAYOUT = parameters[i].substring(pos+1);
		}
	}
}


function doPost(formName, action, form2Name, checkBoxesName) {
	ids = "";
	for (i = 0; i<document.forms[form2Name].length; i++) {
		if (document.forms[form2Name][i].name && document.forms[form2Name][i].name==checkBoxesName && document.forms[form2Name][i].checked) {
			if (ids == "") {
				ids = document.forms[form2Name][i].value;
			} else {
				ids += ","+document.forms[form2Name][i].value;
			}
		}
	}
	document.forms[formName].action = action;
	document.forms[formName]["ids"].value = ids;
	document.forms[formName].submit();
} // doPost()

// Ordina una select.
function sortSelect(formName, selectName) {
	var s = document.forms[formName][selectName];
	for (i = 0; i < s.length; i++) {
		for (j = i+1; j < s.length; j++) {
			if (s.options[j].text < s.options[i].text) {
				tempText = s.options[i].text;
				tempValue = s.options[i].value;
				s.options[i].text = s.options[j].text;
				s.options[i].value = s.options[j].value;
				s.options[j].text = tempText;
				s.options[j].value = tempValue;
			}
		}
	}
} // sortSelect()

// Muove un'opzione da una select ad un'altra.
function moveOptions(formName, selectFromName, selectToName) {
	var from = document.forms[formName][selectFromName];
	var to = document.forms[formName][selectToName];
	if (from.selectedIndex != -1) {
		i = 0;
		while (i < from.length) {
			if (from.options[i].selected) {
				newOption = new Option(from.options[i].text, from.options[i].value);
				to.options[to.length] = newOption;
				from.options[i] = null;
			}
			else {
				i++;
			}
		}
		sortSelect(formName, selectToName);
	}
} // moveOptions()

// Seleziona/deseleziona tutte le opzioni di una select.
function forAllItems(formName, selectName, value) {
	for (j = 0; j < document.forms[formName][selectName].length; j++) {
    		document.forms[formName][selectName].options[j].selected = value;
	}
} // forAllItems()

// Seleziona/deseleziona tutte le voci di tutte le select.
function forAllSelects(formName, selectNames, value) {
	for (i = 0; i < selectNames.length; i++) {
		forAllItems(formName, selectNames[i], value);
	}
} // forAllSelects()

function selectTabs(a, b, f)
{
	for (i in subFormTabs) {
		if (i == a) {
			document.getElementById("subFormErrorImage_" + i).src = "./layouts/"+LAYOUT+"/images/error.gif";
			document.getElementById("subFormCaption_" + i).className = subFormTabs[i] + "AndSelected";
			document.getElementById("subFormLink_" + i).href = "javascript:void(0)"; 
			document.getElementById("subFormLink_" + i).className = "orangeback"; 
		} else {
			document.getElementById("subFormErrorImage_" + i).src = "./layouts/"+LAYOUT+"/images/error.gif";
			document.getElementById("subFormCaption_" + i).className = subFormTabs[i] + "AndUnSelected";
			document.getElementById("subFormLink_" + i).href = "javascript:void selectTabs('" + i + "', '" + b + "', '" + f + "')"; 
			document.getElementById("subFormLink_" + i).className = "greyback"; 
		}
		document.getElementById("subFormLink_" + i).href = "javascript:void selectTabs('" + i + "', '" + b + "', '" + f + "')"; 
	}
	for (j in sectionTabs[a]) {
		if (j == b) {
			document.getElementById("sectionErrorImage_" + j).src = "./layouts/"+LAYOUT+"/images/error.gif";
			document.getElementById("sectionCaption_" + j).className = sectionTabs[a][j] + "AndSelected";
			document.getElementById("sectionLink_" + j).href = "javascript:void(0)"; 
			document.getElementById("sectionLink_" + j).className = "orangeback"; 
		} else {
			document.getElementById("sectionErrorImage_" + j).src = "./layouts/"+LAYOUT+"/images/error.gif";
			document.getElementById("sectionCaption_" + j).className = sectionTabs[a][j] + "AndUnSelected";
			document.getElementById("sectionLink_" + j).href = "javascript:void selectTabs('" + a + "', '" + j + "', '" + f + "')"; 
			document.getElementById("sectionLink_" + j).className = "greyback"; 
		}
		document.getElementById("sectionLink_" + j).href = "javascript:void selectTabs('" + a + "', '" + j + "', '" + f + "')"; 
	}
	document.getElementById("contents" + curSelA + "_" + curSelB).style.visibility = "hidden";
	document.getElementById("contents" + a + "_" + b).style.visibility = "visible";
	curSelA = a;
	curSelB = b;
	document.forms[f]["subFormToGo"].value = a;
	document.forms[f]["sectionToGo"].value = b;
} // selectTabs()

// Definizione di variabili varie
var selectsToSelect	= new Array();
var subFormTabs		= new Array();
var sectionTabs		= new Array();
