// GLOBAL VARIABLES
var _GLOBAL_VARIABLES_;


var _console=null;
var defaultStyleName=">>Default<<";
var pDefaults = [];
var pageInitializing = true;
var holdIndexesForOpera = [];
var pulloutsOpen=[];
var sectionsOpen=[2,3,4,6];
var selectsOpen=[];
var trackLabels=[];
var currentPopup = 0;
var ignoreClick = false;
var FreeMaxIndicators=3;
var BasicMaxIndicators=9;
var ExtraMaxIndicators=25;
var BasicMaxStyles=3;
var ExtraMaxStyles=20;
var agt=navigator.userAgent.toLowerCase();
var isIE = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var currentFields=0;//--added 02/22/2006 for efficiency
var sendURLToLink=false;
var savedLink=false;
var refreshCancelled=false;
var localTimeDiff=0;
var refreshCount=0;
var refreshMax=60000*60;//1 hour
var customSizeVisible=false;
var kagiRenkoVisible=false;

//***********************************************************
// UTILITY FUNCTIONS
//***********************************************************
var _UTILITY_FUNCTIONS_;

//-----------------------------------------------------------
// debug(String) - Displays a message in a popup window
//-----------------------------------------------------------
function debug(msg) {
    if (!_console && (_console===null || _console.closed)) {
        _console = window.open("", "console", "width=600,height=300,resizable");
    }
    if (_console) {
        _console.focus();
        _console.document.writeln(msg+"<br>");
    }
}

//-----------------------------------------------------------
// is_IEMac() -
//-----------------------------------------------------------
function is_IEMac() {
    var agt = navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();
    var is = (agt.indexOf("mac") != -1 && appVer.indexOf('msie') != -1 && agt.indexOf("opera") == -1 && agt.indexOf('safari') == -1 && agt.indexOf('konqueror') == -1);
   return is;
}

//***********************************************************
// FORM VERIFICATION AND SUBMISSION FUNCTIONS
//***********************************************************
var _FORM_VERIFICATION_SUBMISSION_FUNCTIONS_;


//-----------------------------------------------------------
// submitIt(String) - Verifies and sends the main workbench
//      form to the server
//-----------------------------------------------------------
function submitIt(action,button) {
  var s = "";
  var theServlet = "/h-sc/ui";
  var f = document.forms.workbench;
  var str = f.dataRange.options[f.dataRange.selectedIndex].value;
  if (typeof(action)=="undefined" || !action) { action=""; }
  if (typeof(button)=="undefined" || !button) { button=false; }

  // If we are using XML Debug mode, only send the XML code to the server
  if ((arguments.length > 0) && (arguments[0].toLowerCase() == "xml")) {
    f.xmlSubmit.value = f.chartXml.value;
    f.action=theServlet;
    f.submit();
    return false;
  }

  // Remove any "problematic" characters from the form variables
  stripProblemChars();
  
  // reset curChartName if the symbol isn't the same as the inputsymbol
  if (f.symbol.value != f.inputsymbol.value && typeof(f.annotation) != "undefined") {
    f.annotation.value = "";
  	f.curChartName.value = "";
  }
  
  if (f.period.options[f.period.selectedIndex].value != f.inputperiod.value && typeof(f.annotation) != "undefined") {
    f.annotation.value = "";
  }
  
  // Validate all the user-entered fields
  checkDate();
  checkWidthHeight("workbench");
  setRangeValues();
  fixupPriceIndicators();

  // OPTIMIZATION: If only the symbol, period and/or duration has changed AND NOTHING ELSE, then just recreate
  //  the chart with the same style ID - passing in the changed fields via URL parameters
  if (f.isPermanentId.value == "true") {
    s = "?s=" + f.symbol.value + "&p=" + f.period.options[f.period.selectedIndex].value;
    if (/^predef/.test(str)) {
      var nYears = (f.years.options) ? f.years.options[f.years.selectedIndex].value : f.years.value;
      var nMonths = (f.months.options) ? f.months.options[f.months.selectedIndex].value : f.months.value;
      var nDays = (f.days.options) ? f.days.options[f.days.selectedIndex].value : f.days.value;
      s += "&yr=" + nYears + "&mn=" + nMonths + "&dy=" + nDays;
    }
    else if (/^userdef/.test(str)) {
      if (!f.start.value)
        { s += "&st=" + f.start.value; }
      if (!f.end.value)
        { s += "&en=" + f.end.value; }
    }
    else if (/^fill/.test(str)) {
      var nBar = (f.bar.options) ? f.bar.options[f.bar.selectedIndex].value : f.bar.value;
      var nGap = (f.gap.options) ? f.gap.options[f.gap.selectedIndex].value : f.gap.value;
      s += "&b=" + nBar + "&g=" + nGap;
    }
    s += "&id=" + f.chartId.value;
  }
  return submitItSimplified(theServlet + s + action,button);
}
//-----------------------------------------------------------
// submitItSimplified() - Submits to the server without 
//			checking data...
//-----------------------------------------------------------

function submitItSimplified(action,button) {

  refreshCancelled=true;

  if (pageInitializing) {
    alert ("The page has not finished loading.  Please wait...");
    return false;
  }
  if (typeof(action)=="undefined" || !action) { action="/h-sc/ui"; }
  var f = document.forms.workbench;
  f.action = action;
  //if (typeof(button)!="undefined" && button) return true;//skip click
  button=document.getElementById("submitButton");
  if (button) 
  {
    var onc=button.onclick;
    button.onclick=null; //we dont want this to run!
    button.click(); 
    button.onclick=onc;
    setTimeout(function(){button.onclick=onc;},1);
  }
  return true;
}

//-----------------------------------------------------------
// submitPrint() - Submits the Print popup's form to
//      the server
//-----------------------------------------------------------
function submitPrint() {
  var width = "";
  var height = "";
  var params = "";
  var f = document.forms.printform;
  var baseUrl = f.baseurl.value;
  
//  checkWidthHeight("printform");
//  if (f.chartSize.value == "Custom") {
//    if (f.customWidth.value)
//      params += "&w="+f.customWidth.value;
//    if (f.customHeight.value)
//      params += "&h="+f.customHeight.value;
//  } else {
    if (f.chartSize.value == "Portrait") {
      width = "670";
      height = "838";
    } else if (f.chartSize.value == "Landscape") {
      width = "850";
      height = "668";
    } else {
      width = f.chartSize.value;
    }
    params += "&w="+width;
    if (height)
      { params += "&h="+height; }
//  }
  
  if (f.monochromeChart.checked) {
    params += "&k=monochrome";
  }
  
  f.extraargs.value = params;               // TODO: What is this for?
  
  f.action = baseUrl + params + "&cmd=print";
  f.submit();
}

//-----------------------------------------------------------
// stripProblemChar() - remove characters that could
//    interfere with the database, etc. from ALL INPUT fields
// SKIP for styles and favorites names....?
//-----------------------------------------------------------
function stripProblemChars() {
  var f = document.forms.workbench;
  if (!f) { return; }                           // TODO: What is this for?
  for (var i=0;i<f.elements.length;i++) {
    if (f.elements[i].nodeName=="INPUT")
      { f.elements[i].value=f.elements[i].value.replace(/[\%\&\"\'\;\>\<\?\\]/g,""); }
  }
}

//-----------------------------------------------------------
// checkDate() - 
//-----------------------------------------------------------
function checkDate() {
  var f = document.forms.workbench;
  var today = new Date();
  f.start.value = parseDate(f.start.value,new Date(today.getFullYear()-1, today.getMonth(), today.getDate()));
  if (f.end.value=="(today)" || (/[\(\)a-z\s]+/i).test(f.end.value)) { f.end.value=""; }
  else if (f.end.value)
    { f.end.value = parseDate(f.end.value,new Date()); }
}

//-----------------------------------------------------------
// parseDate() -
//-----------------------------------------------------------
function parseDate(dateString,defaultDate) {
  var date=0;
  
  if (!dateString)
    { date = defaultDate; }
  else if (!isNaN(Date.parse(dateString)))
    { date = new Date(dateString); }
  else
  {
    var date_split = dateString.match(/(\d+)[-\/ ](\d+)[-\/ ,](\d+)/);
    if (date_split && date_split.length > 3) {
      if (date_split[1].length == 4) //--yyyy-mm-dd?
        { date = new Date(date_split[1],parseInt(date_split[2],10)-1,date_split[3]); }
      else if (parseInt(date_split[1],10)>12) //--dd-mm-yyyy?
        { date = new Date(date_split[3],parseInt(date_split[2],10)-1,date_split[1]); }
      else //--mm-dd-yyyy?
        { date = new Date(date_split[3],parseInt(date_split[1],10)-1,date_split[2]); }
    }
  }
  
  if (!date) 
    { date = defaultDate; }
    
  var year = date.getFullYear();
  var month = 1 + date.getMonth();
  var day = date.getDate();
  
  return year + "-" + ((month < 10) ? "0"+month : month) + "-" + ((day < 10) ? "0"+day : day);
}

//-----------------------------------------------------------
// checkWidthHeight() - 
//    - forces width/height value
//    - called onsubmit
//-----------------------------------------------------------
function checkWidthHeight(s) {
  var f = document.forms[s];
  var chartSize = f.chartSize.options[f.chartSize.selectedIndex].value;
  if (chartSize.toLowerCase().indexOf("custom") < 0)
    { return; }

  var w = parseInt(f.customWidth.value,10);
  var h = parseInt(f.customHeight.value,10);
  if (isNaN(w)) { w=0; }
  if (isNaN(h)) { h=0; }
  
  if (w > 1600)
    { f.customWidth.value = 1600; }
  else if (w < 180)
    { f.customWidth.value = 180; }
  else { f.customWidth.value = w; }  //w+(w%5); 
  
  if (h > 1200)
    { f.customHeight.value = 1200; }
  else if (h < 268)
    { f.customHeight.value = 268; }
  else
    { f.customHeight.value = h; }    //h+(h%5);
}

//-----------------------------------------------------------
// setRangeValues() - 
//   Clears unused Range fields, sets predef hidden values
//   Called onsubmit
//-----------------------------------------------------------
function setRangeValues() {
  var f = document.forms.workbench;
  var str = f.dataRange.options[f.dataRange.selectedIndex].value;
  var period = f.period.options[f.period.selectedIndex].value;

  // Clear user-defined values
  if (!(/^userdef/).test(str)) {
    f.start.value = "";
    f.end.value = "";
  }
  
  // Clear fill values
  if (!(/^fill/).test(str)) {
    f.bar.selectedIndex = 2;
    f.gap.selectedIndex = 0;
  }
  
  // Write special values for prefef
  if ((/^predef/).test(str)) {
    var nYears = (f.years.options) ? f.years.options[f.years.selectedIndex].value : f.years.value;
    var nMonths = (f.months.options) ? f.months.options[f.months.selectedIndex].value : f.months.value;
    var nDays = (f.days.options) ? f.days.options[f.days.selectedIndex].value : f.days.value;
    f.dataTotalDays.value = Number(nYears*365) + Number(nMonths*30) + Number(nDays);
  }
}

//-----------------------------------------------------------
// fixupPriceIndicators() - 
//   Changes price indicator params to match new symbol
//   Called onsubmit
//-----------------------------------------------------------
function fixupPriceIndicators() {
  var f = document.forms.workbench;
  var inputsymbol = f.inputsymbol.value.toUpperCase();
  var symbol = f.symbol.value.toUpperCase();
  var evIndex = 0;
  
  if (inputsymbol == symbol || inputsymbol.indexOf(":") != -1 || symbol.indexOf(":") != -1) { return; }
 
  for (i=0; i < f.elements.length; i++) {
    if (f.elements[i].name.indexOf("indType") != -1 && f.elements[i].options[f.elements[i].selectedIndex].value.indexOf("PRICE") != -1) {
      var elementValue = f.elements[i+1].value;
      elementValue = elementValue.toUpperCase();
      evIndex = elementValue.indexOf(":");
      if (evIndex != -1 && (elementValue.substring(0, inputsymbol.length) + ":") == inputsymbol+":") {
        f.elements[i+1].value = elementValue.replace(inputsymbol+":", symbol+":");
      } else if (evIndex != -1 && (elementValue.substring(evIndex, elementValue.length)) == ":"+inputsymbol) {
        f.elements[i+1].value = elementValue.replace(":"+inputsymbol, ":"+symbol);
      } else if (elementValue == inputsymbol) {
        f.elements[i+1].value=elementValue.replace(inputsymbol, symbol);
      }
    }
  }
  f.inputsymbol.value = f.symbol.value;
}

//***********************************************************
// CHARTLIST UI HANDLERS
//***********************************************************
var _CHARTLIST_UI_HANDLERS_;

//-----------------------------------------------------------
// addChart(formIndex) - 
//   Pass in "1" if handling the upper form, "2" if called
//   from the lower one
//-----------------------------------------------------------
function addChart(formIndex, link) {
  var f = document.forms.workbench;
  var nameField = f["favoritesNameNew"+formIndex];
  var listNum = 0;
  var listField = f["favoritesListAddNew"+formIndex];
  var name=nameField.value;
  if (emptyName(name,"Chart") || invalidChar(name,"Chart")) { return false; }
  var action = "";
  if (listField)
    { listNum = listField.options[listField.selectedIndex].value; }
  else if (f.nMaxIndicators.value == BasicMaxIndicators)
    { listNum = 1; }
  if (listNum!==0) //this means you may get "" or null if value of listField?
    { action = link +"&listNum="+ listNum +"&name="+ escape(name); }
  else
    { action = link +"&name="+ escape(name); }
  submitItSimplified(action);
}

//-----------------------------------------------------------
// editChart() - 
//-----------------------------------------------------------
function editChart(link,formIndex) {
  var f = document.forms.workbench;
  //alert(formIndex);
  var nameField = f["favoritesNameEdit"+formIndex];
  var listField = f["favoritesListEdit"+formIndex];
  var listNum = 0;
  var action = "";
  var name=nameField.value;
  if (emptyName(name,"Chart") || invalidChar(name,"Chart")) { return false; }
  if (listField)
    { listNum = listField.options[listField.selectedIndex].value; }
  else if (f.nMaxIndicators.value == BasicMaxIndicators)
    { listNum = 1; }
  if (listNum!==0)  //this means you may get "" or null if value of listField?  
    { action = link +"&listNum="+ listNum +"&name="+ escape(nameField.value); }
  else
    { action = link +"&name="+ escape(nameField.value); }

  submitItSimplified(action);
}

//-----------------------------------------------------------
// deleteChart() - 
//-----------------------------------------------------------
function deleteChart(link) {
  if (!confirm("Are you sure you want to delete this chart?")) { return false; }
  var action = link;   
  submitItSimplified(action);
}

//-----------------------------------------------------------
// setEntireListToChartStyle() - 
//-----------------------------------------------------------
function setEntireListToChartStyle(link, ln) {
  var action = link +"&listNum="+ ln;
  var doFullUpdate = null;
  var full = "false";
  
  if (!confirm("Are you sure you wish to apply the current style to ALL charts in the current ChartList?")) { return false; }
  doFullUpdate = confirm("Do you want to change the 'Period' setting for all charts in the current ChartList to match the Period setting of the current style?\nNote: Annotations are removed when a chart's period is change.\n\nClick 'OK' to change all Period settings, click 'Cancel' to leave them unchanged.");
  if (doFullUpdate) 
    full = "true";
  else
    full = "false";
  submitItSimplified(action+"&full="+full);
}

//-----------------------------------------------------------
// loadChart() - 
//-----------------------------------------------------------
function loadChart() {
  var f = document.forms.workbench;
  var chartURL = f.favoritesLoad[f.favoritesLoad.selectedIndex].value;
  if (chartURL) {
    //f.method = "GET";
    //f.defaultChart.value="false";
    var action = "/h-sc/ui?" + chartURL;
    if (f.curChartList.value)
      { action += "&listNum=" + f.curChartList.value; }
    if (sendURLToLink && typeof(savedLink.href)!="undefined") {  //--globals
      savedLink.href=action;
      sendURLToLink=false;
      return true;
    }
    else {

refreshCancelled=true;

      window.location.href=action;
    }
    //submitItSimplified(action);
  }
  return false;
}

//-----------------------------------------------------------
// loadFavList() - 
//-----------------------------------------------------------
function loadFavList() {
  var f = document.forms.workbench;
  f.curChartList.value = f.favoritesList.value;
  f.chartId.value = "newlist";
  f.isPermanentId.value = "true";
  f.curChartName.value = "";
  submitIt();
}


//***********************************************************
// CHARTSTYLE UI HANDLERS
//***********************************************************
var _CHART_STYLE_UI_HANDLERS;


//-----------------------------------------------------------
// invalidChar(name,source) - 
//-----------------------------------------------------------
function invalidChar(name,source)
{
  if (source=="ChartStyle" && !(/[,\|]/).test(name)) { return false; }
  if (source=="Chart" && !(/[\|]/).test(name)) { return false; }
  if (source=="ChartStyle") 
    { alert ("Your ChartStyle name contains the invalid characters '|' or ','.  \nPlease enter a different name."); }
  if (source=="Chart") 
    { alert ("Your Chart name contains the invalid character '|'.  \nPlease enter a different name."); }
  return true;
}

//-----------------------------------------------------------
// emptyName(name,source) - 
//-----------------------------------------------------------
function emptyName(name,source)
{
  if (!(/^\s*$/).test(name)) { return false; }
  alert ("Your "+source+" has no name.  \nPlease enter a name before submitting.");
  return true;
}


//-----------------------------------------------------------
// checkSettingSelected() - 
//-----------------------------------------------------------
function checkSettingSelected()
{
  var f = document.forms.workbench;
  var setting = f.settingMain.options[f.settingMain.selectedIndex].value;
  if (setting == "0|||" || setting == "-1|||") { alert("You must select a ChartStyle first."); }
  return (setting != "0|||");
}

//-----------------------------------------------------------
// checkSettingCount() - 
//-----------------------------------------------------------
function checkSettingCount()
{
  var f = document.forms.workbench;
  if (!f || !f.customSettingsCount || !document.getElementById) { return false; }
  var member_type="";
  var test=document.getElementById("sharpCharts2");
  if (test && (/extra\_member/).test(""+test.className)) { member_type="extra"; }
  else if (test && (/basic\_member/).test(""+test.className)) { member_type="basic"; }
  if (member_type=="extra" && f.customSettingsCount.value >= ExtraMaxStyles) {
    alert("You have already saved "+(f.customSettingsCount.value)+" ChartStyles in your 'Extra' account. In order to save additional ChartStyles, you must either replace or delete an existing ChartStyle first.");
    return false;
  } else if (member_type=="basic" && f.customSettingsCount.value >= BasicMaxStyles) {
    alert("You have already saved "+(f.customSettingsCount.value)+" ChartStyles in your 'Basic' account. In order to save additional ChartStyles, you must either replace or delete an existing ChartStyle first. 'Extra' members can save up to "+ExtraMaxStyles+" ChartStyles.");
    return false;
  } 
  return true;
}


//-----------------------------------------------------------
// checkReplaceableSetting() - 
//-----------------------------------------------------------
function checkReplaceableSetting()
{
  var f = document.forms.workbench;
  var setting = f.settingMain.options[f.settingMain.selectedIndex].value;
  if (setting == "0|||" || setting == "-1|||") { 
    alert("You must select a ChartStyle first.");
    return false;
  }
  var setting_split = setting.split('|');
  var recid = "";
  recid = setting_split[0];
  if (recid.length < 3) {
    alert("You cannot choose a Predefined Chart Style for this operation.");
    return false;
  }
  return true;
}

// loadSetting() - 
//   Called by the shortcut buttons
//-----------------------------------------------------------
function loadSetting(value,link) { 
  if (typeof(link)=="undefined") { link=0; }
  if (pageInitializing) { return false; }

  var f = document.forms.workbench;

  if (link && !(/\#$/).test(link.href)){
    link.href="#";
    link=0;
  }
  
  if (typeof(value) != "undefined")
    { f.settingMain.selectedIndex = getOptionIndex(f.settingMain,value); }

  var setting = f.settingMain.options[f.settingMain.selectedIndex].value;

  if (setting != "0|||" && setting != "-1|||" && setting !== "" && setting !== 0) {
    var setting_split = setting.split('|');

    f.chartId.value = setting_split[0];
    f.isPermanentId.value="false";

    var useURL="";
    if (setting_split[0].charAt(0) == "u") {
      useURL = window.location.protocol + "//" + window.location.host + "/h-sc/ui?c=" + f.symbol.value + "," + f.chartId.value + "&def=" + setting_split[3];
    } else {
      useURL = window.location.protocol + "//" + window.location.host + "/h-sc/ui?s=" + f.symbol.value + "&id=" + f.chartId.value + "&def=" + setting_split[3];
    }
    if (f.annotation && f.annotation.value.length > 0 && f.nMaxIndicators.value >= BasicMaxIndicators)
      { useURL+= "&a=" + f.annotation.value; }
    if (f.curChartList.value.length > 0 && f.nMaxIndicators.value > BasicMaxIndicators)
      { useURL+= "&listNum=" + f.curChartList.value; }
    if (f.favoritesLoad && f.favoritesLoad.selectedIndex && f.favoritesLoad.selectedIndex >= 0)
      { useURL+= "&cn=" + f.favoritesLoad.selectedIndex; }
    if (link) {
      link.href=useURL;
      return true;
    }
    else {

refreshCancelled=true;

	  window.location.href=useURL;
      //submitItSimplified(useURL);
    }
  }
  return false;
}


//-----------------------------------------------------------
// defaultSetting() - 
//-----------------------------------------------------------
function defaultSetting() {
  if (!confirm("Are you sure you want to make this the default ChartStyle?")) { return; }

  var f = document.forms.workbench;
  f.isPermanentId.value = "true";
  submitIt("&cmd=defaultsetting");
}


//-----------------------------------------------------------
// addSetting() - 
//-----------------------------------------------------------
function addSetting(link) {
  var f = document.forms.workbench;
  
  var name=f.settingNameNew.value;
  if (name.replace(/\s/g,"") == defaultStyleName) {
    alert("The ChartStyle name >>Default<< is reserved."+
          "\nUse [Make Default] to set this style or choose another name.");
    return false;
  }  
  if (name.length > 30) {
    alert("The ChartStyle name " + name + " is longer than 30 characters."+
          "\nChoose another name that is shorter.");
    return false;
  }
  
  if (emptyName(name,"ChartStyle") || invalidChar(name,"ChartStyle")) { return false; }

  var shortcut = f.shortcutButtonNew.options[f.shortcutButtonNew.selectedIndex].value;
  f.isPermanentId.value = "false";
  if (shortcut !== "") {
    submitIt(link + "&desc=" + escape(name) + "&shortcut=" + shortcut + "&cmd=addsetting");
  } else {
    submitIt(link + "&desc=" + escape(name) + "&shortcut=none&cmd=addsetting");
  }
  return true;
}



//-----------------------------------------------------------
// replaceSetting() - 
//-----------------------------------------------------------
function replaceSetting() {
  var f = document.forms.workbench;
  var setting = f.settingReplace.options[f.settingReplace.selectedIndex].value;
  var desc = f.settingReplace.options[f.settingReplace.selectedIndex].text;
  
  if (desc==defaultStyleName) {
    alert("The ChartStyle name >>Default<< is reserved."+
          "\nUse [Make Default] to replace this style");
    return false;
  }  
  if (setting != "0|||" && setting != "-1|||") {
    var setting_split = setting.split('|');
    var recid = "";
    recid = setting_split[1];
    if (recid.length < 3) {
      alert("You cannot replace a Predefined Chart Style.");
      return;
    }
    f.chartId.value = "";
    f.isPermanentId.value = "false";
    submitIt("?s=" + f.symbol.value  + "&def=" + setting_split[3]+ "&desc='" + escape(desc) + "'" + "&recid=" + recid + "&cmd=replacesetting");
  }
  else { alert("Please select a ChartStyle to replace."); } //--should never be called, see checkSettingSelected()
  return true;
}

//-----------------------------------------------------------
// editSetting() - 
//-----------------------------------------------------------
function editSetting() {
  var f = document.forms.workbench;
  var desc = f.settingNameEdit.value;
  var oldName=f.settingMain.options[f.settingMain.selectedIndex].text;
  //--prevent default name change, does this need an alert?
  if (oldName==defaultStyleName) { desc=defaultStyleName; }
  else if (desc==defaultStyleName) {
    alert("The ChartStyle name >>Default<< is reserved."+
          "\nUse [Make Default] to set this style or choose another name.");
    return false;
  }  
  if (name.length > 30) {
    alert("The ChartStyle name " + name + " is longer than 30 characters."+
          "\nChoose another name that is shorter.");
    return false;
  }

  if (emptyName(desc,"ChartStyle") || invalidChar(desc,"ChartStyle")) 
    { return false; }

  if (!desc)
    { desc = f.settingMain.options[f.settingMain.selectedIndex].text; }
    
  var setting = f.settingMain.options[f.settingMain.selectedIndex].value;
  var recid = "";
  
  if (setting != "0|||" && setting != "-1|||") {
    var shortcut = f.shortcutButtonEdit.options[f.shortcutButtonEdit.selectedIndex].value;
    var setting_split = setting.split('|');
    recid = setting_split[1];
    f.chartId.value = setting_split[0];
    f.isPermanentId.value = "false";

    if (!shortcut)
      { shortcut = "none"; }

    submitIt("?s=" + f.symbol.value + "&def=" + setting_split[3] + "&desc=" + escape(desc) + "&recid=" + recid + "&id=" + f.chartId.value + "&shortcut=" + shortcut + "&cmd=editsetting");
    return true;
  }  
  else { alert("Please select a ChartStyle to edit."); } //--should never be called, see checkSettingSelected()
}

//-----------------------------------------------------------
// deleteSetting() - 
//-----------------------------------------------------------
function deleteSetting() {

  var f = document.forms.workbench;
  var setting = f.settingMain.options[f.settingMain.selectedIndex].value;
  var name=f.settingMain.options[f.settingMain.selectedIndex].text;

  if (name==defaultStyleName)
  {
    alert("You cannot delete the default ChartStyle.");
    return;
  }
  
  if (setting != "0|||" && setting != "-1|||") {
    var setting_split = setting.split('|');
    f.isPermanentId.value = "false";
    if (setting_split[0].length <=2) {
      alert("You cannot delete a Predefined Chart Style.");
      return;
    }
    if (!confirm("Are you sure you want to delete this ChartStyle?")) { return; }
    submitIt("?s=" + f.symbol.value  + "&def=" + setting_split[3] + "&recid=" + setting_split[1] + "&cmd=deletesetting");
  }
}


var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
function isValid(parm,val) {
  if (!parm) { return true; }
  for (i=0; i<parm.length; i++) {
    if (val.indexOf(parm.charAt(i),0) == -1) { return false; }
  }
  return true;
}
 
function isNum(parm) {
	return isValid(parm,numb);
}

function isLower(parm) {
	return isValid(parm,lwr);
}

function isUpper(parm) {
	return isValid(parm,upr);
}

function isAlpha(parm) {
	return isValid(parm,lwr+upr);
}

function isAlphanum(parm) {
	return isValid(parm,lwr+upr+numb);
}

//-----------------------------------------------------------
// addDescription() - 
//-----------------------------------------------------------
function addDescription(fieldName) {
  var f=document.forms.workbench;
  if (!f || !f.symbol || ! document.getElementById(fieldName)) { return; }
  var symbol=f.symbol.value;
  var period=f.period.options[f.period.selectedIndex].text;
  var style=f.symStyle.options[f.symStyle.selectedIndex].text;
  var size=f.chartSize.options[f.chartSize.selectedIndex].text;
  if (size=="Custom") { size+=" ("+f.customWidth.value+"X"+f.customHeight.value+")"; }
  document.getElementById(fieldName).value=symbol+" - "+period+" "+style+", "+size;
}

//-----------------------------------------------------------
// setPeriodPredef() - 
//-----------------------------------------------------------
function setPeriodPredef(p) {
  var f = document.forms.workbench;
  if (!f || !f.period || !f.period2) { return; }
  var period = "";
  
  if (p == "2") {
    period = f.period2.options[f.period2.selectedIndex].value;
    f.period.selectedIndex = f.period2.selectedIndex;
  } else {
    period = f.period.options[f.period.selectedIndex].value;
    f.period2.selectedIndex = f.period.selectedIndex;
  }
    
  return true;
}

//-----------------------------------------------------------
// setPredefChanged() - 
//-----------------------------------------------------------
function setPredefChanged() {
  var f = document.forms.workbench;
  if (!f || !f.dataRange) { return; }
  var selected = f.dataRange.options[f.dataRange.selectedIndex].value;
  
  if (!f.predefChanged || f.predefChanged.value=="true") { return; }
    
  setPeriodPredef();
  
  if ((/^predef/).test(selected)) { f.predefChanged.value="true"; }
}

//-----------------------------------------------------------
// set_ymd(list) - 
//-----------------------------------------------------------
function set_ymd(list)
{
  var rangeShown;
  if (typeof(list)=="undefined" || !list || !document.getElementById) { return false; }
  var form=list.form;
  var value=list.options[list.selectedIndex].value;
  if (!value || !(/^(userdef|predef|fill):/).test(value)) { return false; }

  if ((/^predef:/).test(value))
  {
    var ymd=value.replace("predef:","").split("|");
    if (!ymd || ymd.length<3) { return false; }
    form.years.selectedIndex=getOptionIndex(form.years,ymd[0]);
    form.months.selectedIndex=getOptionIndex(form.months,ymd[1]);
    form.days.selectedIndex=getOptionIndex(form.days,ymd[2]);
    rangeShown=document.getElementById(list.name+"-predef");
  }
  if ((/^userdef:/).test(value))
  {
    var type=value.replace("userdef:","");
    if (type=="ytd")
    {
      var today=new Date();
      form.start.value=parseDate("",new Date(today.getFullYear(), 0, 1));
    }
    rangeShown=document.getElementById(list.name+"-userdef");
  }
  if ((/^fill:/).test(value))
  {
    rangeShown=document.getElementById(list.name+"-fill");
  }
  var sameRangeOptions=(rangeShown && rangeShown.className=="selectVisible");
  return sameRangeOptions;
}

//-----------------------------------------------------------
// resetRange() - 
//-----------------------------------------------------------
function resetRange(list,name) {
  var form=list.form;
  form.dataRange.selectedIndex=getOptionIndex(form.dataRange,name);
}

//***********************************************************
// OVERLAY AND INDICATOR UI HANDLERS
//***********************************************************
var _OVERLAY_AND_INDICATOR_UI_HANDLERS_;


//-----------------------------------------------------------
// getDefault(key) -
//   Loads default params for ind/over selections
//-----------------------------------------------------------
function getDefault(key) {
  if (pDefaults.length === 0) {
    var symbolValue=document.forms.workbench.symbol.value;
    var names  = ["SMA","EMA","BB",  "SAR",     "CHAN","ICHIMOKU",   "ENV",   "KELT",     "ZIGZAG","RETRACE","LABELS","VOLHORIZ","VOL","RSI","MACD",   "MACDHIST","PPO",    "DPO","PVO",    "COSC","CMF","CCI","STOSLOW","STOFAST","STOFULL","STORSI","FORCE","WMR","AROON","AROONOSC","ADX","ACCDIST","OBV","ROC","ATR","ULT",    "TRIX","MFI","BBWIDTH","BBPCT","QRANK", "LINREGSLOPE", "CV", "STDDEV", "BIGQ","PRICE","PRICEPERF","PRICECOMP","TIMESCALE"];
    var values = ["50", "20", "20,2","0.02,0.2","20",  "9,26,52",    "20,2.5","20,2.0,10","",      "",      "",      "",        "",   "14", "12,26,9","12,26,9", "12,26,9","20", "12,26,9","3,10","20", "20", "14,3",   "14,3",   "14,3,3", "14",    "13",   "14", "25",   "25",      "14", "",       "",   "12", "14", "7,14,28","15,9","14", "20,2",   "20,2", "",      "20",          "10", "10",     "",    "$spx", "$spx",     "$spx",     ""];
    for (var i=0; i < names.length; i++) {
      pDefaults[names[i]] = values[i];
    }
  }
  
  if (typeof(pDefaults[key]) == "undefined")
    { return ""; }
  return pDefaults[key];
}


//-----------------------------------------------------------
// getRowIndex(name) -
//   Finds row # in field name (indArgs_1 = 1)
//-----------------------------------------------------------
function getRowIndex(name) {
  if (!name.search)
    { return -1; }
    
  var start = name.search(/\d+$/);
  return (start >= 0) ? name.substr(start)-0 : -1; 
}


//-----------------------------------------------------------
// getRowFields(element) -
//   Returns an array of fields for a given row.
//   Note: Fields must be numbered sequentially with no in-
//      between fields-ex.[field_1 testField field_2] will fail
//
//   !!!!!!!!!!! This ignores the reorder column, so this is one index
//   off from the hide column operations !!!!!!!!!!!!!!!!!!
//-----------------------------------------------------------
function getRowFields(element) {
  var fields = [];
  var row = getParentRow(element);
  var tds = row.getElementsByTagName("td");
  for (var i=0; i < tds.length; i++) {
    var field = getFormField(tds[i]);
    if (field)
      { fields[fields.length] = field; }
  }
  return fields;
}


//-----------------------------------------------------------
// setArgsO(element) -
//    Sets default values for overlay selections
//-----------------------------------------------------------
function setArgsO(element) {
  var selected = getSelectedValue(element);
  var fields = getRowFields(element);
  if (fields && fields.length > 1) 
    { fields[1].value=getDefault(selected); }
  
  if (fields && fields.length > 4) {
    fields[2].selectedIndex=0;
    fields[3].selectedIndex=0;
    fields[4].selectedIndex=0;
  }
  
  hideRowFields(element); //--this checks for P/V
  if (!pageInitializing) { requireNewOverRow(element); }

  currentFields=0;
}

//-----------------------------------------------------------
// setArgsI(element) -
//    Sets default values for indicator selections
//-----------------------------------------------------------
function setArgsI(element) {
  var selected = getSelectedValue(element);
  var fields = getRowFields(element);
  
  if (fields && fields.length > 1) 
    { fields[1].value=getDefault(selected); }
    
  if (fields && fields.length > 8) {
    fields[7].selectedIndex=0;
    fields[8].value="";
  }
  if (fields && fields.length > 6) {
    fields[3].selectedIndex=0;
    fields[4].value="";
  }
  hideRowFields(element); //--this checks for TIMESCALE,Price
  if (!pageInitializing) { requireNewIndRow(element); }

  currentFields=0;
}


//-----------------------------------------------------------
// setArgsIO(element) -
//    Sets default values for overlays-of-indicator selections
//-----------------------------------------------------------
function setArgsIO(element) {
  var selected = getSelectedValue(element);
  var fields=getRowFields(element);
  if (fields && fields.length > 8 && fields[8].name.indexOf("indOverArgs") === 0) 
     { fields[8].value=getDefault(selected); }
}

//-----------------------------------------------------------
// setArgsOther(element) -
//    Sets default values for overlays-of-indicator selections
//-----------------------------------------------------------
function setArgsOther(element) {
  var selected = getSelectedValue(element);
  var target=0;
  if (element.id=="kagiUnit") { target=document.getElementById("kagiReversal"); }
  if (element.id=="renkoUnit") { target=document.getElementById("renkoBoxSize"); }
  if (target)
  {
    if (selected=="percent") { target.value="0.5"; }
    else if (selected=="point") { target.value="1"; }
    else if (selected=="atr") { target.value="14"; }
  }
}


//-----------------------------------------------------------
// setLoc(element) -
//    Sets height/opacity for position also forces DateTime
//    to not use position=behind
//    (see also restrictPositionSelect below)
//-----------------------------------------------------------
function setLoc(element) {
  var f = document.forms.workbench;
  var fields = getRowFields(element);
  
  if (!fields) { return; }
  
  var selected = element.options[element.selectedIndex].value;
  if (selected=="behind") {
    if (fields.length > 0 && fields[0].options[fields[0].selectedIndex].value == "TIMESCALE")
      { element.selectedIndex = 2; }
    else if (fields.length > 6) {
      fields[5].value="";
      fields[6].value="";
    }
  } else if (fields.length > 6) {
    fields[5].value="";
    fields[6].value="";
  }
}


//-----------------------------------------------------------
// setTemporaryId() -
//-----------------------------------------------------------
function setTemporaryId() {
  var f=document.forms.workbench;
  if (!f || !f.isPermanentId || !f.chartId) { return; }
  f.isPermanentId.value=false;
  f.chartId.value=null;
}


//-----------------------------------------------------------
// setPermanentId() -
//-----------------------------------------------------------
function setPermanentId() {
  var f=document.forms.workbench;
  
  if (!f || !f.setPermanentId) { return; }
  f.setPermanentId.value=true;
}


//***********************************************************
// FUNCTIONS THAT CREATE NEW WINDOWS
//***********************************************************
var _NEW_WINDOW_FUNCTIONS_;

//-----------------------------------------------------------
// getFeedback(fn) -
//-----------------------------------------------------------
function getFeedback(fn) {
  if (pageInitializing) { return; }
  var f = document.forms.workbench;
  var w = 800;
  var h = 600;
  win = window.open(fn, "", "scrollbars=yes,resizable=yes,top=0,left=0,width="+w+",height="+h);
  win.focus();
}


//-----------------------------------------------------------
// showChartNotes(fn) -
//-----------------------------------------------------------
function showChartNotes(fn) {
  if (pageInitializing) { return; }
  var f = document.forms.workbench;
  var img = document.getElementById("chartImg");
  if (!img) { return false; }
  var w = img.width + 39;
  var h = img.height + 93;
  var x = w+40;
  var y = h+40;
  var win = window.open(fn+","+w+"|"+h,"ChartNotes","toolbar=0,location=0,scrollbars=1,width="+x+",height="+y+",resizable=1");
  win.focus();
}


//-----------------------------------------------------------
// showStreamer(fn) -
//-----------------------------------------------------------
function showStreamer(fn){
  if (pageInitializing) { return; }
  var f = document.forms.workbench;
  var img = document.getElementById("chartImg");
  if (!img) { return false; }
  var w = img.width + 39;
  var h = img.height + 93;
  var x = w+40;
  var y = h+40;
  var win = window.open(fn+","+w+"|"+h,"","toolbar=0,location=0,scrollbars=1,width="+x+",height="+y+",resizable=1");
  win.focus();
}

//-----------------------------------------------------------
// mailChart(fn) -
//-----------------------------------------------------------
function mailChart(fn) {
  if (pageInitializing) { return; }
  var f = document.forms.workbench;
  var w = 600;
  var h = 600;
  win = window.open(fn, "", "scrollbars=yes,resizable=yes,top=0,left=0,width="+w+",height="+h);
  win.focus();
}


//-----------------------------------------------------------
// printVersion(fn) -
//-----------------------------------------------------------
function printVersion(fn) {
  if (pageInitializing) { return; }
  var f = document.forms.workbench;
  var img = document.getElementById("chartImg");
  if (!img) { return false; }
  var w = img.width;
  var h = img.height;
  var win;
  if (w < 500) { w = 500; } // for the ad for free users
  h += 120;
  w += 16;
  if (document.all) { //ie
    w += 38;
    h += 48;
    if ((window.screen) && (w > screen.width-10))  { w = screen.width-10; }
    if ((window.screen) && (h > screen.height-10)) { h = screen.height-10; }
    win = window.open(fn, "", "scrollbars=yes,resizable=yes,top=0,left=0,width="+w+",height="+h);
  } else {
    w += 16;
    h += 32;
    if ((window.screen) && (w > screen.width-10))  { w = screen.width-10; }
    if ((window.screen) && (h > screen.height-10)) { h = screen.height-10; }
    win = window.open(fn, "", "scrollbars=yes,resizable=yes,screenY=0,sceenX=0,width="+w+",height="+h);
  }
  win.focus();
  return true;
}

//-----------------------------------------------------------
// submitColorScheme() -
//   Called by onClick handler for ColorScheme dropdown
//-----------------------------------------------------------
function submitColorScheme() {
  submitIt();
}

//-----------------------------------------------------------
// submitPeriod() -
//   Called by onClick handler for Period dropdown
//-----------------------------------------------------------
function submitPeriod() {
  setPeriodPredef();
  //submitIt();
}

//-----------------------------------------------------------
// submitPeriod2() -
//   Called by onClick handler for Period dropdown
//-----------------------------------------------------------
function submitPeriod2() {
  setPeriodPredef("2");
  //submitIt();
}

//-----------------------------------------------------------
// submitChartType() -
//   Called by onClick handler for ChartType dropdown
//-----------------------------------------------------------
function submitChartType() {
  submitIt();
}

//***********************************************************
// PAGE RELOAD FUNCTIONS
//***********************************************************
var _PAGE_RELOAD_FUNCTIONS_;

//-----------------------------------------------------------
// confirmReset() -
//-----------------------------------------------------------
function confirmReset() {
  return confirm("This will reset your chart to the defaults.\nAre you sure you want to continue?");
}

//-----------------------------------------------------------
// resetChart() -
//-----------------------------------------------------------
function resetChart() {
  if (pageInitializing) { return; }
  if (!confirmReset()) { return; }

refreshCancelled=true;

  window.location = window.location.protocol + "//" + window.location.host + "/h-sc/ui";
}

//-----------------------------------------------------------
// clearTable() -
//-----------------------------------------------------------
function clearTable(table) {
  if (pageInitializing) { return; }
  if (!table) { return; }
  var trs = table.getElementsByTagName("tr");
  if (!trs) { return; }
  for (var i=0; i < trs.length; i++) {
    var tds = trs[i].getElementsByTagName("td");
    if (!tds) { return; }
    
    for (var j=0; j < tds.length; j++) {
      var field = getFormField(tds[j]);
      if (!field) { continue; }
      if (field.nodeName == "SELECT") 
        { field.selectedIndex = 0; }
      else
        { field.value = ""; }
    
      if (j === 0)
        { field.onchange(); }
    }
  }
}

//-----------------------------------------------------------
// confirmClearOverlays() -
//-----------------------------------------------------------
function confirmClearOverlays() {
  return confirm("This will erase all the overlays and their values.\nAre you sure you want to continue?");
}

//-----------------------------------------------------------
// clearOverlays() -
//-----------------------------------------------------------
function clearOverlays() {
  if (pageInitializing || !document.getElementById || !confirmClearOverlays()) { return; }
  var table = document.getElementById("overStyles");
  clearTable(table);
  for (var i=0;i<ExtraMaxIndicators;i++)
  {
    var oldRow = document.getElementById("overRow_"+i);
    if (oldRow) { setRowReorder(i, oldRow, "over","blank"); }
  }
  setTemporaryId();
}

//-----------------------------------------------------------
// confirmClearIndicators() -
//-----------------------------------------------------------
function confirmClearIndicators() {
  return confirm("This will erase all the indicators and their values.\nAre you sure you want to continue?");
}

//-----------------------------------------------------------
// clearIndicators() - 
//-----------------------------------------------------------
function clearIndicators() {
  if (pageInitializing || !document.getElementById || !confirmClearIndicators()) { return; }
  var table = document.getElementById("indStyles");
  clearTable(table);
  for (var i=0;i<ExtraMaxIndicators;i++)
  {
    var oldRow = document.getElementById("indRow_"+i);
    if (oldRow) { setRowReorder(i, oldRow, "ind","blank"); }
  }
  setTemporaryId();
}

//-----------------------------------------------------------
// createLink() -
//  onClick handler for "Linkable Version"
//-----------------------------------------------------------
function createLink(link) {
  if (pageInitializing) { return; }

refreshCancelled=true;

  window.location=window.location.protocol + "//" + window.location.host+link;
}

//-----------------------------------------------------------
// syncHeights() -
//-----------------------------------------------------------
function syncHeights() {
  if (pageInitializing || !document.getElementById) { return; }
  var height = document.getElementById("syncHeight");
  if (!height) { return; }
  
  //var syncValue=height.options[height.selectedIndex].value;
  var f = document.forms.workbench;
  var i = 0;
  var heightRoot = "indHeight_";
  while (typeof(f[heightRoot+i]) != "undefined") {
    f[heightRoot+i].selectedIndex = height.selectedIndex; //?
    i++;
  }
  setTemporaryId();
}


//***********************************************************
//
//***********************************************************


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getParentRow(child) {
  if (!child.parentNode) { return; }
  var node=child;
  var count=5;
  while (node && node.nodeName != "TR") {
    if (count-- < 0) { return; }
    node = node.parentNode;
  }
  return node;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getParentTableOrTBody(node) {
  var count=5;
  while (node && node.parentNode && count-- > 0) {
    if (node.nodeName == "TABLE" || node.nodeName == "TBODY") { return node; }
    node = node.parentNode;
  }
  return 0;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getFormField(cell) {
  for (var i=0; i < cell.childNodes.length; i++) {
    if (cell.childNodes[i].nodeName=="SELECT" || cell.childNodes[i].nodeName=="INPUT")
      { return cell.childNodes[i]; }
  }
  return 0;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getSelectedIndex(selectList) {
  var index=selectList.selectedIndex;
  
  if (pageInitializing && window.opera) 
    { index = holdIndexesForOpera[selectList.name]; }
  if (!index || index < 0) { index = 0; }
  return index;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getSelectedValue(selectList) {
  var index=getSelectedIndex(selectList);
  return selectList.options[index].value;
}


//--note, this will return 0 on fail
//  0 is not a testable fail (since it can also be a positive)
//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getOptionIndex(selectField, value) {
  if (value != "0.0" && (value === "" || value === 0)) { return 0; }

  for (var i=0; i < selectField.options.length; i++) {
    if (selectField.options[i].value == value)
      { return i; }
  }
  return 0;
}


//----------------------------------------------

//--if needed, creates a new empty row
//--called by setArgsI (select fields onChange), 
//  createIndRow() onload
//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function requireNewIndRow(selectList) {
  var rowCount = getTotalRows("ind");
  var nMax = getMaxRows("ind");
  if (typeof(selectList) != "undefined") {
    var selectIndex = getSelectedIndex(selectList);
    var selectValue = selectList.options[selectIndex].value;
    if (selectIndex === 0 || selectValue === "") { return; }
    var rowIndex = parseInt(selectList.name.replace(/^.*_(\d+)$/,"$1"), 10);
    if (rowIndex < rowCount-1) { return; } //--dont add a new row
    if (rowCount > 0 && rowCount < nMax)
      { createIndRow(rowCount, ""); }
    else if (rowCount == nMax)
    {
      setTotalRows("ind", nMax);
      var oldRow = document.getElementById("indRow_"+rowIndex);
      setRowReorder(rowIndex, oldRow, "ind", "");
    }
  }
}

//--if needed, creates a new empty row
//--called by setArgs0 (select fields onChange), 
//  createOverRow() onload
//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function requireNewOverRow(selectList) {
  var rowCount = getTotalRows("over");
  var nMax = getMaxRows("over");
  if (typeof(selectList) != "undefined") {
    var selectIndex = getSelectedIndex(selectList);
    var selectValue = selectList.options[selectIndex].value;
    if (selectIndex === 0 || selectValue === "") { return; }
    var rowIndex = parseInt(selectList.name.replace(/^.*_(\d+)$/,"$1"), 10);
    if (rowIndex < rowCount-1) { return; } //--dont add a new row
    if (rowCount > 0 && rowCount < nMax)
      { createOverRow(rowCount, ""); }
    else if (rowCount == nMax)
    {
      setTotalRows("over", nMax);
      var oldRow = document.getElementById("overRow_"+rowIndex);
      setRowReorder(rowIndex, oldRow, "over", "");
    }
  }

}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getMaxRows(type) {
  var f = document.forms.workbench;
  if (!f || !f.nMaxOverlays || !f.nMaxIndicators) { return 0; }
  return parseInt((type == "over") ? f.nMaxOverlays.value : f.nMaxIndicators.value, 10);
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getTotalRows(type) {
  var f = document.forms.workbench;
  if (!f || !f.nOverlays || !f.nIndicators) { return 0; }
  return parseInt((type == "over") ? f.nOverlays.value : f.nIndicators.value, 10);
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setTotalRows(type, value) {
  var f = document.forms.workbench;
  if (!f || !f.nOverlays || !f.nIndicators) { return 0; }
  if (type == "over") { f.nOverlays.value = value; }
  else { f.nIndicators.value = value; }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setRowReorder(index, row, type, rowType) {
   if (!row) { return; }
   if (typeof(rowType) == "undefined") { rowType=""; }
   var links = row.getElementsByTagName("a");
   if (!links || links.length<2) { return; }
   var oldRow;
   var linkA = links[0];
   var linkB = links[1];
   var total = getTotalRows(type);
   var max = getMaxRows(type);
   linkA.className = (linkA.className+"").replace(/reorderHidden/g,"");
   linkB.className = (linkB.className+"").replace(/reorderHidden/g,"");
//if ((!pageInitializing) alert (rowType+" index "+index+" total "+total);
   if ((!pageInitializing || rowType=="old blank") &&
      ((index>=total-2 && (total!=max || rowType=="old blank")) || index>=total-1)) 
     { linkB.className += " reorderHidden"; } 
   if (index===0) 
     { linkA.className += " reorderHidden"; }
   if (index>=total-1 && rowType=="blank") {
     linkA.className += " reorderHidden";
     linkB.className += " reorderHidden";
   }
   //--old blank makes it check two lines back 
   if (rowType=="old blank" && index>0) { //--new bottom row, change previous row!
     oldRow = document.getElementById(type+"Row_"+(index-1));
     setRowReorder(index-1, oldRow, type,"old ");
   } else if (rowType!="old " && index>0 && index>=total-1) { //--new bottom row, change previous row!
     if (pageInitializing && rowType!="blank") { return; }
     oldRow = document.getElementById(type+"Row_"+(index-1));
     setRowReorder(index-1, oldRow, type,"old "+rowType);
   }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setRowNames(index, row, type) {
   if (!row) { return; }
   row.id = type + "Row_" + index;
   row.className = "";

   var tds = row.getElementsByTagName("td");
   if (!tds) { return; }
   var fields=[];
   
   for (var i=0; i < tds.length; i++) {
     field = getFormField(tds[i]);
     if (field) {
       fields[fields.length] = field;
       field.id = field.name = field.name.replace(/_\d*$/,"_"+index);       
     } else {
       try {
         tds[i].getElementsByTagName("a")[0].id = tds[i].getElementsByTagName("a")[0].id.replace(/_\d*$/,"_"+index);
         tds[i].getElementsByTagName("a")[1].id = tds[i].getElementsByTagName("a")[1].id.replace(/_\d*$/,"_"+index);
       } catch(e) {}
     }
   }
   currentFields=fields;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setRowValues(index, row, args) { //--cannot handle checkbox/radio
  if (!row) { return; }
  if (!currentFields) { setCurrentFields(row); }

  for (var i=0; i < currentFields.length; i++) {
    var field=currentFields[i];
    if (!field || args.length<i+2) { continue; }
    if (field.nodeName == "SELECT") {
         var selected = getOptionIndex(field, args[i+1]);
         field.selectedIndex = selected;
         if (window.opera)
           { holdIndexesForOpera[field.name] = selected; }
    } else {
         field.value = args[i+1];
    }
  }
  if (currentFields[0].name.indexOf("Type_") >= 0) 
     { hideRowFields(currentFields[0]); } //--skipping default values?
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setCurrentFields(row) {
   if (!row) { return; }
   if (row.nodeName!="TR") { row = getParentRow(row); }
   var tds = row.getElementsByTagName("td");
   if (!tds) { return; }
   var fields = [];
   for (var i=0; i < tds.length; i++) {
     field = getFormField(tds[i]);
     if (field) 
       { fields[fields.length] = field; }
   }
   currentFields=fields;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function createOverRow(index) {
  var sample = document.getElementById("overSampleRow");
  var row = sample.cloneNode(true);

  //IE bug!!
  if (isIE)
  {
    var selects1 = sample.getElementsByTagName("select");
    var selects2 = row.getElementsByTagName("select");
    for (var i=0; i < selects1.length; i++) {
       selects2[i].selectedIndex=selects1[i].selectedIndex; 
    }
  }

  var nMax = getMaxRows("over");
  if (!row || index>=nMax) { return; }
  setRowNames(index, row, "over");

  sample.parentNode.appendChild(row);
  setRowValues(index, row, arguments);
  setTotalRows("over", getTotalRows("over")+1);
  setRowReorder(index, row, "over",(!arguments[1]) ? "blank" : "");
  currentFields=0;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function createIndRow(index) {
  var sample = document.getElementById("indSampleRow");
  var row = sample.cloneNode(true);
  //if (row.innerHTML) row.innerHTML=sample.innerHTML;

  //IE bug!!
  if (isIE)
  {
    var selects1 = sample.getElementsByTagName("select");
    var selects2 = row.getElementsByTagName("select");
    for (var i=0; i < selects1.length; i++) {
       selects2[i].selectedIndex=selects1[i].selectedIndex; 
    }
  }

  var nMax = getMaxRows("ind");
  if (!row || index>=nMax) { return; }
  setRowNames(index,row,"ind");

  sample.parentNode.appendChild(row);
  setRowValues(index, row, arguments);
  setTotalRows("ind", getTotalRows("ind")+1);
  setRowReorder(index,row,"ind",(!arguments[1]) ? "blank" : "");
  currentFields=0;
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function moveRow(link,direction) {
  if (!document.getElementById) { return; }
  if (link.className.indexOf("reorderHidden") > -1) { return; }
  var linkId = link.id;
  var index = parseInt(linkId.replace(/^.*_(\d+)$/, "$1"), 10);
  if (isNaN(index)) { return; }
  var type = linkId.replace(/^(over|ind).*$/, "$1");
  if (direction > 0)
    { index = index + 1; }
  var oldRow = document.getElementById(type + "Row_" + index);
  var newRow = document.getElementById(type + "Row_" + (index-1));
  if (!oldRow || !newRow) { return; }
  oldRow.parentNode.removeChild(oldRow);
  setRowNames(index, newRow, type);

  setRowNames(index-1, oldRow, type);

  newRow.parentNode.insertBefore(oldRow, newRow);
  setRowReorder(index, newRow, type, "old ");
  setRowReorder(index-1, oldRow, type, "old ");
  setTemporaryId();
  link.focus();

  currentFields=0;
}

//--------------------------------------------------------

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function emptyList(list) {
  for (var i=0; i < list.length; i++) {
    list.options[i] = null;
  }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getRadio(radioField) {
  for (var i=0; i < radioField.length; i++) {
    if (radioField[i].checked)
      { return radioField[i].value; }
  }
  return 0;
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function setRadio(radioField, value) {
  for (var i=0; i < radioField.length; i++) {
    if (radioField[i].value && radioField[i].value==value) {
      radioField[i].checked = true;
      if (radioField[i].onchange) { radioField[i].onchange(); }
    } else
      { radioField[i].checked = false; }
  }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function nextPrevFS(type, direction, link) {
  if (typeof(link)=="undefined") { link=0; }
  var f = document.forms.workbench;
  var fieldName = (type == "favorites") ? "favoritesLoad" : "settingMain";
  if (!f || !f[fieldName]) { return; }
  var field = f[fieldName];
  if (field.options.length == 1) { return false; }
  var currentSetting = f.currentSetting.value;
  var currentFavorite = f.favoritesLoad.options[f.favoritesLoad.selectedIndex].value;
  
  for (var i=0; i < field.options.length; i++) {
    if (type == "settings" && field.options[i].value == currentSetting)
      { field.selectedIndex = i; }
    if (type == "favorites" && field.options[i].text == currentFavorite)
      { field.selectedIndex = i; }
  }
  
  if (direction < 0 && field.selectedIndex <= 1) 
    { field.selectedIndex = field.options.length-1; }
  else if (direction > 0 && field.selectedIndex >= field.options.length-1) 
    { field.selectedIndex = 1; }
  else { field.selectedIndex += direction; }

  if (link)
  {
    sendURLToLink=true; //--global
    savedLink=link; //--global
  }
    
  if (field.onchange)  { field.onchange(); }
}


//----------------------------------------------


//--show/hide DHTML tricks:
//  designed to show all fields in older browsers, to pullout for DOM browsers

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function findInArray(list, value) { //--common utility 
  for (var i=0; i < list.length; i++) {
    if (list[i] == value)
      { return i; }
  }
  return -1;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function removeArrayIndex(list,index) {
  var hold = [];
  for (var i in list) {
    if (i != index && !/^(max|min)$/.test(""+i))
      { hold[hold.length] = list[i]; }
  }
  return hold;
}


//----------------------------------------------

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function clickoffPopup() { //--anything not held by clickinPopup() comes here
  if (!currentPopup || ignoreClick) { return; }
  togglePopup(currentPopup, 0);
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function clickinPopup() { //--prevents clickoffPopup() for clicks *within* container
  ignoreClick = true;
  setTimeout("ignoreClick=false;", 10);
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function pastWindowRight(x, width) {
  var screenWidth = 0;
  
  if (window.innerWidth)
    { screenWidth = window.innerWidth-50; }
  else if (document.body.offsetWidth)
    { screenWidth = document.body.offsetWidth-50; }
   
  return (x + width > screenWidth);
}



//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function swapPopup(current,next){
  try {
   var popup = current.getElementsByTagName("span")[0];
   next.appendChild(current.removeChild(popup));
  }
  catch(e) {}
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function togglePopup(id, link) { //--the IE fix for popups
  if (!document.getElementById) { return false; }
  var popupParent = document.getElementById(id);
  var container = document.getElementById("IEFixSelect-container");
  var iframe = document.getElementById("IEFixSelect-bg");
  
  if (!popupParent || !container || !iframe) { return; }
  
  var popup = 0;
  
  try {
    popup = container.getElementsByTagName("span")[0];
  } catch(e) {
    return;
  }
  
  if (popup) { //--return last popup to proper parent
    container.style.left = container.style.top = "-500em";
    var newParent = document.getElementById(currentPopup);
    swapPopup(container,newParent);
    if (id == currentPopup) { //--closing popup entirely
      var links=newParent.getElementsByTagName("a");
      if (links && links.length>0 && links[0].focus) links[0].focus();
      currentPopup = 0;
      if (document.removeEventListener) {
        document.removeEventListener("click", clickoffPopup, false);
      } else if (document.detachEvent) {
        document.detachEvent("onclick", clickoffPopup);
      } 
      return;
    }
  }
  
  try { 
    popup = popupParent.getElementsByTagName("span")[0];
  } catch(e) {
    return;
  }
  
  //--open popup
  if (window.opera) {
    iframe.style.display = "block";
    popup.style.position = "absolute";
  }
  
  var x=0, y=0, w=0, h=0;
  var parent = popupParent;
  if (!parent.offsetParent) { return; }
  while (parent) {
    var isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") > -1);
    if ((isSafari || window.opera) &&
        ((parent.className+"").indexOf("pulloutVisible") > -1 ||
//--see settingsEdit below (pullout Visible has same problem)
         (parent.id == "extraSettingsOptions"))) {
//--settingsEdit is buggy, it = extraSettingsOptions + true settingsEdit
//--to correct, I am removing extraSettingsOptions (since it is duplicated)
      parent = parent.offsetParent;
      continue;
    }
    
    x += parent.offsetLeft;
    y += parent.offsetTop;
    parent = parent.offsetParent;
    if (parent.nodeName == "FORM") { break; }
  }
  
  swapPopup(popupParent, container);
  
  if (document.all && !window.opera && id.indexOf("favorite") == -1)
    { container.style.top = (y+8)+"px"; }
  else
    { container.style.top = y+"px"; }

  w = popup.offsetWidth-popupParent.offsetWidth;
  if (w && pastWindowRight(x-20, w))  //--align right, not left
    { container.style.left = Math.max(0,((x-w)+20))+"px"; }
  else
    { container.style.left = Math.max(0,(x-20))+"px"; }

  try {
  if (container.addEventListener) {
      container.getElementsByTagName("a")[0].addEventListener("click", clickoffPopup, false);
  } else if (container.attachEvent) {
      container.getElementsByTagName("a")[0].attachEvent("onclick", clickoffPopup);
  }
    //container.getElementsByTagName("a")[0].onclick = clickoffPopup;//popupParent.getElementsByTagName("a")[0].onclick;
  } catch(e) { }
  
  iframe.style.width = container.offsetWidth+"px";
  iframe.style.height = container.offsetHeight+"px";
  
  focusPullout(popup);
  currentPopup = id;

  clickinPopup(); //--prevents clickoffPopup being called right away.

  if (container.addEventListener) {
      container.addEventListener("click", clickinPopup, false);
      document.addEventListener("click", clickoffPopup, false);
  } else if (container.attachEvent) {
      container.attachEvent("onclick", clickinPopup);
      document.attachEvent("onclick", clickoffPopup);
  }
  //container.onclick = clickinPopup;
  //document.onclick = clickoffPopup; 
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function focusPullout(pullout) {
  if (pageInitializing) { return; }

  var spans = pullout.getElementsByTagName("span");
  for (var i=0; i < spans.length; i++) {
    if ((spans[i].className+"").indexOf("saveBoxPullout") > -1) 
      { return focusPullout(spans[i]); }
    for (var j=0; j < spans[i].childNodes.length; j++) { 
      if (spans[i].childNodes[j].nodeName=="INPUT" || spans[i].childNodes[j].nodeName=="SELECT") {
        try {
		  if (spans[i].childNodes[j].getAttribute("readonly")) { continue; }
          spans[i].childNodes[j].focus();
          if (spans[i].childNodes[j].nodeName == "INPUT") 
            { spans[i].childNodes[j].select(); }
        } catch(e) { }
        return;
      }
    }
  }
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function togglePullout(id, link, forceVisible) { //--called by more/less arrow links
  if (!document.getElementById) { return false; }
  if (typeof(forceVisible) == "undefined") { forceVisible = -1; }
  var pullout = document.getElementById(id);
  if (!pullout) { return false; }
  var i;
  var pulloutItems = getPulloutItems(pullout);
  var makeVisible = forceVisible;  //--default=define by first one found
  if (makeVisible < 0 && pulloutItems.length > 0)
      { makeVisible = (pulloutItems[0].className.indexOf("pulloutHidden") > -1); }
  var oldClass = (makeVisible) ? "pulloutHidden" : "pulloutVisible";
  var newClass = (makeVisible) ? "pulloutVisible" : "pulloutHidden";
  for (i=0; i < pulloutItems.length; i++) {
    fullClass = pulloutItems[i].className+"";
    pulloutItems[i].className = fullClass.replace(oldClass, newClass);
  }

  if (typeof(link) == "undefined" || !link) {
    var links = pullout.getElementsByTagName("a");
    for (i=0; i < links.length; i++) {
      if (links[i].className && links[i].className.indexOf("pulloutLink") > -1) {
         link = links[i];
         break;
      }
    }
  }

  toggleLabels(id, makeVisible);
  eraseExtra(link,makeVisible);
  togglePulloutLink(pullout, makeVisible);
  savePulloutState(id, makeVisible);
  if (makeVisible) { focusPullout(pullout); }

  if (id == "indStyles") {
    pullout = document.getElementById("syncHeightPullout");
    if (pullout && makeVisible)
      { pullout.className = pullout.className.replace("pulloutHidden", "pulloutVisible"); }
    else if (pullout)
      { pullout.className = pullout.className.replace("pulloutVisible", "pulloutHidden"); }
  }

  link=null;
  pullout=null;
  for (i=0; i < pulloutItems.length; i++) {pulloutItems[i]=null;}

  return false;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function eraseExtra(link,makeVisible) {
  if (!link || !link.childNodes) { return; }
  for (var i=0; i < link.childNodes.length; i++) {
    if (link.childNodes[i].nodeName == "SPAN") {
      //link.removeChild(link.childNodes[i]);
      link.childNodes[i].className=(makeVisible)?"fieldHidden":"";//"hidden" doesn't override css?
      return;
    }
  }
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function toggleLabels(id, makeVisible) { //--called by togglePullout
  labelId = id.replace(/[\d_]+$/,"");
  //--check for other rows open/closed:
  if (typeof(trackLabels[labelId]) == "undefined")
    { trackLabels[labelId] = 0; }
  trackLabels[labelId] += (makeVisible) ? 1 : -1;
  if (!makeVisible && trackLabels[labelId] > 0) 
    { return; }
  var label = document.getElementById("labels-"+labelId);
  if (!label) { return false; }
  var labelItems = (label) ? getPulloutItems(label) : [];
  for (var i=0; i < labelItems.length; i++) {
    labelItems[i].className = labelItems[i].className.replace(
            (makeVisible) ? "pulloutHidden" : "pulloutVisible",
            (makeVisible) ? "pulloutVisible" : "pulloutHidden");
  }
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function togglePulloutLink(pullout, makeVisible) { //--called by togglePullout
  var hold = pullout.getElementsByTagName("a");
  var link = 0;
  
  for (var i=0; i < hold.length; i++) {
    if (hold[i].className && hold[i].className.indexOf("pulloutLink") > -1)
      { link = hold[i]; }
  }
  if (!link) { return; }
  var images = link.getElementsByTagName("img");
  
  if (images && images.length > 0) {
    images[0].src = (makeVisible) ? "http://stockcharts.com/images/button_less.gif": "http://stockcharts.com/images/button_more.gif";
    images[0].alt = (makeVisible) ? "[<]" : "[>]";
    images[0].title = (makeVisible) ? "Hide Advanced Options" : "Show Advanced Options";
  }
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function getPulloutItems(pullout) { //--called by togglePullout
  var hold = pullout.getElementsByTagName("span");
  var count = 0;
  var pulloutItems = [];
  
  for (var i=0; i < hold.length; i++) {
    if (hold[i].className && hold[i].className.indexOf("pullout") > -1)
      { pulloutItems[count++] = hold[i]; }
  }
  
  if (pulloutItems.length > 0) 
    { return pulloutItems; }
    
  hold = pullout.getElementsByTagName("th");
  count = 0;
  pulloutItems = [];
  for (var j=0; j < hold.length; j++) {
    if (hold[j].className && hold[j].className.indexOf("pullout") > -1)
      { pulloutItems[count++] = hold[j]; }
  }
  
  hold = pullout.getElementsByTagName("td");
  for (var k=0; k < hold.length; k++) {
    if (hold[k].className && hold[k].className.indexOf("pullout") > -1)
      { pulloutItems[count++] = hold[k]; }
  }

  return pulloutItems;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function savePulloutState(id, makeVisible) { //--called by togglePullout
  if (pageInitializing) { return; }

  var index = findInArray(pulloutsOpen, id);
  if (makeVisible && index == -1) 
    { pulloutsOpen[pulloutsOpen.length] = id; }
  else if (!makeVisible && index > -1)
    { pulloutsOpen = removeArrayIndex(pulloutsOpen, index); }

  storeCookieState();
}


//----------------------------------------------



//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function toggleSection(sectionIndex) { //--called by open/close section links
  if (!document.getElementById) 
    { return false; }

  var id = "section"+sectionIndex;
  var section = document.getElementById(id);
  
  if (typeof(section) == "undefined" || !section) 
    { return false; }
  var sectionShort = document.getElementById(id+"Short");
  var sectionLong = document.getElementById(id+"Long");
  var makeVisible = (sectionLong.className.indexOf("pulloutHidden")>-1);
  
  if (makeVisible) {
    sectionShort.className += " pulloutHidden";
    sectionLong.className = sectionLong.className.replace(/pulloutHidden/g, "");
    focusLink(sectionLong);
  } else {
    sectionShort.className = sectionShort.className.replace(/pulloutHidden/g,"");
    sectionLong.className += " pulloutHidden";
    focusLink(sectionShort);
  }
  saveSectionState(sectionIndex, makeVisible);

  return false;
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function focusLink(section) {
  if (pageInitializing) { return; }
   var links = section.getElementsByTagName("a");
   if (links && links.length > 0 && links[0].focus)
     { links[0].focus(); }
}


//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function saveSectionState(id, makeVisible) { //--called by toggleSection
  if (pageInitializing) { return; }
  
  var index=findInArray(sectionsOpen, id);
  if (makeVisible && index == -1) 
    { sectionsOpen[sectionsOpen.length] = id; }
  else if (!makeVisible && index > -1)
    { sectionsOpen = removeArrayIndex(sectionsOpen, index); }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function changeSelectFields(selectList) { //--hides/shows sections tied to one option
                    //--called by select fields onChange
  if (!document.getElementById)   { return false; }
//reset (to none) extra space settings for size or kagi|renko:
  if (selectList.id=="symStyle") { 
    kagiRenkoVisible=false;
    checkKagi(false);
  } else if (selectList.id=="chartSize") {
    customSizeVisible=false;
    checkKagi(false);
  } 
//universal show/hide for all dynamic sections:
  for (var i=0; i < selectList.options.length; i++) { 
    var show=selectList.options[i].value;
    var section = document.getElementById(selectList.name+"-"+show);    
    if (!section) { section = document.getElementById(selectList.name+"-"+show.toLowerCase()); }
    if (!section) { section = document.getElementById(selectList.name+"-"+selectList.options[i].text.toLowerCase()); }
    if (!section) { continue; }

    if (i == selectList.selectedIndex) {
      section.className = "selectVisible"; 
      if (selectList.id=="symStyle" && (/(Renko|Kagi)/).test(selectList.options[i].text)) { kagiRenkoVisible=true; } 
      if (selectList.id=="chartSize" && selectList.options[i].text=="Custom") { customSizeVisible=true; }
    } else {
      section.className = "selectHidden"; 
    }
  }
//set  extra space settings for size or kagi|renko:
  if (selectList.id=="symStyle" || selectList.id=="chartSize") { checkKagi(true); } 
//specific fix for range:
  if (/^(predef|userdef|fill):/.test(selectList.options[selectList.selectedIndex].value)) {
    var name=selectList.options[selectList.selectedIndex].value;
    name=name.substr(0,name.indexOf(":"));
    var range = document.getElementById(selectList.name+"-"+name);
    if (range) { range.className = "selectVisible"; }
  }
  return false;
}

function checkKagi(visible)
{
  //use this to only expand when both size and kagi|renko are used together:
  //if (visible && (customSizeVisible==false || kagiRenkoVisible==false)) { visible=false; }
  if (visible && (kagiRenkoVisible==false)) { visible=false; }
  var section=document.getElementById("sharpCharts2");
  if (!section) return;
  if (visible && !(/kagi\-offset/i).test(section.className)) {
    section.className+=" kagi-offset";
  }else if (!visible) {
    section.className=section.className.replace(/kagi\-offset/i,"");
  }
}

function checkChartSize(selectList) {
  if (!document.getElementById) { return false; }
  var size = selectList.options[selectList.selectedIndex].value;
  var field = document.getElementById("bar");
  if (size - 0 > 460) {
    if (!field) { return false; }
    else { field.selectedIndex = 4; }
  } else if (size - 0 === 0) {
	return false;
  } else {
    if (!field)  { return false; }
    else { field.selectedIndex = 2; }
  }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function hideFields(fields, list) {
  var className;
  if (fields.length > 0 && (fields[0].nodeName=="TH" || fields[0].nodeName=="TD"))
    { className = "cellHidden"; }
  else
    { className = "fieldHidden"; }
    
  for (var i=0; i < fields.length; i++) {
    if (!fields[i]) { continue; }
    if (findInArray(list,i) > -1) {
      if (fields[i].className.indexOf(className) == -1)
        { fields[i].className += " "+className; }
    } else 
      { fields[i].className = fields[i].className.replace(className,""); }
  }
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function hideRowFields(selectList) {  //--hides/shows fields/columns tied to one option
                    //--called by hideAllRowFields onload
                    //--called by setArgsI/setArgsIO/setArgsO (select onChange)
  if (!document.getElementById || !selectList) { return; }
  if (!currentFields) { setCurrentFields(selectList); }

  var prefix=(selectList.name).substr(0,3);
  var value = getSelectedValue(selectList).toLowerCase();
  if (prefix == "ind")
  {
    if (value.indexOf("timescale") > -1) {
      hideFields(currentFields, [1,3,4,5,6,7,8]);
      if (currentFields.length > 2)
        { restrictPositionSelect(currentFields[2], 1); }
    } else if (value.indexOf("price") > -1) 
      { hideFields(currentFields, []); }
    else if (getSelectedIndex(selectList) === 0 || value === "")
      { hideFields(currentFields, [3,4,5,6,7,8]); }
    else {
      hideFields(currentFields, [3]); //4=color
      if (currentFields.length > 2)
        { restrictPositionSelect(currentFields[2], 0); } //why?
    }
  }
  else
  {
    if (value.indexOf("volhoriz") > -1) 
      { hideFields(currentFields, [2,3]); }
    else if (getSelectedIndex(selectList) === 0 || value === "")
      { hideFields(currentFields, [2,3,4]); }
    else
      { hideFields(currentFields, []); }
  }
  if (!pageInitializing) { hideUnusedCols(prefix); }
}


//-----------------------------------------------------------
//   !!!!!!!!!!! This counts the reorder column, so this is one index
//   off from the other column operations !!!!!!!!!!!!!!!!!!
//-----------------------------------------------------------
function hideUnusedCols(prefix) {
  var fieldPrefix = (prefix == "ove") ? "overType_" : "indType_";
  var f = document.forms.workbench;
  var rowCount =  (prefix == "ove")?f.nOverlays.value:f.nIndicators.value;
  var allNone = true;
  for (var i=0;i<rowCount;i++)
  {
    if (!f[fieldPrefix+i]) { continue; }
    var index = getSelectedIndex(f[fieldPrefix+i]);
    if (index > 0 && f[fieldPrefix+i].options[index].value) {
      allNone = false;
      break;
    }
  }
  if (!document.getElementById) { return; }
  var table = document.getElementById((prefix == "ove") ? "overStyles" : "indStyles");
  var ths = table.getElementsByTagName("th");
  if (prefix=="ove")
    { hideFields(ths, (allNone) ? [3,4,5] : []); } //changed 1/27/2006, + 1 for reorder move
  else
    { hideFields(ths, (allNone) ? [4,5,6,7,8,9] : []); } //changed 1/27/2006,  + 1 for reorder move

  if (!allNone && prefix == "ind")
    { hidePriceCols(); }
}

//-----------------------------------------------------------
//   !!!!!!!!!!! This counts the reorder column, so this is one index
//   off from the other column operations !!!!!!!!!!!!!!!!!!
//-----------------------------------------------------------
function hidePriceCols() //--unique columns to Price, hide when no Price row found
             //--called by hideRowFields
{
  var f = document.forms.workbench;
  var nIndicators=f.nIndicators.value;
  var found=false;
  for (var i=0;i<nIndicators;i++)
  {
    if (f["indType_"+i] && f["indType_"+i].value.toLowerCase().indexOf("price")>-1)
    {
      found=true;
      break;
    }
  }
  if (!document.getElementById) { return; }
  var table=document.getElementById("indStyles");
  var ths=table.getElementsByTagName("th");  
  hideFields(ths,(found)?[]:[4]);  //5=color//changed 1/27/2006 , + 1 for reorder move
}

//-----------------------------------------------------------
// 
//-----------------------------------------------------------
function restrictPositionSelect(selectList,isDateTime) {  //--DateTime can't be behind
                            //--called by hideRowFields
  if (isDateTime)
    { selectList.options[1].className = "anyHidden"; }
  else
    { selectList.options[1].className = "anyVisible"; }
  if (isDateTime && 1 == selectList.selectedIndex) 
    { selectList.selectedIndex = 2; }
}


//***********************************************************
// KEYBOARD HANDLERS
//***********************************************************
var _KEYBOARD_HANDLERS_;

//-----------------------------------------------------------
// keyCheck() - Handle keypress events
//-----------------------------------------------------------
function keyCheck(evt) 
{
  var e = (evt) ? evt : window.event;
  if (!e || !document.getElementById) { return; }
  if (e.shiftKey || e.altKey || !e.ctrlKey) { return true; }
  var charKey=String.fromCharCode(e.keyCode).toLowerCase();
  if (!e.ctrlKey) { return true; }
  if (e.keyCode==17) { return true; } //--just ctrlKey, no other key pressed yet
  var keyNumber = parseInt(charKey,10);
  if (e.keyCode==192)
  {
    focusTicker();
    return false;
  }
  if (!isNaN(keyNumber) && keyNumber >= 0 && keyNumber <= 9) 
  {
    var shortcut = document.getElementById("shortcut" + keyNumber);
    if (shortcut && shortcut.onclick){
      shortcut.href="#key";
      return shortcut.onclick();
    }
    return false;
  }
  if (e.keyCode==188) //<
  {
    nextPrevFS('favorites',-1);
    return false;
  }
  if (e.keyCode==190) //>
  {
    nextPrevFS('favorites',+1);
    return false;
  }
  return true;
}

//-----------------------------------------------------------
// blockEnterEventsHandler() 
//-----------------------------------------------------------
function blockEnterEventsHandler(evt) 
{
  this.keyCode = evt.keyCode || evt.which;
  this.target = evt.target || evt.srcElement; 
  if (this.keyCode==13) //--cancel
  {
    if (evt.preventDefault) 
    {
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      evt.keyCode = 0;
      evt.returnValue = false;
    }
    var name=this.target.id;
    var xbutton=0;
    if (name=="favoritesNameNew1" || name=="favoritesListAddNew1")
      { xbutton=document.getElementById("favButton1"); }
    if (name=="favoritesNameNew2" || name=="favoritesListAddNew2")
      { xbutton=document.getElementById("favButton3"); }
    if (name=="favoritesNameEdit1" || name=="favoritesListEdit1")
      { xbutton=document.getElementById("favButton2"); }
    if (name=="favoritesNameEdit2" || name=="favoritesListEdit2")
      { xbutton=document.getElementById("favButton4"); }
    if (name=="settingNameNew" || name=="shortcutButtonNew") 
      { xbutton=document.getElementById("styleButton1"); }
    if (name=="settingReplace") 
      { xbutton=document.getElementById("styleButton2"); }
    if (name=="settingNameEdit" || name=="shortcutButtonEdit") 
      { xbutton=document.getElementById("styleButton3"); }
    if (xbutton) { xbutton.click(); }
    return false;
  }
}


//-----------------------------------------------------------
// addBlockEnterEvents() 
//-----------------------------------------------------------
function addBlockEnterEvents() 
{
  var items=[];
  items[0]=document.getElementById("favoritesNameNew1");
  items[1]=document.getElementById("favoritesListAddNew1");
  items[2]=document.getElementById("settingNameNew");
  items[3]=document.getElementById("shortcutButtonNew");
  items[4]=document.getElementById("settingReplace");
  items[5]=document.getElementById("settingNameEdit");
  items[6]=document.getElementById("shortcutButtonEdit");
  items[7]=document.getElementById("favoritesNameNew2");
  items[8]=document.getElementById("favoritesListAddNew2");
  items[9]=document.getElementById("favoritesNameEdit1");
  items[10]=document.getElementById("favoritesListEdit1");
  items[11]=document.getElementById("favoritesNameEdit2");
  items[12]=document.getElementById("favoritesListEdit2");

  for (var i=0;i<items.length;i++)
  {
    if (!items[i]) { continue; }
    if (items[i].addEventListener) {
      items[i].addEventListener("keypress", blockEnterEventsHandler, false);
    } else if (items[i].attachEvent) {
      var r = items[i].attachEvent("onkeypress", blockEnterEventsHandler);
    }
  }
}

//***********************************************************
// PAGE LOAD FUNCTIONS
//***********************************************************
var PAGE_LOAD_FUNCTIONS;

//-----------------------------------------------------------
// isLoggedIn() - TRUE if SCCExtraID cookie found
//-----------------------------------------------------------
function isLoggedIn() {
  return ((document.cookie+"").indexOf("SCCLogin=") > -1);
}


//-----------------------------------------------------------
// storeCookieState() -
//-----------------------------------------------------------
function storeCookieState() {  
  if (pageInitializing) { return; }
  if (!isLoggedIn()) { return; }
  var expires = new Date((new Date()).getFullYear()+5, 1, 1);
  //var expiresNow = new Date((new Date()).getFullYear()-1, 1, 1);
  var cookieExtra = ";expires="+expires.toGMTString()+";path=/;"; //expires=;domain=.stockcharts.com;
  var fixPullouts=[];
  var savePullouts="";
  for (var i in pulloutsOpen){
    if (!/^[\w\-]+$/i.test(""+pulloutsOpen[i]) || !pulloutsOpen[i]) continue;
    fixPullouts[fixPullouts.length]=pulloutsOpen[i];
    savePullouts+=pulloutsOpen[i]+",";
  }
  pulloutsOpen=fixPullouts;
  var pulloutsCookieText=(savePullouts)?savePullouts.substr(0,savePullouts.length-1)+cookieExtra:"";
  document.cookie = "sc2Pullouts="+pulloutsCookieText+cookieExtra;
  //alert (pulloutsCookieText+"\n\n-COOKIE = "+document.cookie);
}

//-----------------------------------------------------------
// loadCookieState() -
//   Loads dynamic state from cookie
//-----------------------------------------------------------
function loadCookieState() {  
  var f = document.forms.workbench;

  if (!isLoggedIn()) {
    return setDefaultPulloutState();
  }

  var scuiPullouts = "";
  var cookies = (document.cookie+"").match(/(sc2Pullouts=[^;]*)/g);
  if (cookies && cookies.length>0) {
    var pair = cookies[0].split("=");
    if (pair[0]=="sc2Pullouts") { pulloutsOpen=pair[1].split(","); }
  } 
  var fixPullouts=[];
  for (var i in pulloutsOpen){
    if (!/^[\w\-]+$/i.test(""+pulloutsOpen[i]) || !pulloutsOpen[i]) continue;
    fixPullouts[fixPullouts.length]=pulloutsOpen[i];
  }
  pulloutsOpen=fixPullouts;
}

//-----------------------------------------------------------
// focusTicker() -
//   Make sure the Ticker box has the keyboard focus 
//-----------------------------------------------------------
function focusTicker() {
  if (document.forms.workbench) {
    ticker = document.forms.workbench.symbol;
    if (ticker) {
      ticker.select();
      ticker.focus();
    }
  }
}

//-----------------------------------------------------------
// initIndicatorOverlayRows() -
//-----------------------------------------------------------
function initIndicatorOverlayRows() {
  setTotalRows("ind", 0); //--fixes javascript refresh bug
  setTotalRows("over", 0);
  if (typeof(createRows) != "undefined") 
    { createRows(); }
  //requireNewOverRow();
  //requireNewIndRow();
  hideUnusedCols("ove");
  hideUnusedCols("ind");
}

//-----------------------------------------------------------
// setDefaultPulloutState() -
//-----------------------------------------------------------
function setDefaultPulloutState()
{
  pulloutsOpen=[];   
  sectionsOpen=[2,3,4,6];
}

//-----------------------------------------------------------
// checkSelectState() -
//-----------------------------------------------------------
function checkSelectState() {
  if (!document.forms.workbench ) { return; }
  
  var f = document.forms.workbench;
  if (f.dataRange &&  f.dataRange.onchange) 
    { f.dataRange.onchange(); }
  if (f.chartSize &&  f.chartSize.onchange)
    { changeSelectFields(f.chartSize); }
  if (f.chartSize &&  f.symStyle.onchange)
    { changeSelectFields(f.symStyle); }
}

//-----------------------------------------------------------
// usePulloutState() - 
//-----------------------------------------------------------
function usePulloutState() { //only called on init
  for (var i=0; i < pulloutsOpen.length; i++) {
    if (pulloutsOpen[i]) { togglePullout(pulloutsOpen[i]); }//show used
  }
}

//-----------------------------------------------------------
// checkStartDate() - 
//-----------------------------------------------------------
function checkStartDate() {
  var f = document.forms.workbench;
  
  if (!f.start.value) { checkDate(); }
  if (!f.end.value) { f.end.value="(today)"; }
}


//-----------------------------------------------------------
// updateChart() - 
//-----------------------------------------------------------
function updateChart(timeout) 
{
  if (refreshCancelled || !document.getElementById) return;
  if (typeof(timeout)=="undefined") return;
  if (!window.onunload) window.onunload=sc2_onunload;

  if (!isMarketOpen())
  {
    var list=document.getElementById("autoUpdateOn");
    if (list) list.selectedIndex=0;
    return;
  }

  refreshCount+=timeout;
  if (refreshCount>refreshMax)
  {
    submitItSimplified();
  }

  var chart=document.getElementById("chartImg");
  var r = Math.round(Math.random()*10000);
  setTimeout(
      function(){
        var oldSrc=chart.src;
        var newSrc=oldSrc.replace(/\&m=o/g,"");
        newSrc=newSrc.replace(/\&r=.+/g,"");
        chart.src = newSrc+"&m=o&r=" + r;
        chart.onload=function(){updateChart(timeout);};
      },timeout);
}  

//-----------------------------------------------------------
// isMarketOpen() - 
//-----------------------------------------------------------
function isMarketOpen()
{
  var fudge=10*60000;//10 minutes?

  var f = document.forms.workbench;
  if (f.opentime.value.length<4) f.opentime.value="0"+f.opentime.value;
  if (f.closetime.value.length<4) f.closetime.value="0"+f.closetime.value;
  var t1=new Date();var t2=new Date();
  t1.setHours(f.opentime.value.substr(0,2)-0,f.opentime.value.substr(2)-0,0);
  t2.setHours(f.closetime.value.substr(0,2)-0,f.closetime.value.substr(2)-0,0);
  var time1=t1.getTime()-fudge;
  var time2=t2.getTime()+fudge;
  var ldtime=(new Date()).getTime();
//alert ("open: "+(new Date(time1))+"\nclosed: "+(new Date(time2))+"\nNOW: "+(new Date(ldtime+localTimeDiff)));
  return (ldtime+localTimeDiff>time1 && ldtime+localTimeDiff<time2);
}

//-----------------------------------------------------------
// checkTimeDiff() - 
//-----------------------------------------------------------
function checkTimeDiff()
{
  var f = document.forms.workbench;
  if (!f || !f.servertime) return;

  if (f.servertime.value.length<4) f.servertime.value="0"+f.servertime.value;
  var t1=new Date();
  t1.setHours(f.servertime.value.substr(0,2)-0,f.servertime.value.substr(2)-0,0);
  var servertime=t1.getTime();
  var ldtime=(new Date()).getTime();
  localTimeDiff=servertime-ldtime;
//alert (servertime+"="+ldtime+"+"+localTimeDiff);//debug
}



//-----------------------------------------------------------
// ieChartCopyFixInitialize() - 
// begins the event handler for fixing IE chart copying
//-----------------------------------------------------------
function ieChartCopyFixInitialize() 
{
  if (!document.all) return; //verify is IE
  var img = document.getElementById("chartImg"); //chart <img> tag
  img.onmousedown=ieChartCopyFix; //onmousedown = before all other mouse activities, including onclick.
}

//-----------------------------------------------------------
// ieChartCopyFix() - 
// re-enables right-click copy for images in IE
//-----------------------------------------------------------
function ieChartCopyFix(e) 
{
  if (event && event.srcElement && (event.button == 2 || event.button == 3)){ //is IE, and we know the srcElement
    try{document.execCommand("Unselect");}catch(e){}//remove select from ticker box
    if (event.srcElement.focus) event.srcElement.focus(); //remove focus from ticker box
  }
}

//-----------------------------------------------------------
// sc2_onload() -
//   Initialization tasks the run when the page is loading
//-----------------------------------------------------------
function sc2_onload() {
  if (!document.getElementById) { return; }
  
  if (document.forms.printform) {
    var f = document.forms.printform;
    if (!f || !f.chartSize || !f.chartSize.onchange) { return; }
    f.chartSize.onchange();
    return;
  }
  
  if (!document.forms.workbench) { return; }
  checkTimeDiff();
  focusTicker();
  ieChartCopyFixInitialize();
  pageInitializing = true;
  loadCookieState();
  checkSelectState();
  usePulloutState();
  initIndicatorOverlayRows();
  checkStartDate();
  pageInitializing = false;
  addBlockEnterEvents(); 

  //document.onkeydown = keyCheck;
  if (document.addEventListener) {
      document.addEventListener("keydown", keyCheck, false);
  } else if (document.attachEvent) {
      document.attachEvent("onkeydown", keyCheck);
  }

  lookForError();
}

//-----------------------------------------------------------
// sc2_onunload() -
//-----------------------------------------------------------
function sc2_onunload()
{
  refreshCancelled=true;
}


//-----------------------------------------------------------
// AJAX Error stuff -
//-----------------------------------------------------------
function lookForError()
{
  try{
    if (!document.getElementById) return;
    var rx=new RegExp('([^\/]\/)[^\/].*$');//NN8 needs this step.
    var parentdir=location.href.replace(rx,"$1");
    var url=parentdir+"error_sc2.txt";    var ajax = new sack(url);
    if(ajax.failed){ return; }
    ajax.onCompletion = function(){printError(this.response);}; 
    ajax.runAJAX();
  }catch(e){}//discard
}

function printError(data)
{
  try{
    data=data.replace(/(^\s+|\s+$)/,"");
    if (!data  || /Page Not Found/i.test(data)) return;
    var base=document.getElementById("sharpCharts2");
    if (!base) return;
    var hold=document.getElementById("siteError");
    if (!hold) 
    {
      hold=document.createElement("div");
      hold.id="siteError";
      hold.innerHTML=data;
      base.insertBefore(hold,base.firstChild);
    }
    else {
      hold.innerHTML=data;
    }
  }catch(e){}//discard
}


/* Simple AJAX Code-Kit (SACK) 2005 Gregory Wild-Smith www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */
/* simplified for use by StockCharts.com */
function sack(file){
  this.requestFile = file;
  this.onCompletion = function() { };
  this.failed=false;
  this.response="";
  this.createAJAX = function() {
    try {
      this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (err) {
        this.xmlhttp = null;
      }
    }
    if(!this.xmlhttp && typeof XMLHttpRequest != "undefined"){
      this.xmlhttp = new XMLHttpRequest();
    }
    if (!this.xmlhttp){
      this.failed = true; 
    }
  };
  this.runAJAX = function(){
    if (this.failed && this.AjaxFailedAlert) return;
    if (this.xmlhttp)
    {
       var self = this;
       this.xmlhttp.open("GET", this.requestFile, true);
       this.xmlhttp.onreadystatechange = function() {
          if (self.xmlhttp.readyState == 4)
          {
              self.response = self.xmlhttp.responseText;
              self.onCompletion();
          }
       };
       this.xmlhttp.send("");
    }
    this.response="";
  };
this.createAJAX();
}

//-----------------------------------------------------------
// Global Initialization Code
//-----------------------------------------------------------