//
// 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"
    }
  }
};
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 = {
  '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) {
  var o = new sbxCascadeDropDownSelector ();
  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);
  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;
}

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]);
  this.original_mouse_over_help = this.description_element.html();
  this.suggest_option_msg = '' + $('#sbx_suggest_option_msg', this.description_element).html();

  this.create_cascade_dropdown (initial_selected_id);
}

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) {
    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;
    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.addOptionToSourceSelectorIfNotExist = function (option_value, option_text) {
  var opt = this.source_selector.children ('[value="' + option_value + '"]');
  if (opt.length == 0) {
    opt = $('<option value="' + option_value + '">' + option_text + '</option>');
    this.source_selector.append (opt);
  }
  return opt;
}

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"><option value="0">' + default_option_text + '</option>';
  for (scid in data) {
    this.addOptionToSourceSelectorIfNotExist (scid, data[scid]);
    selector_markup += "<option value='" + scid + "'>" + data[scid] + "</option>";
  }
  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;
}

