 /**
 * Javascript Form Validation Class
 *
 * This validation class works along with jQuery and CI's validation class
 * to provide a 0-time javascript implementation of the php validation. Use
 * is very easy. Just need to follow theese two steps:
 *
 * 1. Add the onsubmit method to the form:
 *
 * 		onsubmit="return validateForm()"
 *
 * 2. Add the following code at the end of page:
 *
 * 		<?php echo $this->validation->getJsValidation(); ?>
 *
 * @package		Mobile Momma
 * @subpackage	Library
 * @category	Javascript
 * @author		Md Emran Hasan <emran@rightbrainsolution.com>
 * @link		http://www.rightbrainsolution.com
 */

function FormValidator()
{
	// Rules array for holding multiple rules
	var rules = new Array();

	// Adds a rule to the collection
	this.addRule = function (field, message)
	{
		var ruleArray = {
			'field' : field,
			'msg'	: message
		};

		rules.push(ruleArray);
	}

	// Validates a form against all the rules
	this.validate = function()
	{
		var isValid = true;
		rules.reverse();

		for (var i in rules)
		{
			if (!this.checkValue(rules[i]))
			{
				isValid = false;
			}
		}

		return isValid;
	}

	// Checks the value of a form element and determines its validity
    this.checkValue = function (rule)
	{
		// This is the jackpot
		var theValue = "";

		// Check text and password fields
		if($("#" + rule.field).attr('type') == "text" || $("#" + rule.field).attr('type') == "password" || $("#" + rule.field).attr('type') == "checkbox")
		{
			theValue = $("#" + rule.field).val();
		}

		// Check select boxes
        else if($("#" + rule.field).attr('type') == "select")
		{
			theValue = $("#" + rule.field).val();

			if (theValue == "none" || theValue == "-- Select --")
			{
				theValue = "";
			}
		}

		// Check TinyMCE editor
		else
		{
            try {
				theValue = tinyMCE.getContent(name);
			} catch(err) {
				// muri khao
			}
		}

		// If the value is blank, we need to report it
		if(theValue == "")
		{
			errorClass = $("#" + rule.field).parent(".ctrlHolder").attr('class');

			// If error is already displayed, then we don't need to repeat
			if (errorClass.indexOf('error') == -1)
			{
				$("#" + rule.field).parent(".ctrlHolder").addClass("error");
				$("#" + rule.field).parent(".ctrlHolder").append("<div id='error"+ rule.field + "'><font color='red'>" + rule.msg + "</font></div>");
			}

			// Focus on 'em
			$("#" + rule.field).focus();

			// Its *ILLEGAL*
			return false;
		}

		// Well, it seems to be a valid field
		else
		{
			// So, remove the error class if its there
			$("#" + rule.field).parent(".ctrlHolder").removeClass("error");
			$("div").remove("#error"+ rule.field );

			// Its *LEGAL*
			return true;
		}
	}
}