﻿CLC = typeof (CLC) === "undefined" ? {} : CLC; //Create CLC namespace or use existing

//Class for managing security questions on the client
CLC.SecurityQuestions = function()
{
    this._QuestionControls = [];    //array
    this.QuestionControls;          //linq query

    this.Init = function()
    {
        if (typeof (jQuery) == "undefined")
            throw 'jQuery 1.4+ is required for this class';

        if (typeof ($.Enumerable) == "undefined")
            throw 'Linq.js is required for this class http://plugins.jquery.com/project/linqjs';
    };

    //Register the question dropdown to be managed
    this.Add = function(questionControl)
    {
        this._QuestionControls.push(questionControl);

        //Keep track of all other question controls as a linq query
        this.QuestionControls = $.Enumerable.From(this._QuestionControls);

        //Add event handlers, making sure 'this' inside the handler is this instance
        questionControl.add_selectedIndexChanging($.proxy(this.QuestionSelectingHandler, this));
        questionControl.add_selectedIndexChanged($.proxy(this.QuestionSelectedHandler, this));
    };

    //Returns an $.Enumerable of other dropdowns than the one passed in
    this.GetOtherQuestionControls = function(currentControl)
    {
        return this.QuestionControls.Where(function(c) { return c.get_id() != currentControl.get_id() });
    };

    //Executes when the drop down has been initialized
    this.QuestionLoadHandler = function(sender, e)
    {
        var newThis = arguments.callee._parentInstance; //restore the back-reference
        $.proxy(newThis.Add, newThis)(sender);
    };
    this.QuestionLoadHandler._parentInstance = this; //store a back-reference for use in handler

    //Executes before the item is selected
    this.QuestionSelectingHandler = function(sender, e)
    {
        //unhide the currently selected question in other dropdowns
        this.GetOtherQuestionControls(sender).ForEach(function(c)
        {
            c.findItemByValue(sender.get_selectedItem().get_value()).show();
        });
    };

    //Executes right after the item is selected
    this.QuestionSelectedHandler = function(sender, e)
    {
        //hide the newly selected question in other dropdowns
        this.GetOtherQuestionControls(sender).ForEach(function(c)
        {
            c.findItemByValue(e.get_item().get_value()).hide();
        });
    };

    this.Init();
}

