﻿// Elements
var ToggleButton = GetSearchStringForControl("toggleButton");
var ToggleDiv = GetSearchStringForControl("toggleDiv");
var hiddenDDLCount = GetSearchStringForControl("hiddenDDLCount");
var hiddenClassGroupID = GetSearchStringForControl("hiddenClassGroupID");
var hiddenSubAppID = GetSearchStringForControl("hiddenSubAppID");
var rateSetDate = GetSearchStringForControl("hiddenRateSetDate");
var lblCompanyDesc = GetSearchStringForControl("lblCompanyDesc");
var txtClassCode = GetSearchStringForControl("txtClassCode");
var drpCompanyClass = GetSearchStringForControl("drpCompanyClass");
var txtOptions = GetSearchStringForControl("txtOptions");
var hiddenDesc = GetSearchStringForControl("hiddenDescription"); 

// ------------------------------------------------------------------------------
// Builds a search string for the HTML element that matches the string passed in.
// ------------------------------------------------------------------------------   
function GetSearchStringForControl(string) 
{
    return "*[id$='" + string + "']";
}

// Variables
var cc_LastQ = null;
var cc_ResultsCurrentlyShown = false;
var cc_DivClicked = false;
var cc_filterOffset = 45; 
var urlLevels = 0;
var nothingSelected = false;
var isoCodeRequest = null;
var companyCodeRequest = null;
var descriptionRequest = null;

// *************************************************************************
//  Access functions
// *************************************************************************

// ------------------------------------------------------------------------------
// Loads the autocomplete control and assigns it to the txtClassCode input box.
// ------------------------------------------------------------------------------
function LoadClassCodeSelectorAutocomplete(levels) 
{
    urlLevels = levels; 

    // fill the autocomplete div behind the scenes with empty data just to load it.
    $(txtClassCode).ClassCodeSelectorAutocomplete("No results.");   
}

// *************************************************************************
// -- $.fn.ClassCodeSelectorAutocomplete --
// This extension kicks off the process, iterates through each element in the
// caller and calls $.ClassCodeSelectorAutocomplete which does all the work.
// *************************************************************************
$.fn.ClassCodeSelectorAutocomplete = function(data) 
{
    // Make sure constants exists
    constants = {};

    // set some bulk local data
    constants.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

    // Set default values for required constants
    constants.inputClass = "cc_input";
    constants.resultsClass = "cc_results";
    constants.lineSeparator = "\n";
    constants.cellSeparator = "|";
    constants.minChars = 1;
    constants.delay = 400;
    constants.matchCase = 0;
    constants.matchSubset = 1;
    constants.matchContains = 0;
    constants.cacheLength = 1;
    constants.mustMatch = 0;
    constants.extraParams = {};
    constants.loadingClass = "cc_loading";
    constants.selectFirst = false;
    constants.selectOnly = false;
    constants.maxItemsToShow = -1;
    constants.autoFill = false;
    constants.width = 600;

    this.each(function() 
	{
        var input = this;
        $.ClassCodeSelectorAutocomplete(input, constants);
    });

    // Don't break the chain!
    return this;
}

// *************************************************************************
// -- $.ClassCodeSelectorAutocomplete --
// This is the main function that does all the work for the autocomplete
// control.
// *************************************************************************
$.ClassCodeSelectorAutocomplete = function(input, constants) {
    // Create a link to self
    var me = this;
    var timeout = null;
    var prev = "";
    var active = -1;
    var keyb = false;
    var cache = [];
    var hasFocus = false;
    var lastKeyPressCode = null;

    // Create jQuery object for input element
    var $input = $(input).attr("autocomplete", "off");

    // Create results div
    var results = document.createElement("div");

    // Create jQuery object for results
    var $results = $(results);

    // do some initial setup work.
    initialSetup();

    // hide the any results we have.
    hideResults();

    // *************************************************************************
    //  Functions
    // *************************************************************************

    // ------------------------------------------------------------
    // Add data to the DOM so it can be displayed to the user.
    // ------------------------------------------------------------     
    function dataToDom(data) {
        var ul = document.createElement("ul");
        var num = data.length;

        // limited results to a max number
        if ((constants.maxItemsToShow > 0) && (constants.maxItemsToShow < num)) num = constants.maxItemsToShow;

        for (var i = 0; i < num; i++) {
            var row = data[i];
            if (!row) continue;

            var li = document.createElement("li");
            li.innerHTML = row;
            li.selectValue = row;

            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j = 1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }

            li.extra = extra;
            ul.appendChild(li);
            $(li).hover(
				    function() {
				        $("li", ul).removeClass("cc_over");
				        $(this).addClass("cc_over");
				        active = $("li", ul).indexOf($(this).get(0));
				    },
				    function() { $(this).removeClass("cc_over"); }
			        ).click(function(e) {
			            e.preventDefault();
			            e.stopPropagation();
			            selectItem(this)
			        });
        }

        return ul;
    };

    // ------------------------------------------------------------
    // Finds the position on the current html page to display
    // the div for the results.
    // ------------------------------------------------------------    
    function findPos() {
        var ddlCount = $(hiddenDDLCount).val();
        if ($(ToggleDiv).is(":hidden") || ddlCount == 0) {
            obj = input;
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;

            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }

            return { x: curleft, y: curtop };
        }
        else {
            var toggleDiv = document.getElementById("toggleDiv");
            obj = toggleDiv;
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;

            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }

            return { x: curleft, y: curtop + 21 };
        }
    }

    // ------------------------------------------------------------
    // Finds the position for the dropdown filter.
    // ------------------------------------------------------------
    function findPosForFilter(obj) {
        if ($.browser.msie) {
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;

            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }

            return { x: curleft + 2, y: curtop - 1 };
        }
        else if ($.browser.mozilla) {
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;

            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }

            return { x: curleft - 1, y: curtop - 14 };
        }
        else {
            var curleft = obj.offsetLeft || 0;
            var curtop = obj.offsetTop || 0;

            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }

            return { x: curleft, y: curtop };
        }
    }

    // ------------------------------------------------------------
    // Hides the results from the user.
    // ------------------------------------------------------------    
    function hideResults() {
        $input.removeClass("cc_loading");
        if ($results.is(":visible")) {
            cc_ResultsCurrentlyShown = false;
            $results.hide();
        }
    };

    // ------------------------------------------------------------
    // Does a simple indexOf on data passed into it.
    // ------------------------------------------------------------    
    function indexOf(e) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == e) return i;
        }

        return -1;
    };

    // ------------------------------------------------------------
    // Moves through the results list.
    // ------------------------------------------------------------    
    function moveSelect(step) {
        var lis = $("li", results);
        if (!lis) {
            return;
        }

        active += step;

        if (active < 0) {
            active = 0;
        }
        else if (active >= lis.size()) {
            active = lis.size() - 1;
        }

        lis.removeClass("cc_over");

        $(lis[active]).addClass("cc_over");
    };

    // ------------------------------------------------------------
    // Called when the text in the input field changes.
    // ------------------------------------------------------------    
    function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if (lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32)) {
            return $results.hide();
        }

        $input.addClass(constants.loadingClass);
        //chogue class code performance
        $(lblCompanyDesc).text("None");
 
        var valList = new Array();
        valList[0] = $(hiddenClassGroupID).val();
        valList[1] = $(hiddenSubAppID).val();
        GetISOCodeListData(valList, false, true, urlLevels);
    };

    // ------------------------------------------------------------
    // Receive data from the GetISOCodeListData method and display it.
    // ------------------------------------------------------------    
    function receiveData(data) {
        if (data) {
            if (data.length > 0) {
                $input.removeClass(constants.loadingClass);
                results.innerHTML = "";

                if ($.browser.msie) {
                    // we put a styled iframe behind the calendar so
                    // HTML SELECT elements don't show through                
                    $results.append(document.createElement('iframe'));
                }

                // add items to ul
                results.appendChild(dataToDom(data));

                showResults();
            }
            else {
                hideResults();
            }
        }
        else {
            hideResults();
        }
    };

    // ------------------------------------------------------------
    // Selects the currently highlighted result in the list.
    // ------------------------------------------------------------    
    function selectCurrent() {
        var li = $("li.cc_over", results)[0];
        if (!li) {
            var $li = $("li", results);
            if (constants.selectOnly) {
                if ($li.length == 1) {
                    li = $li[0];
                }
            }
            else if (constants.selectFirst) {
                li = $li[0];
            }
        }
        if (li) {
            selectItem(li);
            return true;
        }
        else {
            return false;
        }
    };

    // ------------------------------------------------------------
    // Call to select an item in the list and do a bunch of stuff
    // when that happens.
    // ------------------------------------------------------------    
    function selectItem(li) {
        if (!li) {
            li = document.createElement("li");
            li.extra = [];
            li.selectValue = "";
        }

        var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
        input.lastSelected = v;
        prev = v;

        // split result string so it can be displayed in Class Code textbox
        // and Class Code description label.
        var firstDash = v.indexOf("-");
        var classCode = v.substring(0, firstDash - 1);
        var classDesc = v.substring(firstDash + 1, v.length).trim();

        $results.html("");
        $input.val(classCode);
        hideResults();
        //chogue class code performance
        $(lblCompanyDesc).text("None");
        $(lblCompanyDesc).text(classDesc);
        $(hiddenDesc).val(classDesc);

        if (constants.onItemSelect) {
            setTimeout(function() { constants.onItemSelect(li) }, 1);
        }

        var urlprefix = "";
        var i;
        for (i = 0; i < urlLevels; i++) {
            urlprefix += "../";
        }

        // hide filter if it's visible.
        if (!$(ToggleDiv).is(":hidden")) {
            $(ToggleButton).attr('src', urlprefix + 'images/plus.gif');
            $(ToggleDiv).slideToggle('fast');
        }

        // get values for company class list
        RetrieveCompanyClassValues(classCode);

        //chogue class code performance
        //GetISOCodeDescription(classCode);
    };

    // ------------------------------------------------------------
    // Does initial setup work.
    // ------------------------------------------------------------    
    function initialSetup() {
        // Apply inputClass if necessary
        $input.addClass(constants.inputClass);

        $results.hide().addClass(constants.resultsClass).css("position", "absolute");
        $results.css("width", constants.width);

        // setup css for filter div
        var $toggleable = $(ToggleDiv);
        $toggleable.addClass("toggleable").css("position", "absolute");

        var filterDivPos = 0;
        filterDivPos = findPosForFilter(input);

        // get the # of drop down lists to display in the filter div.
        var nmbroflists = $(hiddenDDLCount).val();

        // calculate the width of our filter Div
        var divWidth = (nmbroflists * 100) + (nmbroflists * 5);
        if (divWidth > 750) {
            $toggleable.css
			({
			    width: "750px",
			    height: "60px",
			    overflow: "auto",
			    top: (filterDivPos.y + input.offsetHeight) + "px",
			    left: filterDivPos.x + "px"
			});
        }
        else {
            $toggleable.css
			({
			    width: divWidth + "px",
			    top: (filterDivPos.y + input.offsetHeight) + "px",
			    left: filterDivPos.x + "px"
			});

            cc_filterOffset = 20;
        }

        // Add to body element
        $("body").append(results);

        // show the loading graphic
        $input.addClass(constants.loadingClass);

        // if there is a data array supplied
        if (constants.data != null) {
            var sFirstChar = "", stMatchSets = {}, row = [];

            // loop through the array and create a lookup structure
            for (var i = 0; i < constants.data.length; i++) {
                // if row is a string, make an array otherwise just reference the array
                row = ((typeof constants.data[i] == "string") ? [constants.data[i]] : constants.data[i]);

                // if the length is zero, don't add to list
                if (row[0].length > 0) {
                    // get the first character
                    sFirstChar = row[0].substring(0, 1).toLowerCase();

                    // if no lookup array for this character exists, look it up now
                    if (!stMatchSets[sFirstChar]) stMatchSets[sFirstChar] = [];

                    // if the match is a string
                    stMatchSets[sFirstChar].push(row);
                }
            }

            // add the data items to the cache
            for (var k in stMatchSets) {
                // increase the cache size
                constants.cacheLength++;
                // add to the cache
                addToCache(k, stMatchSets[k]);
            }
        }
    }

    // ------------------------------------------------------------
    // Shows the results div to the user.
    // ------------------------------------------------------------    
    function showResults() {
        var pos = 0;
        pos = findPos();

        // either use the specified width, or autocalculate based on form element
        var iWidth = constants.width;

        cc_ResultsCurrentlyShown = true;
        // reposition
        $results.css
		({
		    width: parseInt(iWidth) + "px",
		    top: (pos.y + input.offsetHeight) + "px",
		    left: pos.x + "px"
		}).show();
    };

    // *************************************************************************
    //  Functions for external use.
    // *************************************************************************

    // ------------------------------------------------------------
    // External method so that functions outside of ClassCodeSelectorAutocomplete can call
    // in to show the results.
    // ------------------------------------------------------------    
    $.fn.ClassCodeSelectorAutocomplete.ShowResults = function() {
        showResults();
    };

    // ------------------------------------------------------------
    // External method so that functions outside of ClassCodeSelectorAutocomplete can call
    // in to hide the results.
    // ------------------------------------------------------------    
    $.fn.ClassCodeSelectorAutocomplete.HideResults = function() {
        hideResults();
    };

    // ------------------------------------------------------------
    // External method so that functions outside of ClassCodeSelectorAutocomplete can call
    // in to get a new set of ISO code data.
    // ------------------------------------------------------------    
    $.fn.ClassCodeSelectorAutocomplete.GetISOCodeListData = function(IDList, select) {
        GetISOCodeListData(IDList, select, refreshCache, levels);
    }

    // ------------------------------------------------------------
    // External method so that functions outside of ClassCodeSelectorAutocomplete can call
    // in to get the ID's from the filters and reset the list of ISO codes.
    // ------------------------------------------------------------    
    $.fn.ClassCodeSelectorAutocomplete.CollectIDsFromClassCodeFilter = function() {
        CollectIDsFromClassCodeFilter();
    }

    // *************************************************************************
    //  Callback Functions
    // *************************************************************************

    // ------------------------------------------------------------
    // Callback to flush cache.
    // ------------------------------------------------------------    
    this.flushCache = function() {
        flushCache();
    };

    // ------------------------------------------------------------
    // Callback to set constants.extraParams 
    // ------------------------------------------------------------    
    this.setExtraParams = function(p) {
        constants.extraParams = p;
    };

    // *************************************************************************
    //  Event Handlers
    // *************************************************************************

    // ------------------------------------------------------------
    // Click event on the body of the document.
    // ------------------------------------------------------------
    $('body').click(function() {
        hideResults();
    });

    // ------------------------------------------------------------
    // Handles keydown event for input field.
    // ------------------------------------------------------------    
    $input.keydown(function(e) {
        // track last key pressed
        lastKeyPressCode = e.keyCode;
        switch (e.keyCode) {
            case 38: // up
                e.preventDefault();
                moveSelect(-1);
                break;
            case 40: // down
                e.preventDefault();
                moveSelect(1);
                break;
            case 9:  // tab     
                var classCode = $input.val();
                // get values for company class list
                RetrieveCompanyClassValues(classCode);
                // get the iso class description
                GetISOCodeDescription(classCode);
                //chogue class code performance
                hideResults();
                break;
            case 13: // return
                if (selectCurrent()) {
                    // make sure to blur off the current field
                    $input.get(0).blur();
                    e.preventDefault();
                }
                break;
            default:
                active = -1;
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(function() { onChange(); }, constants.delay);
                break;
        }
    });

    // ------------------------------------------------------------
    // Called when the input field gains focus.
    // ------------------------------------------------------------    
    $input.focus(function() {
        // track whether the field has focus, we shouldn't process 
        // any results if the field no longer has focus
        hasFocus = true;

        // if the field regains focus we should show the list of data if 
        // there is any in the cache.
        receiveData(cache);
    });

//chogue class code performance
    // ------------------------------------------------------------
    // Called when the input field loses focus.
    // ------------------------------------------------------------    
//    $input.blur(function(e) {
//        if ($input.val().length > 0) {
//            var urlprefix = "";
//            var i;
//            for (i = 0; i < urlLevels; i++) {
//                urlprefix += "../";
//            }

//            // hide filter if it's visible.
//            if (!$(ToggleDiv).is(":hidden")) {
//                $(ToggleButton).attr('src', urlprefix + 'images/plus.gif');
//                $(ToggleDiv).slideToggle('fast');
//            }

//            var classCode = $input.val();
//            // get values for company class list
//            RetrieveCompanyClassValues(classCode);
//            // get the iso class description
//            GetISOCodeDescription(classCode);
//        }

//        // track whether the field has focus
//        hasFocus = false;

//        hideResults();

//        // kill any asynch process currently running
//        if (isoCodeRequest != null) {
//            isoCodeRequest.abort();
//        }
//    });

    // ------------------------------------------------------------
    // Called when results UL gains focus.
    // ------------------------------------------------------------    
    $results.focus(function() {
        if ($results.html() != "") {
            showResults();
        }
    });

    // ------------------------------------------------------------
    // Called when results UL loses focus.
    // ------------------------------------------------------------    
    $results.blur(function() {
        // IE has a weird bug where the focus & blur events
        // fire when the div initially gains focus.
        if (!cc_DivClicked) {
            cc_DivClicked = true;
            $results.focus();
        }
        else {
            cc_DivClicked = false;
            hideResults();
        }
    });

    // ------------------------------------------------------------
    // Click event for the results div ul list.
    // ------------------------------------------------------------
    $results.click(function(event) {
        event.stopPropagation();
    });

    // -------------------------------------------------------------------------------------------------------------------------------------
    //  AJAX Webservice Calls - [BEGIN]
    // -------------------------------------------------------------------------------------------------------------------------------------

    // ------------------------------------------------------------
    // Calls the ClassCodeLookupService webservice and returns the data in xml format.
    // called by RetrieveCompanyClassValues data method below.
    // ------------------------------------------------------------    
    function GetCompanyClassData(classCode, classGroupID, subAppID, rateSetEffDate, callback) {
        var urlprefix = "";
        var i;
        for (i = 0; i < urlLevels; i++) {
            urlprefix += "../";
        }

        var params = '{ "classCode":"' + classCode + '", "classGroupID":"' + classGroupID + '", "subAppID":"' + subAppID + '", "rateSetEffDate":"' + rateSetEffDate + '" }';
        //var params = { classCode: classCode, classGroupID: classGroupID, subAppID: subAppID, rateSetEffDate: rateSetEffDate };

        companyCodeRequest = $.ajax
		({
		    type: "POST",
		    url: urlprefix + "Webservices/ClassCodeLookupService.asmx/GetCompanyClassInfo",
		    data: params,
		    contentType: "application/json; charset=utf-8",
		    dataType: "json",
		    success: function(result) {
		        callback(result);
		    }
		});
    }

    // ------------------------------------------------------------
    // Retrieves the description for the iso code entered in the input box.
    // ------------------------------------------------------------    
    function GetISOCodeDescription(isoCode) {
        var urlprefix = "";
        var i;
        for (i = 0; i < urlLevels; i++) {
            urlprefix += "../";
        }

        var params = '{"isoCode":"' + isoCode + '"}';

        descriptionRequest = $.ajax
        ({
            type: "POST",
            url: urlprefix + "Webservices/ClassCodeLookupService.asmx/GetISODescription",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                $(lblCompanyDesc).text(result.d);
                $(hiddenDesc).val(result.d);
            }
        });
    }

    // ------------------------------------------------------------
    // Retrieves the ISO codes from the webservice.
    // ------------------------------------------------------------
    function RetrieveISOCodes(IDList, userInput, callback) {
        var urlprefix = "";
        var ratesetEffDate = $(rateSetDate).val();
        var i;
        
        for (i = 0; i < urlLevels; i++) {
            urlprefix += "../";
        }

        var params = '{"groupIDArray":"' + IDList + '","userInput":"' + userInput + '","ratesetEffDate":"' + ratesetEffDate + '" }';

        isoCodeRequest = $.ajax
		({
		    type: "POST",
		    url: urlprefix + "Webservices/ClassCodeLookupService.asmx/GetClassCodes",
		    data: params,
		    contentType: "application/json; charset=utf-8",
		    dataType: "json",
		    success: function(result) {
		        callback(result);
		    }
		});
    }

    // -------------------------------------------------------------------------------------------------------------------------------------
    //  Data Methods - [BEGIN]
    // -------------------------------------------------------------------------------------------------------------------------------------

    // ------------------------------------------------------------
    // Retrieves the company class values for the drop down list.
    // ------------------------------------------------------------    
    function RetrieveCompanyClassValues(classCode) {
        var baseGroupID = $(hiddenClassGroupID).val();
        var subAppID = $(hiddenSubAppID).val();
        var rateSetEffDate = $(rateSetDate).val();
        var resultsFound = false;

        // call GetCompanyClassData to access the web service
        GetCompanyClassData(classCode, baseGroupID, subAppID, rateSetEffDate, function(result) {
            companyCodeRequest = null;
            var data = "";

            for (var i = 0; i < result.d.length; i++) {
                var companyClassCode = result.d[i].CompanyClassCode;
                var companyClassDescription = result.d[i].CompanyClassDescription;
                var classKey = result.d[i].ClassKey;

                if (companyClassDescription == "None") {
                    data += classKey + "|" + companyClassCode + " - None" + "||";
                }
                else {
                    data += classKey + "|" + companyClassCode + " - " + companyClassDescription + "||";
                }
            }

            // create an array of data for the autocomplete control
            var finaldata = data.split("||");

            // clear drop down
            $(drpCompanyClass).find('option').remove();

            // loop through array and add to drop down list.
            if (finaldata.length > 0) {
                var options = "";
                if (finaldata.length > 1) {
                    for (var i = 0; i < finaldata.length - 1; i++) {
                        var firstPipe = finaldata[i].indexOf("|");
                        var firstDash = finaldata[i].indexOf("-");
                        var classKey = finaldata[i].substring(0, firstPipe);
                        var classCode = finaldata[i].substring(firstPipe + 1, firstDash - 1);
                        var classDesc = finaldata[i].substring(firstDash + 1, finaldata[i].length).trim();

                        // build options list
                        options += '<option title="' + classCode + ' - ' + classDesc + '" value=\"' + classKey + '~' + classCode + '~' + classDesc + '\">' + classCode + ' - ' + classDesc + '</option>';
                    }

                    $(drpCompanyClass).html(options);
                }
                else {
                    options = '<option value=noresults">No results found.</option>';
                    //chogue class code performance
                    //$(lblCompanyDesc).text("None");
                    $(drpCompanyClass).html(options);
                }
            }
        })
    }

    // ------------------------------------------------------------
    // Gets the ISO code data for the dropdown list.
    // ------------------------------------------------------------    
    function GetISOCodeListData(IDList, select) {
        var userInput = "";
        var baseGroupID = $(hiddenClassGroupID).val();

        if (select == false) {
            userInput = $(txtClassCode).val();
            var valList = new Array();
            valList[0] = $(hiddenClassGroupID).val();
            valList[1] = $(hiddenSubAppID).val();
            IDList = valList;
        }

        if (IDList != undefined && userInput != undefined) {
            $(txtClassCode).addClass("cc_loading");

            // call RetrieveISOCodes to access the web service
            RetrieveISOCodes(IDList, userInput, function(result) {
                isoCodeRequest = null;
                var data = "";

                for (var i = 0; i < result.d.length; i++) {
                    var classCode = result.d[i].ClassCode;
                    var className = result.d[i].ClassName;
                    data += classCode + " - " + className + "||";
                }

                if (data == "") {
                    data += "No results returned based on search criteria.";
                }

                $(txtClassCode).removeClass("cc_loading");

                // create an array of data for the autocomplete control
                var finaldata = data.split("||");

                cache = finaldata;
                receiveData(finaldata);
            })
        }
    }

    // ------------------------------------------------------------
    // Goes through all drop down lists in the filter functionality and
    // creates an array of values. It then calls GetISOCodeListData to 
    // get the data from the webservice and refresh the cache.
    // ------------------------------------------------------------    
    function CollectIDsFromClassCodeFilter() {
        var foundValue = false;
        var valueList = new Array();
        var valueCounter = 0;
        var i;
        var ddlCount = $(hiddenDDLCount).val();

        for (i = 0; i < ddlCount; i++) {
            var obj = document.getElementById("select" + (i + 1));
            if (obj != null) {
                if (obj.value != "-1") {
                    valueList[i] = obj.value;
                    foundValue = true;
                }
            }
        }

        if (foundValue == true) {
            valueList[ddlCount] = $(hiddenSubAppID).val();
        }

        // we had all -1's in the drop downs we need to load the default list.
        if (foundValue == false) {
            valueList[0] = $(hiddenClassGroupID).val();
            valueList[1] = $(hiddenSubAppID).val();
        }

        // fill the autocomplete div behind the scenes with data    
        GetISOCodeListData(valueList, true);
    }
}
