﻿/*************************************************************
// 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 IndustryCategoryControl2()
    {        
    }

    // Properties for xml doc and settings.
    IndustryCategoryControl2.prototype.XDoc = null;
    
    ///<summary> Determines whether to show a listbox ( for multiple selection )
    /// or a drop down list box. </summary>
    IndustryCategoryControl2.prototype.IsMultiSelectUI = true;
    
    ///<summary> Determines whether or not multiple categories can be selected.</summary>
    IndustryCategoryControl2.prototype.AllowMultiCategorySelection = true;
    
    ///<summary> Determines whether or not a category must be selected.</summary>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.prototype.EnableAllCategorySelection = false;

    // USAGE INTERNAL !!!! Should not be publicly used by client code.
    // Properties for industry / category list control id's.
    IndustryCategoryControl2.prototype.IndustriesControlId = "";
    IndustryCategoryControl2.prototype.CategoriesControlId = "";
    IndustryCategoryControl2.prototype.IndustryListControl = null;
    IndustryCategoryControl2.prototype.CategoryListControl = null;
    

    // These represent the hidden fields used to store the state
    // of the control.
    IndustryCategoryControl2.prototype.ControlIdToStoreSelectedIndustryId = "";
    IndustryCategoryControl2.prototype.ControlIdToStoreSelectedCategoryIds = "";

    // Properties for storing state.
    IndustryCategoryControl2.prototype.SelectedIndustryId = 0;
    IndustryCategoryControl2.prototype.SelectedCategoryIds = null;

    
    //Load the industry/category listboxes.
    IndustryCategoryControl2.prototype.Load = function()
    {
        this.IndustryListControl = document.getElementById(this.IndustriesControlId);
        this.CategoryListControl = document.getElementById(this.CategoriesControlId);
        this.ConfigureUI();
        this.RestoreState();
    }


    ///<summary>Configures the industry / category control and the UI should behave.</summary>
    IndustryCategoryControl2.prototype.ConfigureUI = function()
    {
        // Add "All" to industry selection.
        if(this.EnableAllCategorySelection)
        {
            AddOptionToList(this.IndustriesControlId, SELECT_ALL, INDUSTRY_SELECTION_ID_ALL);
        }

        this.InsertIndustries();

        var numVisibleRows = 1;

        if( this.IsMultiSelectUI )
        {
             numVisibleRows = 10;
        }
        else
        {
            this.AllowMultiCategorySelection = false;
        }

        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.multiple = this.AllowMultiCategorySelection;
        this.CategoryListControl.size = numVisibleRows;
        
        //select nothing by default
        this.CategoryListControl.selectedIndex = -1; 
    }


    ///<summary> Selects the first industry and displays it's corresponding categories.</summary>    
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.prototype.SetCategoriesByIndexes = function(categoriesIndexList)
    {
        if(!categoriesIndexList)
            return;

        var cntSelectedCategories = categoriesIndexList.length;
        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]);

            // check the bounds and set selected.
            if( ndxCategory >= 0 && ndxCategory < cntTotalCategories )
            {
                categoriesControl.options[ndxCategory].selected = true;
            }
        }
    }


    /// <summary>Load industries form the xml document.
    /// Insert them into the industry list control.
    /// </summary>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.prototype.InsertCategoriesByIndustryId = function( industryId )
    {
        ClearList(this.CategoriesControlId);

        // If the industry id == [all]
        if( industryId == INDUSTRY_SELECTION_ID_ALL )
            return;
            
        // Add "all" to the categories.
        if( this.EnableAllCategorySelection == true)
        {
            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 dropdown = document.getElementById(this.CategoriesControlId);

        var otherOption;
        var blnAddOtherAtEnd = false;
        
        // for each category.
        for(ndx = 0; ndx < categoriesList.length; ndx++ )
        {
            categoryNode = categoriesList[ndx];

            var option = document.createElement("option");
            option.text = categoryNode.getAttribute("name");
            option.value = categoryNode.getAttribute("id");
            
            if(option.text.indexOf("Other") == -1)
            {
                dropdown.options.add(option);
            }
            else
            {
                blnAddOtherAtEnd = true;
                otherOption = option;
            }
        }
        if(blnAddOtherAtEnd && otherOption != null)
        {
            dropdown.options.add(otherOption);
        }
    }


    /// <summary>Event handler for when a category is selected.</summary>
    /// <remarks>Validates the control on the client side.</remarks>
    IndustryCategoryControl2.prototype.OnCategorySelected = function()
    {
        this.Validate();
    }


    ///<summary>Returns an empty string if valid, an error string otherwise.</summary>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.prototype.AreCategoriesSelected = function()
    {
        var selectedCategoryIds = GetSelectedListValuesAsDelimitedString( this.CategoriesControlId );
        if( selectedCategoryIds.length == 0 )
            return false;

        return true;
    }

    
    /// <summary>Determines if any industries are selected.</summary>
    IndustryCategoryControl2.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>
    IndustryCategoryControl2.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.
            if( this.CategoryListControl.selectedIndex >= 0 )
            {
                this.SelectedCategoryIds = GetSelectedListValuesAsDelimitedString(this.CategoriesControlId);
                document.getElementById(this.ControlIdToStoreSelectedCategoryIds).value = this.SelectedCategoryIds;
            }
        }
    }

    
    ///<summary>Restores the state of the control on the client side by populating the
    /// selected industry and selected category.
    /// </summary>
    IndustryCategoryControl2.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;

        // [All] categories.
        if(categoriesDelimtedFromState == INDUSTRY_SELECTION_ID_ALL )
        {
            this.CategoryListControl.selectedIndex = 0;
            return;
        }
        
        var arrCategoryIds = ConvertDelimitedStringToArray(categoriesDelimtedFromState);

        SetListOptionsUsingArrayOfValues(this.CategoriesControlId, arrCategoryIds);
    }



