$(document).ready(function() {
  var listitems = $('#savedopps li');
  var savedOpps = [];

  // add our icon
  listitems.each(function() {
    // store the opp ids in the savedOpps array
    savedOpps[savedOpps.length] = $(this)[0].id.substring(8);

    $(this).prepend('<img class="pngimg" style="margin-right: 3px; vertical-align: middle; cursor: pointer;" src="/images/iconsets/silk/delete.png" height="16" width="16" alt="Remove from this list" title="Remove from this list" border="0" />');
  });

  // hook up removal

  listitems.find('img').click(function() {
    var li = $(this).parent().get(0);
    var ul = $(li).parent().get(0);
    var div = $(ul).parent().get(0);

    // remember the opp id
    var oppId = li.id.substring(8);

    // remove the handler
    $(this).unbind();

    // remove the clicked item
    $(li).remove();

    // if we were the last, remove the div
    if ($(ul).find('li').length === 0) {
      $(div).remove();
    }

    var newOpps = "";
    var rmIdx = -1;

    // go through the entries in savedOpps and remove the one that was clicked.
    for (var i in savedOpps) {
      var currId = savedOpps[i];
      if (currId == oppId) {
        rmIdx = i;
      } else {
        newOpps = newOpps + "|" + currId;
      }
    }

    // remove the entry from savedOpps
    if (rmIdx != -1) {
      savedOpps.splice(rmIdx, 1);
    }

    if (newOpps != "") {
      newOpps = newOpps.substring(1);
    }

    //  update the cookie
    $.cookie('savedOpps', newOpps, { path: '/', number: 365 });
  });
});

