/*=======================================================================
 *
 * checkFormTags.js
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

function trim(TRIM_VALUE){
  if (TRIM_VALUE.length < 1) { return ""; }
  TRIM_VALUE = rtrim(TRIM_VALUE);
  TRIM_VALUE = ltrim(TRIM_VALUE);
  if (TRIM_VALUE==""){ return ""; } else { return TRIM_VALUE; }
}

function rtrim(VALUE){
  var w_space = String.fromCharCode(32);
  var v_length = VALUE.length;
  var strTemp = "";
  if (v_length < 0){ return""; };
  var iTemp = v_length -1;
  while (iTemp > -1){
     if(VALUE.charAt(iTemp) == w_space){
     } else {
       strTemp = VALUE.substring(0,iTemp +1);
       break;
     }
     iTemp = iTemp-1;
  }
  return strTemp;
}

function ltrim(VALUE){
  var w_space = String.fromCharCode(32);
  if (v_length < 1){ return ""; };
  var v_length = VALUE.length;
  var strTemp = "";
  var iTemp = 0;
  while (iTemp < v_length){
    if (VALUE.charAt(iTemp) == w_space){
    } else {
      strTemp = VALUE.substring(iTemp,v_length);
      break;
    }
    iTemp = iTemp + 1;
  }
  return strTemp;
}

function padl(str,len,fillChar) {
  if (fillChar == '') {fillChar = '0';};
  var strLength = str.length;
	if (strLength < len) {
		 for (var i = strLength; i < len; i++) {
         str = fillChar + str;
		 }
  }
	return str;
}

// Checks syntax of the content a single mail-field.
function checkMailAddress(field, msg, checkSingleAdress = '', singleAdressMsg = '') {

  var mailField = field.value;
  var mailAdresses = mailField.split(",");
  var numOfMailAdresses = mailAdresses.length;
  var checkAddress;

  // Check for single address
  if (checkSingleAdress != '' && singleAdressMsg != '') {
     for (var j = 0 ; j < numOfMailAdresses ; j++) {
     	   if (!(mailAdresses[j + 1] === undefined) && mailAdresses[j + 1] != '') {
  	        alert(singleAdressMsg);
  	        return false;
         }
     }
  }

  // Check format of the addresses
  for (var j = 0 ; j < numOfMailAdresses ; j++) {
      checkAddress = trim(mailAdresses[j]);
      // if (checkAddress.match(/^[A-Za-z\'0-9]+([._-][A-Za-z\'0-9]+)*@([A-Za-z0-9]([-][A-Za-z0-9]+)*)+([.][A-Za-z0-9]+([-][A-Za-z0-9]+)*)+$/)==null) {  
      // if (checkAddress.match(/^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/)==null) {
      if (checkAddress.match(/^([a-zA-Z0-9_\-+])+(\.([a-zA-Z0-9_\-+])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/)==null) {
         alert(msg);
         return false;
      }
  }
  return true;
}

// Checks content of a field being a number.
function checkIsNaN(fieldValue, msg) {

  if(isNaN(fieldValue) == true) {
    alert(msg);
    return false;
  } else {
    return true;
  }
}

// Checks content of a field being a number.
// Blanks will be removed out of the string.
function checkIsNaNIgnoreSpace(fieldValue, msg) {
    
  // Remove spaces in fieldValue
  var fieldValueWithoutBlanks = '';
  fieldValueLen = fieldValue.length;
  for (var j = 0 ; j <= fieldValueLen-1 ; j++) {
      if (fieldValue.charAt(j) != ' ') {
         fieldValueWithoutBlanks += fieldValue.charAt(j);
      }				
  }  

  if(isNaN(fieldValueWithoutBlanks) == true) {
    alert(msg);
    return false;
  } else {
    return true;
  }
}

// Checks content of a field being a number.
function checkIsNumeric(checkObj, msg) {
	var objVal = checkObj.value;
	objVal = objVal.replace(/,/, ".");
  if(isNaN(objVal)) {
    alert(msg);
    checkObj.value = '';
    setTimeout(() => {
      checkObj.focus();
    }, 0);    
    return false;
  }
  return true;
}

// Checks the range of a numberfield
function checkNumRanges(checkObj,lowerRange,upperRange,msg) {
  if (!checkIsNaN(checkObj.value, msg)) {
     checkObj.value = lowerRange;
     checkObj.focus();
  }
  if (checkObj.value > upperRange) {
     checkObj.value = upperRange;     
     alert("Die Obergrenze liegt bei " + upperRange + " Tagen!");
     checkObj.focus();
  }
  if (checkObj.value < lowerRange) {
     checkObj.value = lowerRange;     
     alert("Die Untergrenze liegt bei " + lowerRange + " Tagen!");
     checkObj.focus();
  }  
};

// Gets the selected value for a special select box
function getSelectedValue(nameOfElem) {
	var retVal = '';
  elem = eval('document.forms[0].' + nameOfElem);
  if (elem) {
     var len = elem.length;
     for(var i=0; i<len; ++i) {
       	if (elem.options[i].selected == true) {
       		  retVal = elem.options[i].value;
       	}
     }
  } else {
  	alert('Der Wert für ' + nameOfElem + ' wurde nicht gesetzt!');
  }
  return retVal;
}

// Sets a special value for a special select box
function setSelectedValue(nameOfElem, val) {
  elem = eval('document.forms[0].' + nameOfElem);
  if (elem) {
     var len = elem.length;
     for(var i=0; i<len; ++i) {
        if (elem.options[i].value == val) {
           elem.options[i].selected = true;
        }
     }
  } else {
  	alert('Der Wert für ' + nameOfElem + ' wurde nicht gesetzt!');
  }
}

// Checks for existence of a value of an "option" of a "select" object
function existSelectOptionValue (nameOfElem, optVal) {
	elem = eval('document.forms[0].' + nameOfElem);
  optExists = false;
  var len = elem.length;
    for(i=0; i<len; ++i) {
    if (elem.options[i].value == optVal) {
       optExists = true;
    }
  }
  return optExists;
}

// Inserts a new "option" into an existing "select" object
function insertNewOption (nameOfElem, optVal, optText, optSel, checkExistence) {
  elem = eval('document.forms[0].' + nameOfElem);
  var len = elem.length;
  // First check for existence
  if (elem) {
  	 if (checkExistence == '') {checkExistence = false};
  	 optExists = false;
  	 if (checkExistence) {optExists = existSelectOptionValue(nameOfElem, optVal);};
     if (!optExists) {
        if (optSel == '') {optSel = false};
        if (elem && optVal != '' && optText != '') {
           newOption = new Option(optText, optVal, false, optSel);
           elem.options[len] = newOption;
        } else {
        	alert('Einer der Parameter ist nicht vollständig!');
        }
     // } else {
     //   alert('Eine Option mit dem Wert ' + optVal + ' existiert schon!');
     }
  } else {
  	alert('Der Wert für ' + nameOfElem + ' wurde nicht gesetzt!');
  }
}

// Removes an option from an existing "select" object
function removeExistingOption (nameOfElem, optVal) {
  elem = eval('document.forms[0].' + nameOfElem);
  elem.options[optVal] = null;
}


function checkDateFields(checkObj,mode) {
  var now = new Date();
  var currentYear = now.getFullYear();
  // var monthNum = now.getMonth();
  // var dayNum = now.getDay();
  // var monthNames = new Array("Januar","Februar","M&auml;rz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember");
  // monthNames[monthNum]
  // var dayNames = new Array("Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag");
  // dayNames[monthNum]	  
  
  var resetObjectValue = false;
  var checkObjValue = checkObj.value;
  var checkObjName = checkObj.name;
  
  if (checkObjValue != '') {
     if (isNaN(checkObjValue) == true) {
        alert('Bitte ein Zahl eingeben!');
        resetObjectValue = true;
     }
     if (mode == 'day') {
        if (checkObjValue < 1 || checkObjValue > 31) {
           alert('Tagesangaben bitte zwischen 1 und 31');
           resetObjectValue = true;
        }
     }
     if (mode == 'month') {
        if (checkObjValue < 1 || checkObjValue > 12) {
           alert('Monatsangaben bitte zwischen 1 und 12');
           resetObjectValue = true;
        }
     }
     if (mode == 'year') {
        if (checkObjValue < (currentYear-1) || checkObjValue > (currentYear+1)) {
           alert('Jahresangaben zwischen ' + (currentYear-1) + ' und ' + (currentYear+1));
           resetObjectValue = true;
        }
     }
     if (mode == 'hour') {
        if (checkObjValue < 0 || checkObjValue > 23) {
           alert('Stundenangaben bitte zwischen 0 und 23');
           resetObjectValue = true;
        }
     }
     if (mode == 'minute') {
        if (checkObjValue < 0 || checkObjValue > 59) {
           alert('Stundenangaben bitte zwischen 0 und 59');
           resetObjectValue = true;
        }
     }
  }
  return resetObjectValue;
};

function checkTimeFields(mf) {
	var frm = document.forms[0];
	var f_Y = padl(frm.f_year.value,2,'0');   f_Y_to = padl(frm.f_year_to.value,2,'0');
	var f_m = padl(frm.f_month.value,2,'0');  f_m_to = padl(frm.f_month_to.value,2,'0');
	var f_d = padl(frm.f_day.value,2,'0');    f_d_to = padl(frm.f_day_to.value,2,'0');
	var f_H = padl(frm.f_hour.value,2,'0');   f_H_to = padl(frm.f_hour_to.value,2,'0');
	var f_i = padl(frm.f_minute.value,2,'0'); f_i_to = padl(frm.f_minute_to.value,2,'0');

  // Behaviour on the same day
	if (f_Y == f_Y_to && f_m == f_m_to && f_d == f_d_to) {
		 if (mf == 'H_to') {
		 	  if (f_H_to < f_H) {
		 	     if (f_i_to >= f_i) {
		 	       setSelectedValue('f_hour', parseInt(f_H_to));
		 	     } else {
             setSelectedValue('f_hour', (parseInt(f_H_to) - 1));
		 	     }
		 	  }
		 	  if (f_H_to == f_H) {
		 	     if (f_i_to < f_i) {
             setSelectedValue('f_minute_to', parseInt(f_i));
		 	     }
		 	  }
		 };
		 if (mf == 'H') {
		 	  if (f_H_to < f_H) {
		 	     if (f_i >= f_i_to) {
		 	       setSelectedValue('f_hour_to', parseInt(f_H));
		 	     } else {
             setSelectedValue('f_hour_to', (parseInt(f_H) + 1));
		 	     }
		 	  }
		 	  if (f_H_to == f_H) {
		 	     if (f_i > f_i_to) {
             setSelectedValue('f_minute_to', parseInt(f_i));
		 	     }
		 	  }
		 };
		 if (mf == 'i') {
		 	  if (f_H_to == f_H) {
		 	     if (f_i > f_i_to) {
             setSelectedValue('f_minute_to', parseInt(f_i));
		 	     }
		 	  }
		 };
		 if (mf == 'i_to') {
		 	  if (f_H_to == f_H) {
		 	     if (f_i > f_i_to) {
             setSelectedValue('f_minute', parseInt(f_i_to));
		 	     }
		 	  }
		 };
  }
}

// Shows/Hides display areas [Classic version]
function changeHideShow(areaSwitched,displayState) {
	var areaShow = areaSwitched;
	var areaShowAction = areaSwitched + 'Action';
  var areaReducedAction = areaSwitched + 'ReducedAction';

  if (displayState == 'on') {
  	 myshow(areaShow);
  	 myshow(areaShowAction);
  	 myhide(areaReducedAction);
     elem = eval('document.forms[0].' + areaShow + 'Switch');
     elem.value = '1';
  };
  if (displayState == 'off') {
     myhide(areaShow);
     myhide(areaShowAction);
     myshow(areaReducedAction);
     elem = eval('document.forms[0].' + areaShow + 'Switch');
     elem.value = '0';
  };
}

// Shows/Hides display areas
function changeHideShow2(areaSwitched,displayState) {
  if (displayState == 'on') {
  	 myshow(areaSwitched);
     elem = eval('document.forms[0].' + areaSwitched + 'Switch');
     elem.value = '1';
  };
  if (displayState == 'off') {
     myhide(areaSwitched);
     elem = eval('document.forms[0].' + areaSwitched + 'Switch');
     elem.value = '0';
  };
}

// Checks equality of two arrays
function arraysEqual(a,b) {
	var retVal = true;
	var aLen = a.length;
	var bLen = b.length;
	if (aLen == bLen) {
	   for(i=0;i<aLen;++i) {
		    if (a[i] != b[i]) {
		    	 retVal = false;
		    }
	   };
	} else {
		retVal = false;
  }
  return retVal;
}