// bind() allows scope altering
Function.prototype.bind = function(obj) {
  var method = this,
  temp = function() {
    return method.apply(obj, arguments);
  };
             
  return temp;
}

var ResultTable = function () {
  this.display_fields = ['Trade Name', 'Generic Name', 'Results'];

  this.header_row = function() {
    var row = ['<tr class="header_row"><td>',
               this.display_fields.join('</td><td>'),
               '</td></tr>'
               ];
    return row.join('');
  };

  this.format_row = function(info, i) {
    var row = ['<tr class="',
               ((i % 2 == 0) ? 'odd' : 'even'),
               '" id="row',
               i,
               '">'
               ];
    this.display_fields.each(function(item) {
      var cell = ['<td>'];
      if (item == 'Results' && info['Drug Page']) {
        cell.push((info['Potential']) ? 'Potential ' : '');
        cell.push('Positive for <a href="/drug_facts__effects/');
        cell.push(info['Drug Page']);
        cell.push('">');
        cell.push(info['Drug Name']);
        cell.push('</a>');
      } else {
        cell.push(info[item]);
      }
      cell.push('</td>');
      row.push(cell.join(''));
    });
    row.push('</tr>');
    return row.join('')
  };

  this.get_results = function(data) {
    var table = ['<table id="results_table">',
                 this.header_row()
                 ];
    var row_func = this.format_row.bind(this);
    data.each(function (item, i) {
      table.push(row_func(item[1], i));
    });
    table.push('</table>');
    return table.join('')
  };
};

// the dataFinder class allows user to filter a list of data using multiple pickers(dropdowns)
var DataFinder = function (pickerDiv, resultDiv, countDiv, formatObj) {
  this.name = 'DataFinder';
  this.loaded = false;
  this.pickers = [];
  this.picked = {};
  this.dataRows = [];
  this.pickerDiv = $(pickerDiv);
  this.resultDiv = $(resultDiv);
  this.countDiv = $(countDiv);
  this.formatObj = new formatObj();

  this.toString = function() {
    return this.name + '(' + this.pickerDiv.id + ', ' + this.resultDiv.id + ', ' + this.countDiv.id + ')';
  };

  this.init = function (data) {
    this.pickers = data[0];
    this.dataRows = data[1];
    this.loaded = true;
    this.finder = $('finder');
    this.finderBg = $('finderBg');
  };

  this.open = function () {
    this.finder.style.display = "block";
    this.finderBg.style.display = "block";
    this.populate_pickers();
  };

  this.close = function () {
    this.clearResults();
    this.finder.style.display = "none";
    this.finderBg.style.display = "none";
  };

  this.reset = function () {
    this.hideResults();
    this.clearResults();
    this.clearPicked();
    this.populate_pickers();
  };
  
  this.hideResults = function () {
    this.resultDiv.style.display = "none";
    $('view_link').style.display = "block";
  };

  this.showResults = function () {
    this.resultDiv.style.display = "block";
    $('view_link').style.display = "none";
  };

  this.clearResults = function () {
    this.resultDiv.empty();
    $('view_link').style.display = "none";
  };

  this.hideMenus = function () {
    $$('.pick_menu').each(function(item) {
      item.style.display = "none";
    });
  };

  this.clearPicked = function (pick) {
    if (pick) {
      this.picked[pick] = '';
    } else {
      this.picked = {};
      $$('.chooser').each(function(item) {
        item.innerHTML = item.id;
      });
    }
  };

  this.setPicked = function (pick, val) {
    this.picked[pick] = val;
  };

  this.pickEvent = function(eObj) {
    var pick = eObj.parentNode.parentNode.id;
    //eObj.parentNode.parentNode.firstChild.innerHTML = eObj.id;
    this.hideMenus();
    this.setPicked(pick, eObj.id);
    this.filter_list();
    return
  };

  this.clearEvent = function(eObj) {
    var pick = eObj.parentNode.parentNode.id;
    //eObj.parentNode.parentNode.firstChild.innerHTML = pick;
    this.hideMenus();
    this.setPicked(pick, '');
    this.filter_list();
  };

  this.chooseEvent = function(eObj) {
    this.hideMenus();
    eObj.parentNode.lastChild.style.display = "block";
  };

  this.populate_pickers = function (dataList) {
    var data = dataList || this.dataRows;
    this.pickerDiv.empty();
    var valDict = {};
    var linkDict = {};
    this.pickers.each(function(pick) {
      valDict[pick] = [];
      linkDict[pick] = [];
    });

    var get_unique_opts = function(item, i) {
      var info = item[1];
      this.pickers.each(function(pick) {
        var val = info[pick];
        if (val && !valDict[pick].contains(val)) { 
            valDict[pick].push(val);
            linkDict[pick].push(['<a id="', val, '" class="opt_link" onclick="javascript:finder.pickEvent(this);">', val, '</a>'].join(''));
        }
      });
    }
    var process_func = get_unique_opts.bind(this);
    data.each(process_func);

    _picked = this.picked;
    var makePickerHtml = function(pick) {
      var dd = ['<div id="',
                pick,
                '" class="pick_link"><span class="label">', pick, '</span><a class="chooser" id="',
                pick,
                '" onclick="javascript:finder.chooseEvent(this);">',
                (_picked[pick]) ? _picked[pick] : "Select",
                '<img src="templates/default/images/arrow_pick_link.gif"/></a><div class="pick_menu"><a class="clearer" onclick="javascript:finder.clearEvent(this);">[Clear Choice]</a>'
                ];
      linkDict[pick] = linkDict[pick].sort();
      dd.extend(linkDict[pick]);
      dd.push('</div></div>');
      return dd.join('');
    };

    var picker_func = makePickerHtml.bind(this);
    var pickHTML = [];
    this.pickers.each(function(pick) {
      pickHTML.push(picker_func(pick));
    });
    this.pickerDiv.innerHTML = pickHTML.join('');
  };
  
  this.populate_results = function (dataList) {
    var data = dataList || this.dataRows;
    this.resultDiv.empty();
    this.resultDiv.innerHTML = this.formatObj.get_results(data);
    this.countDiv.innerHTML = (data.length);
  };

  this.filter_list = function () {
    this.hideResults();
    var _pickers = this.pickers;
    var _picked = this.picked;
    var newList = this.dataRows.filter(function(item, i) {
      var show = true;
      _pickers.each(function(k) {
        if (_picked[k]) {
          show = (show && item[1][k] == _picked[k]);
        }
      });
      return show
    });

    this.populate_pickers(newList);
    this.populate_results(newList);

    var cnt = newList.length;
    this.countDiv.innerHTML = (cnt);
    if ((cnt) <= 5) {
     this.showResults(); // show results when list get down to 5 
    }
  };
};

var finder;
window.addEvent('domready', function(){
  finder = new DataFinder('pickers', 'results', 'count', ResultTable);
  finder.init(reactionData);
});


function toggleDrugDD(eObj) {
  var image = eObj.firstChild;
  var menu = eObj.parentNode.lastChild;
  if (menu.style.display != 'block') {
    showDrugDD(menu, image);
  } else {
    hideDrugDD(menu, image);
  }
}

function hideDrugDD(menuObj, image) {
  menuObj.style.display = 'none'
  if (!image) {
    var image = menuObj.parentNode.firstChild.firstChild;
  }
  image.src = image.src.replace('_down', '_up');
}

function showDrugDD(menuObj, image) {
  menuObj.style.display = 'block'
  if (!image) {
    var image = menuObj.parentNode.firstChild.firstChild;
  }
  image.src = image.src.replace('_up', '_down');
}

function openCutOff() {
  $('finderBg').style.display = "block";
  $('cutoff').style.display = "block";
}

function closeCutOff() {
  $('finderBg').style.display = "none";
  $('cutoff').style.display = "none";
}


