﻿/*  (c) 2006 Zach Parrish - Ariamedia
 *
 *  Page_HighlightValidator encapsulates the base .NET validator and the additional
 *  properties added by the HighlightValidator.
 *
 *  Page_HighlightValidators serves as a collection/managment utility for all
 *  active HighlightValidators.  It also overrides the base validation functionality
 *  to create the new functionality of the HighlightValidators.
 *
 *  Dependencies: Prototype.js
 *
/*--------------------------------------------------------------------------*/
var Page_HighlightValidator = Class.create({
    initialize: function(val, errorClass, errorFunction, controlToHighlight) {
        this.validator = $(val);
        this.errorClass = errorClass;
        this.errorFunction = errorFunction;
        if ($(controlToHighlight))
        {
            this.controlToHighlight= $(controlToHighlight);
        }
        else
        {
            this.controlToHighlight= $(this.validator.controltovalidate);
        }
        this.originalTitle = "";
    },
    
    setTitle: function() {
        if (this.controlToHighlight)
        {
            this.originalTitle = $(this.validator.controltovalidate).title;
        }
    }
});

var Page_HighlightValidators = {
    validators: [],
    areTitlesSet: false,
    
    add: function(highlightValidator) {
        //remove it if it already exists
        this.remove(highlightValidator.validator);
        
        this.validators.push(highlightValidator);
    },

    remove: function(val) {
        this.validators = this.validators.reject(function(validator) {
            return validator.validator == val;
        });
    },
    
    destroy: function() {
        this.validators = [];
        this.areTitlesSet = false;
        
        this.AllValidatorsValidHandler = null;
        this.ValidationSummaryOnSubmitHandler = null;
        AllValidatorsValid = this.m_oldAllValidatorsValid;
        ValidationSummaryOnSubmit = this.m_oldValidationSummaryOnSubmit;
        
        // Remove objects created by base validators
        $A(Page_Validators).each(function(validator) {
            if (window[validator.id])
            {
                window[validator.id] = null;
            }
        });
    },
    
    // Get the Page_HighlighValidator that wraps the given .NET validator
    GetHighlightValidatorByValidator: function(val) {
        return this.validators.find(function(validator) {
                    return validator.validator == val;
                });
    },
    
    // Gets all Page_HighlightValidator objects that wrap a validator with the specified
    // control to validate.  valToExclude is an optional parameter that, if specified, will
    // exclude the given validator from the results.
    GetHighlightValidatorsByControl: function(controlToHighlight, valToExclude) {
        return this.validators.findAll(function(highlightValidator) {
            var hasSameControlToValidate = (highlightValidator.controlToHighlight == controlToHighlight);
            if (valToExclude)
            {
                var isSameValidator = (highlightValidator.validator == valToExclude);
                return (hasSameControlToValidate && !isSameValidator);                
            }
            else
            {
                return hasSameControlToValidate;
            }
        });    
    },
    
    OverrideUpdateDisplay: function() {
        if (typeof(AllValidatorsValid) != "undefined")
        {
            if (this.AllValidatorsValidHandler == null)
            {
                // hijack AllValidatorsValid method
                this.AllValidatorsValidHandler = this.AllValidatorsValid.bind(this);
                this.m_oldAllValidatorsValid = AllValidatorsValid;
                AllValidatorsValid = this.AllValidatorsValidHandler;
            }
            
        }
        
        if (typeof(ValidationSummaryOnSubmit) != "undefined")
        {
            if (this.ValidationSummaryOnSubmitHandler == null)
            {
                // hijack ValidationSummaryOnSubmit method
                this.ValidationSummaryOnSubmitHandler = this.ValidationSummaryOnSubmit.bind(this)
                this.m_oldValidationSummaryOnSubmit = ValidationSummaryOnSubmit;
                ValidationSummaryOnSubmit = this.ValidationSummaryOnSubmitHandler;
            }
        }
        
        Event.stopObserving(window, "load", highlightValidatorsOverrideUpdateDisplay);
    }, 
    
    SetTitles: function() {
        if (!this.areTitlesSet)
        {
            this.validators.each(function(validator) {
                validator.setTitle();
            });
            this.areTitlesSet = true;
        }
    },
    
    AllValidatorsValid: function(validators) {
        // Store original title of all controls to validate so that they may be
        // restored later.
        this.SetTitles();
        
        // Set the correct display of each control to validate
        this.validators.each(this.ValidatorUpdateDisplay.bind(this));
        
        // Return the value of the hijacked AllValidatorsValid function as it is
        // what sets the Page_IsValid variable.
        return this.m_oldAllValidatorsValid(validators);
    },
    
    ValidatorUpdateDisplay: function(highlightValidator) {
        if (!highlightValidator.controlToHighlight)
        {
            return;
        }
        var val = highlightValidator.validator;
        if (highlightValidator.errorClass != "")
        {        
            // See if any other validators attached to this control are also invalid
            var hasOtherInvalid = false;
            var otherValidators = this.GetHighlightValidatorsByControl(highlightValidator.controlToHighlight, val);
            if (otherValidators.length > 0)
            {
                hasOtherInvalid = otherValidators.any(function(controlValidator) {
                    return !controlValidator.validator.isvalid;
                });
            }
            
            // If this validator is valid and so are all other validators, 
            // remove the error class and remove the tooltip    
            if (val.isvalid && !hasOtherInvalid)
            {
                Element.removeClassName(highlightValidator.controlToHighlight, highlightValidator.errorClass);
                highlightValidator.controlToHighlight.title = highlightValidator.originalTitle;
            }
            // If this validator is invalid, add the error class and change the tooltip of the control
            else if (!val.isvalid)
            {
                Element.addClassName(highlightValidator.controlToHighlight, highlightValidator.errorClass);
                highlightValidator.controlToHighlight.title = val.errormessage;
            }
        }
        
        // If this validator is invalid then call the user specified function
        if (highlightValidator.errorFunction != "" && eval("typeof("+highlightValidator.errorFunction+")") == "function")
        {
            if (!val.isvalid)
            {
                highlightValidator.errorFunction(val);
            }        
        }  
    },
    
    ValidationSummaryOnSubmit: function(validationGroup) {
        if (typeof(Page_ValidationSummaries) == "undefined")
        {
            return;
        }
        var summary, sums, s;
        for (sums = 0; sums < Page_ValidationSummaries.length; sums++) 
        {
            summary = Page_ValidationSummaries[sums];
            summary.style.display = "none";
            if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) 
            {
                var i;
                if (summary.showsummary != "False") 
                {
                    summary.style.display = "";
                    if (typeof(summary.displaymode) != "string") 
                    {
                        summary.displaymode = "BulletList";
                    }
                    switch (summary.displaymode) 
                    {
                        case "List":
                            headerSep = "<br>";
                            first = "";
                            pre = "";
                            post = "<br>";
                            end = "";
                            break;
                        case "BulletList":
                        default:
                            headerSep = "";
                            first = "<ul>";
                            pre = "<li>";
                            post = "</li>";
                            end = "</ul>";
                            break;
                        case "SingleParagraph":
                            headerSep = " ";
                            first = "";
                            pre = "";
                            post = " ";
                            end = "<br>";
                            break;
                    }
                    s = "";
                    if (typeof(summary.headertext) == "string") 
                    {
                        s += summary.headertext + headerSep;
                    }
                    s += first;
                    for (i=0; i<Page_Validators.length; i++) 
                    {
                        if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") 
                        {
                            s += pre + "<label style=\"cursor:pointer; cursor:hand;\" for=\"" + Page_Validators[i].controltovalidate + "\">" + Page_Validators[i].errormessage + "</label>" + post;
                        }
                    }
                    s += end;
                    summary.innerHTML = s;
                    window.scrollTo(0,0);
                }
                if (summary.showmessagebox == "True") 
                {
                    this.m_oldValidationSummaryOnSubmit(validationGroup);
                }
            }
        }    
    }
}
var highlightValidatorsOverrideUpdateDisplay = Page_HighlightValidators.OverrideUpdateDisplay.bind(Page_HighlightValidators);
Event.observe(window, "load", highlightValidatorsOverrideUpdateDisplay);
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();