/*
*  jQuery form validation
*
*  Author: Malcolm Elsworth (electricputty.co.uk)
*  Date: 05-10-09
*  Version: 1.5
*  Dependacies:
*     jquery-1.3.2.min.js
*     jquery.scrollTo-min.js
*     jquery-dom.js
*     jquery-funcs.js
*
*/




// Create closed namespace for jQuery code.
(function($) {


    // ------------------------------------------------------
    // Global variable
    var $theError;
    var $highlightInput;
    var $validationCount = 0;


    // ------------------------------------------------------
    // Perform validation on all required inputs within specified parent
    $validateInputs = function($obj)
    {
        $theError = "";
        $theRequired = $obj.find(".required");
        $theErrorHolder = $obj.find(".errorExplanation");
        $validationCount = $validationCount + 1;

        $theRequired.each(function()
        {
            $self = $(this);
            $val = $(this).val();
            $highlightInput = true;

            //--console.log($self.attr("id"));

            // If this input has a parent of "partner-inputs" check this it is visible - if not ignore it
            if($self.parents(".partner-inputs").length > 0)
            {
                if($self.parents(".partner-inputs").hasClass("hide")) $runProcess = false;
            }

            // Radio inputs
            if($self.attr("type") == "radio")
            {
                $anyChecked = false;
                $theParent = $self.parents(".input-set");
                $theRadios = $theParent.find(".imp-radio");
                $theRadios.each(function()
                {
                    if($(this).is(':checked')) $anyChecked = true;
                });

                if(!$anyChecked)
                {
                    $theError += "Please " + $self.parents(".input-set").attr("title").toLowerCase() + "|";
                    //$highlightInput = false;
                    $addError($self.parent());
                }
                else
                {
                    $removeError($self.parent());
                }
            }

            // Checkboxes
            else if($self.attr("type") == "checkbox")
            {
                if($(this).is(':checked'))
                {
                    $removeError($self.parent());
                }
                else
                {
                    $theError += "Please " + $self.attr("title").toLowerCase() + "|";
                    $addError($self.parent());
                }
			}

            // Text / Textarea / Select inputs
            else
            {
                if($val == "" || $val == null)
                {
                    //--console.log("CHECK 1: " + $self.attr("id")+" - "+ $dependentFieldsAreEmpty($self));
                    // If this field has dependencies and these are all empty we can ignore this fail
                    if($dependentFieldsAreEmpty($self))
                    {
                        $removeError($self);
                    }
                    else
                    {
                        $theError += "Please " + $self.attr("title").toLowerCase() + "|";
                        $addError($self);
                    }
                }
                // The input isn't empty, but dooes it meet all the requirements...
                else
                {
                    // Is it a valid email address?
                    if ($self.hasClass("email") && !$validateEmail($val))
                    {
                        $theError += "Please enter a valid email address" + "|";
                        $addError($self);
                    }
                    // Is the password at least 4 characters?
                    else if ($self.hasClass("password") && $val.length < 4)
                    {
                        $theError += "Please enter a password of at least 4 characters" + "|";
                        $addError($self);
                    }
                    // Does this confirmation match the original input?
                    else if ($self.hasClass("confirm"))
                    {
                        $targetID = $self.attr("class").split("[")[1];
                        $targetID = $targetID.substring(0,$targetID.indexOf("]"));
                        //--console.log($targetID);
                        $targetVal = $("#" + $targetID).val();
                        //--console.log("val: " + $val + " :: targetVal: " + $targetVal);
                        if($val != $targetVal)
                        {
                            $theError += "Please confirm your password" + "|";
                            $addError($self);
                        }
                    }
                    else
                    {
                        $removeError($self);
                    }
                }
            }

        });
        // $theRequired.each

        if($theError == "")
        {
            $hideErrorMessage($obj);
            return true;
        }
        else
            return $displayErrorMessage($obj);
    };
    // $validateInputs()


    // Check to see if this inputs validation is dependent on another - if this is empty ignore it
    $dependentFieldsAreEmpty = function($obj)
    {
        if($obj.hasClass("dependent"))
        {
            // Extract the ID(s) of the dependent field(s)
            $targetID = $obj.attr("class").match(/[[\A-Za-z0-9|_]*\]/).toString();
            $targetID = $targetID.substring(3,$targetID.length-1);
            //--console.log($targetID);

            // Do we have more than one dependent field?
            if ($targetID.indexOf("|") != -1)
            {
                $targetIDs = $targetID.split("|");
                $hasDependentValue = false;
                for($t=0; $t<$targetIDs.length; $t++)
                {
                    $targetVal = $("#" + $targetIDs[$t]).val();
                    //--console.log($validationCount + " - " + $t + " - " + $obj.attr("id") + " - " + $targetIDs[$t] + " - " + $targetVal);
                    if($targetVal != "") $hasDependentValue = true;
                }
                // If we have found a dependent value, return false
                return !$hasDependentValue;
            }
            else
            {
                $targetVal = $("#" + $targetID).val();
                if($targetVal == "" || $targetVal == null) return true;
            }
        }
        return false;
    }
    // $dependentFieldsAreEmpty()



    // ------------------------------------------------------
    // Add error classes to form inputs
    $addError = function($obj)
    {
        if($highlightInput) $obj.addClass("imp-error");

        // If this is *form* input (as in not a login screen) - add a class to the "form-controls" parent
        $fcParent = $obj.parents(".form-controls");
        $fcParent.addClass("error");
    };
    // $addError()


    // ------------------------------------------------------
    // Remove all error classes from form inputs
    $removeError = function($obj)
    {
        $obj.removeClass("imp-error");

        // If this is *form* input (as in not a login screen) - remove the class from the "form-controls" parent if no other fields within it have an error class
        $fcParent = $obj.parents(".form-controls");
        $otherErrors = $fcParent.find(".imp-error");
        if($otherErrors.length == 0) $fcParent.removeClass("error");
    };
    // $removeError()


    // ------------------------------------------------------
    // Build error message, add it to the DOM and then scroll to it
    $displayErrorMessage = function($obj)
    {
        $theErrors = $theError.split("|");
        $theMessage = "<h2>There was a problem with your details</h2>\n<ul>";
        for(var $i= 0; $i<$theErrors.length; $i++)
        {
            if ($theErrors[$i].length > 0) $theMessage += "<li>" + $theErrors[$i] + "</li>\n";
        }
        $theMessage += "</ul>\n";
        $("#errorExplanation").removeClass("hide").html($theMessage);
        $.scrollTo("#errorExplanation", 600);
        return false;
    };
    // $displayErrorMessage()


    // ------------------------------------------------------
    // Hide error message
    $hideErrorMessage = function($obj)
    {
        $(".errorExplanation").addClass("hide");
        return true;
    };
    // $hideErrorMessage()


    // ------------------------------------------------------
    // Validate email string
    $validateEmail = function($addr)
    {
        var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
        for (i=0; i<invalidChars.length; i++)
        {
            if ($addr.indexOf(invalidChars.charAt(i),0) > -1) return false;
        }
        for (i=0; i<$addr.length; i++)
        {
            if ($addr.charCodeAt(i)>127) return false;
        }
        var atPos = $addr.indexOf('@',0);
        if (atPos == -1) { return false; }
        if (atPos == 0) { return false; }
        if ($addr.indexOf('@', atPos + 1) > - 1) { return false; }
        if ($addr.indexOf('.', atPos) == -1) { return false; }
        if ($addr.indexOf('@.',0) != -1) { return false; }
        if ($addr.indexOf('.@',0) != -1){ return false; }
        if ($addr.indexOf('..',0) != -1) { return false; }
        var suffix = $addr.substring($addr.lastIndexOf('.')+1);
        if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') return false;
        return true;
    };
    // $validateEmail()


    // ------------------------------------------------------
    // Events to load on "document.ready"
    $(document).ready(function() {

        // ------------------------------------------------------
        // Get all forms with the class 'validate'
        $("form.validate").submit(function()
        {
            if($validateInputs($(this)) == true)
            {
                //$theButton = $(this).find(".save-page button");
                //$theButton.parent().removeClass("save-page");
                //$theButton.parent().addClass("processing");
                //$theButton.html("Processing...");
                return true;
            }
            else
            {
                return false;
            }
        });

    });
})(jQuery);



