/**
 * Removes whitespaces at the beginning and at the end of a string
 */
function stringTrim( string ) {
  return string.replace( /^\s+/g, '').replace( /\s+$/g, '');
}



/**
 * Checks the passed form input field (Syntax).
 */
function checkField( inputField, isOnBlur ) {
  
  if ( ! inputField ) {
    return true;
  }
  
  var checkType = inputField.getAttribute("check_type");
  if ( ! checkType ) {
    return true;
  }

  var errorLabelID = inputField.getAttribute("check_errorLabelID");
  if ( ! errorLabelID ) {
    // alert("check_errorLabelID is undefined");
    return true;
  }
  errorLabel = document.getElementById(errorLabelID)
  if ( ! errorLabel ) {
    // alert("could not find errorLabel");
    return true;
  }
  
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "length" ) {
    var lengthMin = inputField.getAttribute("check_lengthMin");
    var lengthMinError = inputField.getAttribute("check_lengthMinError");
    var lengthMax = inputField.getAttribute("check_lengthMax");
    var lengthMaxError = inputField.getAttribute("check_lengthMaxError");

    // optional:
    var counterLabelID = inputField.getAttribute("check_counterLabelID");
    if ( ! counterLabelID ) {
      counterLabel = null;
    }
    else {
      counterLabel = document.getElementById(counterLabelID);
    }
    // counterLabel might still be undefined


    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
    }

    if ( inputField.value.length < lengthMin ) {
      
      // Show warning "too short" only if lostFocus (not while typing)
      if ( isOnBlur ) {

        // Check if nothing entered AND special error message is defined
        if ( inputField.value.length==0 
             && inputField.getAttribute("check_emptyError") ) {
          errorLabel.innerHTML = inputField.getAttribute("check_emptyError");
        }
        else {
          // set error message "too short"
          errorLabel.innerHTML = lengthMinError;
        }
        inputField.style.backgroundColor = "#FFCCCC";
        
        if ( counterLabel ) {
          if ( ( lengthMax - inputField.value.length ) < 0 ) {
            counterLabel.innerHTML = "("+ ( inputField.value.length - lengthMax ) +" Zeichen zu viel) ";
          }
          else {
            counterLabel.innerHTML = "(noch "+ ( lengthMax - inputField.value.length ) +" Zeichen) ";
          }
        }
        return false;
      }
      
      if ( counterLabel ) {
        if ( ( lengthMax - inputField.value.length ) < 0 ) {
          counterLabel.innerHTML = "("+ ( inputField.value.length - lengthMax ) +" Zeichen zu viel) ";
        }
        else {
          counterLabel.innerHTML = "(noch "+ ( lengthMax - inputField.value.length ) +" Zeichen) ";
        }
      }
      return true;
    }
    else if ( inputField.value.length > lengthMax ) {
      errorLabel.innerHTML = lengthMaxError;
      inputField.style.backgroundColor = "#FFCCCC";
      
      if ( counterLabel ) {
        if ( ( lengthMax - inputField.value.length ) < 0 ) {
          counterLabel.innerHTML = "("+ ( inputField.value.length - lengthMax ) +" Zeichen zu viel) ";
        }
        else {
          counterLabel.innerHTML = "(noch "+ ( lengthMax - inputField.value.length ) +" Zeichen) ";
        }
      }
      return false;
    }
    else {
      errorLabel.innerHTML = "";
      inputField.style.backgroundColor = "#FFFFFF";
      
      if ( counterLabel ) {
        if ( ( lengthMax - inputField.value.length ) < 0 ) {
          counterLabel.innerHTML = "("+ ( inputField.value.length - lengthMax ) +" Zeichen zu viel) ";
        }
        else {
          counterLabel.innerHTML = "(noch "+ ( lengthMax - inputField.value.length ) +" Zeichen) ";
        }
      }
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "email" ) {
    var emailError = inputField.getAttribute("check_emailError");

    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
    }

    if ( inputField.value.match( /((@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|,)/ ) 
     || !inputField.value.match( /^[\S]+\@[a-zA-Z0-9\-\.]+\.([a-zA-Z][a-zA-Z]|com|net|org|edu|gov|int|mil|jobs|aero|coop|mobi|museum|name|info|biz|pro)$/ ) ) {
      
      // Show warning only if lostFocus (not while typing)
      if ( isOnBlur ) {

        // Check if nothing entered AND special error message is defined
        if ( inputField.value.length==0
             && inputField.getAttribute("check_emptyError") ) {
          errorLabel.innerHTML = inputField.getAttribute("check_emptyError");
        }
        else {
          // set error message "too short"
          errorLabel.innerHTML = emailError;
        }
        inputField.style.backgroundColor = "#FFCCCC";
        return false;
      }
      return true;
    }
    else {
      errorLabel.innerHTML = "";
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "price" ) {
    
    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
    }
    
    if ( ! inputField.value.match( /^[0-9]{0,7}$/ ) ) {  // 0..7 digits
      inputField.style.backgroundColor = "#FFCCCC";
      return false;
    }
    else {
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "country" ) {
    
    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
      inputField.value = inputField.value.toUpperCase();
    }
    
    if ( ! inputField.value.match( /^[A-Z][A-Z]$/ ) ) {
      inputField.style.backgroundColor = "#FFCCCC";
      return false;
    }
    else {
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "canton" ) {
    
    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
      inputField.value = inputField.value.toUpperCase();
    }
    
    if ( ! inputField.value.match( /^ZH|BE|LU|UR|SZ|OW|NW|GL|ZG|FR|SO|BS|BL|SH|AR|AI|SG|GR|AG|TG|TI|VD|VS|NE|GE|JU$/ ) ) {
      inputField.style.backgroundColor = "#FFCCCC";
      return false;
    }
    else {
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "equals" ) {
    var equalsError = inputField.getAttribute("check_equalsError");
    
    // Remove spaces ONLY if lostFocus (not while typing)
    if ( isOnBlur ) {
      inputField.value = stringTrim( inputField.value );
    }
    
    if ( inputField.value != document.getElementById(inputField.getAttribute("equalToID")).value) {
      errorLabel.innerHTML = equalsError;
      inputField.style.backgroundColor = "#FFCCCC";
      return false;
    }
    else {
      errorLabel.innerHTML = "";
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }
  //- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (checkType == "checked" ) {
    var checkedError = inputField.getAttribute("check_checkedError");
    
    if ( !inputField.checked == true) {
      errorLabel.innerHTML = checkedError;
      inputField.style.backgroundColor = "#FFCCCC";
      return false;
    }
    else {
      errorLabel.innerHTML = "";
      inputField.style.backgroundColor = "#FFFFFF";
      return true;
    }
  }

  // everything okay  
  return true;
}





/**
 * Checks an entire form. (Syntax)
 */
function checkForm( inForm ) {
  
  if (!inForm) {
    return true;
  }
  
  var inputFieldToFocus = null;

  // walk thru all form fields
  for (var i = inForm.elements.length - 1; i >= 0; i--) {
    var formElement = inForm.elements[i];
    
    // if this is one of our inputFields WITH syntax check defined
    if ( formElement.getAttribute("check_type") ) {
      if ( ! checkField( formElement, true ) ) {
        inputFieldToFocus = formElement;
      }
    }
  }

  // set focus the bad input field
  if ( inputFieldToFocus ) {
    inputFieldToFocus.focus();



    var errorLabelID = inputFieldToFocus.getAttribute("check_errorLabelID");
    if ( errorLabelID ) {
       errorLabel = document.getElementById(errorLabelID)
       if ( errorLabel ) {
    
          var theID = inputFieldToFocus.id;
          if ( theID ) {
            window.setTimeout( "setBlinkHidden( '"+ errorLabelID +"' )" , 200);
            window.setTimeout( "setBlinkVisible(   '"+ errorLabelID +"' )" , 400);
            window.setTimeout( "setBlinkHidden( '"+ errorLabelID +"' )" , 600);
            window.setTimeout( "setBlinkVisible(   '"+ errorLabelID +"' )" , 800);
//            window.setTimeout( "setBlinkHidden( '"+ errorLabelID +"' )" , 500);
//            window.setTimeout( "setBlinkVisible(   '"+ errorLabelID +"' )" , 600);
         }
       }
    }


    return false;
  }

  return true;
}


/**
 * Sets background of an element (used to blink an input field).
 * (not nice, but setTimeout() only accepts arguments as String)
 */
function setBlinkHidden( inputFieldID ) {
  if ( inputFieldID
       && document.getElementById( inputFieldID )
       && document.getElementById( inputFieldID ).style ) {
        
    //document.getElementById( inputFieldID ).style.backgroundColor = "#FFFFFF";
    document.getElementById( inputFieldID ).style.visibility = 'hidden';


  
 //   var errorLabelID = document.getElementById( inputFieldID ).getAttribute("check_errorLabelID");
 //   if ( ! errorLabelID ) {
//      // alert("check_errorLabelID is undefined");
//      return true;
//    }
//    errorLabel = document.getElementById(errorLabelID)
//    if ( ! errorLabel ) {
//      // alert("could not find errorLabel");
//      return true;
//    }
//    errorLabel.style.visibility = 'hidden';


  }
}


function setBlinkVisible( inputFieldID ) {
  if ( inputFieldID
       && document.getElementById( inputFieldID )
       && document.getElementById( inputFieldID ).style ) {
        
    //document.getElementById( inputFieldID ).style.backgroundColor = "#FFCCCC";
    document.getElementById( inputFieldID ).style.visibility = 'visible';





//    var errorLabelID = document.getElementById( inputFieldID ).getAttribute("check_errorLabelID");
//    if ( ! errorLabelID ) {
//      // alert("check_errorLabelID is undefined");
//      return true;
//    }
//    errorLabel = document.getElementById(errorLabelID)
//    if ( ! errorLabel ) {
//      // alert("could not find errorLabel");
//      return true;
//    }
//    errorLabel.style.visibility = 'visible';


  }
}





/* Waring if email syntax not okay */
function checkEmailSyntax( inputElement, isOnBlur, infoLabel ) {

  if( inputElement.value.match( /((@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|,)/ ) 
  || !inputElement.value.match( /^[\S]+\@[a-zA-Z0-9\-\.]+\.([a-zA-Z][a-zA-Z]|com|net|org|edu|gov|int|mil|jobs|aero|coop|mobi|museum|name|info|biz|pro)$/ ) ) {
    // show warning "invalid" only if lostFocus (not when typing)
    // otherwise leave prefious warning (if any)
    if ( isOnBlur ) {
      infoLabel.innerHTML = "Ungueltig!";
      infoLabel.style.color = "red";
      inputElement.style.backgroundColor = "#FFCCCC";
    }
  }
  else {
    // remove ONLY this warnings
    if ( infoLabel.innerHTML == "Ungueltig!" ) {
      infoLabel.innerHTML = "";
      inputElement.style.backgroundColor = "#FFFFFF";
    }
  }

  return true;
}



/* Waring if entered text too short or too long OLD */
function checkMinMaxLength( inputElement, isOnBlur, minLength, maxLength, infoLabel ) {

  if(inputElement.value.length < minLength) {
    // show warning "too short" only if lostFocus (not when typing)
    // otherwise leave prefious warning (if any)
    if ( isOnBlur ) {
      infoLabel.innerHTML = "Zu kurz!";
      infoLabel.style.color = "red";
      inputElement.style.backgroundColor = "#FFCCCC";
    }
  }
  else {
    // remove ONLY this warnings
    if ( infoLabel.innerHTML == "Zu kurz!" ) {
      infoLabel.innerHTML = "";
      inputElement.style.backgroundColor = "#FFFFFF";
    }
  }

  if(inputElement.value.length > maxLength) {
    infoLabel.innerHTML = "Zu lang!";
    infoLabel.style.color = "red";
    inputElement.style.backgroundColor = "#FFCCCC";
  }
  else {
    // remove ONLY this warnings
    if ( infoLabel.innerHTML == "Zu lang!" ) {
      infoLabel.innerHTML = "";
      inputElement.style.backgroundColor = "#FFFFFF";
    }
  }

  return true;
}



function returnObjById( id ) {
  if (document.getElementById)
    var returnVar = document.getElementById(id);
  else if (document.all)
    var returnVar = document.all[id];
  else if (document.layers)
    var returnVar = document.layers[id];
  return returnVar;
}


function highlightBackground(e, light) {
  if (light) {
    e.style.background = "#FFFFCC";                      
  }
  else {
      e.style.background = "#FFFFFF";
  }
}


/**
 * Resizes height of Textarea (not exact)
 */
function resizeTextareaHeightFuzzy( textarea, minHeight, maxHeight ) {
  textareaValue = textarea.value;
  newlineCount = 1;

  // check every character
  for (i=0; i<textareaValue.length; i++) {
    if ( textareaValue.charAt(i) == '\n' ) {
      newlineCount +=1;
    }
  }

  // if text is wrapped automatically, try to guess again:
  // (only works for fixed-width fonts)
  if ( textarea.cols ) {
    if (newlineCount < ( textareaValue.length / textarea.cols )) {
      newlineCount = 1 + ( textareaValue.length / textarea.cols );
    }
  }

  // always show 2 lines more:
  newlineCount += 2;

  // limit min/max
  if ( newlineCount > maxHeight ) {
    newlineCount = maxHeight;
  }
  if ( newlineCount < minHeight ) {
    newlineCount = minHeight;
  }

  textarea.rows = newlineCount;
}


/**
 * Set cookie
 */
function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) 
                  + ((expires) ? "; expires=" + expires.toGMTString() : "") 
                  + ((path) ? "; path=" + path : "") 
                  + ((domain) ? "; domain=" + domain : "") 
                  + ((secure) ? "; secure" : "");
}

