﻿/*************************************************************
// Author:  Kishore Reddy
// Comments: This javascript code is used for creating,
// manipulating, and configuring the industry category control.
*************************************************************/

    var INDUSTRY_SELECTION_ID_ALL = -1;
    var CATEGORY_SELECTION_ID_ALL = -1;
    var XMLELEM_CATEGORY = "category";
    var SELECT_ALL = "All";

    function IndustryCategoryControl3()
    {
    }

    // Properties for xml doc and settings.
    IndustryCategoryControl3.prototype.XDoc = null;

    ///<summary> Determines whether or not a category must be selected.</summary>
    IndustryCategoryControl3.prototype.IsSelectionRequired = false;

    ///<summary>Determines whether or not to add "All" to the drop-down list.
    /// so "all" can be selected to represent all categories.
    ///</summary>
    IndustryCategoryControl3.prototype.EnableAllCategorySelection = false;

    // USAGE INTERNAL !!!! Should not be publicly used by client code.
    // Properties for industry / category list control id's.
    IndustryCategoryControl3.prototype.IndustriesControlId = "";
    //IndustryCategoryControl3.prototype.CategoriesControlId = "";
    IndustryCategoryControl3.prototype.IndustryListControl = null;
    // CategoryListControl
    IndustryCategoryControl3.prototype.CategoryJSController = null;

    // These represent the hidden fields used to store the state
    // of the control.
    IndustryCategoryControl3.prototype.ControlIdToStoreSelectedIndustryId = "";
    IndustryCategoryControl3.prototype.ControlIdToStoreSelectedCategoryIds = "";

    // Properties for storing state.
    IndustryCategoryControl3.prototype.SelectedIndustryId = 0;
    IndustryCategoryControl3.prototype.SelectedCategoryIds = null;


    //Load the industry/category listboxes.
    IndustryCategoryControl3.prototype.Load = function()
    {
        this.IndustryListControl = document.getElementById(this.IndustriesControlId);

        //TODO: ensure: this.CategoryJSController is set through load script

        this.ConfigureUI();
        this.RestoreState();
    }


    ///<summary>Configures the industry / category control and the UI should behave.</summary>
    IndustryCategoryControl3.prototype.ConfigureUI = function()
    {

        // Add "All" to industry selection.
        if(this.EnableAllCategorySelection)
        {
            AddOptionToList(this.IndustriesControlId, SELECT_ALL, INDUSTRY_SELECTION_ID_ALL);
        }

        this.InsertIndustries();

        var numVisibleRows = 10;


        this.IndustryListControl.multiple = false;
        this.IndustryListControl.size = numVisibleRows;
        // industry list will either select [Select] item if it was added or select nothing by default
        // it is important to update selectedIndex after industries are loaded with InsertIndustries, or selection will be reverted to "first industry in the list"
        // later, selection is updated with RestoreState()
        this.IndustryListControl.selectedIndex = FindIndexOfListOption( this.IndustriesControlId, INDUSTRY_SELECTION_ID_ALL, false );

        //this.CategoryListControl.size = numVisibleRows;

        //select nothing by default
        this._GetCatController().ClearSelection();
        //this.CategoryListControl.selectedIndex = -1;
    }


    ///<summary> Selects the first industry and displays it's corresponding categories.</summary>
    IndustryCategoryControl3.prototype.SelectFirstIndustry = function( )
    {
        if( this.EnableAllSelection == false )
        {
            this.SetIndustryByIndex(0, false);
        }
        else
        {
            this.SetIndustryByIndex(1, false);
        }
    }


    ///<summary> Sets the industry by the index in the list control.<summary>
    IndustryCategoryControl3.prototype.SetIndustryByIndex = function(indexIndustry, adjustForAllSelection)
    {
        if(indexIndustry < 0)
        {
            return;
        }

        // The first industry is "[All]"
        if( adjustForAllSelection && this.EnableAllSelection )
        {
            indexIndustry = industryIndex + 1;
        }

        var selectedIndex = parseInt(indexIndustry);
        var industryId = this.IndustryListControl.options[selectedIndex].value;

        this.IndustryListControl.selectedIndex = selectedIndex;
        this.InsertCategoriesByIndustryId(industryId);
    }


    /// <summary> Sets the selected categories in list by array of indexes.
    /// Pass in array of integers.
    /// </summary>
    IndustryCategoryControl3.prototype.SetCategoriesByIndexes = function(categoriesIndexList)
    {
        if(!categoriesIndexList)
            return;

        var cntSelectedCategories = categoriesIndexList.length;
        var cat_ctrl =  this._GetCatController();
        //var categoriesControl = document.getElementById(this.CategoriesControlId);
        //var cntTotalCategories = categoriesControl.options.length;

        // For each index.
        for( ndx = 0; ndx < cntSelectedCategories; ndx++ )
        {
            var ndxCategory = parseInt( categoriesIndexList[ndx] );
            cat_ctrl.CheckIndex( ndxCategory, true );
        }
    }


    /// <summary>Load industries form the xml document.
    /// Insert them into the industry list control.
    /// </summary>
    IndustryCategoryControl3.prototype.InsertIndustries = function()
    {
        var industriesList = this.XDoc.getElementsByTagName('industry');
        var industryNode;

        for (ndx = 0; ndx < industriesList.length; ndx++ )
        {
            industryNode = industriesList[ndx];
            this.InsertIndustry(industryNode);
        }
    }


    /// <summary> Inserts an industry into the industries dropdown list.</summary>
    IndustryCategoryControl3.prototype.InsertIndustry = function( industryNode )
    {
        var industryName = industryNode.getAttribute("name");
        var dropdown = document.getElementById( this.IndustriesControlId );

        var option = document.createElement("option");
        option.text = industryName;
        option.value = industryNode.getAttribute("id");
        dropdown.options.add(option);
    }


    /// <summary> Returns a category list for the specified industryId.</summary>
    IndustryCategoryControl3.prototype.GetCategoryList = function( industryId )
    {
        var xpath = "/industries/industry[@id='" + industryId + "']";
        var industryNodes = this.XDoc.selectNodes(xpath);
        var industryNode = industryNodes[0];
        var categoriesList = industryNode.getElementsByTagName(XMLELEM_CATEGORY);
        return categoriesList;
    }


    /// <summary>Inserts all the categories from the currently
    /// selected industry into the categories list control.
    /// </summary>
    IndustryCategoryControl3.prototype.InsertCategories = function()
    {
        var industryDropDown = document.getElementById(this.IndustriesControlId);
        var industryId = industryDropDown.options[industryDropDown.selectedIndex].value;

        this.InsertCategoriesByIndustryId(industryId );
    }


    /// <summary>Inserts all the categories from the currently
    /// selected industry.
    /// </summary>
    IndustryCategoryControl3.prototype.InsertCategoriesByIndustryId = function( industryId )
    {
        var cat_ctrl =  this._GetCatController();

        cat_ctrl.Clear();

        // If the industry id == [all]
        if( industryId == INDUSTRY_SELECTION_ID_ALL )
            return;

        // Add "all" to the categories.
        if( this.EnableAllCategorySelection == true)
        {
            cat_ctrl.Add( CATEGORY_SELECTION_ID_ALL, SELECT_ALL, false );
            //AddOptionToList(this.CategoriesControlId, SELECT_ALL, CATEGORY_SELECTION_ID_ALL);
        }

        // Now add the actual categories.
        var xpath = "/industries/industry[@id='" + industryId + "']";
        var industryNodes = this.XDoc.selectNodes(xpath);
        var industryNode = industryNodes[0];
        var categoriesList = industryNode.getElementsByTagName(XMLELEM_CATEGORY);
        var categoryNode;

        var item_other = null;
        var blnAddOtherAtEnd = false;

        // for each category.
        for(ndx = 0; ndx < categoriesList.length; ndx++ )
        {
            categoryNode = categoriesList[ndx];

            var item = new CheckListItem( categoryNode.getAttribute("name"), categoryNode.getAttribute("id"), false )

            //if(option.text.indexOf("Other") == -1)
            if( item.text.indexOf( "Other" ) == -1 )
            {
                cat_ctrl.AddItem( item );
            }
            else
            {
                blnAddOtherAtEnd = true;
                item_other = item;
            }
        }
        if( blnAddOtherAtEnd && item_other != null )
        {
            cat_ctrl.AddItem( item_other );
        }
    }


    /// <summary>Event handler for when a category is selected.</summary>
    /// <remarks>Validates the control on the client side.</remarks>
    IndustryCategoryControl3.prototype.OnCategorySelected = function()
    {
        this.Validate();
    }


    ///<summary>Returns an empty string if valid, an error string otherwise.</summary>
    IndustryCategoryControl3.prototype.Validate = function()
    {
        DisplayErrorUI("lstIndustryErrorUI", false);
        DisplayErrorUI("lstCategoryErrorUI", false);
        if( !this.IsSelectionRequired )
            return "";

        var indSelected = this.AreIndustriesSelected();
        var catSelected = this.AreCategoriesSelected();

        if( indSelected && catSelected )
            return "";

        if( !indSelected )
          DisplayErrorUI("lstIndustryErrorUI", true);

        if( !catSelected )
          DisplayErrorUI("lstCategoryErrorUI", true);

        return "Industry and category must be selected.";
    }


    /// <summary>Determines if any categories are selected. </summary>
    IndustryCategoryControl3.prototype.AreCategoriesSelected = function()
    {
        var selectedCategoryIds = this._GetCatsSerialized();

        return ( selectedCategoryIds.length != 0 );
    }


    /// <summary>Determines if any industries are selected.</summary>
    IndustryCategoryControl3.prototype.AreIndustriesSelected = function()
    {
        var selectedIndustryIds = GetSelectedListValuesAsDelimitedString( this.IndustriesControlId );
        if( selectedIndustryIds.length == 0 )
            return false;

        return true;
    }


    ///<summary>Stores the current state by saving the selected categories</summary>
    IndustryCategoryControl3.prototype.StoreCurrentState = function()
    {
        // Check that industry is selected.
        if( this.IndustryListControl.selectedIndex >= 0 )
        {
            // Now get the the selected industry and store it.
            this.SelectedIndustryId = this.IndustryListControl.options[this.IndustryListControl.selectedIndex].value;
            document.getElementById(this.ControlIdToStoreSelectedIndustryId).value = this.SelectedIndustryId;

            // check category is selected.
            var cat_ctrl =  this._GetCatController();

            var ser_val = this._GetCatsSerialized();

            this.SelectedCategoryIds = ser_val;

            document.getElementById( this.ControlIdToStoreSelectedCategoryIds ).value = ser_val;

        }
    }


    IndustryCategoryControl3.prototype._GetCatController  = function()
    {
      var rc = eval( this.CategoryJSController );

      if( "undefined" == typeof( rc ) || null == rc )
        { throw "Unable to get category controller reference"; }

      return rc;
    }

    IndustryCategoryControl3.prototype._GetCatsSerialized  = function()
    {
      var cat_ctrl =  this._GetCatController();

      var ser_val = "";
      for( var i = 0; i < cat_ctrl.Count(); ++i )
      {
        var item = cat_ctrl.GetByIndex( i );
        if( item.checked )
        {
          ser_val = ser_val.concat( ( 0 == ser_val.length ) ? "" : ",", item.value );
        }
      }
      return ser_val;
    }

    ///<summary>Restores the state of the control on the client side by populating the
    /// selected industry and selected category.
    /// </summary>
    IndustryCategoryControl3.prototype.RestoreState  = function()
    {
        var industryIdFromState = document.getElementById(this.ControlIdToStoreSelectedIndustryId).value;

        if( industryIdFromState == "" )
            return;

        industryIdFromState = parseInt(industryIdFromState);

        // [All] industries.
        if(industryIdFromState == INDUSTRY_SELECTION_ID_ALL )
        {
            this.IndustryListControl.selectedIndex = 0;
            return;
        }

        var industryIndexFromState = FindIndexOfListOption(this.IndustriesControlId, industryIdFromState, false);
        this.SetIndustryByIndex(industryIndexFromState, false);

        // Now set the categories.
        var categoriesDelimtedFromState = document.getElementById(this.ControlIdToStoreSelectedCategoryIds).value;

        if(categoriesDelimtedFromState == "" )
            return;

        var cat_ctrl =  this._GetCatController();

        // [All] categories.
        if(categoriesDelimtedFromState == INDUSTRY_SELECTION_ID_ALL )
        {
            cat_ctrl.ClearSelection();
            return;
        }

        var arrCategoryIds = ConvertDelimitedStringToArray(categoriesDelimtedFromState);

        for ( var i = 0; i < arrCategoryIds.length; ++i )
        {
          cat_ctrl.CheckValue( arrCategoryIds[ i ], true );
        }


    }


