﻿
//In General, for form you need to include (in the same order!)

// - includes/com/cs/util/Event.js
// - includes/com/cs/util/Date.js
// - includes/com/cs/forms/Validation.js
// - includes/com/cs/ui/form.js


//REQUIRES: - com/CS/Forms/Validation.js 
//                 - com/cs/util/Date.js

if (!com) var com = new Object();
if (!com.cs) com.cs = new Object();
if (!com.cs.ui) com.cs.ui = new Object();
if (!com.cs.ui.form) com.cs.ui.form = new Object();

if (!com.cs.forms || !com.cs.forms.Validation)
{
    alert("Please include 'com/CS/Forms/Validation.js' for 'com/CS/ui/Form.js' to function property.  Make sure the include is BEFORE the Form.js file.");
}
if (!com.cs.util || !com.cs.util.event)
{
    alert("Please include 'com/CS/Util/Event.js' for 'com/CS/ui/Form.js' to function property.  Make sure the include is BEFORE the Form.js file.");
}

if (!_global) 
    var _global = this;
   
_global._Forms = null;
_global.form_validationGroup = 'main';
_global.buttons_validationGroup = new Array();

_global.form_doValidation = 'yes';
_global.form_validationGroup = 'main';

_global.formSubmittedByButton = false;

com.cs.ui.form.ValidationGroup = function(group)
{
    this.group = group;
    this.elements = new Array();
    this.addField = function(fld)
    {
        this.elements.push(fld);
    }
}
com.cs.ui.form.setValidationGroup = function(group)
{
    _global.form_validationGroup = group;
}

function Form_CheckClickedSubmitButton()
{
   var i;
   _global.formSubmittedByButton = true;
   for (i = 0; i < _global.buttons_validationGroup.length; i++)
   {
      if (_global.buttons_validationGroup[i].validationGroup == _global.form_validationGroup)
      {
          var elem = getElem(_global.buttons_validationGroup[i].buttonID);
          elem.click();
          return;
      }
   }
}

//Returns the appropriate field for that particular element.
// elem- Can be either string or the element itself
com.cs.ui.form.FindField = function(elem)
{
    if (typeof(elem) == "string")
    {
        elem = document.getElementById(elem);
    }
    var i,j;
    if (_global._Forms != null)
    {
        for (i =0; i < _global._Forms.length;i++)
        {
            if (_global._Forms[i].fields != null)
            {
                for (j =0; j < _global._Forms[i].fields.length; j++)
                {
                    if (_global._Forms[i].fields[j].element == elem)
                        return _global._Forms[i].fields[j];
                }
            }
        }
    }
    return null;
    
}

//Adds a form to the global list of forms
com.cs.ui.form.AddForm = function(form)
{
    if (_global._Forms == null)
        _global._Forms = new Array();
    _global._Forms.push(form);
}   

//Retrieves the form from the list of global forms
com.cs.ui.form.FindForm = function(group)
{
    if (_global._Forms != null)
    {
        var i;
        for (i =0; i < _global._Forms.length; i++)
        {
            if (_global._Forms[i].validationGroup.toUpperCase() == group.toUpperCase())
                return _global._Forms[i];
        }
    }
    return null;
} 

//Adds a field to the particular validation group

com.cs.ui.form.addField = function(field,group)
{
    var f = com.cs.ui.form.FindForm(group);
    if (f == null)
    {
        f = new com.cs.ui.form.Form(group);
        com.cs.ui.form.AddForm(f);
    }
    f.addField(field);
}

//validates all forms, and produces an alert message box if invalid, and sets focus to first field invalid
com.cs.ui.form.validate = function()
{
    var result = true;
    var i;
    if (_global._Forms != null)
    {
        var f = com.cs.ui.form.FindForm(_global.form_validationGroup);
        if (f != null)
        {
        
            result = f.validate();
            if (!result)
            {
                if (f.ErrorFirstElem.select) { 
                    //Since <select> items does not have this method
                    f.ErrorFirstElem.select();
                }
                f.ErrorFirstElem.focus();
                alert(f.ValidationMessage);
            }
        }
    }
    return result;
}

com.cs.ui.form.Form = function(validationGroup) 
{
    if (validationGroup == undefined || validationGroup == null) validationGroup = "";
    this.validationGroup = validationGroup;
    this.ValidationMessage = '';
    this.fields = new Array();   
    this.requiredGroups = null;
    this.ErrorFirstElem = null;
    var scope = this;
    
    /**
    field - com.cs.ui.form.Field
    */
    this.addField = function(field) 
    {
        field.Form = this;
        scope.fields.push(field);
    }
    
    this.addToRequiredGroups = function(field) 
    {
        var valParams = field.validationParams;
        if (!valParams.Required && valParams.RequiredGroup != '' && valParams.RequiredGroup != null)
        {
           var group = valParams.RequiredGroup;
           if (scope.requiredGroups == null)
              scope.requiredGroups = new Array();
           var found = false;
           var i;
           var reqGroup = null;
           for (i =0; i < scope.requiredGroups.length ;i++)
           {
           
               if (scope.requiredGroups[i].group.toUpperCase() == group.toUpperCase())
               {
                    found = true;
                    reqGroup = scope.requiredGroups[i];
               }
           }
           if (!found)
           {
               reqGroup = new com.cs.ui.form.ValidationGroup(group);
               scope.requiredGroups.push(reqGroup);
           }
           reqGroup.addField(field);
        }
    }
    
    //validates Required Groups, and returns true or false if ok.  Also updates the 'ValidationMessage' property
    this.validateRequiredGroups = function ()
    {
        var err = false;
        var msg = '';
        if (scope.requiredGroups != null && scope.requiredGroups.length > 0)
        {
            var i,j;
            for (i =0; i < scope.requiredGroups.length; i++)
            {
                if (scope.requiredGroups[i] != null && scope.requiredGroups[i].elements.length > 0)
                {
                    var ok = false;
                    for (j = 0; j < scope.requiredGroups[i].elements.length; j++)
                    {
                        var fld = scope.requiredGroups[i].elements[j];
                        
                        if (fld.element.value != '')
                        {
                            ok = true;
                            break;
                        }
                    }
                    if (!ok)
                    {
                        msg = "At least one of ";
                        for (j = 0; j < scope.requiredGroups[i].elements.length; j++)
                        {
                            if (j > 0)
                            {
                                if (j < scope.requiredGroups[i].elements.length -1)
                                    msg += ", ";
                                else    
                                    msg += " or ";
                            }
                            
                            var fld = scope.requiredGroups[i].elements[j];
                            if (j == 0 && scope.ErrorFirstElem == null)
                            {
                                scope.ErrorFirstElem = fld.element;
                            }
                            
                            
                            msg += fld.title;
                            fld.setError(true);
                        }
                        msg += " must be filled in";
                        scope.ValidationMessage += " - " + msg + "\r\n";
                        break;
                    }
                }
            }
            err = !ok;
        }
        return !err;
    }
    
    
    
    this.validate = function(displayMesages) {
        
        var valid = true;
        var res = false;
        
        scope.ValidationMessage = '';
        scope.requiredGroups = null;
        for (var i=0;i<scope.fields.length;i++) 
        {
            if (scope.fields[i].element != null && !scope.fields[i].element.disabled)
            {
                scope.fields[i].setError(false);
                scope.addToRequiredGroups(scope.fields[i]);
                res = scope.fields[i].validate();
                if (!res)
                {
                    if (valid)
                        scope.ErrorFirstElem = scope.fields[i].element;
                    scope.ValidationMessage += scope.fields[i].ValidationMessage + "\r\n";
                    valid = false;
                }
            
            // Do validation here.  
            // return false on error
            }
        }
        res = scope.validateRequiredGroups();
        if (!res)
        {
            valid = false;
        }
        return valid;
    }
}


com.cs.ui.form.ValidationParams = function() 
{
    var _self = this;
    this.HasValidation = true;
    this.Delimeter = '#$#';
    this.AlphaNumericOnly = false;
	this.AlwaysAllowedValues = '';
	this.DateBeforeTxt = '';
	this.DateFrom = '';
	this.DateTo = '';
	this.DateFormat = "dd/mm/yyyy";
	this.TimeFormat = "hh:mm"; //These are used in the error message for the keyboard restriction
	this.FileExtensions = '';
	this.InitValue = '';
	this.IsInteger = false;
	this.IsFile = false;
	this.IsNumeric = false;
	this.IsDate = false;
	this.IsTime = false;
	this.IsWebsite = false;
	this.HasTime = false;
	this.IsEmail = false;
	this.MinLength = null;
	this.MaxLength = null;
	this.NumFrom = null;
	this.NumTo = null;
	this.NegativeOnly = false;
	this.PositiveOnly = true;
	this.Required = false;
	this.RequiredGroup = '';
	this.SameAsTxt = '';
	this.ValueInTxt = '';
	this.ValueNotInTxt = '';
	this.ValueIn = '';
	this.ValueNotIn = '';
	
	this.ValidationMessage ='';
	
	//This will validate string 's' according to the set parameters,
	//and return the message in 'validation message'
	this.validate = function(s)
	{
	    return _self.validateWithTitle(s);
	}
	
	this.setValidationMessage = function(s)
	{
	    if (s != "" && s != null)
	        _self.ValidationMessage = " - " + s;
	    else
	        _self.ValidationMessage = '';
	}
	
	this.validateWithTitle = function(s,title)
	{
	    var alwaysAllowedMsg = '';
	    var err = false;
	    var elem = null;
	    var alwaysAllowed = false;
	    var result;
	    var msg = '';
	    var errRequired = false;
	    if (_self.HasValidation)
	    {
	        if (_self.AlwaysAllowedValues != '' && _self.AlwaysAllowedValues != null)
	        {
	            result = com.cs.forms.Validation.AlwaysAllowedValues(s,_self.AlwaysAllowedValues,_self.Delimeter);
	            if (result.Result)
	            {
	                alwaysAllowed = true;
	                err = false;
    	        }
    	        else
    	        {
	                alwaysAllowedMsg = " or " + result.ExtraMessage;
    	        }
	        }

	        if (_self.InitValue != '' && _self.InitValue != null && s == _self.InitValue)
	            s = '';
	        if (!alwaysAllowed)
	        {
                if (!err && _self.Required)
                {
                    err = !com.cs.forms.Validation.IsRequired(s);
                    if (err)
                    {
                        msg = title + " is required";
                        errRequired = true;
                    }
                }
                if (s != '' && s != null)
                {

                    if (!err && _self.AlphaNumericOnly && !com.cs.forms.Validation.IsAlphaNumericOnly(s))
                    {
                        err = true;
                        msg = title + " must contain only alpha-numeric characters ('A-Z','a-z','0-9','_', and '^')";
                    }
                    
                    if (!err && _self.IsDate)
                    {
                        result = com.cs.forms.Validation.IsDate(s,_self.HasTime);
                        if (!result.Result)
                        {
                            msg = '';
                            err = true;
                            msg = title + " must contain a valid date";
                            if (_self.HasTime)
                                msg += " and time";
                            msg += " (dd/mm/yyyy";
                            if (_self.HasTime)
                                msg += " HH:mm";
                            msg += ")";
                            var date = result.Date;
                            if (false)
                            { //does not look good
                                if (date.ErrorYear)
                                    msg += " - Invalid Year"
                                else if (date.ErrorMonth)
                                    msg += " - Invalid Month"
                                else if (date.ErrorDay)
                                    msg += " - Invalid Day"
                                else if (_self.HasTime)
                                {
                                    if (date.ErrorHour)
                                        msg += " - Invalid Hour"
                                    else if(date.ErrorMinute)
                                        msg += " - Invalid Minute";
                                    else if(date.ErrorSecond)
                                        msg += " - Invalid Second";
                                    
                                }
                            }
                        }
                    }
                    if (!err && _self.IsDate)
                    {
                        if (!err && _self.DateBeforeTxt != '' && _self.DateBeforeTxt != null)
                        {
                            elem = _self.DateBeforeTxt;
                            if (typeof(_self.DateBeforeTxt) == "string")
                                elem = document.getElementById(_self.DateBeforeTxt);
                            var dtBefore = new Date();
                            var beforeOK = dtBefore.ParseString(elem.value);
                            var dtCurr = new Date();
                            dtCurr.ParseString(s);
                            if (beforeOK && dtCurr.CompareTo(dtBefore) > 0)
                            {
                                err = true;
                                msg = title + " must contain a date value, before " + elem.getField().title;
                            }
                        }
	                    if (!err && (_self.DateFrom != '' && _self.DateFrom != null) || (_self.DateTo != '' && _self.DateTo != null))
	                    {
	                        var dtFromOK = false;
	                        var dtToOK = false;
                            var dtFrom = new Date();
                            dtFromOK = dtFrom.ParseString(_self.DateFrom);
                            var dtTo = new Date();
                            dtToOK = dtTo.ParseString(_self.DateTo);
                            var dtCurr = new Date()
                            dtCurr.ParseString(s);
                            if ( _self.DateFrom != '' && _self.DateFrom != null && _self.DateTo != '' && _self.DateTo != null && dtFromOK && dtToOK &&
                                (dtCurr.CompareTo(dtFrom) < 0 || dtCurr.CompareTo(dtTo) > 0))
                            {
                                err = true;
                                msg = title + " must contain a date value from " + dtFrom.toString() + " to " + dtTo.toString();
                            }
                            else if (_self.DateFrom != '' && _self.DateFrom != null && dtFromOK && dtCurr.CompareTo(dtFrom) < 0)
                            {
                                err = true;
                                msg = title + " must contain a date value equal to or after " + dtFrom.toString();
                            }
                            else if (_self.DateTo != '' && _self.DateTo != null && dtToOK &&  dtCurr.CompareTo(dtTo) > 0)
                            {
                                err = true;
                                msg = title + " must contain a date value equal to or before " + dtTo.toString();
                            }
	                    }
                    }
                    if (!err && _self.FileExtensions != '' && _self.FileExtensions != null)
                    {
                        result = com.cs.forms.Validation.IsFileExtension(s,_self.FileExtensions,_self.Delimeter);
                        if (!result.Result)
                        {
                            err = true;
                            msg = title + " must contain a file of extension " + result.ExtraMessage;
                        }
                    }
                    if (!err && _self.IsEmail)
                    {
                        err = !com.cs.forms.Validation.IsEmail(s);
                        if (err)
                        {
                            msg = title + " must contain an email address";
                        }
                    }
                    if (!err && _self.IsWebsite)
                    {
                        err = !com.cs.forms.Validation.IsWebsite(s);
                        if (err)
                        {
                            msg = title + " must contain a website address (URL)";
                        }
                    }
                    if (!err && _self.IsNumeric)
                    {
                        err = !com.cs.forms.Validation.IsNumeric(s);
                        if (!err && _self.PositiveOnly)
                            err = !com.cs.forms.Validation.IsPositiveNumOnly(s);
                        else if (!err && _self.NegativeOnly)
                            err = !com.cs.forms.Validation.IsNegativeNumOnly(s);
                            
                        if (err)
                        {
                            msg = title + " must contain a ";
                            if (_self.PositiveOnly)
                                msg += "positive ";
                            else if (_self.NegativeOnly)
                                msg += "negative ";
                            msg += "number";
                        }
                    }

                    if (!err && _self.IsNumeric && _self.IsInteger)
                    {
                        err = !com.cs.forms.Validation.IntegersOnly(s);
                        if (err)
                        {
                            msg = title + " must contain only integer values";
                        }
                    }
                    if (!err && (_self.MaxLength != null || _self.MinLength != null))
                    {
                        if (!err && _self.MaxLength != null)
                            err = !com.cs.forms.Validation.IsMaxLength(s,_self.MaxLength);  
                        if (!err && _self.MinLength != null)
                            err = !com.cs.forms.Validation.IsMinLength(s,_self.MinLength);
                        if (err)
                        {
                            if (_self.MaxLength != null&&  _self.MinLength != null)
                                msg = title + " must contain at least " + _self.MinLength + " characters and at most " + _self.MaxLength + " characters";
                            else if (_self.MaxLength != null)
                                msg = title + " must contain at most " + _self.MaxLength + " characters";
                            else if (_self.MinLength != null)
                                msg = title + " must contain at least " + _self.MinLength + " characters";
                        }
                    }
                    if (!err && (_self.NumFrom != null || _self.NumTo != null))
                    {
                        if (!err && _self.NumFrom != null)
                            err = !com.cs.forms.Validation.NumberFrom(s,_self.NumFrom);
                        if (!err && _self.NumTo != null)
                            err = !com.cs.forms.Validation.NumberTo(s,_self.NumTo);
                        if (err)
                        {
                            if (_self.NumFrom != null && _self.NumTo != null)
                                msg = title + " must contain a number between " + _self.NumFrom + " and " + _self.NumTo;
                            else if (_self.NumFrom != null)
                                msg = title + " must contain a number equal to or greater than " + _self.NumFrom;
                            else if (_self.NumTo != null)
                                msg = title + " must contain a number equal to or smaller than " + _self.NumTo;
                        }
                            
                    }
                    if (!err && _self.SameAsTxt != null && _self.SameAsTxt != '')
                    {
                        elem = _self.SameAsTxt;
                        if (typeof(elem) == "string")
                            elem = document.getElementById(elem);
                        err = !com.cs.forms.Validation.SameAs(s,elem.value);
                        if (err)
                            msg = title + " must contain the same value as " + elem.getField().title;
                    }
                    if (!err && _self.ValueIn != '' && _self.ValueIn != null)
                    {
                        err = !com.cs.forms.Validation.ValueIn(s,_self.ValueIn,_self.Delimeter);
                        if (err)
                            msg = title + " value must match predefined information";
                    }
                    if (!err && _self.ValueNotIn != '' && _self.ValueNotIn != null)
                    {
                        err = !com.cs.forms.Validation.ValueNotIn(s,_self.ValueNotIn,_self.Delimeter);
                        if (err)
                            msg = title + " already exists! Please choose another one.";
                    }
                }
            }
        }
	    if (!errRequired && alwaysAllowedMsg != '' && alwaysAllowedMsg != null)
	        msg += "," + alwaysAllowedMsg;
	    _self.setValidationMessage(msg);
	    return !err;
	}
	
}


//Initialises a field.  
//
// element              - ID of element or element itself (select,input,textarea)
// title                - Description of text
// useDefaultCSSClasses - By default is true, self-explanatory

//methods: setError(bool),setRequired(bool)
com.cs.ui.form.Field = function(element, title, required,useDefaultCSSClasses,form) 
{
    if (typeof(element) == "string") element = document.getElementById(element);
    if (useDefaultCSSClasses == undefined || useDefaultCSSClasses == null) { useDefaultCSSClasses = true; }
    if (title == undefined || title == null) title = element.id;
    this.Form = form;
    this.title = title;
    this.element = element;
    if (element != null && !element.getField)
    {
        element._Field = this;
        element.getField = function()
        {
            if (this._Field == null)
                this._Field = com.cs.ui.form.FindField(this);
            return this._Field;
        }
    }
    if (!required)
        required = false;
    this.ValidationMessage = '';
    this.validationParams = new com.cs.ui.form.ValidationParams();
    this.validationParams.Required = required;
    this._VP = this.validationParams;
    this.focused = false;
    this.error = false;
    
    this.useDefaultCSSClasses = useDefaultCSSClasses;
    
    
    this.cssNoFocus = null;
    this.cssNoFocusOver = null;
    this.cssFocus = null;    
    this.cssError = null;
    this.cssErrorOver = null;
    this.cssErrorFocus = null;
    this.cssDisabled = null;

    this.cssNoFocusR = null;
    this.cssNoFocusOverR = null;
    this.cssFocusR = null;    
    this.cssErrorR = null;
    this.cssErrorOverR = null;
    this.cssErrorFocusR = null;
    this.cssDisabledR = null;
    
    this.code_OnFocus = '';
    this.code_OnBlur = '';
    this.code_OnChange = '';
    this.code_OnMouseOver = '';
    this.code_OnMouseOut = '';
    
    if (this.element != null)
        this.lastFieldValue = this.element.value;
    else 
        this.lastFieldValue = '';
    
    this.invalidInputCounter = 0;    
    this.maxInvalidInputs = 5; // This will show an alert message if the amount of invalid inputs exceeds this value.
                               // 0 indicates no alert messages
    
    var scope = this;
    
    // This will update wheter the inserted input was valid or not
    // - validInput True / False, wheter the input is valid or not
    // - Error message to display if the amount of invalid inputs exceed the max limit
    this.updateInvalidInput = function(validInput, errorMessage) {
        if (scope.maxInvalidInputs != 0) {
            if (!validInput) {
                scope.invalidInputCounter++;
                
                if (scope.invalidInputCounter >= scope.maxInvalidInputs) {
                    scope.invalidInputCounter = 0;
                    alert(errorMessage);
                }
            }

        }
        
    }
    /**
    This will restrict the user numeric input.  If the field is numeric, it will only let you input numerical values.
    It will also restrict positive / negative values
    */
    this.restrictNumericalInput = function() 
    {
        var newValue = scope.element.value;
        newValue += "0"; // since if the field is empty it would be 0.. If he enters - only, that would mean -0
        var lastValue = scope.lastFieldValue;
        var lastValueValid = true;
        var ok = true;
        if (ok) {
            ok = com.cs.forms.Validation.IsNumeric(newValue);
            if (!ok) {
                
                lastValueValid = com.cs.forms.Validation.IsNumeric(lastValue);
            }
            
            scope.updateInvalidInput(ok, "Please insert a numeric value");
        }
        if (ok && scope.validationParams.IsInteger) {
            ok = com.cs.forms.Validation.IntegersOnly(newValue);
            if (ok && newValue.toString().indexOf(".") != -1) {
                ok = false;
            }
            if (!ok) {
                
                lastValueValid = com.cs.forms.Validation.IntegersOnly(lastValue);
            }
            
            scope.updateInvalidInput(ok, "Please insert an integer value (whole number)");
        }
        if (ok && scope.validationParams.NegativeOnly) { 
            ok = com.cs.forms.Validation.IsNegativeNumOnly(newValue);
            
            if (!ok) {            
                lastValueValid = com.cs.forms.Validation.IsNegativeNumOnly(lastValue);
            }
            scope.updateInvalidInput(ok, "Please insert a negative number");
        }
        if (ok && scope.validationParams.PositiveOnly) 
        {
        
            ok = com.cs.forms.Validation.IsPositiveNumOnly(newValue);
            if (ok && newValue.indexOf("-") != -1) {
                ok = false;
            }
            if (!ok) {                
                lastValueValid = com.cs.forms.Validation.IsPositiveNumOnly(lastValue);
            }
            scope.updateInvalidInput(ok, "Please insert a positive number");
        }
        
        if (!ok) {
            if (lastValueValid) {
                scope.element.value = scope.lastFieldValue;
            }
            else {
                scope.element.value = "";
            }
        }
        else {
            scope.invalidInputCounter = 0; // reset counter;
        }
        
    }
    
    /** This will restrict date time input for a textfield.  It will allow values
    only of the format dd/mm/yyyy hh:mm in case of a date time */
    this.restrictDateTimeInput = function() {
    
        var value = scope.element.value;
        var dateValue = "";
        var timeValue = "";
        
        var dd, mm, yyyy, HH, MM;
        dd = mm = yyyy = HH = MM = "";
        
        
        
        var isInserting = value.length > scope.lastFieldValue.length;
    
        var replaceDelimiters = function(str, otherDelimiters, delimiter) {        
            for (var i = 0;i<otherDelimiters.length;i++) {
                var d = otherDelimiters[i];
                while (str.indexOf(d) != -1) {
                    str = str.replace(d, delimiter);                    
                }
            }            
            return str;            
        }
        
        var removeDoubleDelimiters = function(delimiter, str) {
            while (str.indexOf(delimiter + delimiter) != -1) {
                str = str.replace(delimiter + delimiter, delimiter);
            }
            return str;
        }
        
        if (scope.validationParams.IsDate) {
            var dateDelimiter = "/";
        
            var dateValue = value;
            if (value.indexOf(" ") != -1) {
                dateValue = value.substring(0, value.indexOf(" "));
            }
            
            dateValue = replaceDelimiters(dateValue, [",","|","-"],dateDelimiter);
            dateValue = removeDoubleDelimiters(dateDelimiter, dateValue);
            
            
            var items = dateValue.split(dateDelimiter);
            var amtDelimiters = items.length-1;
            
            
            if (items[0]) dd = items[0];
            if (items[1]) mm = items[1];
            if (items[2]) yyyy = items[2];
            
            if (!dd) amtDelimiters = 0; // not even date is filled
            
            if (dd && dd.length > 2)
            {   
                     
                mm = dd.substring(2);
                dd = dd.substring(0,2);
            }
            if (mm && mm.length > 2)
            {
                yyyy = mm.substring(2) + yyyy;
                mm = mm.substring(0,2);
            }
            if (yyyy && yyyy.length > 4) yyyy = yyyy.substring(0,4);
            dateValue = "";
            if (dd) dateValue = dd;
            if (mm) dateValue += dateDelimiter + mm;
            if (yyyy) dateValue += dateDelimiter + yyyy;
            
            if (!mm && (amtDelimiters >= 1 || (isInserting && dd && dd.length == 2))) dateValue += dateDelimiter;
            if (!yyyy && (amtDelimiters >= 2 || (isInserting && mm && mm.length == 2))) dateValue += dateDelimiter;
            
            if (isInserting && scope.validationParams.HasTime && yyyy && yyyy.length == 4 && value.indexOf(" ") == -1) {
                dateValue += " ";
            }
            
        }
        
        if (scope.validationParams.IsTime || (scope.validationParams.IsDate && scope.validationParams.HasTime)) {
            var middleValue = "";
            var timeDelimeter = ":";
            if (scope.validationParams.IsTime) {
                timeValue = value;
            }
            else {
                var beginIndex = value.indexOf(" ");
                if (beginIndex != -1) {
                    middleValue = " ";
                    var endIndex = value.lastIndexOf(" ");
                    if (endIndex == beginIndex) {
                        endIndex = value.length;
                    }
                    timeValue = value.substring(beginIndex +1, endIndex);
                    
                }
                
            }
            if (timeValue) {
                timeValue = replaceDelimiters(timeValue, [",","-","|"], timeDelimeter);
                
                
                
                var items = timeValue.split(timeDelimeter);
                var amtDelimiters = items.length -1;
                if (items[0]) HH = items[0];
                if (items[1]) MM = items[1];
                if (!HH) amtDelimiters = 0; // not even hours is filled
                
                if (HH && HH.length > 2) {
                    MM = HH.substring(2) + MM;
                    HH = HH.substring(0,2);
                }
                if (MM && MM.length > 2 ) {
                    MM = MM.substring(0,2);
                }
                timeValue = "";
                if (HH) timeValue = HH;
                if (MM) timeValue += timeDelimeter + MM;
                
                if (!MM && (amtDelimiters >= 1 || (isInserting && HH && HH.length == 2))) timeValue += timeDelimeter;
            
                
                
                
            }
            timeValue = middleValue + timeValue;
            
        }
        
        
        scope.element.value = dateValue + timeValue;
    
        var ok = true;
        
        var checkValues = [dd,mm,yyyy,HH,MM];
        for (var i = 0;i<checkValues.length;i++) {
            var value = checkValues[i];
            
            if (value) {
               
                 if (value.indexOf(".") != -1) ok = false;
                 if (!ok) break;
                 ok = (com.cs.forms.Validation.IsNumeric(value));
                 if (!ok) break;
                 ok = (com.cs.forms.Validation.IntegersOnly(value));
                 if (!ok) break;
                 
            }
        }
        
        var errMsg = "Please insert a ";
        if (scope.validationParams.IsDate) {
            errMsg += "date";
            if (scope.validationParams.HasTime) {
                errMsg += " and time"
            }
        }
        else if (scope.validationParams.IsTime) {
            errMsg += "time";
        }
        errMsg += " value in the format [";
        if (scope.validationParams.IsDate) {
            errMsg += scope.validationParams.DateFormat;
            if (scope.validationParams.HasTime) {
                errMsg += " " + scope.validationParams.TimeFormat;
            }
        }
        else if (scope.validationParams.IsTime) {
            errMsg += scope.validationParams.TimeFormat;
        }
        errMsg += "].\nAll values must be numeric.";
        
        scope.updateInvalidInput(ok, errMsg);
        
        if (ok) scope.invalidInputCounter = 0; // reset
        
        if (!ok) {
            scope.element.value = scope.lastFieldValue;
        }
        else {
            scope.element.value = dateValue + timeValue;
        }
    }
    
    /** This will restrict the lenght of the string inputted in the textfield */
    this.restrictLength = function() {
       
        scope.element.maxLength = scope.validationParams.MaxLength;
        if (scope.element.value.length > scope.validationParams.MaxLength) {
            scope.element.value = scope.element.value.substring(0,scope.validationParams.MaxLength);
        }
    }
    /**
    This function will restrict keyboard input if applicable.  This is called whenever a new key is inputted
    */
    this.restrictKeyboardInput = function() {
        
        if (scope.validationParams.AlwaysAllowedValues == '' || scope.validationParams == null)
        {
            if (scope.element.value != scope.lastFieldValue) {        
                if (scope.validationParams.IsNumeric) 
                {
                    scope.restrictNumericalInput();
                }
                if (scope.validationParams.IsDate || scope.validationParams.IsTime) {
                    scope.restrictDateTimeInput();
                }
                if (scope.validationParams.MaxLength) {
                    scope.restrictLength();
                }
                scope.lastFieldValue = scope.element.value;
            }
        }
    }


    //Get either the required class, or the normal class depending on wheter the field is required or not
    this.getDefaultClassName = function(required, normalClassVar, requiredClassVar) {       
        if (required) 
        {
            return _global[requiredClassVar] || _global[normalClassVar];
        }
        else 
        {
            return _global[normalClassVar];
        }            
    }

    /** Will set the CSS class of the element.  
    CSSClass - The CSS Class name (If left null, it will use the default class if useDefaultCSSClasses is true
    CSSClassRequired - The CSS Class name for the required (If left null, it will refer to the normal CSS
                       class, if also that is null, it will use the default class if useDefaultCSSClasses is true
    defaultCSSVarName - The CSS variable name of the not required alternative if 'null' is specified in CSSClass
    defaultRequiredCSSVarName - The CSS variable name of the required alternative if 'null' is specified in CSSClass
    */
    this.setCSSClass = function(CSSClassNormal, CSSClassRequired, defaultCSSVarName, defaultRequiredCSSVarName) {
        var CSSClass;
        if (scope.validationParams.Required) {
            CSSClass = CSSClassRequired;
        }
        else {
            CSSClass = CSSClassNormal;
        }
        
        
        if (!CSSClass && scope.useDefaultCSSClasses) {
            // Get the default class name
            CSSClass = scope.getDefaultClassName(scope.validationParams.Required, defaultCSSVarName, defaultRequiredCSSVarName);            
        }
        if (CSSClass) 
        {
            scope.element.className = CSSClass;
        }
        else
        {
        //this is so that the alert is only shown once! [cool feature by karl)
            
            if (scope.useDefaultCSSClasses && !_global.ErrorForCSSClass)
            {            
                _global.ErrorForCSSClass = true;
                alert("Default CSS Class for '" + defaultCSSVarName + "' or '" + defaultRequiredCSSVarName + "' is not found.  \n\nCheck that you included params_client or params_admin.js");
            }
        }
    }
    
    // This will refresh the CSS classes of the field according to the current field status
    //
    this.updateCSSClasses = function()
    {
        if (scope.element !=null)
        {
            if (scope.element.disabled) {
            
                scope.setCSSClass(scope.cssDisabled, scope.cssDisabledR, "CLASS_DISABLED", "CLASS_DISABLED_REQUIRED");
                
            }
            else {
                if (scope.error) 
                {
                    scope.setCSSClass(scope.cssError, scope.cssErrorR, "CLASS_ERROR", "CLASS_ERROR_REQUIRED");     
                }
                else {
                    scope.setCSSClass(scope.cssNoFocus, scope.cssNoFocusR, "CLASS_NOFOCUS", "CLASS_NOFOCUS_REQUIRED");     
                }
            }
        }
    
    }
    this.setValidationGroup = function()
    {
        com.cs.ui.form.setValidationGroup(scope.Form.validationGroup);
    }
    
    this.onchange = function() {
        scope.restrictKeyboardInput();
        scope.setValidationGroup();
    }
    
    this.onmouseout = function() {
        if (!scope.focused) {
            scope.updateCSSClasses();
        }
        
    }
    
    this.onmouseover = function() 
    {        
    
        if (!scope.focused) 
        {
            if (scope.error) {
                scope.setCSSClass(scope.cssErrorOver, scope.cssErrorOverR, "CLASS_ERROR_OVER", "CLASS_ERROR_OVER_REQUIRED");     
            }
            else {
                scope.setCSSClass(scope.cssNoFocusOver, scope.cssNoFocusOverR, "CLASS_NOFOCUS_OVER", "CLASS_NOFOCUS_OVER_REQUIRED");     
            }
        }
    } 
    
    this.onfocus = function() {
        scope.focused = true;
        if (form != null)
            _global.form_validationGroup = scope.Form.validationGroup;
        if (scope.validationParams.InitValue != '' && scope.validationParams.InitValue != null && element.value == scope.validationParams.InitValue)
            element.value = '';
        if (scope.error) {
            scope.setCSSClass(scope.cssErrorFocus, scope.cssErrorFocusR, "CLASS_ERROR_FOCUS", "CLASS_ERROR_FOCUS_REQUIRED");     
        }
        else {
            scope.setCSSClass(scope.cssFocus, scope.cssFocusR, "CLASS_FOCUS", "CLASS_FOCUS_REQUIRED");     
        }
        scope.setValidationGroup();
    }
    
    // Checks the value of the textbox initial value and if the user leaves it null, it will
    // re set the initial text value of the textfield
    this.checkInitialValue = function() {
        if (scope.validationParams.InitValue != '' && scope.validationParams.InitValue != null && (element.value == '' || element.value == null))
        {
            element.value = scope.validationParams.InitValue;
        }            
    }
    
    // This will update the date format to dd/mm/yyyy if it is a valid date.  
    this.updateDateFormat = function() {
        if (scope.validationParams.IsDate && scope.element.value != '' && scope.element.value != null)
        {
            var d = new Date();
            
            var ok = d.ParseString(scope.element.value, scope.validationParams.HasTime);
            if (ok)
            {
                var format = "#DD#/#MM#/#YYYY#";
                if (scope.validationParams.HasTime)
                    format += " #hhh#:#mm#";
                scope.element.value = d.CustomFormat(format);
            }
        }
    }
    
    this.onblur = function() {
        scope.focused = false;        
        if (scope.error) {
            scope.setCSSClass(scope.cssError, scope.cssErrorR, "CLASS_ERROR", "CLASS_ERROR_REQUIRED");     
        }
        else {
            scope.setCSSClass(scope.cssNoFocus, scope.cssNoFocusR, "CLASS_NOFOCUS", "CLASS_NOFOCUS_REQUIRED");     
        }
        scope.checkInitialValue();
        scope.updateDateFormat();
    } 
    
    
    /**
    This will define the normal, over and onfocus classNames.  If the provided class names are null or empty, the relevant event handler is not set
    */
    this.setCSSClasses = function(cssNoFocus, cssNoFocusOver, cssFocus, cssError, cssErrorOver, cssErrorFocus, cssDisabled,
                                  cssNoFocusR, cssNoFocusOverR, cssFocusR, cssErrorR, cssErrorOverR, cssErrorFocusR, cssDisabledR) {
        scope.cssNoFocus = cssNoFocus;
        scope.cssNoFocusOver = cssNoFocusOver;
        scope.cssFocus = cssFocus;
        scope.cssError = cssError;
        scope.cssErrorOver = cssErrorOver;
        scope.cssErrorFocus = cssErrorFocus;
        scope.cssDisabled = cssDisabled;
        
        
        //Classes used when field is required
        scope.cssNoFocusR = cssNoFocusR;
        scope.cssNoFocusOverR = cssNoFocusOverR;
        scope.cssFocusR = cssFocusR;
        scope.cssErrorR = cssErrorR;
        scope.cssErrorOverR = cssErrorOverR;
        scope.cssErrorFocusR = cssErrorFocusR;
        scope.cssDisabledR = cssDisabledR;
        
        scope.updateCSSClasses();
    }
    
    
    this.initHandlers = function() 
    {
    
        if (scope.element != null)
        {
            com.cs.util.event.AddEvent(scope.element,"onmouseover",scope.onmouseover);
            com.cs.util.event.AddEvent(scope.element,"onmouseout",scope.onmouseout);
            com.cs.util.event.AddEvent(scope.element,"onblur",scope.onblur);
            com.cs.util.event.AddEvent(scope.element,"onfocus",scope.onfocus);

            var funcKeyPress = function() {
                var f = function() {
                    scope.onchange();
                }
                interval = setTimeout(f,5);
            }
            
            com.cs.util.event.AddEvent(scope.element,"onkeypress",funcKeyPress);
        }

    }
    
    // Whether field is required (boolean)
    this.setRequired = function(required) 
    {
        scope.validationParams.Required = required;
        scope.updateCSSClasses();
        
    }
    
    // Whether field has error (boolean)
    this.setError = function(error) 
    {
   
        scope.error = error;
        scope.updateCSSClasses();
        
    }
    // Whether field has error (boolean)
    this.setEnabled = function(enabled) 
    {
   
        scope.element.disabled = !enabled;
        scope.updateCSSClasses();
        /* MARK DO HERE */

    }
    ///Sets whether validation is to be done or not on this field
    this.setValidationState = function()
    {
        scope.validationParams.HasValidation = state;
    }
    this.setDisabled = function(disabled) {
        scope.setEnabled(!disabled);
    }
    
    /** Set the initial class for the field (in case it is not set via the attribute 'class' */
    this.initCSSClass = function() 
    {
        
        scope.updateCSSClasses();
    }

    this.init = function() 
    {
        if (scope.element != null)
        {
            scope.initHandlers();
            scope.initCSSClass();
            scope.updateCSSClasses();
        }
       
    }
    
    this.init();
    
    
    this.validate = function() 
    {
    
        var valid = true;
        if (scope.element != null)
        {
            var value = scope.element.value;
            if (scope.validationParams.InitValue != null && scope.validationParams.InitValue != "" && 
            scope.validationParams.InitValue.toLowerCase() == value.toLowerCase())
            {
                value = '';
            }
            valid = scope.element.disabled || scope.validationParams.validateWithTitle(value,scope.title);
            // If it is disabled, omit validation
            scope.setError(!valid);
            this.ValidationMessage = scope.validationParams.ValidationMessage;
        }
        return valid;
    }

}

