﻿(function () {
    var scriptName = "BaseValidator";

    function execute() {

        Type.registerNamespace("Movielocker.Web.Controls");

        Movielocker.Web.Controls.BaseValidatorBehavior = function (element) {
            /// <summary>
            /// The BaseValidatorBehavior applies a rounded corners to a textbox
            /// </summary>
            /// <param name="element" type="Sys.UI.DomElement" domElement="true">
            /// Textbox associated with the behavior
            /// </param>
            Movielocker.Web.Controls.BaseValidatorBehavior.initializeBase(this, [element]);

            // Properties

            this._validCssClass = null;
            this._invalidCssClass = null;

            this._servicePath = null;
            this._serviceMethod = null;
            this._extraParams = null;
            this._inProgressID = null;
            this._successID = null;
            this._noteID = null;
            this._errorID = null;
            this._coupledID = null;
            this._submitControlID = null;
            this._isRequired = true;
            this._validationGroup = null;
            this._initialState = false;
            this._valid = false;
            this._lastValidationGroup = null;

            // Member variables
            this._origClassName = null;
            this._invalidReason = '';

            this._timer = null;
            this._tickHandler = null;
            this._lastCheckedText = '';
            this._inProgress = false;

            // Hook into the ASP.NET WebForm_DoPostbackWithOptions
            if ((typeof (WebForm_DoPostBackWithOptions) == 'function') && !Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_DoPostBackWithOptions) {
                Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_DoPostBackWithOptions = WebForm_DoPostBackWithOptions;
                WebForm_DoPostBackWithOptions = Movielocker.Web.Controls.BaseValidatorBehavior.WebForm_DoPostBackWithOptions;
            }
            // Hook into the ASP.NET WebForm_OnSubmit function to clear watermarks prior to submission
            if ((typeof (WebForm_OnSubmit) == 'function') && !Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_OnSubmit) {
                Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_OnSubmit = WebForm_OnSubmit;
                WebForm_OnSubmit = Movielocker.Web.Controls.BaseValidatorBehavior.WebForm_OnSubmit;
            }
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (!Movielocker.Web.Controls.BaseValidatorBehavior._prmInitializeRequestInstalled) {
                prm.add_initializeRequest(Movielocker.Web.Controls.BaseValidatorBehavior._prmInitializeRequest);
                Movielocker.Web.Controls.BaseValidatorBehavior._prmInitializeRequestInstalled = true;
            }
        }
        Movielocker.Web.Controls.BaseValidatorBehavior.prototype = {
            initialize: function () {
                /// <summary>
                /// Initialize the behavior
                /// </summary>
                Movielocker.Web.Controls.BaseValidatorBehavior.callBaseMethod(this, 'initialize');

                var e = this.get_element();

                // Capture the initial style so we can toggle back and forth
                this._origClassName = e.className;

                if (this._inProgressID) {
                    $get(this._inProgressID).style.visibility = 'hidden';
                }
                if (this._successID) {
                    $get(this._successID).style.display = 'none';
                }
                if (this._errorID) {
                    $get(this._errorID).innerHTML = '';
                    $get(this._errorID).style.display = 'none';
                }
                if (this._noteID) {
                    $get(this._noteID).style.display = '';
                }

                this._valid = !this._isRequired || this._initialState;

                // Create delegates
                this._tickHandler = Function.createDelegate(this, this._onTimerTick);

                this._timer = new Sys.Timer();
                this.initializeTimer(this._timer);

                this._lastCheckedText = this.getTargetValue();
                this._timer.set_enabled(true);

                this.registerPartialUpdateEvents();
            },

            dispose: function () {
                /// <summary>
                /// Dispose the behavior
                /// </summary>
                var e = this.get_element();

                if (this._timer) {
                    this._timer.dispose();
                    this._timer = null;
                }

                Movielocker.Web.Controls.BaseValidatorBehavior.callBaseMethod(this, 'dispose');
            },

            initializeTimer: function (timer) {
                timer.set_interval(200);
                timer.add_tick(this._tickHandler);
            },

            get_ValidCssClass: function () {
                return this._validCssClass;
            },
            set_ValidCssClass: function (value) {
                this._validCssClass = value;
            },

            get_InvalidCssClass: function () {
                return this._invalidCssClass;
            },
            set_InvalidCssClass: function (value) {
                this._invalidCssClass = value;
            },

            get_ServicePath: function () {
                return this._servicePath;
            },
            set_ServicePath: function (value) {
                this._servicePath = value;
            },

            get_ServiceMethod: function () {
                return this._serviceMethod;
            },
            set_ServiceMethod: function (value) {
                this._serviceMethod = value;
            },

            get_InProgressID: function () {
                return this._inProgressID;
            },
            set_InProgressID: function (value) {
                this._inProgressID = value;
            },

            get_SuccessID: function () {
                return this._successID;
            },
            set_SuccessID: function (value) {
                this._successID = value;
            },

            get_NoteID: function () {
                return this._noteID;
            },
            set_NoteID: function (value) {
                this._noteID = value;
            },

            get_ErrorID: function () {
                return this._errorID;
            },
            set_ErrorID: function (value) {
                this._errorID = value;
            },

            get_CoupledID: function () {
                return this._coupledID;
            },
            set_CoupledID: function (value) {
                this._coupledID = value;
            },

            get_ExtraParams: function () {
                return this._extraParams;
            },
            set_ExtraParams: function (value) {
                this._extraParams = value;
            },

            get_SubmitControlID: function () {
                return this._submitControlID;
            },
            set_SubmitControlID: function (value) {
                this._submitControlID = value;
            },

            get_IsRequired: function () {
                return this._isRequired;
            },
            set_IsRequired: function (value) {
                this._isRequired = value;
            },

            get_ValidationGroup: function () {
                return this._validationGroup;
            },
            set_ValidationGroup: function (value) {
                this._validationGroup = value;
            },

            get_InitialState: function () {
                return this._initialState;
            },
            set_InitialState: function (value) {
                this._initialState = value;
            },

            _onTimerTick: function (sender, eventArgs) {
                if (this._inProgress) return;
                var text = this.getTargetValue();
                if (this._lastCheckedText == text) return;
                this.PerformValidation();
            },

            PerformValidation: function () {
                this._inProgress = true;
                var text = this.getTargetValue();
                this._invalidReason = '';
                if (this._successID) $get(this._successID).style.display = 'none';
                if (this._errorID) $get(this._errorID).style.display = 'none';
                if (this._noteID) $get(this._noteID).style.display = '';
                if (this._inProgressID) $get(this._inProgressID).style.visibility = 'visible';

                if ((text == '') && !this._isRequired) {
                    this._onMethodComplete('', text, this._serviceMethod);
                }
                else {

                    if (this._servicePath && (this._servicePath != '')) {

                        var params = { value: text };
                        if (this._extraParams) {
                            eval('var exParams = ' + this._extraParams + ';');
                            for (var param in exParams) {
                                params[param] = exParams[param];
                            }
                        }
                        Sys.Net.WebServiceProxy.invoke(this.get_ServicePath(), this.get_ServiceMethod(), false,
                                            params,
                                            Function.createDelegate(this, this._onMethodComplete),
                                            Function.createDelegate(this, this._onMethodFailed),
                                            text);

                    }
                    else if (this._serviceMethod) {
                        eval('var result = ' + this._serviceMethod + ';');
                        this._onMethodComplete(result, text, this._serviceMethod);
                    }
                }
                if (this._coupledID) {
                    var coupledComponent = $find(this._coupledID);
                    if (coupledComponent && !coupledComponent.isValid()) coupledComponent.PerformValidation();
                }

            },

            _onMethodComplete: function (result, context, methodName) {
                this._lastCheckedText = context;
                this._inProgress = false;
                var text = this.getTargetValue();
                if (context != text) return;
                if (this._inProgressID) $get(this._inProgressID).style.visibility = 'hidden';
                if (result == 'UnexpectedValidation') return;
                if (result == '') this._onValid();
                else this._onInvalid(result);
            },

            _onMethodFailed: function (err, response, context) {
                this._lastCheckedText = context;
                this._inProgress = false;
                if (this._inProgressID) $get(this._inProgressID).style.visibility = 'hidden';
                this._onError(err.get_message());
            },

            _onValid: function () {
                this._invalidReason = '';
                this._valid = true;
                if (this._successID) {
                    $get(this._successID).style.display = '';
                }
                if (this._errorID) {
                    $get(this._errorID).style.display = 'none';
                }
                if (this._noteID) {
                    $get(this._noteID).style.display = '';
                }
                if (this._validCssClass) {
                    this.get_element().className = this._validCssClass;
                }
                else {
                    this.get_element().className = this._origClassName;
                }
                if (this._submitControlID) this._onValidateAllControls();
            },

            _onInvalid: function (reason) {
                this._invalidReason = reason;
                this._valid = false;
                if (this._successID) {
                    $get(this._successID).style.display = 'none';
                }
                if (this._errorID) {
                    $get(this._errorID).innerHTML = reason;
                    $get(this._errorID).style.display = '';
                }
                if (this._noteID) {
                    $get(this._noteID).style.display = 'none';
                }
                if (this._invalidCssClass) {
                    this.get_element().className = this._invalidCssClass;
                }
                if (this._submitControlID) this._onValidateAllControls();
            },

            _onError: function (error) {
                this._valid = false;
                if (this._successID) {
                    $get(this._successID).style.display = 'none';
                }
                if (this._errorID) {
                    $get(this._errorID).innerHTML = 'Network error';
                    $get(this._errorID).style.display = '';
                }
                if (this._noteID) {
                    $get(this._noteID).style.display = 'none';
                }
                if (this._invalidCssClass) {
                    this.get_element().className = this._invalidCssClass;
                }
                if (this._submitControlID) this._onValidateAllControls();
            },

            isValid: function () {
                if ((this._lastValidationGroup || this._validationGroup) && (this._lastValidationGroup != this._validationGroup)) return true;
                if (this._inProgress) return false;
                if (this._valid) return true;
                if (!this._submitControlID) this.PerformValidation();
                return false;
            },

            _onValidateAllControls: function () {
                var allValid = true;
                var components = Sys.Application.getComponents();
                for (var i = 0; i < components.length; i++) {
                    var component = components[i];
                    if (Movielocker.Web.Controls.BaseValidatorBehavior.isInstanceOfType(component)) {
                        if (!component.isValid()) {
                            allValid = false;
                            break;
                        }
                    }
                }
                if (allValid) $get(this._submitControlID).disabled = false;
                else $get(this._submitControlID).disabled = true;
            }
        }

        Movielocker.Web.Controls.BaseValidatorBehavior.registerClass('Movielocker.Web.Controls.BaseValidatorBehavior', Sys.Extended.UI.BehaviorBase);

        Movielocker.Web.Controls.BaseValidatorBehavior.WebForm_DoPostBackWithOptions = function (options) {
            var result = Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_DoPostBackWithOptions(options);
            var components = Sys.Application.getComponents();
            for (var i = 0; i < components.length; i++) {
                var component = components[i];
                if (Movielocker.Web.Controls.BaseValidatorBehavior.isInstanceOfType(component)) {
                    component._lastValidationGroup = options.validationGroup;
                }
            }
            return result;
        }

        Movielocker.Web.Controls.BaseValidatorBehavior._prmInitializeRequest = function (sender, args) {
            var cancel = args.get_cancel();
            if (!cancel) {
                var components = Sys.Application.getComponents();
                for (var i = 0; i < components.length; i++) {
                    var component = components[i];
                    if (Movielocker.Web.Controls.BaseValidatorBehavior.isInstanceOfType(component)) {
                        if (!component.isValid()) cancel = true;
                        component._lastValidationGroup = null;
                    }
                }
            }
            if (cancel) {
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.abortPostBack();
                args.set_cancel(true);
            }
        }

        Movielocker.Web.Controls.BaseValidatorBehavior.WebForm_OnSubmit = function () {
            /// <summary>
            /// Wraps ASP.NET's WebForm_OnSubmit in order to strip all watermarks prior to submission
            /// </summary>
            /// <returns type="Boolean">
            /// Result of original WebForm_OnSubmit
            /// </returns>
            var result = Movielocker.Web.Controls.BaseValidatorBehavior._originalWebForm_OnSubmit();
            if (result) {
                var components = Sys.Application.getComponents();
                for (var i = 0; i < components.length; i++) {
                    var component = components[i];
                    if (Movielocker.Web.Controls.BaseValidatorBehavior.isInstanceOfType(component)) {
                        if (!component.isValid()) result = false;
                        component._lastValidationGroup = null;
                    }
                }
            }
            return result;
        }

    } // execute

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(scriptName, ["ExtendedBase", "ExtendedCommon"], execute);
    }
    else {
        execute();
    }

})();

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();