/*
 * Functions to handle the movie animation features on this website
 * 
 * $Id: movieAnimation.js,v 1.3 2010/08/12 11:38:59 obo Exp $
 */

/*
 * Global colors and images
 */ 
var BG_UP = "#00FF00";
var BG_DOWN = "#FF0000";
var BG_NO_CHANGE = "#FFFFFF";
var TEXT_UP = "#008000";
var TEXT_DOWN = "#FF0000";
var TEXT_NO_CHANGE = "#000000";
var ARROW_CHANGE_UP = '/resources/images/dojo/arrow_up_black.gif';
var ARROW_CHANGE_DOWN = '/resources/images/dojo/arrow_down_black.gif';
var ARROW_NO_CHANGE = '/resources/images/trans.png';

/*
 * Execute the movie-player inside the given index table on the homepage
 */
function initIndexMovie(tableId) {
  var pane = dijit.byId(tableId).domNode;
  dojo.query("script", pane).forEach(
    function(scriptTag) {
      var appendNode = dojo.doc.body;
      var n = appendNode.ownerDocument.createElement('script');
      n.type = "text/javascript";
      appendNode.appendChild(n);
      n.text = scriptTag.innerHTML;
    }
  );
}

/*
 * Set the text color for a percentage or absolute delta value in the given cell
 */
function setTextColor(cell) {
  var deltaValue = cell.lastChild.data;
  deltaValue = parseFloat(deltaValue);
  if (deltaValue < 0)
    dojo.style(cell, "color", TEXT_DOWN);
  else if (deltaValue > 0)
    dojo.style(cell, "color", TEXT_UP);
}

/*
 * Get the text color depending on the supplied percentage or absolute delta value.
 */
function getTextColor(deltaValue) {
  deltaValue = parseFloat(deltaValue);
  if (deltaValue < 0)
    return TEXT_DOWN;
  else if (deltaValue > 0)
    return TEXT_UP;
  return TEXT_NO_CHANGE;
}

/*
 * Highlight and fade-out cell in appropriate color
 */
function flashCellBG(cell, delta) {
  if (cell != null) {
     var imgInTd = cell.getElementsByTagName('img')[0];
     if (imgInTd) {
       var color = BG_NO_CHANGE;
       imgInTd.src = ARROW_NO_CHANGE;
       if (delta > 0) {
         color = BG_UP;
         imgInTd.src = ARROW_CHANGE_UP; 
       }
       else if (delta < 0) {
         color = BG_DOWN;
         imgInTd.src = ARROW_CHANGE_DOWN; 
       }
      highlightIndexCell(cell, color, 1500);
      opacityFading(imgInTd, 1500);
     }
  }
}    

/*
 * Highlight the given node (eg. set cell background color)
 */
function highlightIndexCell(nodeName, color, duration) {
  var anim = common.fx.highlight({node:nodeName, color:color, duration:duration});
  anim.play();
};

/*
 * Fade out the given node (eg. up-down arrow image)
 */
function opacityFading(nodeName, duration) {
  var anim = common.fx.opacityFading({node:nodeName, duration:duration});
  anim.play();
};

/*
 * Switch the index displayed in the chart on the homepage
 */
function switchIndex(setName, key, easyName) {

  //Declare the list of indices available in the chart 
  var indexList = ["SX5E", "SX5P", "DK5F", "EUE15P", "EEBCP", "SXB5P", "SXYBP"];

  // Get the list of indices in this set
  var index = 0;
  for (var i=0; i < indexList.length; i++) {

    // For the required index, switch on visibility and load it
    if (indexList[i] == key) {
      index = i;
      dojo.style(setName + "Box" + key, "visibility", "");

      // Load values if not already done
      if (!dojo.eval("smallchart" + indexList[i] + ".values_domain.id")) {
        dojo.eval("smallchart" + indexList[i] + ".getAjaxValues(\"id\", smallchart" + indexList[i] + ".id)");
      }
    }
    else {

      // For the others, switch off visibilty
      dojo.style(setName + "Box" + indexList[i], "visibility", "hidden");
    }
  }
  
  // Switch the chart title
  dojo.byId("chartTitle").innerHTML = easyName;
  return index;
}

/*
 * Cell updater for the performance table at the bottom of the chart detail page.
 */
function sip_cp_updateCell(updateEvent) {
  var updateCol = updateEvent.columnid;
  if (updateEvent.newValue.replace(/^\s+|\s+$/g, '').replace(/\u00A0/g, "")  == "")
    return; // movie problem, updates shoud not be empty
  var cell = dojo.byId("SIP_CP_"+updateCol);
  var data_change_value = dojo.byId("data_change_value");
  var updateSelectedPeriodColumn = false;
  if (cell) {          
    var oldValue = cell.innerHTML;     
    cell.innerHTML = updateEvent.newValue;
    if (updateCol == "MonthAgoDelta" ||
        updateCol == "MonthSixAgoDelta" ||
        updateCol == "YearAgoDelta" ||
        updateCol == "YearThreeAgoDelta") {
      dojo.style(dojo.byId("SIP_CP_" + updateCol + "Special"),
          "color", getTextColor(updateEvent.newValue));
    }
    
    if ( updateSelectedPeriodPriceEnabled ) {
    
      if ( updateCol == "MonthAgoDelta" && selectedTimeRange == "1m" ) {
          data_change_value.innerHTML = updateEvent.newValue;
          updateSelectedPeriodColumn = true;
      }
    
      if ( updateCol == "MonthSixAgoDelta" && selectedTimeRange == "6m" ) {
          data_change_value.innerHTML = updateEvent.newValue;
          updateSelectedPeriodColumn = true;
      }
    
      if ( updateCol == "YearAgoDelta" && selectedTimeRange == "1y" ) {
          data_change_value.innerHTML = updateEvent.newValue;
          updateSelectedPeriodColumn = true;
      }
    
      if ( updateCol == "YearThreeAgoDelta" && selectedTimeRange == "3y" ) {
          data_change_value.innerHTML = updateEvent.newValue;
          updateSelectedPeriodColumn = true;
      }
      
    }
    
    // Flash cell background according to new value
    if (oldValue != updateEvent.newValue) {
      flashCellBG(dojo.byId("SIP_CP_" + updateCol + "Special"),
          updateEvent.newValue.replace('%','')-oldValue.replace('%',''));
      if ( updateSelectedPeriodColumn )
        flashCellBG(dojo.byId("data_change_cell"),
            updateEvent.newValue.replace('%','')-oldValue.replace('%',''));
    }
  }              
}
/*
 * Cell updater for the price table at the RHS of the overview page.
 */
function sip_ov_updateCell(updateEvent) {
  var updateCol = updateEvent.columnid;
  if (updateEvent.newValue.replace(/^\s+|\s+$/g, '').replace(/\u00A0/g, "")  == "")
    return; // movie problem, updates shoud not be empty

  var cell = dojo.byId("SIP_OV_" + updateCol);
  if (cell) {
    if (updateCol == "DailyHighTime" || updateCol == "DailyLowTime")
      updateEvent.newValue = updateEvent.newValue.substring(0,5); // remove seconds
    
    // Update the cell value
    cell.innerHTML = updateEvent.newValue;
    
    // Change or set colors etc.
    if (updateCol == "ClosingPrice") {
      // Special case, update another cell
      var absChange = updateEvent.newValue - SIP_OV_SavedPreviousClosingPrice;
      absChange = absChange.toFixed(2); 
      dojo.byId("SIP_OV_ClosingPriceDiff").innerHTML = absChange;
      
      // 52 weeks change
      changeDeltaValue("SIP_OV_HistoricPercentSpecial",
          window.SIP_OV_SavedHistoricPrice, updateEvent.newValue);
      
      // Prev year change
      changeDeltaValue("SIP_OV_PrevYearPercentSpecial",
          window.SIP_OV_SavedPrevYearPrice, updateEvent.newValue);
      
      // 1 week difference
      changeDeltaValue("SIP_OV_OneWeekPercentSpecial",
          window.SIP_OV_SavedOneWeekPrice, updateEvent.newValue);
    } else if (updateCol == "ClosingDelta") {
      dojo.style(dojo.byId("SIP_OV_ClosingPriceSpecial"), "color", getTextColor(updateEvent.newValue));
    }
  }
        
}
/*
 * Changes the color and value of a delta when we have to calculate the delta from the
 * latest closing price and don't have it directly.
 */
function changeDeltaValue(cellId, prevPrice, currPrice) {
  var cell = dojo.byId(cellId);
  if (cell && prevPrice > 0) {
    var deltaValue = 100 * (currPrice - prevPrice) / prevPrice;
    dojo.style(cell, "color", getTextColor(deltaValue));
    cell.innerHTML = deltaValue.toFixed(2) + "%";
  }
}


