﻿function ValidatorManagerItem(n, add, remove)
{
    this.name = n;
    this.addFunction = add;
    this.removeFunction = remove;
    this.isSet = false;
    this.isRestored = false;
}

function ValidatorManager()
{
    this.Validator = null;
    this.Items = new Array();

    this.add = function(name, addFunction, removeFunction)
    {
        this.Items.push(new ValidatorManagerItem(name, addFunction, removeFunction));
    }

    this.setContext = function(name)
    {
        for (var i = 0; i < this.Items.length; i++)
        {
            if (this.Items[i].name == name)
            {
                this.Items[i].addFunction();
                this.Items[i].isSet = true;
            }
            else
            {
                this.Items[i].removeFunction();
            }
        }
    }

    this.restoreContext = function()
    {
        for (var i = 0; i < this.Items.length; i++)
        {
            if (this.Items[i].isSet)
                this.Items[i].addFunction();
        }

        if (!this.isRestored)
        {
            this.isRestored = true;
            this.Validator.form();
        }
        else
        {
            this.isRestored = false;
        }
    }

    this.validateAndClick = function(group, onSuccess)
    {
        this.setContext(group);

        this.Validator.settings["submitHandler"] = function()
        {
            jQuery.validator.manager.restoreContext();
            onSuccess();
        }
    }

    this.validate = function(group)
    {
        this.setContext(group);

        this.Validator.settings["submitHandler"] = function()
        {
            jQuery.validator.manager.restoreContext();            
        }
    }

    this.setValidator = function(validator)
    {
        this.Validator = validator;
    }
}