
// $Id: productExplorer.js,v 1.6 2010/07/16 16:17:51 grb Exp $

/**********************************
 * Global variables
 **********************************/
var explorerResultRoot = "/admission/listing/";

var configSaveURL = "/marketpulse/tools/mymarketpulse/explorer_config_save_";
var configSaveExtension = ".json";

// keep last search for reusing it to sort/change chunk, page
var oldSearchForm = new Object();
// normal collasing form (can be overwritten for special pages)
var collapsingTitlePaneId = "formTitlePane";
// configuration
var chunkSizes = [10, 20, 50];

/**********************************
 * Explorer initialization
 **********************************/

/*
 * Initializes the explorer for specified segment and context.
 */
function initProductExplorer(portalSegment, context) {
  var configuration = configuration_PE[portalSegment + context];
  var pane = dijit.byId("resultsPane_" + portalSegment);

  // if the results pane is in a tab, do nothing 
  if (!pane)
    return;

  // show the dijit elements after everything is finished
  if (dojo.byId("searchForm")) {
    dojo.style("searchForm", "visibility", "visible");
  }

  // remove focus on the config button programatically (For firefox selectionbox)
  if (dijit.byId("configButton_" + portalSegment)) {
    dijit.byId("configButton_" + portalSegment).domNode.onfocus = function() { this.blur(); }
  }

  // call this after the resultsPane is refreshed
  dojo.connect(pane, "onLoad", pane, function() {
    afterResultsLoaded(portalSegment);
  });
  
  // change the loading and error Messages
  setLoadingHeight(portalSegment);
  pane.errorMessage = '<span class="dijitContentPaneError">'+errorMsg+'</span>';
  pane.loadingMessage = '<div style="text-align: left;" class="dijitContentPaneLoading">'+loadingMsg+'</div>';

  // Mode 1: If we are coming from the explorer itself, the URL will have a hash (#) in it.
  var hash = window.location.hash;

  // Mode 2: If coming from a page that uses the explorer to generate a result-view, the URL
  // will have a query-string delimiter (?).
  var queryString = window.location.search;

  // Mode 3: If included in a page without a search form, the queryString will be set in 
  // that page so we pick it up from there.
  var includedQS = includedQS_PE[portalSegment+context];
  if (includedQS != null)
    queryString = "?" + includedQS;

  // Coming from auxiliary page that jumps to explorer results using an FQSSelect parameter
  if ("" != queryString) {

    // Load the oldSearchForm with queryString parameters
    var queryAsObject = dojo.queryToObject(queryString.substring(1));
    oldSearchForm.FQSSelect = queryAsObject.FQSSelect;
    oldSearchForm.d = queryAsObject.d;
    oldSearchForm.s = queryAsObject.s;
    oldSearchForm["indexName"] = queryAsObject["indexName"];

    var str = "";
    var displayedFirst = false;
    for (colName in configuration.customColumns) {
      if (configuration.customColumns[colName]) {
        if (displayedFirst)
          str += ",";
        str += colName;
        displayedFirst = true;
      }
    }
    
    queryString += "&customColumns="+str;

    // load the results pane with explorer results
    loadResultsPane(portalSegment, context, queryString);
  }
  
  // Canonical case: coming from explorer form - query is in the hash
  else if ("" != hash) {
    if (hash.indexOf("savedHash=true") != -1) {
      var searchForm = dojo.byId("searchForm");

      // save original sortBy
      var defaultSort = searchForm.srtBy.value;

      // load the form
      populateInputForm(hash.substring(1));

      if (!oldSearchForm) oldSearchForm = dojo.formToObject(searchForm);

      // place default sortBy back
      searchForm.srtBy.value = defaultSort;

      // do not take customColumns
      var str = "";
      var displayedFirst = false;
      for (colName in configuration.customColumns) {
        if (configuration.customColumns[colName]) {
          if (displayedFirst)
            str += ",";
          str += colName;
          displayedFirst = true;
        }
      }
      if (hash.indexOf("customColumns") != -1) {
        var part1 = hash.substring(0, hash.indexOf("customColumns"));
        var part2 = hash.substring(hash.indexOf("&", hash.indexOf("customColumns")) + 1);
        hash = part1 + part2;
      }
      hash += "&customColumns="+str;

      // change the resultsPane href with the new one and load data
      loadResultsPane(portalSegment, context, "?" + hash.substring(1)); 
    }
  }
}

/**********************************
 * Search form management
 **********************************/

/**
 * Resets the current explorer search form.
 */
function resetForm() {
  var formNode = dojo.byId("searchForm");
  // form.reset() is not supported by dojo. Do it manually
  for(var i = 0; i < formNode.elements.length; i++){
    var elm = formNode.elements[i];
    
    if (elm.name == "st") continue; // DO NOT RESET SECURITY TYPE!
    if (elm.name == "s") continue;  // DO NOT RESET SORT BY!
    
    if (elm.type=="checkbox") {
      elm.checked = false;
      try {
        dijit.byId(elm.id).setChecked(false);
      } catch (Exception) {}
    } else if (elm.type=="submit") {
      continue;
    } else {
      if(elm.value!="") {
        elm.value="";
      }
    }
  }
}

/**
 * Updates the list of indices accordint to selected family. 
 * This method is used only for Equities explorer search.
 */
function changeIndexName(value) {
  if (!dijit.byId("indexName")) return; // first call for nothing!
  if (value == "") {
    value = "ALL_INDEX";
  }
  var data = dojo.eval(value+"_Data");
  var store = new dojo.data.ItemFileReadStore(data);
  dijit.byId("indexName").store = store;
  dijit.byId("indexName").setValue(data.data.items[0].v);
}

/**
 * Make the form titlepane colapse (close with animation)
 */
function collapseSearchForm() {
  // IPO-338 : temporarely disabled
//  var titlePane = dijit.byId(collapsingTitlePaneId);
//  if (titlePane && titlePane.open) {
//    titlePane.toggle();
//  }
}

/* 
 * Checks if the ratings are in the right order, otherwise, changes them. This method is called when
 * searching bonds in the bonds explorer. 
 */
function checkRatingInput() {
  if (!dijit.byId("raf") || !dijit.byId("rat")) return;
  
  var raf = dijit.byId("raf").getValue();
  var rat = dijit.byId("rat").getValue();
  
  if (!raf || !rat) return; // One or both are empty, don't care
  
  if (raf < rat) { // inversed
    dijit.byId("raf").setValue(rat);
    dijit.byId("rat").setValue(raf);
  }
}

/**********************************
 * Results page management
 **********************************/    

function reloadResults(portalSegment, context, why, value, collapse) {
  var configuration = configuration_PE[portalSegment + context];
      
  if (why == "form") {
    var form = dojo.byId(value);
    oldSearchForm = dojo.formToObject(form);
    // this was a real search query, change the loading message to the 'request' one
    dijit.byId("resultsPane_" + portalSegment).loadingMessage = '<div style="text-align: left;" class="dijitContentPaneLoading">'+reqLoadingMsg+'</div>';
  }
  else if (why == "sort") {
    var sortByAndDescending = getSortByAndDescendingFromNode(value);
    oldSearchForm.srtBy = sortByAndDescending.srtBy;
    oldSearchForm.descDir = sortByAndDescending.descDir;
  } 
  else if (why == "page") {
    oldSearchForm.page = value;
  } 
  else if (why == "indexName") {
    oldSearchForm.indexName = value;
  } 
  else if (why == "chunk") {
     // nothing to do
  }
  else if (why == "excelExport") {
     // nothing to do
  }

  // Copy chunk and config type from configuration object
  oldSearchForm.chunk = configuration.chunk;
  
  var str = "";
  var displayedFirst = false;
  for (colName in configuration.customColumns) {
    if (configuration.customColumns[colName]) {
      if (displayedFirst) str += ",";
      str += colName;
      displayedFirst = true;
    }
  }
  oldSearchForm.customColumns = str;   // add custom columns to show by default

  var params = dojo.objectToQuery(oldSearchForm);
  if (dojo.isIE) // replace =null 
    params = params.replace(/=null&/g, "=&").replace(/=null$/, "=");
  
  if (includedQS_PE[portalSegment+context]) {
    // Add the original querystring in case we need anything off it
    params += "&" + includedQS_PE[portalSegment+context];
  } 
  else {
    // Only if no includedQS (otherwise we get confused) 
    // save the state in the Hash of the url (for browser history)
    window.location.hash = params += "&savedHash=true";
  }

  //case excel generation
  if(why == "excelExport"){
    // Select the urlDir using portalSegment
    var dir = "shares";
    if (portalSegment == "BO")
            dir = "bonds";
    if (portalSegment == "FU")
            dir = "funds";
    if (portalSegment == "IN")
            dir = "indices";
    if (portalSegment == "EQ_FU")
            dir = "indices";
    if (portalSegment == "DE")
            dir = "derivatives";
    var href = explorerResultRoot + dir + "/explorer_export_" + lang + ".xls?" + params;
          
    window.open(href ,''
        ,'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes')  
  }
  else{
    // remove the column configurator button line (will be redisplayed after loaded)
    dojo.style("config_button_line_" + portalSegment, "visibility", "hidden");
    
    // change the resultsPane href with the new one
    loadResultsPane(portalSegment, context, "?" + params, collapse);

    oldSearchForm.page = null;  // don't keep the page on the next search!
  }
}

/*
 * Reloads the pane displaying results when it is an included one (like for list of issuers). 
 */
function includedReloadResults(portalSegment, context) {
  
  var configuration = configuration_PE[portalSegment + context];
  
  // add the list of current selected columns
  var selectedColumns = "";
  var displayedFirst = false;
  for (colName in configuration.customColumns) {
    if (configuration.customColumns[colName]) {
      if (displayedFirst)
        selectedColumns += ",";
      selectedColumns += colName;
      displayedFirst = true;
    }
  }  
  selectedColumns = "&customColumns=" + selectedColumns;
  
  // hide the configuration button
  dojo.style("config_button_line_" + portalSegment, "visibility", "hidden");
   
  // load the results     
  loadResultsPane(portalSegment, context, "?" + includedQS_PE[portalSegment+context] + selectedColumns);
}

/*
 * Triggers a (re)load of the results pane with the given query string for the
 * appropriate portal segment. If collapse = true, the search form is supposed to
 * collapse after loading (only used in explorer).
 */
function loadResultsPane(portalSegment, context, queryString, collapse) {
  // stop old player if it exists
  if (qp_PE[portalSegment] != null)
    qp_PE[portalSegment].stop();
          
  var pane = dijit.byId("resultsPane_" + portalSegment);
  
  // Select the urlDir using portalSegment
  var dir = "shares";
  if (portalSegment == "BO")
    dir = "bonds";
  if (portalSegment == "FU")
    dir = "funds";
  if (portalSegment == "IN")
    dir = "indices";
  if (portalSegment == "EQ_FU")
    dir = "indices";
  if (portalSegment == "DE")
    dir = "derivatives";

  queryString += "&segment=" + portalSegment;
  queryString += "&context=" + context;

  if (pane) {
    pane.href= explorerResultRoot + dir + "/explorer_results_" + lang + ".html" + queryString;
    
    if (collapse) {
      pane.href += "&collapse=true";
    }

    pane.refresh();
  }
}

function getSortByAndDescendingFromNode(node) {
  var cell = node.parentNode;  // this should be the cell that was clicked
  var searching = true;         // but let's search from here the first TD node we find
  while (searching) {           // in case there was some image or the link
    if (cell == null) {
      searching = false;
      break;
    }
    if (cell.nodeName == "TD") {
      searching = false;
      break;
    }
    cell = cell.parentNode;  // Search in parent node
  }
  var descending = null;
  if (dojo.hasClass(cell, "ascSort")) { // already asc sorted, sort it desc now
    descending = true;
  } else if (dojo.hasClass(cell, "descSort")) { // already desc, sort it asc
    descending = false;
  } else if (dojo.hasClass(cell, "ascByDefaultSort")) { // not sorted and asc by default
    descending = false;
  } else {                    // not sorted and desc by default
    descending = true;
  }
  var id = cell.id.substring(6);  // removes eg, 'PE_EQ_'
  
  //ProductlExplorer.SORT_BY_FORM_PARAM and ProductlExplorer.DESCENDING_FORM_PARAM 
  return { "srtBy": id,
           "descDir": descending };
}
      
function afterResultsLoaded(portalSegment) {

  // execute the javascript inside the ajax page (to get the new movie)
  var pane = dijit.byId("resultsPane_" + portalSegment).domNode;
  dojo.query("script", pane).forEach(
          function(scriptTag) {
            // We can't use dojo.eval(scriptTag.innerHTML), it does not always work
            var appendNode = dojo.doc.body;
            var n = appendNode.ownerDocument.createElement('script');
            n.type = "text/javascript";
            appendNode.appendChild(n);
            n.text = scriptTag.innerHTML;
          }
  );

  // show the configurator button
  dojo.style("config_button_line_" + portalSegment, "visibility", "visible");

  // show the table after that
  dojo.style("result_table_" + portalSegment, "display", "");

  // set the new loadingPane height to the actual table height
  setLoadingHeight(portalSegment, pane.offsetHeight);
  dijit.byId("resultsPane_" + portalSegment).loadingMessage = '<div style="text-align: left;" class="dijitContentPaneLoading">'+loadingMsg+'</div>';

  // Reset original cell colors (new request, new cell colors!)
  _originalColors = [];

  // make a player and play the new movie
  qp_PE[portalSegment] = new swx.QuotePlayer(movie_PE[portalSegment], function(updateEvent) {updateCell(updateEvent, portalSegment);} , animateCells);
  qp_PE[portalSegment].play();
}      
      
/* Change the loadingPane height, makes it more ajax friendly */
function setLoadingHeight(portalSegment, height) {
  if (height == null) height = 80;
  if (height > 520) height = 520;
  if (dojo.byId("changeHeightWhileLoading_" + portalSegment)) 
    dojo.style("changeHeightWhileLoading_" + portalSegment, "height", height);
}

/**********************************
 * Configuration management
 **********************************/

/*
 * Change the size of each result page.
 */
function changeChunkSize(newSize, portalSegment, context) {
  for(var i=0; i<chunkSizes.length; i++) {
    if (chunkSizes[i] == newSize) continue;
    var id = "chunk_" + chunkSizes[i] + "_" + portalSegment;
    dijit.byId(id).setChecked(false);
  }
 // change configuration
  configuration_PE[portalSegment + context].chunk = newSize;
  // reload table
  reloadResults(portalSegment, context, "chunk");
}

/*
 * Change the state of a single column.
 */
function changeColumnDisplay(columnName, displayMe, portalSegment, context) {
  var configuration = configuration_PE[portalSegment+context];
  var displayString =  null;
  if (displayMe) {
    displayString = "";
    configuration.customColumns[columnName] = true;
  } else {
    displayString = "none";
    configuration.customColumns[columnName] = false;
  }
  
  // Loop over all the Reuters columns. If none are displayed,
  // switch off the credit. If any is displayed, switch on the credit.
  //            dojo.style("reutersCredit", "display", "");
  var reutersColumns = ["APENORM", "AROEPCT", "ADIVSHR", "ADIV5YAVG", "YLD5YAVG", "AEPSNORM"];         
  var reutersDisplay = "none";
  for (var i = 0; i < reutersColumns.length; i++) {
    if (configuration.customColumns[reutersColumns[i]]) {
      reutersDisplay = "";
    }
  }
  dojo.style("reutersCredit", "display", reutersDisplay);

  // changing styles is slow on IE. It is not searching the nodes, it is really changing display style
  dojo.forEach( dojo.query("#PE_" + portalSegment + "_" + columnName+"_width, .class_" + portalSegment + "_" +columnName, dojo.byId("resultsPage")), function (node) {
      if (dojo.style(node, "display") == displayString) return; // nothing to do for this one!
      dojo.style(node, "display", displayString);
  });
}

/*
 * Changes the state of all attributes following a click on "All" in configuration.
 */
function changeAllDisplay(displayMe, portalSegment, context) {
   var configuration = configuration_PE[portalSegment+context];
  for (colName in configuration.customColumns) {
    if ("All" == colName) return;
    changeColumnDisplay(colName, displayMe, portalSegment, context);
    dijit.byId("cb_" + colName + "_" + portalSegment).setChecked(displayMe);
  };
  configuration.customColumns["All"] = displayMe;
}

/*
 * Saves the current column configuration : it transmits to the server the column states. The target 
 * XSP handle the incoming data and is responsible of writing the configuration in the database.
 */
function saveColumns(portalSegment, context) {
 var configuration = configuration_PE[portalSegment+context];
  
  // We add custom columns to the query-string only if they are set.
  var targetURL = configSaveURL + lang + configSaveExtension + "?portalSegment=" + portalSegment + "&context=" + context + "&save=Columns&";
  for (colName in configuration.customColumns) {
    if (configuration.customColumns[colName]) {
      targetURL += colName + "=" + configuration.customColumns[colName] + "&";
    }
  }
  targetURL = targetURL.substring(0, targetURL.length-1);
  
  // Make a request to the XSP that handles the configuration
  dojo.xhrGet( {
    url: targetURL,
    handleAs: "json-comment-filtered",
    timeout: 5000, // Time in milliseconds

    load: function(response, ioArgs) {
      dojo.byId("configDialogInfoSpan").innerHTML = response.Message;
      dijit.byId("configDialogOKButton").setDisabled(false);
      return response;
    },

    error: function(response, ioArgs) {
      var errMessage = response.dojoType + ": ";
      if (response.dojoType == "error") {
        errMessage += ioArgs.xhr.status;
      }
      dojo.byId("configDialogInfoSpan").innerHTML = errMessage;
      dijit.byId("configDialogOKButton").setDisabled(false);
      return response;
    }
  });
}

/*
 * Displays the text in a dialog box (used to inform the user of the current state when saving).
 */
function infoDialog(text) {
  dojo.byId("configDialogInfoSpan").innerHTML = text;
  dijit.byId("configDialogOKButton").setDisabled(false);
}

/*
 * Shows or hides things and shows config dialog for saving query.
 */
function initQuerySave() {
  dojo.style("configDialog_textBox", "display", "");      // show textbox input field
  dojo.style("configDialog_emptyNameError", "display", "none"); // do not show empty name error message
  dojo.style("configDialog_dropDown", "display", "none"); // do not show dropdown input field
  dojo.style("configDialog_info", "display", "none");     // do not show result and ok button yet
  dijit.byId("queryName_textBox").setValue(""); // FIXME: this does not actually clear the data!
  resetAndShowConfigDialog();                             // reset some other things and show dialog
}

/*
 *  Shows or hides things and shows config dialog for load or delete
 */
function initQueryLoadDelete() {
  dojo.style("configDialog_textBox", "display", "none");  // do not show textbox input field
  dojo.style("configDialog_emptyNameError", "display", "none"); // do not show empty name error message
  dojo.style("configDialog_dropDown", "display", "");     // show dropdown input field
  dojo.style("configDialog_info", "display", "none");     // do not show result and ok button yet
  dijit.byId("queryName_dropDown").setValue("");    // FIXME: this does not actually clear the data if no value has ""!
  dijit.byId("queryName_dropDown").setDisplayedValue(""); // FIXME: this does not actually clear the data!
  resetAndShowConfigDialog();                             // reset some other things and show dialog
}

/*
 * Shows or hides things and shows config dialog for load or delete
 */
function initInfoDialog() {
  dojo.style("configDialog_textBox", "display", "none");  // do not show textbox input field
  dojo.style("configDialog_dropDown", "display", "none"); // do not show dropdown input field
  dojo.style("configDialog_info", "display", "");         // show result and ok button (but disabled)
  resetAndShowConfigDialog();                             // reset some other things and show dialog
}

/*
 * 
 */
function resetAndShowConfigDialog() {
  dijit.byId("configDialogOKButton").setDisabled(true);   // disable OK button until the response is received
  dojo.byId("configDialogInfoSpan").innerHTML = PLEASE_WAIT_STR; // reset to please wait string
  dijit.byId("configDialog").show();                      // show the dialog box
}

/*
 * Transmits the current query string to the server in order to save a query.
 */
function saveDeleteQuery(portalSegment, context, queryName, doWhat, okString) { // doWhat = save or delete (used on the server side!)
  if (queryName == "") {
    dojo.style("configDialog_emptyNameError", "display", "");
    return;
  }
  dojo.style("configDialog_textBox", "display", "none"); 
  dojo.style("configDialog_dropDown", "display", "none");
  dojo.style("configDialog_info", "display", "");
  
  // Everything after the "save=Query&name=wibble" token is taken as the query-string
  // of the form.
  var targetURL = configSaveURL + lang + configSaveExtension + "?portalSegment=" + portalSegment + "&context=" + context +"&" + doWhat + "=Query&name=" + queryName;
  
  if ("save" == doWhat) {
      targetURL += "&" + dojo.formToQuery(dojo.byId('searchForm'));
  }
  
  // Make a request to the XSP that handles the configuration
  dojo.xhrGet( {
      url: targetURL,
      handleAs: "json-comment-filtered",
      timeout: 5000, // Time in milliseconds

      load: function(response, ioArgs) {
          if (response.Message == null) {
              dojo.byId("configDialogInfoSpan").innerHTML = okString;
              dijit.byId("queryName_dropDown").store = new dojo.data.ItemFileReadStore( response );
          } else {
              dojo.byId("configDialogInfoSpan").innerHTML = response.Message;
          }
          dijit.byId("configDialogOKButton").setDisabled(false);
          return response;
      },

      error: function(response, ioArgs) {
          var errMessage = null;
          if (response.dojoType) {
            errMessage += response.dojoType + ": ";
            if (response.dojoType == "error") {
              errMessage += ioArgs.xhr.status;
            }
          } else {
            errMessage += "error!";
          }
          dojo.byId("configDialogInfoSpan").innerHTML = errMessage;
          dijit.byId("configDialogOKButton").setDisabled(false);
          return response;
      }
  });
}

/*
 * Populates the search form from a saved query
 */
function populateInputForm(queryString) {
  var formObject = dojo.queryToObject(queryString);
  
  var formNode = dojo.byId("searchForm");
  resetForm();

  for (var x in formObject) {
    if (x && x.length>0 && formObject[x]) {
      try {
        formNode[x].value = formObject[x];
      } catch (Exception) {}
      
      try {
        dijit.byId(x).setValue(formObject[x]);
      } catch (Exception) {}
      
      try {
        dijit.byId(x).setChecked(formObject[x]);
      } catch (Exception) {}
      
      try {
        var dateObj = dojo.date.stamp.fromISOString(formObject[x]);
        if (dateObj != null) dijit.byId(x).setValue(dateObj);
      } catch (Exception) {}
      
    }
  }
}

/**********************************
 * Results display
 **********************************/

/*
 * Creates a dropdown button for the index members in the product explorer results list. 
 * Creating these dropdowns all when the results are shown is very slow, so now these 
 * dropdowns are created on the fly when the user clicks on the index members icon.
 * 
 * WARNING: These dropdowns replace the original images, so if we change something here (like icon)
 *          you have to change it as well in the explorer_results.xsp in the indexMembers part!
 */
function showIndexMemberDropDown(node, list, portalSegment) {
        
  var menu = new dijit.Menu();
  for (var i=0; i<list.length; i+=2) {
    var h = {
      url : list[i+1],
      f : function() {window.location = this.url}
    }
    var menuItem = new dijit.MenuItem({ label: list[i], parentMenu: menu , onClick: dojo.hitch(h, "f") });
    menu.addChild(menuItem); 
  }
  
  _createDropDownInsteadOfNode(node, menu, "width: 16px; height: 16px; overflow: hidden;", "linksButton indexMembersButton");
}

/*
 * Creates a dropdown button for the index members in the product explorer results list. 
 * Creating these dropdowns all when the results are shown is very slow, so now these 
 * dropdowns are created on the fly when the user clicks on the 'extra' icon.
 * 
 * WARNING: These dropdowns replace the original images, so if we change something here (like icon)
 *          you have to change it as well in the explorer_results.xsp in the 'more' part!
 */
function showMoreDropDown(node, list, securityId, portalSegment, getLoginToUseString, fqsShortName, 
                       watchMaxEntries, watchCurrentEntries, fqsValorSymbol, fqsLastPrice,
                       alarmMaxEntries, alarmCurrentEntries, MAX_SIDEBAR_CHARTS) {
  
  var menu = new dijit.Menu();
  
  for (var i=0; i<list.length; i+= 3) {
    var iconClass = list[i];
    var labl = list[i+2];
    
    var h = {
      onklik : list[i+1],
      f: function() { dojo.eval(this.onklik)}
    }
    var menuItem = new dijit.MenuItem({ iconClass: iconClass, parentMenu: menu, 
      onClick: dojo.hitch(h, "f"),
      label: labl 
    });
    menu.addChild(menuItem); 
  }

  _createDropDownInsteadOfNode(node, menu, "", "linksButton");
}

/*
 * Creates a dropdown button instead of the node.
 */
function _createDropDownInsteadOfNode(node, dropdownMenu, dropdownStyle, dropdownClass) {
  var params = {
    dropDown: dropdownMenu,
    style: dropdownStyle
  };
  params["class"] = dropdownClass;   // cheat because class can't be an object member?
  var widget = new dijit.form.DropDownButton(params, node);
  
  // bring up the dojo menu by fireing an onclick event
  if (dojo.isIE) {
     widget.domNode.fireEvent("onclick",document.createEventObject());
  } else {
     var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window, 0, 0, 0,
             0, 0, false, false, false, false, 0, null);
    widget.domNode.dispatchEvent(evt);
  }
}

