// *******************************************************
//
// wbForm Validation
// Copyright 2008 Holodyn Corporation
//
// *******************************************************

// *******************************************************
// Forms Class
// *******************************************************

if( typeof wbForm == 'undefined' ){
  var wbForm = function( formId ){

    // Form Element Reference
    this.form = document.getElementById(formId);
    if(!this.form)return null;
    this.form.parent = this;

    // Testing - Permanent Submission Cancel
    // this.form.action = 'javascript:void(0);';

    // Class Setup
    this.formNew  = true;
    this.formId   = formId;
    this.aColor   = '#000000'; //active
    this.dColor   = '#AAAAAA'; //default
    this.vColor   = '#333333'; //valid
    this.iColor   = '#993333'; //invalid
    this.fields   = []; //array of fields
    this.errField = null;

    // ------------------------------------
    // Store Existing onSubmit Function
    // ------------------------------------
    this.osubfunc = null;
    if(this.form.onsubmit){
      this.form.osubfunc = "'"+this.form.onsubmit+"'" ;
      this.form.osubfunc=this.form.osubfunc.replace(/^\'.*?\{/,'');
      this.form.osubfunc=this.form.osubfunc.replace(/\}\'$/,'');
    };

    // ------------------------------------
    // Form Submission
    // ------------------------------------
    this.form.onsubmit = function(){
      if(this.osubfunc){
        this.parent.cleanup();
        if( eval(this.osubfunc) ){
          this.parent.cleanup();
          return true;
        };
        this.parent.cleanup();
        return false;
      } else {
        this.parent.cleanup();
        if( !this.parent.validate() ){
          this.parent.cleanup();
          return false;
        };
      };
      return true;
    };

    // ------------------------------------
    // Form Initilization
    // ------------------------------------
    this.init = function(){
      dataSet = this.loadDataSet();
      if( !dataSet.length ) return;
      for(var i=0;i<dataSet.length;i++){
        if( dataSet[i].length < 2 )continue;
        if( dataSet[i][1].length < 1 )continue;
        // var mo = document.getElementById(dataSet[i][0]);
        var mo = dataSet[i][1][0];
        if(dataSet[i][1].length > 1)
          mo.setNodes = dataSet[i][1];
        if(mo){
          mo.params = new wbFieldParams();
          mo.params.load( mo );
          // Tag Specific Functions
          if(mo.tagName=='INPUT'){
            if(mo.type.toUpperCase()=='TEXT'){
              this._ae('onkeypress','this.filter();',mo);
            } else if(mo.type.toUpperCase()=='RADIO'){
            } else if(mo.type.toUpperCase()=='CHECKBOX'){
            } else if(mo.type.toUpperCase()=='FILE'){
            };
          } else if(mo.tagName=='TEXTAREA') {
            this._ae('onkeypress','this.filter();',mo);
          } else if(mo.tagName=='SELECT') {
          };
          // On Focus / Blur Check
          this._ae('onfocus','this.check(1);',mo);
          this._ae('onblur','this.check();',mo);
          if( mo.setNodes ){
            for(var sn=1;sn<mo.setNodes.length;sn++){
              mo.setNodes[sn].parent = this;
              this._ae('onfocus','this.parent.highlight(this,1);',mo.setNodes[sn]);
              this._ae('onblur','this.parent.highlight(this);',mo.setNodes[sn]);
            }
          }
          // General Associations
          mo.filter   = this.filterVal;
          mo.check    = this.checkVal;
          mo.getValue = this.getFieldValue;
          mo.setValue = this.setFieldValue;
          mo.parent   = this;
          mo.check();
          this.fields.push(mo);
        };
      };
      if(this.fields.length>0){
        this.fields[0].blur();
        this.fields[0].focus();
      }
    };

    // ------------------------------------
    // Post Form Alert
    // ------------------------------------
    this.doAlert = function(val,sig,fldId,focus){
      if( val == undefined )return;
      if( fldId != undefined && document.getElementById(fldId+'_alert') ){
        var mf = document.getElementById(fldId+'_alert');
        clearTimeout(mf.cleanup);
        mf.innerHTML = val;
        if( sig != undefined && sig ){ alert( val ); };
        mf.cleanup = setTimeout('document.getElementById(\''+fldId+'_alert\').innerHTML="";',10000);
      } else if( document.getElementById(this.formId+'_alert') != undefined ) {
        var mf = document.getElementById(this.formId+'_alert');
        clearTimeout(mf.cleanup);
        mf.innerHTML = val;
        mf.hideAlert = function(){this.setValue('');};
        if( sig != undefined && sig ){ alert( val ); };
        mf.cleanup = setTimeout('document.getElementById(\''+this.formId+'_alert\').innerHTML="";',10000);
      } else if( sig != undefined && sig ){
        alert( val );
      };
      if( fldId != undefined )
        document.getElementById(fldId).focus();
    };

    // ------------------------------------
    // Cleanup Value Trigger
    // ------------------------------------
    this.cleanup = function(){
      for(var i=0;i<this.fields.length;i++)
        if( this.fields[i] == this.errField )
          this.fields[i].focus();
        else
          this.fields[i].check();
      this.errField = null;
    };

    // ------------------------------------
    // Field Wrapper Highlight
    // ------------------------------------
    this.highlight = function(myObj,focus){
      var myObj = myObj.parentNode;
      while( myObj.className.match(/field/) == null )
        myObj = myObj.parentNode;
      if( (typeof myObj == 'object') && (myObj.tagName == 'DIV') ){
        var myClass = myObj.className;
        if(focus){
          if( !myClass.match(/active/) )
            myClass = myClass+' active';
        } else {
          if( myClass.match(/active/) )
            myClass = myClass.replace(/ active/,'');
        }
        myObj.className = myClass;
        // document.getElementById('formGimp_msg').innerHTML = myClass;
      }
    }

    // ------------------------------------
    // Check Value on Focus and Blur
    // ------------------------------------
    this.checkVal = function(focus){
      this.parent.highlight(this,focus);
      var val = this.getValue(this);
      if( val == undefined )return;
      if(val==this.params.example){
        this.setValue('');
        this.style.color=this.parent.aColor;
      } else if(val==''){
        this.setValue(this.params.example);
        if( this.params.required )
          this.style.color=this.parent.iColor;
        else
          this.style.color=this.parent.dColor;
      } else
        this.style.color=this.parent.vColor;
    };

    // ------------------------------------
    // Filter Value Trigger
    // ------------------------------------
    this.filterVal = function(){
      if( this.params.filter != null ){
        var valid = 1;
        var regx = new RegExp(this.params.filter);
        var repv = (this.params.filter_replace != null)?this.params.filter_replace:'';
        var ov = this.getValue();
        var nv = ov.replace(regx,repv);
        if( nv != ov ) valid = 0;
        if( !valid && this.params.filter_msg != null )
          this.parent.doAlert(this.params.filter_msg,0,this.id);
        this.setValue(nv);
      };
    };

    // ------------------------------------
    // Get the Value of a Field
    // ------------------------------------
    this.getFieldValue = function(){
      if(this.tagName == 'INPUT'){
        if(this.type.toUpperCase()=='TEXT'
          || this.type.toUpperCase()=='FILE'){
          return trim(this.value);
        }else if(this.type.toUpperCase()=='CHECKBOX'
          || this.type.toUpperCase()=='RADIO'){
          if( this.setNodes ){
            var values = [];
            for(var n=0;n<this.setNodes.length;n++){
              if( this.setNodes[n].checked )
                values.push( trim(this.setNodes[n].value) );
            };
            return values;
          } else {
            if( this.checked )
              return trim(this.value);
          };
          return null;
        };
      }else if(this.tagName == 'TEXTAREA'){
        return trim(this.value);
      }else if(this.tagName == 'SELECT'){
        if(this.multiple){
          var values = [];
          for(var i=0;i>this.options.length;i++)
            if(this.options[i].selected)
              values.push(this.options[i].value);
          return values;
        }else{
          return this.options[ this.selectedIndex ].value;
        };
      };
      return null;
    };

    // ------------------------------------
    // Set the Value of a Field
    // ------------------------------------
    this.setFieldValue = function(value){
      if(typeof value == 'undefined' || value == null)
        value = '';
      if(this.tagName == 'INPUT'){
        if(this.type.toUpperCase()=='TEXT'){
          this.value = value;
          return true;
        }else if(this.type.toUpperCase()=='CHECKBOX'
          || this.type.toUpperCase()=='RADIO'){
          if( !isArray(value) )value = [value];
          if( this.setNodes ){
            var numallow = this.numallow;
            for(var n=0;n<this.setNodes.length;n++){
              if( inArray(this.setNodes[n].value,value) )
                this.setNodes[n].checked = true;
              else
                this.setNodes[n].checked = false;
            };
          } else {
            if( inArray(this.value,value) )
              this.checked = true;
            else
              this.checked = false;
          };
          return true;
        };
      }else if(this.tagName == 'TEXTAREA'){
        this.value = value;
        return true;
      }else if(this.tagName == 'SELECT'){
        if( !isArray(value) )value = [value];
        for(var f=0;f>this.options.length;f++){
          if( inArray(this.options[f].value,value) ){
            this.options[f].selected = true;
            if(!this.multiple)return true;
          } else
            this.options[f].selected = false;
        };
      };
      return false;
    };

    // ------------------------------------
    // Load Form Data on Initialization
    // ------------------------------------
    this.loadDataSet = function(){
      var dataSet = [];
      for(var i=0;i<this.form.childNodes.length;i++)
        if( this.form.childNodes[i].tagName == 'DIV' )
          if(this.form.childNodes[i].className.match(/field/)){
            fSet = this.loadFieldData( this.form.childNodes[i] );
            if( fSet[0] != '' ) dataSet.push( fSet );
          };
      return dataSet;
    };

    // ------------------------------------
    // Load Field Data on Initialization
    // ------------------------------------
    this.loadFieldData = function( obj, fields ){
      var id = null;
      if( !fields )
        var fields = [];
      for(var i=0;i<obj.childNodes.length;i++){
        if( obj.childNodes[i].tagName == 'INPUT' ){
          var fType = obj.childNodes[i].type.toLowerCase();
          if( fType == 'text' || fType == 'radio' || fType == 'checkbox' ){
            if( obj.childNodes[i].id )
              id = obj.childNodes[i].id;
            fields.push( obj.childNodes[i] );
          }
        } else if( obj.childNodes[i].tagName == 'SELECT' ){
          if( obj.childNodes[i].id )
            id = obj.childNodes[i].id;
          fields.push( obj.childNodes[i] );
        } else if( obj.childNodes[i].tagName == 'TEXTAREA' ){
          if( obj.childNodes[i].id )
            id = obj.childNodes[i].id;
          fields.push( obj.childNodes[i] );
        } else if( obj.childNodes[i].tagName == 'DIV' ){
          var fSet = this.loadFieldData( obj.childNodes[i], fields );
          if( fSet[0] != '' && id == '' ) id = fSet[0];
        }
      };
      return [id, fields];
    };

    // ------------------------------------
    // Validate Field Value
    // ------------------------------------
    this.validate = function(){
      for(var i=0;i<this.fields.length;i++){
        var valid = 0;
        var errorMsg = '';
        var myVal = this.fields[i].getValue();
        if( isArray(myVal) ){
          var numallow = this.fields[i].params.numallow;
          var numrequire = this.fields[i].params.numrequire;
          if( numallow != null && numrequire != null ){
            if( numallow < myVal.length )
              errorMsg = numallow+' maximum values allowed';
            else if( numrequire > myVal.length )
              errorMsg = numrequire+' values must be selected';
            else
              valid = 1;
          };
        } else if( myVal != '' ){
          this.fields[i].setValue(myVal);
          if( this.fields[i].params.validate != null ){
            var regx = new RegExp(this.fields[i].params.validate);
            if( this.fields[i].params.validate.match(/\[\^/) ){
              var nv = myVal.replace(regx,'');
              if( nv != myVal )
                this.fields[i].setValue( nv );
              else
                valid = 1;
            }else if(this.fields[i].params.validate_replace != null){
              var nv = myVal.replace(regx,this.fields[i].params.validate_replace);
              if( nv != myVal ){
                this.fields[i].setValue( nv );
                valid = 1;
              };
            }else{
              if( myVal.match(regx) )
                valid = 1;
            };
          } else valid = 1;
        };
        if( !valid && this.fields[i].params.required ){
          if( this.fields[i].params.validate_msg != null )
            this.doAlert('Invalid: '+this.fields[i].params.validate_msg+(errorMsg?"\n"+errorMsg:''),1,this.fields[i].id);
          else
            this.doAlert('Invalid: '+this.fields[i].params.label+(errorMsg?"\n"+errorMsg:''),1,this.fields[i].id);
          this.errField = this.fields[i];
          return false;
        };
      };
      return true;
    };

    // ------------------------------------
    // Add Event
    // ------------------------------------
    this._ae=function(oN,eF,cO){
      if(typeof oN!='string')return false;
      if(typeof eF=='function')eF=("'"+eF+"'").replace(/\n|\r/,' ').replace(/^\'.*?\{/,'').replace(/\}\'$/,'');
      if(eval('typeof '+(cO?'cO.'+oN:oN))!='function')return eval((cO?'cO.'+oN:oN)+'= function(e){ '+eF+' }');
      var oF=("'"+eval((cO?'cO.'+oN:oN))+"'").replace(/\n|\r/,' ').replace(/^\'.*?\{/,'').replace(/\}\'$/,'');
      return eval((cO?'cO.'+oN:oN)+'=function(e){'+eF+' '+oF+'}');
    };

    // ------------------------------------
    // Delete Event
    // ------------------------------------
    this._de=function(oN,eF,cO){
      if(typeof oN != 'string')return false;if(eval('typeof '+(cO?cO.call(oN):oN)) != 'function')return true;
      if(typeof eF=='function')eF=("'"+eF+"'").replace(/\n|\r/,' ').replace(/^\'.*?\{/,'').replace(/\}\'$/,'');
      var oD=("'"+eval((cO?cO.call(oN):oN))+"'").replace(/\n|\r/,' ').replace(/^\'.*?\{/,'').replace(/\}\'$/,'').replace(eF,'');
      if(oD.replace(/\s+/,'').length>0)return eval((cO?cO.call(oN):oN)+'=function(e){'+oD+'}');else return eval((cO?cO.call(oN):oN)+'=function(e){}');
    };

  };
};

// *******************************************************
// Field Parameter Storage Class
// *******************************************************

if( typeof wbFieldParams == 'undefined' ){
  var wbFieldParams = function(){
    this.label            = null;
    this.required         = 0;
    this.defvalue         = null;
    this.example          = null;
    this.numallow         = null;
    this.numrequire       = null;
    this.validate         = null;
    this.validate_replace = null;
    this.validate_msg     = null;
    this.filter           = null;
    this.filter_replace   = null;
    this.filter_msg = null;
    this.load = function( myObj ){
      if( myObj.getAttribute('label') != null )
        this.label = myObj.getAttribute('label');
      else this.label = myObj.name;
      if( myObj.getAttribute('required') == 1 )
        this.required = 1;
      if( myObj.getAttribute('defvalue') != null )
        this.defvalue = myObj.getAttribute('defvalue');
      if( myObj.getAttribute('example') != null )
        this.example = myObj.getAttribute('example');
      if( myObj.getAttribute('numallow') != null )
        this.numallow = myObj.getAttribute('numallow');
      if( myObj.getAttribute('numrequire') != null )
        this.numrequire = myObj.getAttribute('numrequire');
      if( myObj.getAttribute('validate') != null )
        this.validate = myObj.getAttribute('validate');
      if( myObj.getAttribute('validate_replace') != null )
        this.validate_replace = myObj.getAttribute('validate_replace');
      if( myObj.getAttribute('validate_msg') != null )
        this.validate_msg = myObj.getAttribute('validate_msg');
      if( myObj.getAttribute('filter') != null )
        this.filter = myObj.getAttribute('filter');
      if( myObj.getAttribute('filter_replace') != null )
        this.filter_replace = myObj.getAttribute('filter_replace');
      if( myObj.getAttribute('filter_msg') != null )
        this.filter_msg = myObj.getAttribute('filter_msg');
    };
  };
};