/**
 * Script for handeling the bar medadim data.
 * @author Nir Geier Apr 2010
 */
var finapi = 'http://finapi.themarker.com/tmfinapi/q?rm=m&cb=TM.BarMedadim.parseReply&enc=utf-8&qm=ib';

var generalOrder = [];


var nav = {
  root: [{
    'name': 'כללי',
    'type': 5,
    'url': finapi + 'g'
  }, {
    'name': 'ת"\א',
    'type': 1,
    'url': finapi + 'ta',
    'graphParams': '&since=09:45&till=16:35&tickers='
  }, {
    'name': 'ארה"\ב',
    'type': 2,
    'url': finapi + 'us',
    'graphParams': '&since=15:30&till=22:00&tickers='
  }, {
    'name': 'אירופה',
    'type': 3,
    'url': finapi + 'eu',
    'graphParams': '&since=10:00&till=18:30&tickers='
  }, {
    'name': 'מטבעות',
    'type': 4,
    'url': finapi + 'c'
  }]

};


/**
 * * This file will server the bar medadim data * Author : Nir Geier
 */
if (typeof TM === 'undefined') {
  TM = {};
};

/**
 * Define the BarMedadim object
 */
TM.BarMedadim = function(){

  // The timer for the details expantion
  var detailsTimer;

  // The current element we want to expand
  var currentElement;

  // Timer for the update interval
  var updateTimer;

  /**
   * The global settings that cab be override later
   */
  var settings = {
    // The update iteval in miliseconds
    updateInterval: 20000,

    // The DCLK calls
    dclkBaseUrl: 'http://dclk.themarker.com/html.ng/site=tm&affiliate=atmsnws&saftm=sanshp&adsize=100x37',

    // The base URL for the madad info
    secURL: 'http://finance.themarker.com/f/currency/indexIndPage.jhtml?secCode=',

    //  The delay for the mouseover
    animationDelay: 500,

    //  The delay for the mouseover
    axpandInterval: 500,

    // The current item we want to expand
    currentBarItem: undefined,

    // The animation timer. used for the delay
    animationTimer: undefined,

    // The url for the graphs
    graphBaseURL: 'http://finapi.themarker.com/tmfinapi/png?'
  };

  /**
   * Mark the current selected tab
   */
  function markCurrent(){

    // Mark the selected tab
    jQuery('.navBar .selected').removeClass('selected');
    jQuery(this).addClass('selected');
    getUpdate();
  };

  /**
   * This function will get the update from server and update bar values
   * Since we need cross domain AJAX we will inject the script to the page
   */
  function getUpdate(){

    // Clear the update timer
    clearTimeout(updateTimer);
    // Display ajax idicator
    //jQuery('<img src="/tmc/i/c/barMedadim/ajaxLoader.gif">').appendTo(jQuery('.barData'));

    if (jQuery('#barData').size() > 0) {
      jQuery('#barData').remove();
    };

    var script = document.createElement('SCRIPT');
    script.src = jQuery('.navBar .selected').attr('url');
    script.id = 'barData';
    document.body.appendChild(script);

    updateTimer = setTimeout(getUpdate, settings.updateInterval);

  };

  /**
   * Read the required data for the bar
   */
  function init(){
	
	if(navigator.userAgent.indexOf('iPhone') == -1 && navigator.userAgent.indexOf('Android') == -1 && navigator.userAgent.indexOf('iPad') == -1){
		jQuery('#barMedadimWrapper').css({'display': 'block'});
	    // Get the daily trade times by secCode
	    // Init the bar strip
	    for (var ind = 0; ind < nav.root.length; ind++) {
	      var li = jQuery('<li></li>');
	      li.attr({
	        'url': nav.root[ind].url,
	        'indType': nav.root[ind].type
	      });
	      li.click(TM.BarMedadim.markCurrent);
	
	      var html = '';
	      html += '<div class="topLine"></div>';
	      html += '<div class="cell">' + nav.root[ind].name + '</div>';
	
	      li.html(html);
	
	      jQuery('.navBar').append(li);
	    };
	
	    jQuery(window).bind('resize', TM.BarMedadim.centerBar);
	    jQuery('.navBar li:first').click();
	
	    // Center the bar
	    centerBar();
	}
	else{
		jQuery('#barMedadimWrapper').css({'display': 'none'});
	}
  };

  /**
   * Center the bar at the center of the page
   */
  function centerBar(){
    // Set the space between the page and the bar
    jQuery('body').css({
      'margin': '0 0 38px 0'
    });

    var right = parseInt((jQuery(window).width() - 960) / 2 + 6, 10);
    jQuery('.navBar').css({
      'right': right
    });

    jQuery('.barData').css({
      'right': Number(right + 2)
    });


  };

  /**
   * Parse the Json reply we got from the script
   */
  function parseReply(){
    var results = arguments[0].r[1];
    var barData = jQuery('.barData');

    // Clear current data
    barData.html('');

    // Fill the data
    for (var r = 0; r < results.length; r++) {
      var data = results[r];

      for (var i = 0; i < data.length; i++) {
        var summary = jQuery('#template li').clone().appendTo(barData);

        // Set the background
        var className = 'madadGreen';
        if (parseFloat(data[i].PCTCHANGE, 10) < 0) {
          className = 'madadRed';
        };
        jQuery('.barItem', summary).addClass(className);
        jQuery('.barItemContent', summary).addClass(className + 'Open');

        var graphLink = data[i].GRAPH_LINK;
        if (!graphLink) {
          //  Set the sec code for the image
          // Build the graph link.
         // graphLink = 'http://finapi.themarker.com/tmfinapi/png?';
          graphLink = settings.graphBaseURL;
          graphLink += 'type=' + data[i].TYPE;
          graphLink += '&inst=' + data[i].INST;
          graphLink += '&ex=' + data[i].EX;
          graphLink += '&s=' + data[i].SEC_CODE;
          graphLink += '&w=' + '100';
          graphLink += '&h=' + '78';
          graphLink += '&rs=' + 'newIntraday';
        };
        jQuery('.barItemContent [name=graphURL]', summary).val(graphLink);

        var pageLink = data[i].PAGE_LINK;
        if (!pageLink) {
          pageLink = settings.secURL + data[i].SEC_CODE + '&IndType=' + data[i].IND_TYPE;
        };
        // Set the link to the finance page
        var link = jQuery('<a></a>').attr({
          'class': 'financeLink',
          'href': pageLink,
          'target': '_blank'
        });

        // Set the click event to the finance page
        jQuery('.barItem', summary).wrap(link);
        // Set the Title
        jQuery('.madadTitle', summary).html(data[i].HEB_NAME);
        // Set the changes
        var value = Number(data[i].LAST);
        // Check to see if this is currency - if true display 3 digits
        if (data[i].INST === 'cur') {
          value = parseInt(Number(value) * 1000)/1000;
        }else{
          value = parseInt(Number(value) * 100)/100;
        };
        jQuery('.madadData', summary).html(data[i].PCTCHANGE + '%' + '&nbsp;|&nbsp;' + value);

      };
          }; // for loop
    /**
     * Attach the events to the bar items
     */
    jQuery('.barItem').hover(function(){
      // Keep reference to the current item
      settings.currentBarItem = jQuery('.barItemContent', this);

      // Clear previous element
      if (settings.animationTimer) {
        clearTimeout(settings.animationTimer);
      };

      // Set timer for the animation
      settings.animationTimer = setTimeout(TM.BarMedadim.expandDetails, settings.animationDelay);

    }, function(){
      var className = jQuery('.barItemContent [name=class]', this).val();

      // Clear previous element
      if (settings.animationTimer) {
        clearTimeout(settings.animationTimer);
      };

      jQuery('.barItemContent', this).animate({
        bottom: '-191px'
      });
      updateTimer = setTimeout(getUpdate, settings.updateInterval);

      //}
    });

  }; // parseReply
  /**
   * Open the bar details.
   * We display the details after a timeout of 1 sec
   */
  function expandDetails(){

    // Clear the update timer
    clearTimeout(updateTimer);

    // DCLK Iframe
    var summary = settings.currentBarItem;
    if (jQuery('IFRAME', summary).attr('src').length < 1) {
      jQuery('IFRAME', summary).attr('src', settings.dclkBaseUrl + '&pagearea=line' + jQuery('.navBar .selected').attr('indType') + '&adpos=0' + jQuery('.barItemContent').index(summary));
      // Add Graph
      jQuery('img', summary).attr('src', jQuery('[name=graphURL]', summary).val());
    };

    settings.currentBarItem.animate({
      bottom: '0px'
    });

  }; // expandDetails
  return {
    init: init,
    expandDetails: expandDetails,
    parseReply: parseReply,
    getUpdate: getUpdate,
    markCurrent: markCurrent,
    centerBar: centerBar
  };// return
}();


TM.BarMedadim.init();

