/*******************************************************************************
*
* © 2008 Copyright A-Vision
*
* File description :       Form verification functions FORM.JS
* 
* Created by       :       Arnold Velzel
* Created on       :       15/12/2008
*
* Last changed by  :       Arnold Velzel
* Last changed on  :       <LastChanged>
* 
*******************************************************************************/

function setShadowField( fld)
{
 var shadowField = document.createElement('div');
 shadowField.style.position = "absolute";
 shadowField.style.top = "0px";
 shadowField.style.left = "0px";
 shadowField.style.zIndex = 1;
 shadowField.style.cursor = "text";
 shadowField.parentField = fld;
 var i = document.createElement(fld.nodeName);
// i.style.paddingLeft = "22px";
 i.style.border = '0px solid transparent';
 i.style.padding = '2px';
 i.style.paddingLeft = '3px';
 i.readOnly = true;
 i.tabIndex = -1;
 i.disabled = true;
	shadowField.appendChild(i);

 iw = fld.offsetWidth;
 ih = fld.offsetHeight;

	var clone1 = shadowField.cloneNode(true);
 clone1.style.width = eval(iw) + "px";
 inp = clone1.getElementsByTagName(fld.nodeName)[0];
 inp.className = fld.className+" shadowfield noprint";
 inp.style.width = eval(iw-4) + "px";
 inp.style.height = eval(ih-4) + "px";
 inp.style.backgroundColor = "#fff";
 clone1.onclick = function() {
  this.parentField.focus();
 }
// if ( fld.getAttribute('default')) {
//  inp.value = fld.getAttribute('default');
// }

 fld.parentNode.style.position = "relative";
	fld.style.position = "relative";
 fld.style.zIndex = 2;
 fld.style.backgroundColor = "transparent";
	fld.parentNode.appendChild( clone1);
 return( clone1.getElementsByTagName(fld.nodeName)[0]);
}

function findValue( fld)
{
 if ( !fld) return;
 SQL = fld.getAttribute('searchSQL');
 SQL = SQL.replace( 'FINDVALUE', fld.value);
 url = "includes/searchdatabase.php?random="+Math.random()+"&SQL="+escape(SQL);
// alert(url);

 if ( fld.value != "") {
  getServerHtmlData( url, fld.shadowField, function() { window.setTimeout("copyFoundData( "+fld.id+")",10); });
 }
}
function copyFoundData( fldID)
{
 fld = document.getElementById( fldID);
 if ( fld) {
  l = fld.value.length;
	if ( l && fld.shadowField.value.length) {
   fld.value = fld.shadowField.value.substr(0,l);
	}
 }
}

function initAutofillFields(fieldtype) {
//	if (!W3CDOM) return;

 ie = ( navigator.userAgent.toUpperCase().indexOf("MSIE") >= 0);

	var x;
 if ( !fieldtype) fieldtype = "input";
 x = document.getElementsByTagName(fieldtype);
	for (var i=0;i<x.length;i++) {

		if (x[i].type != 'text') continue;
		if (x[i].getAttribute('autofill') != 'yes') continue;
		if (!x[i].getAttribute('search') && !x[i].getAttribute('searchSQL')) continue;

  if (x[i].getAttribute('fill')) {
   fills = x[i].getAttribute('fill').split(",");
   if ( fills.length) {
    for (f=0;f<fills.length;f++) {
     fill = fills[f].split(".");
     fld = x[i].form.elements[ "details["+fill[fill.length-1]+"]"];
     if ( fld) {
      fld.setAttribute('search',x[i].getAttribute('search'));
      fld.setAttribute('return',fills[f]);
      fld.shadowField = setShadowField( fld);
     }
    }
   }
  }

  x[i].shadowField = setShadowField( x[i]);
		x[i].onkeydown = function (e) {
    if ( !e) e = window.event;
    ie = ( navigator.userAgent.toUpperCase().indexOf("MSIE") >= 0);
    fillvalues = false;
    if ((trim(this.value)!="") && (e.type == 'keydown') && (( e.keyCode == 13) || ( e.keyCode == 9))) {
     // Check if the entered value is the same as the found part
     if ( this.shadowField.value.substr( 0, this.value.length).toLowerCase() == this.value.toLowerCase()) {
      fillvalues = true;
      if ( ie) {
       e.keyCode = 9;
      }
     }
    } else {
     if (this.getAttribute('default') && ( this.shadowField.value == "") && (e.type == 'keydown') && (( e.keyCode == 13) || ( e.keyCode == 9))) {
      // Check if there's a default parameter set to be used to fill in the shadow field on entering the field
      this.shadowField.value = this.getAttribute('default');
      fillvalues = true;
      if ( ie) {
       e.keyCode = 9;
      }
     }
    }

    this.id = Math.random(); // Generate a (hopefully) unique ID to refer to
    this.setAttribute('find',this.value);
    if ( fillvalues) {
     this.value = this.shadowField.value;
     this.shadowField.value = "";
     if ( this.getAttribute('furtherfunction')) {
      if ( ie) {
       eval( this.furtherfunction);
      } else {
       eval(this.getAttribute('furtherfunction'));
      }
     }
    } else {
     window.setTimeout("findValue( document.getElementById('"+this.id+"'));",250);
    }
    if (this.getAttribute('fill')) {
     fills = this.getAttribute('fill').split(",");
     if ( fills.length) {
      for (f=0;f<fills.length;f++) {
       fill = fills[f].split(".");
       fld = this.form.elements[ "details["+fill[fill.length-1]+"]"];
       if ( fld) {
        fld.id = Math.random(); // Generate a (hopefully) unique ID to refer to
        fld.setAttribute('find',this.value);
        if ( trim(fld.value)=="") {
         if ( fillvalues) {
          fld.value = fld.shadowField.value;
          fld.shadowField.value = "";
         } else {
          window.setTimeout("findValue( document.getElementById('"+fld.id+"'));",250);
         }
        }
       }
      }
     }
    }
    return( true);
		}
   
//   x[i].onkeyup = x[i].onkeydown;
	}
 if( fieldtype == "input") initAutofillFields("textarea");
}


function lockField( fld)
{
 if ( !fld.getAttribute("locked")) {
  fld.setAttribute("locked",true)
  fld.readonly = true;
  fld.style.backgroundColor = "rgb(255,191,127)";
 }
}

function releaseField( fld, restore)
{
 db = document.getElementById("debugErrorData")
 if ( db) {
  if(document.all){
   errorText = db.innerText;
  } else{
   errorText = db.textContent;
  }
  if ( trim(errorText) != "") {
   if ( errorText.indexOf("ERROR") >= 0) {
    restore = true;
   }
   if(document.all){
    db.innerText = "";
   } else{
    db.textContent = "";
   }
   alert( errorText);
  }
 }

 if ( restore) {
  if( fld.defaultValue) {
   fld.value = fld.defaultValue;
  }
  fld.focus();
  if ( fld.select) {
   fld.select();
  }
 } else {
  if ( fld.value) {
   fld.defaultValue = fld.value;
  }
  if ( typeof(updateLastChanged)=='function') {
   updateLastChanged();
  }
 }

 if ( fld.getAttribute("locked")) {
  fld.setAttribute("locked",false)
  fld.style.backgroundColor = fld.getAttribute("BGC");
 }
}

function instantSave(fld, anyfurther)
{
 // AVE :: Added to allow pre-submitting validation 
 if ( fld.getAttribute( "f_validation")) {
  var validationFunction = fld.getAttribute( "f_validation");
  validationFunction = validationFunction.replace(/this/g, 'fld');
  if ( !eval( validationFunction)) {
   if ( fld.getAttribute( "f_validationInfo")) {
    alert( fld.getAttribute( "f_validationInfo"));
   } else {
    alert("Invalid field value.");
   }
   fld.focus();
   stopEvents();
   return(false);
  }
 }

 fld.setAttribute("BGC", fld.style.backgroundColor);
 lockField(fld);

 fldtype = fld.getAttribute("type");
 if ( !fldtype) fldtype = fld.type;
 if ( fldtype.toLowerCase()=="date") {
  if ( !isDate( fld)) {
   alert("Invalid date entered.");
   return( false);
  }
 }

 if ( fld.getAttribute("instantsaveurl")) {
  url = fld.getAttribute("instantsaveurl");
 } else {
  url = "includes/instantsave.php";
 }
 url += "?random="+Math.random();
 if ( fld.getAttribute("dbtable")) {
  url += "&dbtable="+encodeURIComponent(fld.getAttribute("dbtable"));
 } else {
  frm = fld.form;
  if ( frm) {
   fldtblname = frm.elements["dbtable"];
   url += "&dbtable="+encodeURIComponent(fldtblname.value);
  }
 }
 fldname = fld.name;
 if ( !fldname) fldname = fld.getAttribute("name");
 if ( fldname) {
  url += "&tbfield="+encodeURIComponent(fldname);
 }
 fldvalue = fld.value;
 if ( !fld.value) fldvalue = fld.getAttribute("value");
 if ( !fld.value) fldvalue = "";

 if ( fldtype.toLowerCase()=="date") {
  // change to database date format
  var aDate = fldvalue.split( "/");
  fldvalue = aDate[2]+"-"+aDate[1]+"-"+aDate[0];
 }
 url += "&fldvalue="+encodeURIComponent(fldvalue);
 if ( fld.getAttribute("validation")) {
  url += "&validation="+encodeURIComponent(fld.getAttribute("validation"));
 }

 if ( typeof(fld.getAttribute("indexname"))=='string' && typeof(fld.getAttribute("indexvalue"))=='string') {
  url += "&idxfldname="+encodeURIComponent(fld.getAttribute("indexname"));
  url += "&idxfldvalue="+encodeURIComponent(fld.getAttribute("indexvalue"));
 } else {
  frm = fld.form;
  if ( frm) {
   fldinxname = frm.elements["indexname"];
   if ( fldinxname) {
    inxname = fldinxname.getAttribute("value");
    if ( inxname) {
     url += "&idxfldname="+encodeURIComponent(inxname);
    }
   }
   fldinxvalue = frm.elements["indexvalue"];
   if ( fldinxvalue) {
    inxvalue = fldinxvalue.getAttribute("value");
    if ( inxvalue) {
     url += "&idxfldvalue="+encodeURIComponent(inxvalue);
    }
   }
  }
 }
 var special = fld.getAttribute("dbspecial");
 if ( special) url += "&dbspecial="+encodeURIComponent(special);

 getServerHtml( url, document.getElementById("debugErrorData"), function( blk) { 
  if ( anyfurther) {
   anyfurther();
  }
  releaseField(fld, false);
 }, function() { releaseField(fld, true); });
 return( true);
}

function setInstantSaves(blk)
{
 if ( !blk) blk = document.body;
 var inputs = blk.getElementsByTagName('INPUT');
 for (var i=0;i<inputs.length;i++) {
  if ( inputs[i].getAttribute('instantsave')) {
   if (( inputs[i].getAttribute("type")=="checkbox") || ( inputs[i].getAttribute("type")=="radio")) {
    alreadyset = false;
    if ( inputs[i].onclick) {
     alreadyset = ( inputs[i].onclick.toString().indexOf("instantSave") >= 0);
    }
    if ( !alreadyset) {
     if ( inputs[i].onclick) inputs[i]._onclick = inputs[i].onclick;
     inputs[i].onclick = function() {
      if ( !this._onclick || (this._onclick && this._onclick())) {
       if ( this.getAttribute("type")=="checkbox") {
        this.value = this.checked?1:0;
       }
       if ( this.parentNode) this.parentNode.setAttribute("recentlychanged","yes");
       return instantSave(this);
      } else {
       return( false);
      }
     }
    }
   } else {
    if ( inputs[i].onchange) {
     var oc = inputs[i].onchange.toString();
     if ( oc.indexOf("instantSave") < 0) inputs[i]._onchange = inputs[i].onchange;
    }
    inputs[i].onchange = function() {
     if ( this.parentNode) this.parentNode.setAttribute("recentlychanged","yes");
     if ( this._onchange) this._onchange();
     return instantSave(this);
    }
   }
  }
 }

 var inputs = document.getElementsByTagName('TEXTAREA');
 for (var i=0;i<inputs.length;i++) {
  if ( inputs[i].getAttribute('instantsave')) {
   if ( inputs[i].onchange) {
    var oc = inputs[i].onchange.toString();
    if ( oc.indexOf("instantSave") < 0) inputs[i]._onchange = inputs[i].onchange;
   }
   inputs[i].onchange = function() {
    if ( this.parentNode) this.parentNode.setAttribute("recentlychanged","yes");
    if ( this._onchange) this._onchange();
    return instantSave(this);
   }
  }
 }

 var inputs = document.getElementsByTagName('SELECT');
 for (var i=0;i<inputs.length;i++) {
  if ( inputs[i].getAttribute('instantsave')) {
   if ( inputs[i].onchange) {
    var oc = inputs[i].onchange.toString();
    if ( oc.indexOf("instantSave") < 0) inputs[i]._onchange = inputs[i].onchange;
   }
   inputs[i].onchange = function() {
    if ( this.parentNode) this.parentNode.setAttribute("recentlychanged","yes");
    if ( this._onchange) this._onchange();
    return instantSave(this);
   }
  }
 }
}

function setTextareaLimits( blk)
{
 var TAs = null;
 var TA = null;
 if ( blk && (typeof(blk)=="object")) {
  TAs = blk.getElementsByTagName("TEXTAREA");
 } else {
  TAs = document.getElementsByTagName("TEXTAREA");
 }
 for (var t=0;t<TAs.length;t++) {
  TA = TAs[t];
  if ( TA.getAttribute("maxlength") && (TA.getAttribute("maxlength")>0)) {
   TA.onkeydown = function(e) {
    if ( !e) e = window.event;
    if ( this.oldBorder && ( this.value.length < this.getAttribute("maxlength"))) {
     this.style.border = this.oldBorder;
     this.oldBorder = null;
    } else {
     if ( this.value.length >= this.getAttribute("maxlength")) {
      if ( this.oldBorder) {
      } else {
       this.oldBorder = this.style.border;
       this.style.border = "1px solid #c00";
      }
     }
    }
    if ( e.keyCode == 8) return( true);
    if ( e.keyCode == 46) return( true);
    if ( e.ctrlKey) return( true);
    if ( this.value.length >= this.getAttribute("maxlength")) {
     if ( this.oldBorder) {
     } else {
      this.oldBorder = this.style.border;
      this.style.border = "1px solid #c00";
     }
     return( false);
    }
   }
  }
 }
}

function setReadOnlyInputEdits( blk)
{
 if ( !blk) blk = document.body;
 var inputs = blk.getElementsByTagName("INPUT");
 for ( var i=0;i<inputs.length;i++) {
  if ( inputs[i].getAttribute("readonly") && (inputs[i].className.indexOf("editable")>=0)) {
   inputs[i].onclick = function( evt) {
    if ( !evt) evt = window.event;
    if ( this.readOnly) this.blur();
    stopEvents(evt);
   }
   inputs[i].onmousedown = function( evt) {
    if ( !evt) evt = window.event;
    if ( mouseOffsetX( evt)<20) {
      this.readOnly=false;
      this.select();
      this.oldValue = this.value;
      stopEvents(evt);
    }
   };
   inputs[i].onblur = function( evt) {
    if ( !evt) evt = window.event;
    this.readOnly = true;
   };
   inputs[i].onkeyup = function( evt) {
    if ( !evt) evt = window.event;
    if ( evt && (evt.keyCode==13)) this.blur();
   };
  }
 }
}

function validateField( fld, includehidden)
{
 if ( typeof(includehidden)=="undefined") includehidden=false;
 var valid = true;

 if ( typeof(fld.getAttribute("required"))=="string") {
  if ( fld.value.trim() == "") {
   try {
    fld.focus();
    valid = false;
   }
   catch (e) {
    valid = !includehidden;
   }
   return( valid);
  }
 }

 return( valid);
}

function validateForm( frm)
{
 var valid = true;
 if ( frm.nodeName == "FORM") {
  for ( f=0;f<frm.elements.length;f++) {
   elm = frm.elements[f];
   if ( !validateField( elm)) {
    
    var strname = elm.getAttribute("strname");
    if ( !strname) strname = name;
    alert( "The field '"+strname+"' is required.");
    return(false);
   }
   valid &= validateField( elm);
  }
 }
 return( valid);
}

function findForm( elm)
{
 // Find a form within the given element
 // If not found, then try to go parenting until a form object has been found
 // If nothing found in the body, return( false)
 var frms = elm.getElementsByTagName("FORM");
 if ( frms && frms.length) {
  return( frms[0]);
 }

 while (( elm.nodeName != "FORM") && ( elm.nodeName != "BODY")) {
  frms = elm.getElementsByTagName("FORM");
  if ( frms && frms.length) {
   return( frms[0]);
  }
  elm = elm.parentNode;
 }

 if ( elm.nodeName == "FORM") {
  return( elm);
 }

 var forms = document.getElementsByTagName("FORM");
 if ( forms && forms.length) {
  return( forms[0]);
 }

 return( false);
}

