/* genereer een string van numChars willekeurige tekens */
function randomString(numChars) {
    var returnString = '';

    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    for (var i=0; i < numChars ; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        returnString += chars.substring(rnum,rnum+1);
    }
    return returnString;
}


/* controleer of inputstring een syntactisch geldig e-mailadres is */
function checkEmail (emailaddress) {
    var validemailaddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
    var result = emailaddress.search (validemailaddress);
    if (result == -1) {
        return false;
    }
    else {
        return true;
    }
}

/* geef het object met id id */
function getObjectByID(id) {
    if (document.getElementById) {
        return document.getElementById(id);
    }
    else if (document.all) {
        return document.all[id];
    }
    else if (document.layers)  {
        return document.layers[id];
    };
}

/* geef een getal weer als correct geformatteerd geldbedrag */
function formatMoney(amount) {
    amount += "";
    amount = amount.replace(/,/,".");
    amount = Math.round(amount * 100);
    amount = amount / 100;
    amount +=  "";
    if((amount.indexOf(".") > -1) && (amount.substr(amount.indexOf(".")).length > 3)) {
        cents = "0." + amount.substr(amount.indexOf(".") + 1);
        cents = Math.round(cents * 100);
        if (cents < 10) {
            cents = '0' + cents;
        };
        amount = amount.substr(0,amount.indexOf(".")) + "." + cents;
    }
    if(amount.indexOf(".") < 0) {
        amount = amount + ",00";
    }
    else {
        if(amount.substr(amount.indexOf(".")).length < 3) {
            amount = amount + "0";
        }
    }
    amount = amount.replace(/\./,",");
    if(amount.length > 9) {
        amount = amount.replace(/(\d*)(\d\d\d)(\d\d\d,\d\d)/,"$1.$2.$3");
    }
    else if(amount.length > 6) {
        amount = amount.replace(/(\d*)(\d\d\d,\d\d)/,"$1.$2");
    }
    return amount;
}

/*

get the value of an input named InputName in form object FormObject

transparently handles selects, radios, checkboxes, etc

*/
function getInputValue(InputName, FormObject) {
    var Value = '';
    if(! FormObject) {
        return false;
    };
    for(var i = 0; i < FormObject.elements.length ; i++) {
        var InputElement = FormObject.elements[i];
        if((InputElement) && (InputElement.name == InputName)) {
            var InputType = InputElement.type;
            if(InputType == 'radio') {
                if(InputElement.checked) {
                    Value=InputElement.value;
                };
            };
            if(InputType == 'checkbox') {
                if(InputElement.checked) {
                    Value=InputElement.value;
                };
            };
            if(InputType == 'select-one') {
                Value=InputElement.value;
            };
            if(InputType == 'text') {
                Value=InputElement.value;
            };
            if(InputType == 'button') {
                Value=InputElement.value;
            };
            if(InputType == 'hidden') {
                Value=InputElement.value;
            };
            if(InputType == 'textarea') {
                Value=InputElement.value;
            };
            // not, strictly speaking, correct, but for what we're
            // using this for (we need the file name) it's ok
            if(InputType == 'file') {
                Value=InputElement.value;
            };
        };
    };
    return Value;
}
/*

set the value of an input named InputName in form object FormObject to Value

transparently handles selects, radios, checkboxes, etc

*/
function setInputValue(InputName, FormObject, Value) {
    if(! FormObject) {
        return false;
    };
    for(var i = 0; i < FormObject.elements.length ; i++) {
        var InputElement = FormObject.elements[i];
        if((InputElement) && (InputElement.name == InputName)) {
            var InputType = InputElement.type;
            if(InputType == 'radio') {
                if(InputElement.value == Value) {
                    InputElement.checked = true;
                } else {
                    InputElement.checked = false;
                };
            };
            if(InputType == 'checkbox') {
                if(InputElement.value == Value) {
                    InputElement.checked = true;
                } else {
                    InputElement.checked = false;
                };
            };
            if(InputType == 'select-one') {
                for(var j = 0 ; j < InputElement.options.length ; j++) {
                    if(InputElement.options[j].value == Value) {
                        InputElement.options[j].selected = true;
                    } else {
                        InputElement.options[j].selected = false;
                    };
                };
            };
            if(InputType == 'text') {
                InputElement.value = Value;
            };
            if(InputType == 'hidden') {
                InputElement.value = Value;
            };
            if(InputType == 'textarea') {
                InputElement.value = Value;
            };
        };
    };
}


/*
    appendFieldToForm: append a field to a form object

    we call this a "saves you a lot of typing" function
*/
function appendField(FieldName, FieldValue, FieldType, FormObject) {
    var InputField = document.createElement('INPUT');
    InputField.setAttribute('name', FieldName);
    InputField.setAttribute('value', FieldValue);
    InputField.setAttribute('type', FieldType);
    FormObject.appendChild(InputField);
}


// thank you http://www.quirksmode.org/dom/getstyles.html
function getStyle(elementObject,styleProp)  {
    if (elementObject.currentStyle)
        var value = elementObject.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var value = document.defaultView.getComputedStyle(elementObject,null).getPropertyValue(styleProp);
    return value;
}
// append a hidden div with id hidddenDivID to htmlElementObject with
// contents hiddenDivContents (this goes in as innerHTML)
function appendHiddenDiv(htmlElementObject, hiddenDivID, hiddenDivContents) {
    var hiddenDivObject = document.createElement('DIV');
    hiddenDivObject.style.display = 'none';
    hiddenDivObject.setAttribute('id', hiddenDivID);
    hiddenDivObject.innerHTML = hiddenDivContents;
    htmlElementObject.appendChild(hiddenDivObject);
};
function validateFormRegExp(formObj, inputBackgroundColor, inputErrorColor) {
    var everythingok = 1;
    var formName = formObj.name;
    // build a hash labels that contains inputname => label object
    var allLabels = document.getElementsByTagName('label');
    var labels = new Object;
    for(var i =0 ;i < allLabels.length ;i++) {
      // IE dies a horrible death if you try to access its for attribute.
      // Hence a custom attribute it is. Grrr.
      var labelInputName = allLabels[i].getAttribute('inputname');
      if(labelInputName) {
        labels[labelInputName] = allLabels[i];
      }
    };
    // First, all error display objects must be closed
    for(var i = 0; i < formObj.elements.length ; i++) {
      var elementObj = formObj.elements[i];
      if(elementObj.getAttribute('errordisplay')) {
        var errorDisplayObject = document.getElementById(elementObj.getAttribute('errordisplay'));
        if(errorDisplayObject && elementObj.getAttribute('errormessage')) {
          errorDisplayObject.style.display = 'none';
        };
      };
      // and the background color reset to normal
      if(inputBackgroundColor) {
        elementObj.style.backgroundColor = inputBackgroundColor;
      };
    };
    
    for(var i = 0; i < formObj.elements.length ; i++) {
      var elementObj = formObj.elements[i];
      var mustMatch = elementObj.getAttribute('mustmatch');
      if(mustMatch) {
        mustMatchRE = new RegExp(mustMatch);
        var elementMatches = elementObj.value.match(mustMatchRE);
        var errorMessage = elementObj.getAttribute('errormessage');
        var elementName = elementObj.name;
        var labelObject = labels[elementName];
        var errorColor = '#ff0000';
        if(elementObj.getAttribute('errorcolor')) {
          errorColor = elementObj.getAttribute('errorcolor');
        }
        
        // get the original color for the label
        if(labelObject) {
          var labelStyleString ='';
          var labelObjectOrigColor = labelObject.getAttribute('origcolor');
          if(! labelObjectOrigColor) {
            labelObjectOrigColor = getStyle(labelObject, 'color');
            labelObject.setAttribute('origcolor', labelObjectOrigColor);
          };
        };
        
        // get the original color and the original value for the status element
        var statusObject = getObjectByID('status_' + formName + '_' + elementName);
        if(statusObject) {
          var statusObjectOrigTextObject = getObjectByID('statusorig_' + formName + '_' + elementName);
          var statusObjectOrigText = statusObject.innerHTML;
          if(statusObjectOrigTextObject) {
            statusObjectOrigText = statusObjectOrigTextObject.innerHTML;
          }
          var statusObjectOrigColor = statusObject.getAttribute('origcolor');
          if(! statusObjectOrigColor) {
            statusObjectOrigColor = getStyle(statusObject, 'color');
          };
        };
        
        if(elementMatches) {
          if(labelObject){
            labelObject.style.color = labelObjectOrigColor;
          };
          if(statusObject) {
          statusObject.innerHTML = statusObjectOrigText;
          statusObject.style.color = statusObjectOrigColor;
          };
        } else {
          if(statusObject) {            
            if(! statusObjectOrigTextObject) {
              appendHiddenDiv(formObj, 'statusorig_' + formName + '_' + elementName, statusObject.innerHTML);
            };
            if(! statusObject.getAttribute('origcolor')) {
              statusObject.setAttribute('origcolor', statusObjectOrigColor);
            };
            statusObject.innerHTML = errorMessage;
            statusObject.style.color =errorColor;
          };
          if(labelObject) {
            if(! labelObject.getAttribute('origcolor')) {
              labelObject.setAttribute('origcolor', labelObjectOrigColor);
            };
            labelObject.style.color = errorColor;
          };
          if(inputErrorColor) {
            elementObj.style.backgroundColor = inputErrorColor;
          }
          // only focus the first time. also, if the input has an attribute errordisplay,
          // the first time an incorrect field is encoutered, fill the html element
          // with the ID in errordisplay with the error message
          if(everythingok) {
            if(elementObj.getAttribute('errordisplay')) {
              var errorDisplayObject = document.getElementById(elementObj.getAttribute('errordisplay'));
              if(errorDisplayObject && elementObj.getAttribute('errormessage')) {
                errorDisplayObject.innerHTML = elementObj.getAttribute('errormessage');
                errorDisplayObject.style.display = 'block';
                everythingok = 0;
              }
            };            
            elementObj.focus();
          };
          everythingok = 0;
        };
      };
    };
    
    if(everythingok) {
      return true;
    };
    
    return false;
  };


// turn a | separated  CSV into an associative array
function ProcessCSV(csvData) {
    csvData = csvData.replace(/^\s*/, '');
    csvData = csvData.replace(/\s*$/, '');
    var csvLines = csvData.split(/\s*\n\s*/);
    var dataStructure = new Object;
    var fieldNames = new Array();
    for(var i = 0; i < csvLines.length ; i++) {
        if(i == 0) {
            fieldNames = csvLines[i].split(/\s*\|\s*/);
        } else {
            var fields = csvLines[i].split(/\s*\|\s*/);
            dataStructure[i - 1] = new Object;
            for(var j = 0; j < fieldNames.length ; j++) {
                var fieldName = fieldNames[j];
                var field = fields[j];
                dataStructure[i - 1][fieldName] = field;
            };
        };
    };
    return dataStructure;
};


// set the value of propertyName for the class named className
// to newValue
//
// NOTE: this seems to cause IE to crash
function modifyCSSClassProperty(className, propertyName, newValue) {
    className = '.' + className;
    var allStyles = document.styleSheets;
    for(var i = 0; i < allStyles.length ; i++) {
        var cssRules = allStyles[i].cssRules || allStyles[i].rules; // standards || IE 
        for(var j = 0; j < cssRules.length ; j++) {
            if(cssRules[j].selectorText == className) {
                var styleObject = cssRules[j].style;
                styleObject[propertyName] = newValue;
            };
        };
    };
};
