/*
 * This file contains functions and variables global to the advanced 
 * graph page for configuration.
 * 
 * $Id: chart_config_Advanced.js,v 1.3 2010/07/05 13:18:27 obo Exp $
 */  

/*
 * This function fills the input mask with the custom config it gets in arguments
 * 
 * It does NOT change anything to the graph, only the input mask. No onChange are 
 * triggered
 * 
 */
function chartFillFormFromCustomConfig(config) {
  chartFillLineType(config);
  chartFillCrosshairType(config);
  chartFillEvents(config);
  chartFillVolume(config);
  chartFillCompareWithSecurity(config);
  chartFillCompareWithIndex(config);
  chartFillTechnicalIndicator(config);
}

function chartFillLineType(config){
  var widget = dijit.byId("fs_lineType");
  var configValue = config.renderStyle;
  
  chartFillDropdownWithoutOnChange(widget, configValue);
}

function chartFillCrosshairType(config) {
  var widget = dijit.byId("fs_crosshair");
  var configValue = config.crosshairStyle;
  
  chartFillDropdownWithoutOnChange(widget, configValue);
}
function chartFillEvents(config){
  // set all to false by default
  chartSetCheckboxWithoutOnChange(dijit.byId("events_divs_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_news_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_generalMeetings_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_splits_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_managementTransaction_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_amalgamations_cb"), false);
  chartSetCheckboxWithoutOnChange(dijit.byId("events_ccychanges_cb"), false);
  
  if (config && config.events) {
    if (typeof config.events == "string") { // backwards compatible
      var widget = dijit.byId("events_"+eventType+"_cb");
      chartSetCheckboxWithoutOnChange(widget, true);
    } else if (typeof config.events == "object") {
      for (i in config.events) {
        var eventType = config.events[i];
        var widget = dijit.byId("events_"+eventType+"_cb");
        chartSetCheckboxWithoutOnChange(widget, true);
      }
    }
  }
}

function chartFillVolume(config){
  var widget = dijit.byId("fs_volume");
  var configValue = config.volume;
  
  chartFillDropdownWithoutOnChange(widget, configValue);
}

function chartFillCompareWithSecurity(config){
  var widget = dijit.byId("chart_ivs");
  chartFillCompareWithIdx12("idx2", widget, config)
}

function chartFillCompareWithIndex(config){
  var widget = dijit.byId("fs_chart_index");
  chartFillCompareWithIdx12("idx1", widget, config)
}

function chartFillCompareWithIdx12(idxType, widget, config){
  var configValue = config[idxType];
  if (configValue == "" || configValue) {
    var disp = "";
    if (configValue == "") {
      disp = "none";
    }
    chartFillDropdownWithoutOnChange(widget, configValue);
  
    var node = dojo.byId("img_"+idxType);
    if (node) {
      dojo.style(node, "display", disp);
      node.title = widget.getDisplayedValue(); // get SMI instead of CH....
    }
    node = dojo.byId("legend_"+idxType);
    if (node) {
      dojo.style(node, "display", disp);
      node.innerHTML = widget.getDisplayedValue(); // get SMI instead of CH....
    }
    node = dojo.byId("trash_"+idxType);
    if (node) dojo.style(node, "display", disp);
  }
}

function chartFillTechnicalIndicator(config){
  
  for (var i=1; i<=10; i++) {
    var techId = config["ti"+i];
    if (techId!="" && !techId) continue;
    if (techId.indexOf("SMA") != -1) {
      chartFillTechnicalIndicatorSMA(techId, i);
    } else if (techId.indexOf("EMA") != -1) {
      chartFillTechnicalIndicatorEMA(techId, i);
    } else if (techId.indexOf("BB") != -1) {
      chartFillTechnicalIndicatorBB(techId);
    } else if (techId.indexOf("RSI") != -1) {
      chartFillTechnicalIndicatorRSI(techId);
    } else if (techId.indexOf("MOM") != -1) {
      chartFillTechnicalIndicatorMOM(techId);
    } else if (techId == "") {
      // Set the dropdown to nothing
      var widget = dijit.byId("fs_techId");
      widget.setValue('');
      removeTechnicalIndicatorsHTML();
    }
  }
}
function chartFillTechnicalIndicatorSMA(techId, i) {
  chartFillTechnicalIndicatorSMA_EMA(techId, i, "Simple Moving Average");
}
function chartFillTechnicalIndicatorEMA(techId, i) {
  chartFillTechnicalIndicatorSMA_EMA(techId, i, "Exponential Moving Average");
}
function chartFillTechnicalIndicatorSMA_EMA(techId, i, indicatorNiceName) {
  // Set the dropdown
  var SMAEMALabel = getEMASMAsParamsLabel(defaultConfig.language)[i-1];
    
  var widget = dijit.byId("fs_techId");
  var indicatorType = techId.substring(0,3);
  chartFillDropdownWithoutOnChange(widget, indicatorType);
  
  var period = techId.substring(3);
  dijit.byId(indicatorType+"Period"+i).setValue(period);
  
  var icons = [];
  var legends = [];
  while (i>1) {
    icons.push(null);
    legends.push(null);
    i--;
  }
  icons.push(SMAEMALabel + " : "+period);
  legends.push(indicatorType);
  prepareTechnicalIndicatorsHTML(icons, null, legends);
}
function chartFillTechnicalIndicatorBB(techId) {
  // Set the dropdown to momentum / RSI 
  var widget = dijit.byId("fs_techId");
  chartFillDropdownWithoutOnChange(widget, "BB");
  
  var periodAndSigmaFactor = techId.split("\t");
  var period = periodAndSigmaFactor[0].substring(2);
  var sigmaFactor = periodAndSigmaFactor[1];
  
  dijit.byId('BBPeriod').setValue(period);
  dijit.byId('BBSigmaFactor').setValue(sigmaFactor);
  
  var bbLabel = getBBParamsLabel(defaultConfig.language);

  prepareTechnicalIndicatorsHTML([bbLabel[0] + " : "+period, null, bbLabel[1] + " : "+sigmaFactor], null, ["BB", null, null]);
  
}
function chartFillTechnicalIndicatorRSI(techId) {
  chartFillTechnicalIndicatorMOM_RSI(techId, "Relative strength index");
}
function chartFillTechnicalIndicatorMOM(techId) {
  chartFillTechnicalIndicatorMOM_RSI(techId, "Momentum");
}
function chartFillTechnicalIndicatorMOM_RSI(techId, indicatorNiceName) {
  // Set the dropdown to momentum / RSI 
  var widget = dijit.byId("fs_techId");
  var indicatorType = techId.substring(0,3);
  chartFillDropdownWithoutOnChange(widget, indicatorType);
        
  // Set the hidden dialog and technical indicator label
  var period = techId.substring(3);
  dijit.byId(indicatorType+"Period").setValue(period);
  if (period != null && period.length > 0) {
     var MOMRSILABEL = getMOMRSIParamsLabel(defaultConfig.language);
     prepareTechnicalIndicatorsHTML([MOMRSILABEL + " : "+period], indicatorNiceName+" ( "+period+" )");
  }
  
}


function chartFillDropdownWithoutOnChange(widget, configValue) {
  if ((configValue != "" && !configValue) || !widget) return; // Nothing specific to do
  
  // Save original onChange function
  var oldOnChangeFunction = widget.onChange;
  
  // Make it do nothing when we change the value
  widget.onChange = function() {};
  
  // Set the new value
  widget.setValue(configValue);
  
  // replace old onChange function
  widget.onChange = oldOnChangeFunction;
}

function chartSetCheckboxWithoutOnChange(widget, checked) {
  if (!widget) return; // nothing specific to do
  
  // Save original onChange function
  var oldOnChangeFunction = widget.onChange;
  
  // Make it do nothing when we change the value
  widget.onChange = function() {};

  // Set the new value
  widget.setChecked(checked);
  
  // replace old onChange function
  widget.onChange = oldOnChangeFunction;
}

/**
 * This function changes the chart depending on the custom config it gets in arguments.
 * It then loads/calculates the data needed and redraws the chart
 * 
 */
function chartChangeGraphFromCustomConfig(chart, config, skipRedraw) {
  chartChangeGraphLineType(chart, config);
  chartChangeGraphCrosshairStyle(chart, config);
  chartChangeGraphEvents(chart, config);
  chartChangeGraphVolume(chart, config);
  chartChangeGraphCompareWithSecurity(chart, config);
  chartChangeGraphCompareWithIndex(chart, config);
  chartChangeGraphTechnicalIndicators(chart, config);
  
  if (!skipRedraw) {
    // Load everything and redraw the chart
    // Set the displayed values and redraw (changeGraph calls draw)
    if (config.domain) {
      changeGraph(config.domain);
    } else if ("" != selectedTimeRange) {
      changeGraph(selectedTimeRange);
    } else {
      changeCustomPeriod(
        new Date(chart.values_domain.id.vals[0].d),
        new Date(chart.values_domain.id.vals[chart.values_domain.id.vals.length-1].d)
      );
    }
  }
}

function chartChangeGraphLineType(chart, config) {
  if (config.renderStyle) {
    chart.chartDrawer.renderStyle = config.renderStyle;
  }
};

function chartChangeGraphCrosshairStyle(chart, config) {
  if (config.crosshairStyle) {
    setCrosshairStyle(config.crosshairStyle, chart);
  }
}
function chartChangeGraphEvents(chart, config) {
  chart.showedEvents = {}; // remove all showed events
  if (config && config.events) {
    if (typeof config.events == "string") { // backwards compatible
      chart.showedEvents[config.events] = defaultConfig.language; // save language for download
    } else if (typeof config.events == "object") {
      for (i in config.events) {
        var eventType = config.events[i];
        chart.showedEvents[eventType] = defaultConfig.language; // save language for download
      }
    }
    chart.chartDrawer.showEvents();
  } else {
    chart.chartDrawer.hideEvents();
  }
};

function chartChangeGraphVolume(chart, config) {
  if (config.volume && config.volume != "false") {
    chart.chartDrawer.showVolume();
  } else {
    chart.chartDrawer.hideVolume();
  }
};

function chartChangeGraphCompareWithSecurity(chart, config) {
  if (config.idx2) {
    // compare with security
    chart.showedLines["idx2"] = config.idx2;
  } else {
    chart.showedLines["idx2"] = null;
  }
};

function chartChangeGraphCompareWithIndex(chart, config) {
  if (config.idx1) {
    // compare with index
    chart.showedLines["idx1"] = config.idx1;
  } else {
    chart.showedLines["idx1"] = null;
  }
};

function chartChangeGraphTechnicalIndicators(chart, config) {
  
  for (var i=1; i<=10; i++) {
    chart.showedLines["ti"+i] = null;
  }
  chart.chartDrawer._addonDrawer.hideTechnicalIndicator();

  for (var i=1; i<=10; i++) {
    if (config["ti"+i]) {
      var ti = config["ti"+i];
      if (ti.indexOf("BB") != -1) {
        chart.showedLines["ti3"] = "fake";
        chart.showedLines["ti4"] = "fake";
      }
      chart.showedLines["ti"+i] = config["ti"+i];
    }
  }
};

function chartResetConfig(config) {
  chartFillFormFromCustomConfig(config);
  chartChangeGraphFromCustomConfig(advancedChart, config);
}

function chartCreateConfigFromForm() {
  var config = {};
  
  var lineType = dijit.byId("fs_lineType").getValue();
  if (lineType) config.renderStyle = lineType;
  
  var crosshairStyle = dijit.byId("fs_crosshair").getValue();
  if (crosshairStyle) config.crosshairStyle = crosshairStyle;
  
  var domain = selectedTimeRange;
  if (domain) config.domain = domain;
  
  var events = [];
  var eventsDiv = dijit.byId("events_divs_cb");
  if (eventsDiv != null && eventsDiv.checked) events.push("divs");
  
  var eventsNews = dijit.byId("events_news_cb");
  if (eventsNews!= null && eventsNews.checked) events.push("news");
  
  var eventsGM = dijit.byId("events_generalMeetings_cb");
  if (eventsGM != null && eventsGM.checked) events.push("generalMeetings");
  
  var eventsSplits = dijit.byId("events_splits_cb");
  if (eventsSplits != null && eventsSplits.checked) events.push("splits");

  var eventsMT = dijit.byId("events_managementTransaction_cb");  
  if (eventsMT != null &&  eventsMT.checked) events.push("managementTransaction");
  
  var eventsAM = dijit.byId("events_amalgamations_cb");  
  if (eventsAM != null &&  eventsAM.checked) events.push("amalgamations");

  var eventsCC = dijit.byId("events_ccychanges_cb");  
  if (eventsCC != null &&  eventsCC.checked) events.push("ccychanges");

  if (events.length > 0) config.events = events;

  var widget = dijit.byId("fs_volume");
  if (widget) {
    var volume = dijit.byId("fs_volume").getValue();
    if (volume) config.volume = volume;
  }

  var idx2 = dijit.byId("chart_ivs").getValue();
  if (idx2) config.idx2 = idx2;

  var idx1 = dijit.byId("fs_chart_index").getValue();
  if (idx1) config.idx1 = idx1;

  var techId = dijit.byId("fs_techId").getValue();
  if (techId) {
    if (techId.indexOf("SMA") != -1) {
      for (var i=1; i<=3; i++) {
        var period = dijit.byId("SMAPeriod"+i).getValue();
        if (period) {
          config["ti"+i] = "SMA"+period;
        }
      }
    } else if (techId.indexOf("EMA") != -1) {
      for (var i=1; i<=3; i++) {
        var period = dijit.byId("EMAPeriod"+i).getValue();
        if (period) {
          config["ti"+i] = "EMA"+period;
        }
      }
    } else if (techId.indexOf("BB") != -1) {
      var period = dijit.byId('BBPeriod').getValue();
      var sigmaFactor = dijit.byId('BBSigmaFactor').getValue();
      if (period && sigmaFactor) {
        config.ti1 = "BB"+period+"\t"+sigmaFactor;
        config.ti3 = "fake";
        config.ti4 = "fake";
      }
    } else if (techId.indexOf("RSI") != -1) {
      var period = dijit.byId("RSIPeriod").getValue();
      if (period) {
        config.ti1 = "RSI"+period;
      }
    } else if (techId.indexOf("MOM") != -1) {
      var period = dijit.byId("MOMPeriod").getValue();
      if (period) {
        config.ti1 = "MOM"+period;
      }
    }
  }
  
  return config;
}

function chartSaveCustomConfig() {
        
  var config = chartCreateConfigFromForm();
  
  // Send an ajax response to save the config and display a dialog saying it's ok
  dojo.xhrGet( {
      url          : siteChartConfig.CHART_CONFIG_URL + dojo.toJson(config),
      handleAs     : "json",
      timeout      : 20000, // ms
      preventCache : true,

      load: function(response, ioArgs) {
              if (response.errorCode == 0) {
                dojo.style("chartConfigSavedOK", "display", "");
                dojo.style("chartConfigSavedKO", "display", "none");
              } else {
                dojo.style("chartConfigSavedOK", "display", "none");
                dojo.style("chartConfigSavedKO", "display", "");
              }
              dijit.byId("chartConfigurationSavedDialog").show();
      },

      error: function(response, ioArgs) {
              dojo.style("chartConfigSavedOK", "display", "none");
              dojo.style("chartConfigSavedKO", "display", "");
              dijit.byId("chartConfigurationSavedDialog").show();
              return response;
      }       // end error

  } );        // end dojo.xhrGet
  
}
