/**
* @version		$Id: validate.js 7401 2007-05-14 04:12:55Z eddieajau $
* @package		Joomla
* @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

/**
 * Unobtrusive Form Validation library
 *
 * Inspired by: Chris Campbell <www.particletree.com>
 *
 * @package		Joomla.Framework
 * @subpackage	Forms
 * @since		1.5
 */
var JFormValidator = new Class({
	initialize: function()
	{
		// Initialize variables
		this.handlers	= Object();
		this.custom		= Object();

		// Default handlers
		this.setHandler('username',
			function (value) {
				regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
				return !regex.test(value);
			}
		);

		this.setHandler('password',
			function (value) {
				regex=/^\S[\S ]{2,98}\S$/;
				return regex.test(value);
			}
		);

		this.setHandler('numeric',
			function (value) {
				regex=/^(\d|-)?(\d|,)*\.?\d*$/;
				return regex.test(value);
			}
		);

		this.setHandler('email',
			function (value) {
				regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
				return regex.test(value);
			}
		);

		// Attach to forms with class 'form-validate'
		var forms = $$('form.form-validate');
		forms.each(function(form){ this.attachToForm(form); }, this);
	},

	setHandler: function(name, fn, en)
	{
		en = (en == '') ? true : en;
		this.handlers[name] = { enabled: en, exec: fn };
	},

	attachToForm: function(form)
	{
		// Iterate through the form object and attach the validate method to all input fields.
		$A(form.elements).each(function(el){
			el = $(el);
			if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') {
				if (el.hasClass('validate')) {
					el.onclick = function(){return document.formvalidator.isValid(this.form);};
				}
			} else {
				el.addEvent('blur', function(){return document.formvalidator.validate(this);});
			}
		});
	},

	validate: function(el)
	{
		// If the field is required make sure it has a value
		if ($(el).hasClass('required')) {
			if (!($(el).getValue())) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Only validate the field if the validate class is set
		var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
		if (handler == '') {
			this.handleResponse(true, el);
			return true;
		}

		// Check the additional validation types
		if ((handler) && (handler != 'none') && (this.handlers[handler]) && $(el).getValue()) {
			// Execute the validation handler and return result
			if (this.handlers[handler].exec($(el).getValue()) != true) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Return validation state
		this.handleResponse(true, el);
		return true;
	},

	isValid: function(form)
	{
		var valid = true;

		// Validate form fields
		for (var i=0;i < form.elements.length; i++) {
			if (this.validate(form.elements[i]) == false) {
				valid = false;
			}
		}

		// Run custom form validators if present
		$A(this.custom).each(function(validator){
			if (validator.exec() != true) {
				valid = false;
			}
		});

		return valid;
	},

	handleResponse: function(state, el)
	{
		// Find the label object for the given field if it exists
		if (!(el.labelref)) {
			var labels = $$('label');
			labels.each(function(label){
				if (label.getProperty('for') == el.getProperty('id')) {
					el.labelref = label;
				}
			});
		}

		// Set the element and its label (if exists) invalid state
		if (state == false) {
			el.addClass('invalid');
			if (el.labelref) {
				$(el.labelref).addClass('invalid');
			}
		} else {
			el.removeClass('invalid');
			if (el.labelref) {
				$(el.labelref).removeClass('invalid');
			}
		}
	}
});

document.formvalidator = null;
Window.onDomReady(function(){
	document.formvalidator = new JFormValidator();
});

/*
Window.onDomReady(function() {
        document.formvalidator.setHandler('homephone', function(value) {
                regex=/^\[1-9]\d{2}\-\d{3}\-\d{4}$/;
                if(!regex.test(value)) {
                	alert("Phone Number must be entered as: 416-555-1234");
               	}
                return regex.test(value);
        })
});
*/
Window.onDomReady(function() {
        document.formvalidator.setHandler('mobilephone', function(value) {
                regex=/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
                if(!regex.test(value)) {
                	alert("Phone Number must be entered as: (416) 555-1234");
               	}
                return regex.test(value);
        })
});
Window.onDomReady(function() {
        document.formvalidator.setHandler('extraField-EmergencyPhone', function(value) {
                regex=/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
                if(!regex.test(value)) {
                	alert("Phone Number must be entered as: (416) 555-1234");
               	}
                return regex.test(value);
        })
});

Window.onDomReady(function() {
        document.formvalidator.setHandler('extraField-DOB', function(value) {
                regex=/^[0-1]\d{1}\/[0-3]\d{1}\/[1]\d{3}$/;
                //regex=/^\d{2}\/\d{2}\/\d{4}$/;
                if(!regex.test(value)) {
                	alert("Date of Birth must be entered as: 08/31/1970");
               	}
                return regex.test(value);
        })
});

Window.onDomReady(function() {
        document.formvalidator.setHandler('extraField-SIN', function(value) {

		    if(value == "") {
		        	alert("You left the SIN field blank.");
		           	return false;
	     	}
	    	inStr = value;
	   		sin = value;
	    	inLen = inStr.length;

			if (inLen > 11 || inLen < 11) {
				alert("SIN must be entered as: 999-999-999");
				return false;
			}

 			for (var i = 0; i < text.length; i++) {
		 		var ch = text.substring(i, i + 1)

				if ((ch < "0" || "9" < ch) && (ch != "-"))  {
	 				alert("You must enter a 9 digits and two dashes.\nFormat 999-999-999.")
					return false;
	   			}
	      		if ((i == 3 || i == 7) && (ch != "-")) {
	        		alert("Invalid character in position 4 or 8;\nMust be a dash!");
	       			return false;
	          	}
			}
   			lastdigit = text.substring(10, 10 + 1);
      		// add numbers in odd positions; IE 1, 3, 6, 8
			var odd = ((text.substring(0,0 + 1)) * (1.0)  + (text.substring(2,2 + 1)) * (1.0)
						+(text.substring(5, 5+1)) * (1.0) + (text.substring(8,8 + 1)) * (1.0));

            // form texting of numbers in even positions IE 2, 4, 6, 8
            var enumbers =  (text.substring(1,1 + 1)) + (text.substring(4,4 + 1))+
            				(text.substring(6,6 + 1)) + (text.substring(9,9 + 1));

            // add together numbers in new text string
            // take numbers in even positions; IE 2, 4, 6, 8
            // and double them to form a new text string
            // EG if numbers are 2,5,1,9 new text string is 410218
            for (var i = 0; i < enumbers.length; i++) {
         		var ch = (enumbers.substring(i, i + 1) * 2);
         		ch_sum = ch_sum + ch;
         	}

            for (var i = 0; i < ch_sum.length; i++) {
         		var ch = (ch_sum.substring(i, i + 1));
           		esum = ((esum * 1.0) + (ch * 1.0));
			}

			checknum = (odd + esum);

			// subtextact checknum from next highest multiple of 10
   			// to give check digit which is last digit in valid SIN
			if (checknum <= 10) {
				(checdigit = (10 - checknum));
			}
			if (checknum > 10 && checknum <= 20) {
				(checkdigit = (20 - checknum));
			}
			if (checknum > 20 && checknum <= 30) {
				(checkdigit = (30 - checknum));
			}
   			if (checknum > 30 && checknum <= 40) {
				(checkdigit = (40 - checknum));
			}
   			if (checknum > 40 && checknum <= 50) {
				(checkdigit = (50 - checknum));
			}
   			if (checknum > 50 && checknum <= 60) {
				(checkdigit = (60 - checknum));
			}

			if (checkdigit != lastdigit) {
				alert(sin + "  is an invalid SIN; \nCheck digit incorrect!\nShould be: " + checkdigit);
   					return false;
        	}
        	return true;
        })
});

