/*
 * Javascript for Eons Forms
 *
 *
 *
 *
 */

/* Trim - remove leading and trailing whitespace.
 */
function old_trim(str)
{  while(str.charAt(0) == (" ") )
  {  str = str.substring(1);
  }
  while(str.charAt(str.length-1) == " " )
  {  str = str.substring(0,str.length-1);
  }
  return str;
}
/* isBlank - return true for null, empty or whitespace strings
 */
function isBlank(str) {
  if (str == null || str == "") { return true; }
  if (Trim(str) == "") { return true; }
  return false
}

/* TODO - Add these methods to String class.
 * String.prototype.trim = function(value) { body of trim }
 */
function Truncate(len, id) {
var p = document.getElementById('truncateMe');
if (p) {

  var trunc = p.innerHTML;
  if (trunc.length> len) {

    /* Truncate the content of the P, then go back to the end of the
       previous word to ensure that we don't truncate in the middle of
       a word */
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/\w+$/, '');

    /* Add an ellipses to the end and make it a link that expands
       the paragraph back to its original size */
    trunc += '<a href="#" ' +
      'onclick="this.parentNode.innerHTML=' +
      'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
      '...<\/a>';
    p.innerHTML = trunc;
  }
}
}

// Removes leading whitespaces
function LTrim( value ) {

        var re = /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim( value ) {

        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function Trim( value ) {

        return LTrim(RTrim(value));

}

/*
 *  FormUtil - class with a set or methods used for forms.
 */

// Create a FormUtil instance
var FormUtil = new Object;

/*
 * FormUtil.init_form - Initialize all form event handlers.
 *
 *  Call when the window is loaded.
 *  Usage: Event.observe(window, 'load', FormUtil.init_form, false);
 *
 * TODO: Create FormUtil method with prototype.
 *  function FormUtil( arg1, arg2){
 *   this.property = arg1
 *   this.created_at = new Date
 * ...
 * }
 *  FormUtil.prototype.init_form = function() {...}
 */
FormUtil.init_form =  function(){
  // get all the forms
  var forms_ = $A(document.getElementsByTagName('form'))

  // Set all forms to invoke FormUtil.handleSubmit on the submit event.
  forms_.findAll(function(form){ Event.observe(form, 'submit', FormUtil.handleSubmit, false ); })

}
  FormUtil.submitForm = function(submitForm) {
       try{
         //         debugger;
         //alert("foobar");
         var form_ = $(submitForm);

         form_.submit();
         return true;
       }catch(e){
         alert("Error submitting form, msg = "+ e.message);
       }
  }

  /* FormUtil.getFormInputs - get all the forms name/values pairs.
   * return empty string if the form doesn't have an id
   */
    FormUtil.getFormInputs = function(form){
		return Form.serialize(form);
  }
		
      FormUtil.submitAllForms = function(submitFormId, parameters) {
    try{

      // disable the form
      Form.disable(submitFormId)
      var params = FormUtil.getAllFormParameters();

      if ( !isBlank( parameters)) {
        params = params + parameters;
      }

      var formToSubmit = $(submitFormId);
    //    alert ( "action = " + formToSubmit.action);
    //     formToSubmit.action =  '?' + params;
    //    debugger;
    //    formToSubmit.submit();
    var url = formToSubmit.action;
	if (submitFormId == "service-form") {
		params = params + "&form=done"
	}
	if (submitFormId == "location-form") {
		params = params + "&form=done"
	}
//alert("within FormUtil.submitAllForms, form " + submitFormId + " params " + params + "  url:" + url)
        var myAjax = new Ajax.Request( url, {  method: 'post',   postBody: params,  asynchronous: true,  onFailure: FormUtil.getResponse,    onException: FormUtil.getResponse,
          onComplete: FormUtil.getResponse,
          on302: FormUtil.doRedirect
            }
        );
    // goto next
    //  document.location=request.getResponseHeader('location');
    }catch(e){
      alert("Fatal Error in obits_form.js: submitAllForms, exception = "+ e.message);
    }

  }
    FormUtil.doRedirect = function(response) {
      //      debugger;
      //      document.location=response.getResponseHeader('location');
      // alert("get redirect handler" +  response.responseText);
      //      alert(" response headers = " + response.getAllResponseHeaders());
    }
    FormUtil.getResponse = function(response){

      //      debugger;
      //      alert("get to the response handler" +  response.responseText);
      //      alert(" response headers = " + response.getAllResponseHeaders());
    }
  FormUtil.getAllFormParameters = function() {
    try{
      // get all the forms
      var forms_ = $A(document.getElementsByTagName('form'));
      var  submitStr = ""
      // Set all forms to invoke FormUtil.handleSubmit on the submit event.
      for( var i =0; i< forms_.length; i++){
        var form = forms_[i];
        //debugger;
        var tmp = FormUtil.getFormInputs(form) + "&";
        //debugger;
        if(!isBlank(tmp)){
          submitStr = submitStr + tmp;
        }
      }
    }catch(e){
      alert("Fatal Error in obits_form.js, exception = "+ e.message);
    }
    return submitStr;
  }
/*
 * FormUtil.handleSubmit - handle form submit event
 *
 * Validate the form. Stop submission if validation fails.
 */
  FormUtil.handleSubmit = function(e){
    try {
      //      debugger;
      // get the form/element that invoked this event
    element= Event.element(e);

    // validate the form
    var validateOK = FormUtil.validateForm(element);

    // stop submission if validation failed
    if ( !validateOK) { Event.stop(e); }
    return validateOK;
    }catch(e){
      alert("Fatal Error in obits_form.js, exception = "+ e.message);
      return false;
    }
  }

  /*
   * FormUtil.validateForm
   *
   * Validate the form.
   */
    FormUtil.validateForm = function(form){
      // get all the form elements
      elArray = $A(form.elements);

      var validationSuccess = true;
      elArray.each( function(el) {  if(!FormUtil.validateField(el)) { validationSuccess = false; } } );
      return validationSuccess;
    }

    /*
     * FormUtil.validateField
     *
     * Validate the form field.
     */
      FormUtil.validateField = function(field){
//        var emailPattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/;
		var emailPattern = /^([^@\s]+)@((?:[\w-]+\.)+[a-zA-Z]{2,})$/
//		var emailPattern = /^([\w-]+((?:\+[\w-]+)*)+((?:\.[\w-]+)*))@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
        var fullnameRegxp = /^([a-zA-Z\s\.\-']+)$/; // first and last names
        var unameRegxp = /^([a-zA-Z\s\.]+)$/; // userName
        var stnameRegxp = /^([a-zA-Z0-9',\s\.]+)$/; // Store Name (allows apostrophes, commas, numerals, spaces and periods)
        var houseRegxp = /^([0-9A-Za-z]+)$/; // House address
        var pcodeRegxp = /^([A-Za-z]{1,2})([0-9]{2,3})([A-Za-z]{2})$/; // british postal code
        var telnoRegxp = /^([0-9]{11})$/; // phone number, real dumb
        var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // email
        var urlRegxp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
        var dateRegxp = /^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-)([0-9]){4}$/; // dob 09-3-1977

        //        debugger;

		// RJM 11/08/06: Revamped all error messages

        if(  /(^| )checkRequired( |$)/.test(field.className)) {
	      if (field.type == "checkbox" && !field.checked) {
            FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": This box must be checked" );
            field.focus();
            return false;
	      }
	      else if (field.value == "") {
            FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": This field is required" );
            field.focus();
            return false;
          }
        }

        //    if($(field).value == "" ) { alert("Is empty");}else { alert("Not empty"); }

        // ignore empty fields, they must not have been required, made it past above check
        if( $(field).value == "" ) {
          //   alert("empty field id = ", field.id);
          // validation ok, remove error message if any
          FormUtil.removeErrorMsg(field);
          return true;
        }

        if(  /(^| )checkEmail( |$)/.test(field.className)  &&  !emailPattern.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": " + field.value + " is not a valid Email address");
          field.focus();
          return false;
        }

		if(  /(^| )checkIsEqual( |$)/.test(field.className)  &&  $('email').value != field.value ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": Entered emails do not match");
          field.focus();
          return false;
        }

        if(  /(^| )checkName( |$)/.test(field.className)  &&  !unameRegxp.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": " + field.value + " contains non-alphabetic characters");
          field.focus();
          return false;
        }
        
        if(  /(^| )checkFullname( |$)/.test(field.className)  &&  !fullnameRegxp.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": " + field.value + " contains non-alphabetic characters");
          field.focus();
          return false;
        }
        
        if(  /(^| )checkStoreName( |$)/.test(field.className)  &&  !stnameRegxp.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": " + field.value + " contains invalid characters");
          field.focus();
          return false;
        }
        
        if(  /(^| )checkURL( |$)/.test(field.className)  &&  !urlRegxp.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": " + field.value + " is not a valid web address");
          field.focus();
          return false;
        }
        if(  /(^| )checkDate( |$)/.test(field.className)  &&  !dateRegxp.test(field.value) ) {
          FormUtil.showErrorMsg(field, FormUtil.getFieldLabel(field) + ": Please use the format mm-dd-yyyy or mm/dd/yyyy");
          field.focus();
          return false;
        }

        // validation ok, remove error message if any
        FormUtil.removeErrorMsg(field);

        return true;
      }

        FormUtil.getFieldLabel = function(field) {
          var fieldlabel;
          //           debugger;
          try {
            var span = $(field.id + "_label");
			// RJM 11/08/06: change from innerHTML to textContent
			// The 2nd time through, span includes the (exclamation point) img - we want only the text.
            // UGH: span.textContent works in mozilla, but not in IE
			var chillin = span.childNodes;
			var i = 0;
			while (chillin[i].nodeType != 3 && i < chillin.length) i++;
			if(i<chillin.length) fieldlabel=chillin[i].nodeValue;
			else fieldlabel=field.id;
          }catch(exception){
            alert("no field label for field with id = " + field.id);
            fieldlabel =""
          }

          return fieldlabel;
        }

    /*
       * FormUtil.removeErrorMsg
       *
       * remove the error msg if it exists
       */
        FormUtil.removeErrorMsg = function(field) {
          errid = "error_id_"+field.id;
          if( $(errid) != null){
            Element.remove(errid);
          }
          errid = "error_id_"+field.id+"2";
          if( $(errid) != null){
			// RJM 10/26/06: remove class that was added in showErrorMsg
			var div = $(errid).parentNode.parentNode.parentNode;
			if(div != null){
			  //alert("class name = " + div.className);
			  div.className = div.className.replace(' haserror','');
			  //alert("class name = " + div.className);
			}
            Element.remove(errid);
          }
        }
        /*
         * FormUtil.showErrorMsg
         *
         * Create an error message if one doesn't exist.
         */
        /*
        FormUtil.showErrorMsg = function(field, msg){
               errid = "error_id_"+field.id;
               if($(errid) == null){
                 new Insertion.After(field.id, "<span id='"+ errid + "' class ='errMsg'>" + msg + "</span>");
            }

          }
        */
		FormUtil.showErrorMsg = function(field, msg){

        	// check if an eons errror area exists
			if($('eons_errors') == null){
				// generate an eons error area
				// RJM 10/26/06: changes to make this consistent with the rest of the site
				// error message should be inserted just inside div#jscript_errors
				new Insertion.Before( $('jscript_errors').firstChild,  '<div class="error msg" id="eons_errors"><h1>Sorry, there was a problem with some of the information you entered:</h1><p>There were problems with the following fields:</p><ul id="eons_error_list"></ul></div>')
			}

			// alert("show Error msg for id = " + field.id);
			errid = "error_id_"+field.id;
			if($(errid) == null){
				// RJM 10/26/06: changes to make this consistent with the rest of the site
				// add error to list
				new Insertion.Bottom( $('eons_error_list'), "<li id='"+ errid + "' class ='errMsg'>" + msg + "</li>");
				// insert img INSIDE the span that contains the field label text, before the text
				//i.e. insert before first child of the span element with id==FIELDNAME_label
				//  class='fielderrormarker' should not be necessary -- not sure
				try {
					var span = $(field.id + "_label");
					fieldlabel  = span.innerHTML;
				}catch(exception){
					alert("span label missing for field with id = " + field.id);
				}
				try {
					new Insertion.Top(span, "<img id='"+ errid + "2' src='/glb/g/fielderror.gif' title='there is an error with this field' alt='there is an error with this field'/>");
					// RJM 10/26/06 - need to set class 'haserror' on div.fieldwrapper parent
					// assume span is inside a label which is inside a fieldwrapper div
				}catch(exception){
					alert("image insert failed for " + errid);
				}
				try {
					span.parentNode.parentNode.className += ' haserror';
				}catch(exception){
					alert("error setting haserror on " + errid);
				}
				// and set class fieldWithErrors on a div that contains only the input field.
				// TODO....
            }
			else {
				// RJM 11/08/06: replace text of list item element with new msg
				$(errid).innerHTML = msg;
			}
		}
          /*
           * Just a bunch of Prototype form functions. Not used,yet
           */
            FormUtil.submit= function(form){
              // disables the form making all elements read only
              Form.disable(form)

              // clears values from all form elements
              Form.reset(form)
              // returns an array of all form fields in the form
              Form.getElements(form).findAll( function(element) { alert(element.value) })
              // focuses on the first form field
              Form.focusFirstElement(form)
              // enables a form again
              Form.enable(form)
              /*
              // Get all the element of this form and iterate thu them
              all_elements = Form.getElements(element);
              // show me the id/value for each form element
              all_elements.findAll( function(e) { alert("element id = "+ e.id + " value = " + e.value) })
              // show me what the serialize form looks like
              alert("Form serialized = " + Form.serialize(element))
              */
            }



            /*
             *  TextUtil -
             */
              var TextUtil = new Object;
/*
 *  TextUtil.isNotMax - Enables maxsize for textarea.
 *  If text length > maxsize then return false which wil prevent char addition
 *  Usage: <textarea rows="10" cols="25" maxlength="150"
 *             onkeypress="return TextUtil.isNotMax(this)"> </textarea>
 */

TextUtil.isNotMax = function(oTextArea) {
  return oTextArea.value.length != oTextArea.getAttribute('maxlength')
}


/*
 * TextUtil.blockChars - Block illegal chars in a text box/field.
 * If 2nd arg true then don't allow paste, ctrl-v
 * Usage: <input type="text" onkeypress="return TextUtil.blockChars(event, true)" invalidchars="0123456789" />
 */
  TextUtil.blockChars = function(oEvent, bBlockPaste)  {
    var oTextbox = Event.element(oEvent); // get the element that generated  this event
    var sInvalidChars = oTextbox.getAttribute('invalidchars')
    var sChar = String.fromCharCode(oEvent.charCode)

    var bIsValidChar = sInvalidChars.indexOf(sChar) == -1;
    if(bBlockPaste){
      return bIsValidChar && !(oEvent.ctrlKey && sChar == 'v')
        }else{
      return bIsValidChar || oEvent.ctrlKey;
    }

  }

  /*
   * TextUtil.allowChars - Only allow these chars in a text box/field
   * If 2nd arg true then don't allow paste, ctrl-v
   * Usage: <input type="text" onkeypress="return TextUtil.allowChars(event,false)" invalidchars="0123456789" />
   */
    TextUtil.allowChars = function(oEvent, bBlockPaste) {
      var oTextbox = Event.element(oEvent); // get the element that generated  this event

      var sValidChars = oTextbox.getAttribute('validchars')
      var sChar = String.fromCharCode(oEvent.charCode)
      var bIsValidChar = sValidChars.indexOf(sChar) > -1
      // problem with delete/tab/... characters.
      if( sChar == '\b' || sChar == '\t') { return sChar; }


      if(bBlockPaste){
        return bIsValidChar && !(oEvent.ctrlKey && sChar == 'v')
      }else{
        return bIsValidChar || oEvent.ctrlKey;
      }

    }
/*
 * TextUtil.blurBlock - Only allow these chars in a text box/field on a blur event
 * If 2nd arg true then don't allow paste, ctrl-v
 * Usage: <input type="text" onkeypress="return TextUtil.blockChars(event)" invalidchars="0123456789"
 * onblur="TextUtil.blurBlock(this)" />
 */
TextUtil.blurBlock = function(oTextbox){
  var sInvalidChars = oTextbox.getAttribute("invalidchars");
  var arrInvalidChars = $A(sInvalidChars.split(""));

  for(var i=0; i < arrInvalidChars.length; i++){
    if (oTextbox.value.indexOf(arrInvalidChars[i]) > -1){
      //      alert("Character '" + arrInvalidChars[i] + "' not allowed.");
      oTextbox.focus();
      oTextbox.select();
      return;
    }
  }
  // TODO: do above with Prototype
  //        arrInvalidChars.each( function(c) { if(oTextbox. })
}
