/**
 * This file contains the javascript used by the market overview page of the marketpulse portal
 */


/************************************************
 * Functions and variables for changing graphs  *
 ************************************************/
function reloadTopBottom(index) {

  var pane = dijit.byId("topBottomPane_indexBasket");
  if (pane) {
    pane.setHref("overview_topBottom_"+topBottomLang+".html?basket="+symbols[index]+"&label="+labels[index]);
  }
  
}


/************************************************
 * Functions and variables for TOP BOTTOM movie *
 ************************************************/
 

//topBottomQP = null;  // define a global quoteplayer for the topbottom table
//movie = null;        // define a global movie for the topbottom table
//topBottomDataOfYesterday = false; // define a global boolean to know if the data is from today or not

function initTopBottom() {
  var key = "indexBasket";
  initTopBottomPaneToReload(key);
  
  key = "etfP";
  initTopBottomPaneToReload(key);
  
  key = "etfT";
  initTopBottomPaneToReload(key);
  
  key = "bondT";
  initTopBottomPaneToReload(key);
}
dojo.addOnLoad(initTopBottom);

function initTopBottomPaneToReload(key) {
  var pane = dijit.byId("topBottomPane_"+key);
  if (pane) { // If this overview has this top/bottom pane, tell it to execute js inside
    dojo.connect(pane, "onLoad", pane, 
      function () {
        // execute the javascript inside the pane
        var pane = dijit.byId("topBottomPane_"+key).domNode;
        dojo.query("script", pane).forEach(
          function(scriptTag) {
            // We can't use dojo.eval(scriptTag.innerHTML), it does not always work
            var appendNode = dojo.doc.body;
            var n = appendNode.ownerDocument.createElement('script');
            n.type = "text/javascript";
            appendNode.appendChild(n);
            n.text = scriptTag.innerHTML;
          }
        );
      }
    );
  }
}      

/**
 * Function called every update event to update the top/bottom table
 */
function topBottomUpdateCell_indexBasket(updateEvent) {
  topBottomUpdateCell("indexBasket", updateEvent);
}
function topBottomUpdateCell_etfP(updateEvent) {
  topBottomUpdateCell("etfP", updateEvent);
}
function topBottomUpdateCell_etfT(updateEvent) {
  topBottomUpdateCell("etfT", updateEvent);
}
function topBottomUpdateCell_bondT(updateEvent) {
  topBottomUpdateCell("bondT", updateEvent);
}

function topBottomUpdateCell_flake(key,updateEvent, refreshMe) {
    if (dojo.eval("topBottomDataOfYesterday_"+key)) {
    
     //if (updateEvent.columnid == "LastTime") {
     //   lastTime = updateEvent.newValue;
     //}
    
    if (updateEvent.columnid == "LastDate") {
       // reload pane (new values should be showed)
       window["topBottomDataOfYesterday_"+key] = false;
       //var date = updateEvent.newValue.substring(0, 6) + updateEvent.newValue.substring(8);
      // var cellDate = dojo.byId("topBottomHeaderDate_"+key);
       //cellDate.innerHTML = date;
       //var cellSep = dojo.byId("topBottomHeaderSeparator_"+key);
       //cellSep.innerHTML = "&#160;/&#160";
       //var cellTime = dojo.byId("topBottomHeaderTime_"+key);
       //if ( lastTime) cellTime.innerHTML = lastTime.substring(0, lastTime.lastIndexOf(":"));
       //        
       setTimeout(dojo.hitch(this,function() { 
                              refreshMe.apply();;
                        }),1000);

    }
    //return; 
  }
  else{
        topBottomUpdateCell(key, updateEvent);
  }
}

function topBottomUpdateCell(key, updateEvent) {
  var updateCol = updateEvent.columnid;
  
  if (dojo.eval("topBottomDataOfYesterday_"+key)) {
    // The values displayed are yesterdays values... only look out for a LastDate update and refresh the pane
    
    if (updateCol == "LastDate") {
       // reload pane (new values should be showed)
       dijit.byId("topBottomPane_"+key).refresh();
    }
    return; // do not do the other updates
  }
  
  if (updateCol == "MarketDate") {
    var date = updateEvent.newValue.substring(0, 6) + updateEvent.newValue.substring(8);
    var cell = dojo.byId("topBottomHeaderDate_"+key);
    if (cell) { // we might be changing top/bottom index but the movie is still playing for some seconds
      cell.innerHTML = date;
    }
  } else if (updateCol == "MarketTime") {
    var time = updateEvent.newValue.substring(0, updateEvent.newValue.lastIndexOf(":"));
    var cell = dojo.byId("topBottomHeaderTime_"+key);
    if (cell) { // we might be changing top/bottom index but the movie is still playing for some seconds
      cell.innerHTML = time;
    }
  } else {
    var cell = dojo.byId("topBottom_"+key+"_"+updateEvent.rowid+"_"+updateCol);
    if (cell) {
      if (updateCol == dojo.eval("topBottomFqsAttributeForLink_"+key)) {  
    	var values = updateEvent.newValue.split("\t");
        var attribute = values[0];
        var secId = values[1].replace(/^\s+|\s+$/g,"");
        var link = dojo.eval("topBottomLink_"+key);
        if(link == "" && values.length > 2){
        	//use portal segment from update event new value as link stem 
        	link = "/" + values[2] + "/";
        }
        cell.innerHTML = "<a href=\""+link+"security_info_"+topBottomLang+".html?id="+secId+"\">"+attribute+"</a>";
      } else if (updateCol == "TotalTurnoverCHF") {
        // for TotalTurnoverCHF, transform it into an integer
        
        var newVal = null;
        if (updateEvent.newValue.indexOf("'") != -1) {
          newVal = updateEvent.newValue; // already nicely formatted
        } else {
          newVal = overviewGetNiceNumber(parseFloat(updateEvent.newValue), 0);
        }
        cell.innerHTML = newVal;
      } else {
        cell.innerHTML = updateEvent.newValue;
      }
      if (updateCol == "ClosingDelta") {
        var delta = updateEvent.newValue.replace("%", "");
        var color = "black";
        if (delta > 0) {
          color = "green";
        } else if (delta < 0) {
          color = "red";
        }
        dojo.style(cell, "color", color);
      }
    }
  }
}

function updateIndexCells(updateEvent) {
    var updateCol = updateEvent.columnid;
    var updateRow = updateEvent.rowid;

    if (updateEvent.newValue.replace("\u00a0", "") != "") {

        var cell = dojo.byId("idx_" + updateRow + "_" + updateCol);

        if (cell) {
    
            cell.innerHTML = updateEvent.newValue;

            if (updateCol == "ClosingDelta" || updateCol == "LastOrderbookMidDelta" ) {
                var delta = updateEvent.newValue.replace("%", "");
                var color = "black";
                if (delta > 0) {
                    color = "green";
                } else if (delta < 0) {
                    color = "red";
                }
                dojo.style(cell, "color", color);
            }
        }
    }
}

function overviewGetNiceNumber(number, fixed) {
      var numberFormatted = null;
      var index = null;
      if (fixed!=null && fixed >= 0) {
        numberFormatted = number.toFixed(fixed);
      } else {
        numberFormatted = number + "";
      }
      index = numberFormatted.indexOf(".");
      if (index == -1) index = numberFormatted.length;
      
      // format this number to ###'###'##0.00 (dojo uses the locale to set the grouping seperator!)
      
      while (index > 3) {
        index -= 3;
        numberFormatted = numberFormatted.substring(0, index) + "'" + 
                            numberFormatted.substring(index);
      }
      
      return numberFormatted;
}
