/*     
	2/4/09
	Form Validator
	Jquery plugin for form validation and quick contact forms
	Copyright (C) 2009 Jeremy Fry. www.jeremy-fry.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

jQuery.iFormValidate = {
    build: function(user_options) {
        var defaults = {
            ajax: true,
            validCheck: false,
            divError: "#divError",
            messageError: "",
            actionFile: "/js/formvalidator/send.php"
        };
        return $(this).each(
			function() {
			    var options = $.extend(defaults, user_options);
			    if (options.validCheck) {
			        var $inputs = $(this).find(":input").filter(":not(:submit)").filter(":not(.novalid)"); //.filter(":not(:checkbox)")
			    } else {
			        var $inputs = $(this).find(":input").filter(":not(:submit)"); //.filter(":not(:checkbox)")
			    }
			    //catch the submit
			    $(this).submit(function() {
			        //we need to do a seperate analysis for checboxes
			        var $checkboxes = $(this).find(":checkbox");

			        //we test all our inputs
			        var isValid = jQuery.iFormValidate.validateForm($inputs);
			        //if any of them come back false we quit
			        if (!isValid) {
			            var $errors = $(this).find(".showError");
			            var msgError = options.messageError + '<ul class="errorsList">';
			            $errors.each(function() {
			                msgError += "<li>" + $(this).html() + "</li>";
			                $(options.divError).html(msgError + "</ul>")
			            });
			            window.location.href = options.divError;
			            return false;
			        }
			        if (options.ajax) {
			            var data = {};
			            $inputs.each(function() {
			                data[this.name] = this.value;
			            });
			            $checkboxes.each(function() {
			                if ($(this).is(':checked')) {
			                    data[this.name] = this.value;
			                } else {
			                    data[this.name] = "";
			                }
			            });
			            $(this).parent('div').fadeOut("slow", function() {
			                $(this).load(options.actionFile, data, function() {
			                    $(this).fadeIn("slow");
			                });
			            });
			            return false;
			        } else {
			            return true;
			        }
			    });

			    $inputs.bind("blur", jQuery.iFormValidate.validate);
			    $(this).find(":checkbox").bind("click", jQuery.iFormValidate.validate);
			    $(this).find(":radio").bind("click", jQuery.iFormValidate.validate);
			    $inputs.filter("select").bind("change", jQuery.iFormValidate.validate);
			});
    },
    validateForm: function($inputs) {
        var isValid = true; //benifit of the doubt?
        $inputs.filter(".is_required").each(jQuery.iFormValidate.validate);
        if ($inputs.filter(".is_required").hasClass("invalid")) { isValid = false; }
        return isValid;
    },

    validate: function() {
        var $val = $(this).val();
        var isValid = true;
        var isTypeValid = true;
        if ($(this).hasClass('is_required') && $val.length === 0) {
            isValid = false;
        } else if ($(this).hasClass('vcheckbox')) {
            var isChecked = 0;
            var CbAttr = $(this).attr('name');
            if ($(this).is(':checked')) {
                isChecked = 1;
            }
            else {
                var $myChecboxes = $(this).parents("form").eq(0).find('.' + CbAttr);
                $myChecboxes.each(function() {
                    if ($(this).is(':checked')) {
                        isChecked = 1;
                    }
                });
            }
            if (!isChecked) {
                isValid = false;
            }
        } else if ($(this).hasClass('vradio')) {
            var isChecked = 0;
            var RbAttr = $(this).attr('name');
            if ($(this).is(':checked')) {
                isChecked = 1;
            }
            else {
                var $myChecboxes = $(this).parents("form").eq(0).find('.' + RbAttr);
                $myChecboxes.each(function() {
                    if ($(this).is(':checked')) {
                        isChecked = 1;
                    }
                });
            }
            if (!isChecked) {
                isValid = false;
            }
        } else if ($(this).hasClass('vemail')) {
            var Regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (!Regex.test($val)) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vsame')) {
            var idSameInput = $(this).attr("id");
            idSameInput = idSameInput.replace("Confirm", "");
            var sameVal = $("#" + idSameInput).val();
            if ($val != sameVal || sameVal.length == 0) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vphone')) {
            var Regex = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d*$)/;
            if (!Regex.test($val)) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vnumeric')) {
            var Regex = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)|(^-?\d*$)/;
            if (!Regex.test($val)) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vzip')) {
            var Regex = /^\d{5}$/;
            if (!Regex.test($val)) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vname')) {
            var Regex = /^[^0-9]*$/; //Tout caractère non numérique (Pour mémo : formule pour les lettres alphabétiques et les lettres accentués => /^\s*[a-zA-Zéèàêâçîïôöùûü]+\s*$/)
            if (!Regex.test($val)) { isValid = false; isTypeValid = false; }
        } else if ($(this).hasClass('vdate')) {
            var Regex = /^([\d]|1[0,1,2]|0[1-9])(\-|\/|\.)([0-9]|[0,1,2][0-9]|3[0,1])(\-|\/|\.)\d{4}$/;
            isValid = Regex.test($val);
        } else if ($(this).hasClass('vreqAll')) {
            var $all = $(this).siblings('.vreqAll');
            $all.each(function() {
                if ($val == "" || $(this).val() == "") {
                    isValid = false;
                }
            });
            if (!isValid) {
                $all.each(function() {
                    $(this).addClass("invalid");
                });
            }
            else {
                $all.each(function() {
                    $(this).removeClass("invalid");
                });
            }
        } else if ($(this).hasClass('vpasswordconfirm')) {
            //we need to find the other password field and check it
            $el = $(this);
            //locate the form so we can search for the other field
            while ($el.attr("tagName").toLowerCase() != "form") { $el = $el.parent(); }
            $el = $el.find(".vpassword");
            //store text of other password field
            var checkValue = $el.val();
            //comapre and set the other to red if appropriate, or green
            if ($val != checkValue) {
                isValid = false; $el.removeClass("valid").addClass("invalid");
            } else { $el.removeClass("invalid").addClass("valid"); }
        } else if ($(this).hasClass('vpassword')) {
            $el = $(this);
            while ($el.attr("tagName").toLowerCase() != "form") { $el = $el.parent(); }
            $el = $el.find(".vpasswordconfirm");
            var checkValue = $el.val();
            if ($val != checkValue) {
                isValid = false; $el.removeClass("valid").addClass("invalid");
            } else { $el.removeClass("invalid").addClass("valid"); }
        }

        var labelIdClass = $(this).attr("name");
        if (!isValid && isTypeValid) {
            $(this).removeClass("valid").addClass("invalid");
            $("label." + labelIdClass).addClass("labelInvalid");
            $(this).siblings(".verror").addClass("showError");
        } else if (!isValid && !isTypeValid) {
            $(this).removeClass("valid").addClass("invalid");
            $("label." + labelIdClass).addClass("labelInvalid");
            $(this).siblings(".verror").removeClass("showError");
            $(this).siblings(".vTypeError").addClass("showError");
        } else if (isValid && isTypeValid) {
            $(this).removeClass("invalid").addClass("valid");
            $("label." + labelIdClass).removeClass("labelInvalid");
            $(this).siblings(".verror").removeClass("showError");
            $(this).siblings(".vTypeError").removeClass("showError");
        }
    }
}
jQuery.fn.FormValidate = jQuery.iFormValidate.build;