// bind_func() allows scope altering
Function.prototype.bind_func = function(obj) {
  var method = this;
  var temp_func = function() {
    return method.apply(obj, arguments);
  };
             
  return temp_func;
}

Array.prototype.sortIgnoreCase = function() {
  return this.sort(function (a, b) {
                     return ((a.toLowerCase() > b.toLowerCase()) ? 1 : ((a.toLowerCase() < b.toLowerCase()) ? -1 : 0));
                   });
}

var AmsNav = function (pickerDiv) {
  this.name = 'AmsNav';
  this.loaded = false;
  this.pickers = [];

  this.init = function (data) {
    this.pickers = data[0];
    this.pickerDiv = $(pickerDiv);
    this.dataRows = data[1];
    this.loaded = true;
    this.populate_pickers();
  };

  this.hideMenus = function () {
    $$('.pick_menu').each(function(item) {
      item.style.display = "none";
    });
  };

  this.pickEvent = function(eObj) {
    try {
      document.location = $E('base').href + eObj.id;
    } catch (ex) {
      document.location = eObj.id;
    }
  };

  this.chooseEvent = function(eObj) {
    this.hideMenus();
    eObj.parentNode.lastChild.style.display = "block";
  };

  this.showMenu = function(eObj) {
    eObj.parentNode.lastChild.style.display = "block";
  };
  this.hideMenu = function(eObj) {
    eObj.parentNode.lastChild.style.display = "none";
  };

  this.populate_pickers = function () {
    var data = this.dataRows;
    this.pickerDiv.empty();
    var pickHTML = [];
    this.pickers.each(function(pick) {
      var dd = ['<div class="pick_link"><span class="label">',
                data[pick][0],
                '</span><a class="',
                'chooser', // dd[3] - update to 'selected' style
                '" onclick="javascript:amsNav.chooseEvent(this);">',
                "Select", // dd[5] - update to selected text
                '<img src="/images/arrow_pick_link.gif"/></a><div class="pick_menu" onmouseover="javascript:amsNav.showMenu(this);" onmouseout="javascript:amsNav.hideMenu(this);">'
                ];

      var curr_page = document.location.pathname;
      data[pick][1].each(function(page) {
        if (page[0] == curr_page) {
          dd[3] = 'chooser_on';
          dd[5] = page[1];
        }
        dd.push(['<a id="', page[0], '" onclick="javascript:amsNav.pickEvent(this);">', page[1], '</a>'].join(''));
      });

      dd.push('</div></div>');

      pickHTML.push(dd.join(''));
    });

    this.pickerDiv.innerHTML = pickHTML.join('');
  };
};
