//
// Common JavaScript function to support cascade-drop down select lists.
//
// Use createSbxCascadeDropDownSelector helper function to create binding
//    cascade_dropdown_source_selector_id : The HTML tag ID of the original multi or single selector.
//    cascade_dropdown_data_name : data name to be used to bind with ajax service callbacks
//

// Debug settings
// Set to true to enable debug
//
var cascade_drop_down_debug = false;
//cascade_drop_down_debug = true;
if (cascade_drop_down_debug == true) {
  window.loadFirebugConsole();
}

var sbx_msie6_or_less = false;

// Prepopulated level 1 JavaScript array for page load optimization
//
var sbx_prepopulated_1st_level_dropdown = new Array;
sbx_prepopulated_1st_level_dropdown['customers'] = {
  1 : {
    0 : 0,
    1 : {
      /*
      "1000" : "Department of Agriculture (USDA)",
      "1069" : "Department of Commerce (DOC)",
      "1127" : "Department of Defense (DOD)",
      "1763" : "Department of Education (ED)",
      "1809" : "Department of Energy (DOE)",
      "1936" : "Department of Health and Human Services (HHS)",
      "2103" : "Department of Homeland Security (DHS)",
      "2245" : "Department of Housing and Urban Development (HUD)",
      "2293" : "Department of Justice (DOJ)",
      "2344" : "Department of Labor (DOL)",
      "2375" : "Department of State (DOS)",
      "2420" : "Department of the Interior (DOI)",
      "2460" : "Department of the Treasury",
      "2482" : "Department of Transportation (DOT)",
      "2520" : "Department of Veterans Affairs (VA)",
      "2566" : "Independent Agencies and Government Corporations",
      "3104" : "Boards, Commissions and Committees",
      "3188" : "US Courts",
      "3209" : "Congress",
      "3241" : "Executive Office of the President",
      "3260" : "Quasi-Official Agencies"
      */
      "24503" : "ADVISORY COUNCIL ON HISTORIC PRESERVATION",
      "24504" : "AFRICAN DEVELOPMENT FOUNDATION",
      "24505" : "AGENCY FOR INTERNATIONAL DEVELOPMENT",
      "24506" : "AGRICULTURE",
      "24551" : "AIR FORCE",
      "24690" : "AMERICAN BATTLE MONUMENTS COMMISSION",
      "24691" : "APPALACHIAN REGIONAL COMMISSION",
      "24692" : "ARCHITECTURAL AND TRANSPORTATION BARRIERS COMPLIANCE BOARD",
      "24830" : "ARCTIC RESEARCH COMMISSION",
      "24693" : "ARMED FORCES RETIREMENT HOME",
      "24696" : "ARMY",
      "24831" : "BARRY GOLDWATER SCHOLARSHIP AND EXCELLENCE IN EDUCATION FOUNDATION",
      "25867" : "BROADCASTING BOARD OF GOVERNORS",
      "24832" : "CENTRAL INTELLIGENCE AGENCY",
      "24833" : "CHEMICAL SAFETY AND HAZARD INVESTIGATION BOARD",
      "24834" : "CHRISTOPHER COLUMBUS FELLOWSHIP FOUNDATION",
      "24835" : "CIVIL LIBERTIES PUBLIC EDUCATION FUND BOARD",
      "24836" : "COMMERCE",
      "24858" : "COMMISSION FOR THE PRESERVATION OF AMERICA'S HERITAGE ABROAD",
      "24859" : "COMMISSION OF FINE ARTS",
      "24860" : "COMMISSION ON CIVIL RIGHTS",
      "24861" : "COMMISSION ON EXECUTIVE, LEGISLATIVE AND JUDICIAL SALARIES",
      "24862" : "COMMITTEE FOR PURCHASE FROM PEOPLE WHO ARE BLIND OR SEVERELY DISABLED",
      "24863" : "COMMODITY FUTURES TRADING COMMISSION",
      "24865" : "CONGRESS",
      "24895" : "CONSUMER PRODUCT SAFETY COMMISSION",
      "24896" : "CORPORATION FOR NATIONAL AND COMMUNITY SERVICE",
      "24897" : "CORPORATION FOR PUBLIC BROADCASTING",
      "26598" : "COURT SERVICES AND OFFENDER SUPERVISION AGENCY FOR THE DISTRICT OF COLUMBIA",
      "24898" : "DEFENSE",
      "24988" : "DEFENSE NUCLEAR FACILITIES SAFETY BOARD",
      "116361" : "DELTA REGIONAL AUTHORITY",
      "116360" : "DENALI COMMISSION",
      "24989" : "EDUCATION",
      "116362" : "ELECTION ASSISTANCE COMMISSION",
      "25030" : "ENERGY",
      "25097" : "ENVIRONMENTAL PROTECTION AGENCY",
      "25124" : "EQUAL EMPLOYMENT OPPORTUNITY COMMISSION",
      "25126" : "EXECUTIVE OFFICE OF THE PRESIDENT",
      "25142" : "EXPORT-IMPORT BANK OF THE US",
      "25143" : "FARM CREDIT ADMINISTRATION",
      "25149" : "FEDERAL COMMUNICATIONS COMMISSION",
      "25150" : "FEDERAL DEPOSIT INSURANCE CORP",
      "25151" : "FEDERAL ELECTION COMMISSION",
      "25152" : "FEDERAL FINANCIAL INSTITUTIONS EXAMINATION COUNCIL",
      "25153" : "FEDERAL HOUSING FINANCE BOARD",
      "25154" : "FEDERAL LABOR RELATIONS AUTHORITY",
      "25155" : "FEDERAL MARITIME COMMISSION",
      "25156" : "FEDERAL MEDIATION AND CONCILIATION SERVICE",
      "25157" : "FEDERAL MINE SAFETY AND HEALTH REVIEW COMMISSION",
      "25158" : "FEDERAL RESERVE SYSTEM/BOARD OF GOVERNORS",
      "25159" : "FEDERAL RETIREMENT THRIFT INVESTMENT BOARD",
      "25160" : "FEDERAL TRADE COMMISSION",
      "25162" : "GENERAL SERVICES ADMINISTRATION",
      "25211" : "HARRY S TRUMAN SCHOLARSHIP FOUNDATION",
      "25212" : "HEALTH AND HUMAN SERVICES",
      "25265" : "HOMELAND SECURITY",
      "25284" : "HOUSING AND URBAN DEVELOPMENT",
      "25319" : "INSTITUTE OF AMERICAN INDIAN AND ALASKA NATIVE CULTURE AND ARTS DEVELOPMENT",
      "29388" : "INSTITUTE OF MUSEUM AND LIBRARY SERVICES",
      "25320" : "INTER-AMERICAN FOUNDATION",
      "25321" : "INTERIOR",
      "124820" : "INTERNATIONAL BOUNDRY AND WATER COMMISSION",
      "25355" : "INTERSTATE COMMISSION ON THE POTOMAC RIVER BASIN",
      "25356" : "JAMES MADISON MEMORIAL FELLOWSHIP FOUNDATION",
      "25357" : "JAPAN-US FRIENDSHIP COMMISSION",
      "25358" : "JUSTICE",
      "25402" : "LABOR",
      "25422" : "LEGAL SERVICES CORP",
      "25423" : "MARINE CORPS",
      "25452" : "MARINE MAMMAL COMMISSION",
      "116429" : "MILLENNIUM CHALLENGE CORPORATION",
      "25454" : "MORRIS K UDALL SCHOLARSHIP AND EXCELLENCE IN NATIONAL ENVIRONMENTAL POLICY FOUNDATION",
      "25455" : "NATIONAL AERONAUTICS AND SPACE ADMINISTRATION",
      "25471" : "NATIONAL ARCHIVES AND RECORDS ADMINISTRATION",
      "25480" : "NATIONAL CAPITAL PLANNING COMMISSION",
      "25481" : "NATIONAL COMMISSION ON LIBRARIES AND INFORMATION SCIENCE",
      "25483" : "NATIONAL COUNCIL ON DISABILITY",
      "25484" : "NATIONAL COUNTERINTELLIGENCE CENTER",
      "25485" : "NATIONAL CREDIT UNION ADMINISTRATION",
      "25488" : "NATIONAL FOUNDATION ON THE ARTS AND THE HUMANITIES",
      "25495" : "NATIONAL LABOR RELATIONS BOARD",
      "25496" : "NATIONAL MEDIATION BOARD",
      "25497" : "NATIONAL SCIENCE FOUNDATION",
      "25498" : "NATIONAL TRANSPORTATION SAFETY BOARD",
      "25499" : "NAVY",
      "25636" : "NEIGHBORHOOD REINVESTMENT CORP",
      "25637" : "NUCLEAR REGULATORY COMMISSION",
      "25638" : "NUCLEAR WASTE TECHNICAL REVIEW BOARD",
      "25639" : "OCCUPATIONAL SAFETY AND HEALTH REVIEW COMMISSION",
      "25640" : "OFFICE OF GOVERNMENT ETHICS",
      "25641" : "OFFICE OF NAVAJO AND HOPI INDIAN RELOCATION",
      "25642" : "OFFICE OF PERSONNEL MANAGEMENT",
      "25673" : "OFFICE OF SPECIAL COUNSEL",
      "25674" : "OUNCE OF PREVENTION COUNCIL",
      "25675" : "OVERSEAS PRIVATE INVESTMENT CORP",
      "25676" : "PANAMA CANAL COMMISSION",
      "25677" : "PEACE CORPS",
      "28397" : "PENSION BENEFIT GUARANTY CORP",
      "25678" : "RAILROAD RETIREMENT BOARD",
      "25679" : "RESOLUTION FUNDING CORP (REFCORP)",
      "25680" : "SECURITIES AND EXCHANGE COMMISSION",
      "25682" : "SELECTIVE SERVICE SYSTEM",
      "25683" : "SMALL BUSINESS ADMINISTRATION",
      "25684" : "SMITHSONIAN INSTITUTION",
      "25685" : "SOCIAL SECURITY ADMINISTRATION",
      "25735" : "STATE",
      "25775" : "STATE JUSTICE INSTITUTE",
      "25776" : "TENNESSEE VALLEY AUTHORITY",
      "25778" : "TRANSPORTATION",
      "25803" : "TREASURY",
      "25815" : "UNITED MINE WORKERS OF AMERICA BENEFIT FUNDS",
      "25816" : "US COURTS",
      "25830" : "US HOLOCAUST MEMORIAL COUNCIL",
      "25831" : "US INSTITUTE OF PEACE",
      "25832" : "US INTERNATIONAL TRADE COMMISSION",
      "25453" : "US MERIT SYSTEMS PROTECTION BOARD",
      "25833" : "US POSTAL SERVICE",
      "25777" : "US TRADE AND DEVELOPMENT AGENCY",
      "25834" : "VETERANS AFFAIRS",
      "25866" : "WASHINGTON METROPOLITAN AREA TRANSIT AUTHORITY",
      "116359" : "WOODROW WILSON INTERNATIONAL CENTER FOR SCHOLARS"
    }
  }
};

sbx_prepopulated_1st_level_dropdown['state_customers'] = {
  1 : {
    0 : 0,
    1 : {
      "19787" : "ALABAMA",
      "19850" : "ALASKA",
      "19881" : "ARIZONA",
      "19985" : "ARKANSAS",
      "20037" : "CALIFORNIA",
      "20278" : "COLORADO",
      "20346" : "CONNECTICUT",
      "20408" : "DELAWARE",
      "20445" : "DISTRICT OF COLUMBIA",
      "20483" : "FLORIDA",
      "20622" : "GEORGIA",
      "20732" : "HAWAII",
      "20772" : "IDAHO",
      "20806" : "ILLINOIS",
      "20877" : "INDIANA",
      "20928" : "IOWA",
      "20964" : "KANSAS",
      "21020" : "KENTUCKY",
      "21065" : "LOUISIANA",
      "21110" : "MAINE",
      "21141" : "MARYLAND",
      "21276" : "MASSACHUSETTS",
      "21346" : "MICHIGAN",
      "21386" : "MINNESOTA",
      "21438" : "MISSISSIPPI",
      "21481" : "MISSOURI",
      "21541" : "MONTANA",
      "21574" : "NEBRASKA",
      "21614" : "NEVADA",
      "21652" : "NEW HAMPSHIRE",
      "21689" : "NEW JERSEY",
      "21728" : "NEW MEXICO",
      "21776" : "NEW YORK",
      "21906" : "NORTH CAROLINA",
      "21987" : "NORTH DAKOTA",
      "22020" : "OHIO",
      "22070" : "OKLAHOMA",
      "22120" : "OREGON",
      "22184" : "PENNSYLVANIA",
      "22244" : "PUERTO RICO",
      "22249" : "RHODE ISLAND",
      "22290" : "SOUTH CAROLINA",
      "22370" : "SOUTH DAKOTA",
      "22407" : "TENNESSEE",
      "22461" : "TEXAS",
      "22616" : "UTAH",
      "22660" : "VERMONT",
      "22697" : "VIRGINIA",
      "22857" : "WASHINGTON",
      "22996" : "WEST VIRGINIA",
      "23029" : "WISCONSIN",
      "23105" : "WYOMING",
      "26611" : "GUAM",
      "26814" : "NATIONWIDE",
      "29386" : "AMERICAN SAMOA",
      "29387" : "VIRGIN ISLANDS",
      "30722" : "NORTHERN MARIANA ISLANDS"      
    }
  }
};

sbx_prepopulated_1st_level_dropdown['solutions'] = {
  1: {
    0: 0,
    1: {
      "1": "Architecture, Engineering & Construction (AEC)",
      "255": "Chemicals, Fuels, Lubricants & Oils",
      "256": "Clothing & Textiles",
      "257": "Defense & Aerospace",
      "258": "Electric Components & Parts",
      "259": "Engines & Mechanical Equipment",
      "260": "Fiber Optic Materials & Components",
      "261": "Food & Sanitary Products",
      "262": "Furniture & Appliances",
      "263": "Health Care & Medical Services",
      "84": "IT",
      "266": "Land Vehicles & Equipment",
      "267": "Machinery, Equipment & Tools",
      "268": "Medical/Laboratory Equipment & Products",
      "269": "Natural Resources & Environment",
      "270": "Office Machines, Equipment & Supplies",
      "271": "Operations & Maintenance",
      "272": "Other Products & Materials",
      "150": "Professional Services",
      "276": "Purchase or Lease of Facilities & Equipment",
      "277": "Recreational Equipment",
      "165": "Research and Development",
      "278": "Ship & Marine Equipment",
      "279": "Social Services"
    }
  }
};
sbx_prepopulated_1st_level_dropdown['naics'] = {
  1: {
    0: 0,
    1: {
      "11" : "11  Agriculture, Forestry, Fishing and Hunting",
      "21" : "21  Mining, Quarrying, and Oil and Gas Extraction",
      "22" : "22  Utilities",
      "23" : "23  Construction",
      "31" : "31-33  Manufacturing",
      "42" : "42  Wholesale Trade",
      "44" : "44-45  Retail Trade",
      "48" : "48-49  Transportation and Warehousing",
      "51" : "51  Information",
      "52" : "52  Finance and Insurance",
      "53" : "53  Real Estate and Rental and Leasing",
      "54" : "54  Professional, Scientific, and Technical Services",
      "55" : "55  Management of Companies and Enterprises",
      "56" : "56  Administrative and Support and Waste Management and Remediation Services",
      "61" : "61  Educational Services",
      "62" : "62  Health Care and Social Assistance",
      "71" : "71  Arts, Entertainment, and Recreation",
      "72" : "72  Accommodation and Food Services",
      "81" : "81  Other Services (except Public Administration)",
      "92" : "92  Public Administration"
    }
  }
};

// Default selector option values
//
var sbx_cascadedropdown_ext_mouse_over_help = 'Select a more specific option if necessary. If even more specific options are available for your selection, an additional drop down menu will open.';
var sbx_cascadedropdown_ext_default_option = 'Refine your choice (optional)...';
var sbx_cascadedropdown_1st_default_option = {
  'state_customers' : 'Select a customer...',
  'customers' : 'Select a customer...',
  'naics' : 'Choose an industry (NAICS code)...',
  'solutions' : 'Choose a solution competency...'
};

// Helper factory fucntion to create sbxCascadeDropDownSelector objects
//
function createSbxCascadeDropDownSelector (cascade_dropdown_source_selector_id, cascade_dropdown_data_name, help_rel_link) {
  var o = new sbxCascadeDropDownSelector ();
  o.setHelpRelLink (help_rel_link);
  o.bind (cascade_dropdown_source_selector_id, cascade_dropdown_data_name);
  return o;
}

// sbxCascadeDropDownSelector class definition
//
var cascade_drop_down_log_id_prefix = 'sbx-cascade-dropdown-log-';

function sbxCascadeDropDownSelector () {
  //sbx_msie6_or_less = ($.browser.msie() && $.browser.version.number() < 7.0);
  sbx_msie6_or_less = ($.browser.msie && $.browser.version < 7.0);
  sbx_msie6_or_less = false;
  this.cascade_dropdown_source_selector_id = null;
  this.cascade_dropdown_data_name = null;
  this.source_selector = null;
  this.cascade_selector_list = null;
  this.selection_display = null;
  this.selection_name = 'item';
  this.no_selection_message = 'None required.';
  this.default_select_option_text = "";
  this.original_mouse_over_help = '';
  this.description_element = null;
  this.helpRelLink = '';
}

sbxCascadeDropDownSelector.prototype.bind = function (cascade_dropdown_source_selector_id, cascade_dropdown_data_name) {
  this.cascade_dropdown_source_selector_id = cascade_dropdown_source_selector_id;
  this.cascade_dropdown_data_name = cascade_dropdown_data_name;
  this.source_selector = $('#' + cascade_dropdown_source_selector_id);
  if (this.source_selector.length == 0) {
    return;
  }
  this.is_multiple_select = (this.source_selector.attr ('multiple'));
  if (cascade_drop_down_debug != true) {
    this.source_selector.hide();
  }
  this.selected_name_list = new Array ();
  this.selected_name_list_option_id = new Array ();
  this.cascade_selector_list = new Array();
  var initial_selected_id = (this.is_multiple_select) ? 0 : this.source_selector.val();

  this.description_element = $($('.description', this.source_selector.parent())[0]).remove();
  this.original_mouse_over_help = this.description_element.html();
  this.suggest_option_msg = '' + $('#sbx_suggest_option_msg', this.description_element).html();
  this.fieldLabel = $($('label', this.source_selector.parent())[0]);  
  var fieldLabelText = this.fieldLabel.html();
  var i = fieldLabelText.lastIndexOf (':');
  var l = fieldLabelText.length;
  var helpMarkup = '(<a rel="' + this.helpRelLink + '" title="Learn more about this term" href="/node/200" class="mysbxInfoHelp">?</a>)';
  if (i < 0) {
    fieldLabelText = fieldLabelText + helpMarkup;
  }
  else if (i == 0) {
    fieldLabelText = helpMarkup + fieldLabelText;
  }
  else {
    fieldLabelText = fieldLabelText.substr (0, i) + helpMarkup + fieldLabelText.substr (i);
  }
  this.fieldLabel.html (fieldLabelText);
  
  this.setResourceSubselector();

  this.create_cascade_dropdown (initial_selected_id);
}

sbxCascadeDropDownSelector.prototype.rebind = function (cascade_dropdown_source_selector_id, cascade_dropdown_data_name) {
  this.remove_descendant_selectors(0);
  this.cascade_dropdown_source_selector_id = cascade_dropdown_source_selector_id;
  this.cascade_dropdown_data_name = cascade_dropdown_data_name;
  this.setResourceSubselector();

  this.create_cascade_dropdown (0);
}

sbxCascadeDropDownSelector.prototype.setResourceSubselector = function () {
  switch (this.cascade_dropdown_data_name) {
    case 'customers':
    case 'state_customers':
      var radio = this.cascade_dropdown_source_selector_id + "-radio";
      if ($("input[name='" + radio + "']").length > 0)
        return;
      this.source_selector.before("<div><input type='radio' name='" + radio + "' id='" + radio + "-0' value='0' checked='checked'/><label for='" + radio + "-0' class='radio'>Federal</label><input type='radio' name='" + radio + "' id='" + radio + "-1' value='1' /><label for='" + radio + "-1' class='radio'>State and Local</label></div>");
      var selector = this;
      $("input[name='"+ radio + "']").change(
        function() {
          if ($("input[name='" + radio + "']:checked").val()==1) {
            selector.rebind(selector.cascade_dropdown_source_selector_id, "state_customers");
          }
          else {
            selector.rebind(selector.cascade_dropdown_source_selector_id, "customers");
            
          }
        });

  }
}

sbxCascadeDropDownSelector.prototype.setHelpRelLink = function (relLink) {
  this.helpRelLink = relLink;
}

sbxCascadeDropDownSelector.prototype.setNoSelectionMessageText = function (msg_text) {
  this.oSelectedList.children('#no-select').text (msg_text);
  this.no_selection_message = msg_text;
}

sbxCascadeDropDownSelector.prototype.setDefaultSelectOptionText = function (option_text) {
  /*
  for (selector_index in this.cascade_selector_list) {
    this.cascade_selector_list[selector_index].children ('[@value="0"]').each ( function () {
      $(this).text (option_text);
    });
  }
  */
  this.cascade_selector_list[1].children ('[value="0"]').each ( function () {
    $(this).text (option_text);
  });
  this.default_select_option_text = option_text;
}

sbxCascadeDropDownSelector.prototype.setSelectOptionTypeName = function (name) {
  this.oNewSelectLink.text ('Select another ' + name);
  this.selection_name = name;
}

sbxCascadeDropDownSelector.prototype.create_cascade_dropdown =  function (current_scid) {
  var this_cascade_dropdown = this;
  var data_space_name = this.cascade_dropdown_data_name;
  if (parseInt (current_scid) == 0) {
    init_part_tree (sbx_prepopulated_1st_level_dropdown[data_space_name]);
  }
  else {
    $.getJSON('/mysbx-ajax-service/cascade-dropdowns/full-cascade/' + data_space_name + '/' + current_scid, function (data) {
      init_part_tree (data);
    });
  }
  
  function init_part_tree (part_tree_data) {
    this_cascade_dropdown.init_dropdown_selectors (part_tree_data);
    this_cascade_dropdown.init_dropdown_item_list();
  }
}

sbxCascadeDropDownSelector.prototype.init_dropdown_selectors = function (part_tree) {
  var prev_dom_obj = this.source_selector;
  for (level in part_tree) {
    options = part_tree[level][1];
    selected_scid = part_tree[level][0];
    prev_dom_obj = this.create_dropdown_selector (options, prev_dom_obj, level, selected_scid);
  }
}

sbxCascadeDropDownSelector.prototype.init_dropdown_item_list = function () {
  var this_cascade_dropdown = this;
  
  if (this.is_multiple_select) {
    if (this.oSelectedListContainer!=null) 
      return;
    var noSelectMessage = 'None required.';
    var oNewSelectLink = $('<a class="action mysbxDropdownCascadeSelect"><strong>Select another ' + this.selection_name + '</strong></a>');
    var oSelectedListContainer = $('<div class="listContainer"><span class="selection"><b>Selections:</b></span>' +
      '<ul id="multiSelectedList" class="mysbxSelectedList"><li id="no-select" class="no-select">' + this.no_selection_message + '</li></ul></div>');
    this.oSelectedListContainer = oSelectedListContainer;
    this.oSelectedList = oSelectedListContainer.children("#multiSelectedList");
    this.oNewSelectLink = oNewSelectLink;
    oNewSelectLink.insertAfter (this.source_selector.parent());
    oSelectedListContainer.insertAfter (oNewSelectLink);
    this.newSelectState = true;
    
    oNewSelectLink.bind ('click', function () {
      this_cascade_dropdown.newSelectState = true;
      this_cascade_dropdown.cascade_selector_list[1].val (0);
      this_cascade_dropdown.cascade_selector_list[1].change();
      this_cascade_dropdown.refreshNewSelectLinkDisplay ();
    });
    
    this.refreshSelectedNameListAndItemListBySourceMultiSelector ();
  }
  else {
    var selection_display_id = cascade_drop_down_log_id_prefix + '-' + this.cascade_dropdown_source_selector_id;
    if ($('#' + selection_display_id).length > 0) {
      return;
    }
    var selection_display_sec = $('<br/><div><strong>Current Selection: </strong><span id="' + selection_display_id + '" style="color:green"></span></div>');
    selection_display_sec.insertAfter (this.source_selector.parent());
    this.selection_display = $('#' + selection_display_id);
    var curr_cascade_level = this.cascade_selector_list.length - 1; //JS array is zero based, so for level N we have length N+1
    var curr_selected_item_id = this.cascade_selector_list[curr_cascade_level].val();
    if (curr_selected_item_id == 0 && curr_cascade_level > 1) {
      curr_cascade_level -= 1;
      curr_selected_item_id = this.cascade_selector_list[curr_cascade_level].val();
    }
    var curr_selected_item_name = (curr_selected_item_id == 0) ? 'No selection yet.' : this.cascade_selector_list[curr_cascade_level].children ('option:selected').text();
    this.selection_display.text (curr_selected_item_name);
  }
}

sbxCascadeDropDownSelector.prototype.refreshSelectedNameListAndItemListBySourceMultiSelector = function () {
  var this_cascade_dropdown = this;
  this.selected_name_list = new Array ();
  this.selected_name_list_option_id = new Array ();
  this.source_selector.children (':selected').each ( function () {
    if ($(this).val() != 0) {
      var new_key = this_cascade_dropdown.selected_name_list.length;
      this_cascade_dropdown.selected_name_list[new_key] = $(this).text();
      this_cascade_dropdown.selected_name_list_option_id[new_key] = '' + $(this).val();
    }
  });
  this.displaySelectedNameListToItemList ();
}

sbxCascadeDropDownSelector.prototype.displaySelectedNameListToItemList = function () {
  this.oSelectedListContainer.find ('.sbx-item-list-display').remove();
  var is_item_selected = false;
  for (key in this.selected_name_list) {
    var curr_name = this.selected_name_list[key];
    var curr_id = this.selected_name_list_option_id[key];
    var curr_display_name = curr_name.replace(/\./g, '');
    if (curr_display_name) {
      this.AddNameToItemList (curr_display_name, curr_id);
      is_item_selected = true;
    }
  }
  
  if (!is_item_selected) {
    this.oSelectedListContainer.find ('#no-select').show ();
  }
  
  this.refreshNewSelectLinkDisplay ();
}

sbxCascadeDropDownSelector.prototype.refreshNewSelectLinkDisplay = function(){
  if (this.newSelectState) {
    this.oNewSelectLink.hide();
  }
  else {
    this.oNewSelectLink.show();
  }
}

sbxCascadeDropDownSelector.prototype.AddNameToItemList = function (list_display_name, option_id) {
  var this_cascade_dropdown = this;
  var new_list_item = $('<li class="sbx-item-list-display" option_uid="' + option_id + '">' + list_display_name + '&nbsp;&nbsp;<span class="listDelete">X</span></li>');
  new_list_item.appendTo (this.oSelectedList);
  this.oSelectedListContainer.find ('#no-select').hide ();
  $('.listDelete', new_list_item).click ( function () {
    var optionUid = $(this).parent().attr('option_uid');
    originalOption = this_cascade_dropdown.source_selector.children ('[value="' + optionUid + '"]');
    if (sbx_msie6_or_less) {
      originalOption.get(0).setAttribute ('selected', false);
      originalOption.get(0).removeAttribute ('selected');
    }
    else {
      originalOption.removeAttr('selected');
    }
    this_cascade_dropdown.refreshSelectedNameListAndItemListBySourceMultiSelector ();
  });
}

sbxCascadeDropDownSelector.prototype.applySelectedNameListToSourceMultipleSelector = function () {
  //-- Name might be duplicated -- this.source_selector.val (this.selected_name_list); 
  var selected_name_list_option_id = this.selected_name_list_option_id;
  var source_selector = this.source_selector;
  source_selector.children ().each ( function () {
    if (sbx_msie6_or_less) {
      this.setAttribute ('selected', false);
      this.removeAttribute ('selected');
    }
    else {
      $(this).removeAttr ('selected');
    }
    var option_val = $(this).val();
    if (jQuery.inArray('' + option_val, selected_name_list_option_id) >= 0) {
      if (sbx_msie6_or_less) {
        this.setAttribute ('selected', true);
      }
      else {
        $(this).attr ('selected', 'selected');
      }
    }
  });
}

sbxCascadeDropDownSelector.prototype.create_dropdown = function (url, previous, level, selected_scid) {
  var this_cascade_dropdown = this;
  $.getJSON (url, function (data) {
    this_cascade_dropdown.create_dropdown_selector (data, previous, level, selected_scid);
  });
}
  
sbxCascadeDropDownSelector.prototype.remove_descendant_selectors = function (level) {
  for (level_index in this.cascade_selector_list) {
    if (level_index >= level && this.cascade_selector_list[level_index] != null) {
      this.cascade_selector_list[level_index].parent().remove();
      this.cascade_selector_list[level_index] = null;
    }
  }
  this.refresh_mouse_over_help_text (level-1);
}
   
sbxCascadeDropDownSelector.prototype.refresh_mouse_over_help_text = function (level) {
  var mouse_over_help_text = (level == 1) ? this.original_mouse_over_help : sbx_cascadedropdown_ext_mouse_over_help + this.suggest_option_msg;
  this.description_element.html (mouse_over_help_text);
}

sbxCascadeDropDownSelector.prototype.create_dropdown_selector = function (data, previous, level, selected_scid) {
  var this_cascade_dropdown = this;
  this.remove_descendant_selectors (level);
  if (data == null || data.length == 0 ) {
    return;
  }
  var first_default_option = (this.default_select_option_text != '') ? this.default_select_option_text : sbx_cascadedropdown_1st_default_option[this.cascade_dropdown_data_name];
  var default_option_text = (level ==1) ? first_default_option : sbx_cascadedropdown_ext_default_option;
  selector_markup = '<select class="form-select" style="width:100%"><option value="0">' + default_option_text + '</option>';

  var source_selector_options = "";
  for (scid in data) {
    var opt = $('#' + this.cascade_dropdown_source_selector_id + "_" + scid);
    if (opt.length == 0) {
      source_selector_options+= "<option id='" + this.cascade_dropdown_source_selector_id + "_" + scid + "' value='" + scid + "'>" + data[scid] + "</option>";
    }    
    selector_markup += "<option value='" + scid + "'>" + data[scid] + "</option>";
  }
  this.source_selector.append(source_selector_options);
  selector_markup += "</select>";
  stored_select_object = $(selector_markup);
  var selector_indentation_class = '';
  if (level > 1) {
    var indentation_level = level - 1;
    selector_indentation_class = " cascadeIcon cascadeIndent" + indentation_level;
  }
  stored_select_object.insertAfter (previous).wrap('<div class="form-item mysbx-form-item' + selector_indentation_class + '"></div>');
 
  stored_select_object.val (selected_scid);
  this.cascade_selector_list[level] = stored_select_object;
  stored_select_object.attr ('sbx_tree_level', level);
  
  this.refresh_mouse_over_help_text (level);
  
  stored_select_object.bind ('change', function () {
    var level = parseInt ($(this).attr('sbx_tree_level'));
    var current_value = $(this).val();
		var current_text = '';
    if (current_value == 0) {
			current_text = (level > 1) ? $(this_cascade_dropdown.cascade_selector_list[level-1]).children("option:selected").text() : 'No selection yet.';
    }
    else {
      current_text = $(this).children("option:selected").text();
    }
    
    if (this_cascade_dropdown.is_multiple_select) {
      if (this_cascade_dropdown.newSelectState && current_value != 0) {
        this_cascade_dropdown.current_selected_name_list_key = this_cascade_dropdown.selected_name_list.length;
        this_cascade_dropdown.newSelectState = false;
      }
      
      if (current_value != 0) {
        source_display_name_for_curre_text = this_cascade_dropdown.source_selector.children ('[value="' + current_value + '"]').text();
        this_cascade_dropdown.selected_name_list[this_cascade_dropdown.current_selected_name_list_key] = source_display_name_for_curre_text;
        this_cascade_dropdown.selected_name_list_option_id[this_cascade_dropdown.current_selected_name_list_key] = ''+current_value;
        this_cascade_dropdown.displaySelectedNameListToItemList ();
      }
      else {
        if (this_cascade_dropdown.newSelectState == false) {
          this_cascade_dropdown.selected_name_list[this_cascade_dropdown.current_selected_name_list_key] = '';
          this_cascade_dropdown.selected_name_list_option_id[this_cascade_dropdown.current_selected_name_list_key] = '0';
        }
      }
      this_cascade_dropdown.applySelectedNameListToSourceMultipleSelector ();
    }
    else {
      this_cascade_dropdown.selection_display.text (current_text);
      this_cascade_dropdown.source_selector.val (current_value);
    }

    if (current_value > 0) {
      this_cascade_dropdown.create_dropdown ('/mysbx-ajax-service/cascade-dropdowns/options/' + this_cascade_dropdown.cascade_dropdown_data_name + '/' + current_value, $(this).parent(), level + 1, 0);
    }
    else {
      this_cascade_dropdown.remove_descendant_selectors (level + 1);
      if (!this_cascade_dropdown.is_multiple_select) {
        this_cascade_dropdown.source_selector.val((level > 1) ? this_cascade_dropdown.cascade_selector_list[level - 1].val() : 0);
      }
    }
  });
  return stored_select_object;
}


