String.prototype.trim = function()
{ 
  //return this.replace(/^\s+|\s+$/g, '');
  return this.replace(/^\s+/,'').replace(/\s+$/,'');
};

String.prototype.ucfirst = function()
{
  //var firstLetter = this.substr(0,1).toUpperCase();
  return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
}

String.prototype.ucwords = function()
{
  return this.toLowerCase().replace(/\w+/g,function(s)
  {
    return s.charAt(0).toUpperCase() + s.substr(1);
  })
}

var formFocusHighlight = function()
{
	var fields = $$('.textfield'); // kan ook: $S('#myForm .field') als je meer specifiek wilt zijn
	for (var i=0; i<fields.length; i++)
  {
		if (fields[i].type == 'radio' || fields[i].type == 'checkbox')
    {
      fields[i].onfocus = function()
      {
        $(this.parentNode).addClass('highlight');
      };
      fields[i].onblur = function()
      {
        $(this.parentNode).removeClass('highlight');
      };
		} else
    {
      //type == 'text' etc.
      fields[i].onfocus = function()
      {
        $(this.parentNode).addClass('highlight');
      };
      fields[i].onblur = function()
      {
        $(this.parentNode).removeClass('highlight');
        $(this).value = $(this).value.trim();
      };
		}
	}
}


var validateForm = {
  init: function(whichForm)
  {
    form = whichForm;
    fields = $(form).getElements('input'); //get all input's and put in 'fields' array
    fields.extend($(form).getElements('textarea')); //get all textarea's and add to 'fields' array

    if (!$('required'))
    {
      return true;
    }
    reqFields = $('required').value.split(','); //moet eigenlijk nog (alleen) binnen het form kijken naar deze id

    errorheaderId = 'errorheader';
    errorMsgClass = 'errormsg';
    errorImg = 'images/icons/arrowPointer.gif';
    errorImgAlt = 'Error';

    if ($('validatelanguage').value == 'nl')
    {
      errorheaderMsg = '* Corrigeer a.u.b. de gemarkeerde velden, bedankt.';
      errorMsgRequired = 'Dit veld is verplicht.';
      errorMsgEmail = 'Dit e-mailadres is onjuist.'
      errorImgTitle = 'Dit veld bevat een fout';
    } else
    {
      errorheaderMsg = '* Please correct the marked fields. Thank you.';
      errorMsgRequired = 'This field is required.';
      errorMsgEmail = 'This e-mail address is not correct.'
      errorImgTitle = 'This field has an error';
    }

    allFieldsValidate = false;
    validateForm.addValidation();
  },

  addValidation: function()
  {
    fields.each(function(elm)
    {
      elm.addEvent('blur', function()
      {
        if (this.hasClass('validate-blur'))
        {
          validateForm.field(this);
        }
      });
    });
  },

  allFields: function()
  {
    //clean up possible earlier checks
    if ($(errorheaderId))
    {
      $(errorheaderId).remove();
    }
    //start check
    allFieldsValidate = true;
    fields.each(function(elm)
    {
      if (elm.id != 'required')
      {
        validateForm.field(elm);
      }
    });
    allFieldsValidate = false;
    if (!$(errorheaderId))
    {
      return true;
    } else
    {
			return false;
    }
  },

  field: function(elm)
  {
    validateForm.clearError(elm);
    if (elm.getTag() == 'textarea')
    {
      if (elm.value == '' && reqFields.test(elm.id))
      {
        validateForm.addError(elm,'required');
      }
    } else
    {
      switch (elm.type.toLowerCase())
      {
        case 'text':
        case 'password':
        case 'textarea':
          if ((elm.value == '' && reqFields.test(elm.id)) && (elm.id != 'emailaddress'))
          {
            validateForm.addError(elm,'required');
          } else if (elm.id == 'emailaddress' && !validateForm.isEmailAddress(elm.value))
          {
            validateForm.addError(elm,'emailaddress');
          }
          break;
        case 'checkbox':
          if (!elm.checked && reqFields.test(elm.id))
          {
            validateForm.addError(elm);
          }
          break;
        case 'select-one':
          if (!elm.selectedIndex && elm.selectedIndex == 0)
          {
            validateForm.addError(elm);
          }
          break;
      }
    }
  },

  addError: function(elm,type)
  {
    if ((allFieldsValidate) && (!$(errorheaderId)))
    {
      //create error message and insert before submit button
      var header = new Element('div');
      $(header).setProperty('id', errorheaderId);
      $(header).setHTML(errorheaderMsg);
      if ($E('legend'))
      {
        $(header).injectAfter($E('legend'));
      } else
      {
        //there is no legend, use first block element
        $(header).addClass('alt');
        $(header).injectBefore($$('.block')[0]);
      }
    }

    //create error image
    var errorIndicatorImg = new Element('img');
    $(errorIndicatorImg).setProperties({
      src: errorImg,
      alt: errorImgAlt,
      title: errorImgTitle
    });
    $(errorIndicatorImg).addClass('left');

    //error container + text and image
    var errorIndicator = new Element('div');
    $(errorIndicator).addClass(errorMsgClass);
    $(errorIndicatorImg).injectInside(errorIndicator);
    if (type == 'emailaddress')
    {
      $(errorIndicator).appendText(errorMsgEmail);
    } else if (type == 'required')
    {
      $(errorIndicator).appendText(errorMsgRequired);
    }
    $(errorIndicator).injectAfter(elm);
  },

  clearError: function(elm)
  {
    if (elm.getNext() && elm.getNext().hasClass(errorMsgClass))
    {
      elm.getNext().remove();
    }
  },

  isEmailAddress: function(str)
  {
    return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
  }
};

var contactForm = {
  init: function(id)
  {
		$('formbutton').addEvent('click', contactForm.send);
		currentForm = 'contactform';
		contactForm.addValidation();
  },

  send: function()
  {
    if (!validateForm.allFields())
    {
      return;
    }
		
    var value = $(currentForm).toQueryString();	
		
    new Ajax('formhandler.php',
		{
		 postBody: value,
		 method: 'post',
     update: $('formcontainer')
    }).request();
  },

  addValidation: function()
  {
    validateForm.init(currentForm);
  }
};

var trainingaanmeldenForm = {
  init: function(id)
  {
		$('formbutton').addEvent('click', trainingaanmeldenForm.send);
		currentForm = 'trainingenaanmeldform';
		trainingaanmeldenForm.addValidation();
  },

  send: function()
  {
    if (!validateForm.allFields())
    {
      return;
    }
		
    var value = $(currentForm).toQueryString();	
		
    new Ajax('formhandler.php',
		{
		 postBody: value,
		 method: 'post',
     update: $('formcontainer')
    }).request();
  },

  addValidation: function()
  {
    validateForm.init(currentForm);
  }
};

var cursusaanmeldenForm = {
  init: function(id)
  {
		$('formbutton').addEvent('click', cursusaanmeldenForm.send);
		currentForm = 'cursussenaanmeldform';
		cursusaanmeldenForm.addValidation();
  },

  send: function()
  {
    if (!validateForm.allFields())
    {
      return;
    }
		
    var value = $(currentForm).toQueryString();	
		
    new Ajax('formhandler.php',
		{
		 postBody: value,
		 method: 'post',
     update: $('formcontainer')
    }).request();
  },

  addValidation: function()
  {
    validateForm.init(currentForm);
  }
};