/**
 * product_info.js
 *
 * @author: chris.geheran@barclaysglobal.com
 *
 * @description: Fund page Specific JavaScript
 *
 * @requires: jquery-1.3.2,jquery-bt
 *
 */
$(document).ready(function() {
  /** This builds all the tooltips used within the new fund pages **/
	$('.pi-info-icon').each(function() {
		$(this).attr('title',"<div class='title'>"+$(this).attr('alt')+"</div>"+$(this).attr('title'));
		$(this).bt({positions:new Array('right','left'),shadow:true,shadowOffsetX:50,spikeLength:8,spikeGirth:12,windowMargin:20,strokeStyle:"#60e7f9",strokeWidth:1,fill:'#ecfaff',cornerRadius:3,width:230,cssClass:'pi-info-tip'});
	});

  $('.chartTip').each(function() {
    $(this).bt({positions:new Array('left'),shadow:true,shadowOffsetX:50,spikeLength:8,spikeGirth:12,windowMargin:20,strokeStyle:"#60e7f9",strokeWidth:1,fill:'#ecfaff',cornerRadius:3,width:150,cssClass:'pi-info-tip'});
  });

  $('#dropdown-value a').click(function() {
    if ($('#dropdown-scroller').css("display")=="block") {
      $('#dropdown-scroller').hide();
      $('#page-overlay').hide();
    } else {
      $('#dropdown-scroller').show();
      $('#page-overlay').width($(document).width());
      $('#page-overlay').height($(document).height());
      $('#page-overlay').show();
      $('#page-overlay').click(function() {
        $('#dropdown-scroller').hide();
        $('#page-overlay').hide();
      });
    }

    return false;
  });

  $(".date-chooser").click(function() {
    $('#asofDt').val($(this).attr('id'));
    $('#date-select-form').submit();

    return false;
  });
});



// *******************************************************************
// Ajax and helper functions for Holdings Tables - EQ and Fixed Income
// There are a lot of switches and controls and ui bits to keep track of so Object oriented approach here.
// HoldingsState object is the object that represents the Ajax fed Holdings Table as the user sees it and interacts with it.
// thus the HoldingsState name.
// *******************************************************************
// HoldingsState object var set on page level.  See holdings_eq and holdings_fi modules
var HoldingsState = new Object;
HoldingsState.URL;              // remains CONSTANT for all usage
HoldingsState.AJAX_DECORATION;  // [true, false]  true needed for ajax call to get it to use ajax decorator otherwise too much decoration
HoldingsState.TICKER;           // remains constant during user view of holdings page
HoldingsState.TOTALPAGES;       // remains constant. Not needed for ajax call but useful for pagination to keep it here
HoldingsState.periodCd;         // [d,m] daily or monthly. User interacts with calendar picker which sets this. Backend default is d - daily.
HoldingsState.asofDt;           // [yyyy-mm-dd] ex. 2009-07-31.  User interacts with calendar picker which sets this. Backend default: tbd?  
HoldingsState.sortByID;         // [holding_ticker, holding_nm, net_assets_pct, market_value, identifier, market_nm, fundSectorName, fx_rate]
HoldingsState.itemsPerPage;     // [null, 300] if user clicks View All then this value is set to null. If user clicks show 300 then set it to 300
HoldingsState.sortDir;          // [ASC, DESC].  Initial value is DESC.
HoldingsState.currentPage;      // Current page user is on. Initial value is 1.

// This will put an opacity mask in front of the table so user knows it is being updated - and it keeps them from clicking on col headers
// @tid   - id  of the table to mask
HoldingsState.showMask = function(tid) {
  // *****************
  // Show opacity mask
  // need mask to extend beyond top and bottom of table by 25 px to cover pagination bar. */
  var offSetTop = 25;  // bump top up 25
  var offsetHtExtension = 50; // elongate mask by 50 to cover top and bott pagination bars
  var topCalc = (parseFloat($("#"+tid).offset().top) - offSetTop);
  var htCalc = ($("#"+tid).height() + offsetHtExtension);
  var leftCalc = parseFloat($("#"+tid).offset().left)

  var topPositionSwirly = (topCalc+100);
  var leftPositionSwirly = (leftCalc+325);

  $("#feedbackLayer").css(
  {
    "display":"block",
    "width":$("#"+tid).width(),
    "height":htCalc,
    "top":topCalc+ "px",
    "left":leftCalc + "px"
  });

  // *****************
  // Show swirly on top of that opacity layer.
  $("#feedbackLayer-swirly-icon").css(
  {
          "display":"block",
          "top":topPositionSwirly+ "px",
          "left":leftPositionSwirly+ "px"
  });

  // Visual effect for IE6... reanimate the frozen swirley.
  // Resetting src for img is workaround for IE6. W/out this, animated gif freezes in IE6
  $('#swirl-icon').attr("src","/images/ajax-loader.gif");
}

HoldingsState.hideMask = function(tid) {
  // Hiding mask is really two things - fade the swirly and hide the masking layer.
  // Fadeout of 800 milli seems good balance for IE5 and Fox.  
  // Visual effect for IE6... reanimate the frozen swirley.
  $("#feedbackLayer-swirly-icon").fadeOut(1000, function () {
    //  No call back function here.. don't need one.
  });

  // hide the masking layer.
  $("#feedbackLayer").css("display","none");
}
// This is a wrapper around jquery's $.ajax method so it can be called from different event handlers.
HoldingsState.getRowsFromAjax = function(clickedObject, userAction,tableID) {

  // ***********************************************************************************
  // ***  Show MASKING (to disallow clicks) and show SWIRLY ICON during ajax fetch   ***
  // ***********************************************************************************
  HoldingsState.showMask(tableID); // pass the id of the table to mask

// forming the data parameter of ajax. do NOT send periodCd or asofDt if its blank
  var dataForAjax; // formatted like Jquery expects it
  if ( (HoldingsState.periodCd) && !(HoldingsState.asofDt) ) {  // this is most usual case if user hasn't done much but click on sort or pagin.
    dataForAjax =
    {  // these are expressed as name value pairs - such at ticker:IWV or sortby:holding_ticker
      ticker:HoldingsState.TICKER,
      sortBy:HoldingsState.sortByID,
      itemsPerPage:HoldingsState.itemsPerPage,
      currentPage:HoldingsState.currentPage,
      sortDir:HoldingsState.sortDir,
      periodCd:HoldingsState.periodCd,
      // asofDt:HoldingsState.asofDt,            DO NOT SEND THIS EMPTY PARAM
      ajax:HoldingsState.AJAX_DECORATION       // always set to ajax (see above constant)
    }
  }
  else if ( !(HoldingsState.periodCd) && (HoldingsState.asofDt) ) {
    dataForAjax =
    {
      ticker:HoldingsState.TICKER,
      sortBy:HoldingsState.sortByID,
      itemsPerPage:HoldingsState.itemsPerPage,
      currentPage:HoldingsState.currentPage,
      sortDir:HoldingsState.sortDir,
      // periodCd:HoldingsState.periodCd,      DO NOT SEND THIS EMPTY PARAM
      asofDt:HoldingsState.asofDt,
      ajax:HoldingsState.AJAX_DECORATION       // always set to ajax (see above constant)
    }
  }
  else if ( !(HoldingsState.periodCd) && !(HoldingsState.asofDt) ) {    // this should never happen but may as well check for it
    dataForAjax =
    {
      ticker:HoldingsState.TICKER,
      sortBy:HoldingsState.sortByID,
      itemsPerPage:HoldingsState.itemsPerPage,
      currentPage:HoldingsState.currentPage,
      sortDir:HoldingsState.sortDir,
      // periodCd:HoldingsState.periodCd,        DO NOT SEND THIS EMPTY PARAM
      // asofDt:HoldingsState.asofDt,            DO NOT SEND THIS EMPTY PARAM
      ajax:HoldingsState.AJAX_DECORATION       // always set to ajax (see above constant)
    }
  }
  else { // send them both along with the usual set
    dataForAjax =
    {
      ticker:HoldingsState.TICKER,
      sortBy:HoldingsState.sortByID,
      itemsPerPage:HoldingsState.itemsPerPage,
      currentPage:HoldingsState.currentPage,
      sortDir:HoldingsState.sortDir,
      periodCd:HoldingsState.periodCd,
      asofDt:HoldingsState.asofDt,
      ajax:HoldingsState.AJAX_DECORATION       // always set to ajax (see above constant)
    }
  }

  $.ajax({
    url: HoldingsState.URL,
    type: 'POST',
    data: dataForAjax,   // set this above due to need for not sending empty params for periodCD and asofDt.
    dataType: 'html',
    timeout: 10000,   // 10 second timeout
    error: function(){
        // to do later if want to embellish the error condition...could show a slight visual effect
        // alert('Data did not load correctly. ');
        // window.setTimeout(function() {
        //    $("#feedbackLayer").css ({
        //      "background-color":"red"  // this works but too much red
        //      "border":"1px solid #FFCCCC"
        //    });
        // }, 1500);
        HoldingsState.hideMask(tableID);
    },
    // htmlPayload is a set of table row html from ajax call to url. Like <tr><td>..</td>..</tr>..
    success: function(htmlPayload){
      try {
        // *************************************
        // ***  update table with ajax data  ***
        // *************************************
        // Note: IE6 errors with 'unknown runtime exception' if try to use innerHTML. But JQUERY html() works.
        $('#holdings-table-body').html(htmlPayload);
        // ******************************************

        // *************************************************
        // ***  update column headers and pagination bar ***
        // *************************************************
        // update pagination bar since successful ajax fetch
        HoldingsState.updatePaginationBar(clickedObject, userAction);

        // Only need to do this if user clicked column header. If they clicked Pagination then sort col and directin stays same
        // update column headers  since successful ajax fetch
        if (userAction == 'columnHeaderWasClicked') HoldingsState.updateColumnHeaders(tableID);  // this doesn't really need to know clickedObject, userAction
      }
      catch(ex)  {
         alert(ex.message); // never should see this under normal driving conditions.
      }
      finally{   // hide the opacity mask
        HoldingsState.hideMask(tableID); // pass the id of the table to mask
      }
    }
  }); //ajax function
} // end fooAjaxCaller
// ***************************

// ***************************
// User has clicked Column Header or Pagination bar  - so update table accordingly
// @ clickedObject  - object - the dom element that user clicked
// @ userAction - string - either 'columnHeaderWasClicked' or 'paginationWasClicked'
// MAKING THIS WORK FOR EITHER COLUMN HEADER CLICK OR PAGINATION BAR CLICK
// ***************************
HoldingsState.updateTableRows = function(clickedObject, userAction, tableID) {
  // *************************
  // Begin move to helper func
  // get the id of the clicked element
  // User clicked one of two possible things: A table header OR Pagination Bar.
  // Need to know the difference - because for Pagination Bar we don't switch the direction of the sort. But we do if user clicks on column header.

  // ONLY IF DOING COLUMN SORT DO WE START AGAIN AT PAGE 1 and change the sort direction (possibly).
  if (userAction=='columnHeaderWasClicked') {
    // RESET START PAGE TO FIRST ALWAYS ON A COLUMN CLICK
    HoldingsState.currentPage = 1; //set to page 1 always when a Sort is executed.

    // SET SORT COLUMN TO WHAT USER CLICKED
    var currTableHeader = $(clickedObject).parents('th:eq(0)');
    HoldingsState.sortByID = currTableHeader.attr('id'); // the id of the column header clicked is the same param name as needed by backend. See above possible values.

    // SET SORT DIR
    // figure out which sort to use - ASC or DESC.
    // set sortDir to ASC if certain conditions met. Either it's first click on a column designated as an "alpha" column (which would have alpha-backend class).
    // or set to ASC if the user just sorted DESC previously. So toggle to ASC.
    // if (current column has alpha-backend class AND it does NOT have class headerSortAsc) OR it has Desc class  -we know the sort should be ASC
    if ( ( $(currTableHeader).hasClass('alpha-backend') && !($(currTableHeader).hasClass('headerSortAsc') ) ) ||
       ($(currTableHeader).hasClass('headerSortDesc')) ) {
      HoldingsState.sortDir='ASC'; }
    else {    // must be the case that they haven't yet sorted on this column and thus should sort DESC.
      HoldingsState.sortDir='DESC';
    };
  }

  else if (userAction=='paginationWasClicked') {
    // ***********************
    // update current page for ajax call - there are different things the user might have clicked.
    // if user clicked a page number update to that
    if ( $(clickedObject).hasClass('page-link') ) HoldingsState.currentPage = $(clickedObject).text(); // set current page to  number user clicked on

    // else if user clicked Next or Previuos - increment or decrement by 1.
    else if ( $(clickedObject).hasClass('next-link') ) HoldingsState.currentPage++;
    else if ( $(clickedObject).hasClass('previous-link') ) HoldingsState.currentPage--;

    // else handle click on showAll and show 300
    else if ( $(clickedObject).hasClass('show-300-link') ) {
      HoldingsState.itemsPerPage=300; // set to null force all
      HoldingsState.currentPage=1; // reset current page to 1 (that is the rule for when switching back to show 300 per page from show all)
    }
    else if ( $(clickedObject).hasClass('show-all-link') ) {
      HoldingsState.itemsPerPage=0; // setting to ALL will actually set to null before sending param to ishares tag
      HoldingsState.currentPage=1;  // reset current page to 1 (that is the rule for when switching back to show 300 per page from show all)
    };
  }
  // ***  call ajax function  to get Rows***
  // url EXAMPLE: http://localhost:8080/product_info/fund/holdings_ajax.htm?ticker=IWV&sortBy=holding_ticker&itemsPerPage=300&sortDir=ASC&ajax=true
  HoldingsState.getRowsFromAjax(clickedObject, userAction, tableID);  // passing clickedObject and useraction so that post ajax aftermath functions know what was clicked by user.
}

  // *******************************************************************
  // helper functions for after ajax fetch -  update Column Header and Pagination Bar.
  // update table column header style changes based on what user clicked
  // called by column click event handler
  // @ tableID    - id of the target table to update column headers for.
  HoldingsState.updateColumnHeaders = function (tableID) {
    // lastly flip the style of the clicked column to show it's sort arrow DESC or ASC.
    // also flip the other columns triangle back to sideways since those other columns aren't sorted on anymore. Only one column sorted at any one time.
    var theads =  $("#"+tableID).find("thead tr th") ;
    for (i=0;i<theads.length;i++) {
      if ( $(theads[i]).attr('id') == HoldingsState.sortByID ) {
        // found a match - this is the column user sorting on. So change it's styles to reflect that
        // if (current column has alpha-backend class AND it does NOT have class headerSortAsc) OR it has Desc class  -we know the sort should be ASC
        if ( ( $(theads[i]).hasClass('alpha-backend') && !($(theads[i]).hasClass('headerSortAsc') ) ) ||
          ($(theads[i]).hasClass('headerSortDesc')) ) {
          $(theads[i]).removeClass('headerSortDesc').addClass('headerSortAsc'); // flip the class
        }
        else   {  // user must want to sort desc.
          $(theads[i]).removeClass('headerSortAsc').addClass('headerSortDesc'); // flip the class
        }
      }
      else {   // remove the ASC and DESC styles from the column because it's no longer being sorted on
        $(theads[i]).removeClass('headerSortAsc').removeClass('headerSortDesc');
      }
    } // ******************************************
  }

  // ******************************************************
  HoldingsState.updatePaginationBar = function(clickedObject, userAction) {
  // ******************************************************
    //HIDE AND SHOW THE RIGHT PAGINATION BLOCKS IF USER CLICKED Show All or Show 300
    if ( userAction =='paginationWasClicked') {
      if ( $(clickedObject).hasClass('show-300-link') ) {
        // turn on display of the hidden container again
        $('.show_pagination_container').show();
        // hide the show300 link
        $('.show_300_container').hide();
      }
      // show 300
      else if ( $(clickedObject).hasClass('show-all-link') ) {
        // turn off display of the hidden container again
        $('.show_pagination_container').hide();
        // hide the show300 link
        $('.show_300_container').show();
      };
    }
    // update pageination bar's current page to be Black/BOLD
    // turn on the current page style for page user just clicked. Turn off the current page style for
    // any other page that has the current style. only one page should have the "Current" style at any one time.
    var pageNavItems = $.find("#pagebar-page-*") ;
    $("[id^=pagebar-page-]").each(function(index){
      if ( $(this).text()==HoldingsState.currentPage ) {
        $(this).addClass('current-page');
      }
      else $(this).removeClass('current-page');
    });

    // ****************************************************************
    // handle special cases of whether to show Next or Previous buttons
    // Previous button
    // safe to continue showing Previous button
    if (parseInt(HoldingsState.currentPage) > 1) {
       $('.show-previous').show();  // this will hide the top and bottom previous buttons.
    }
    else  {  // don't show "previous" button anymore
      $('.show-previous').hide();  // this will hide the top and bottom previous buttons.
    }
    // Next button
    if (parseInt(HoldingsState.currentPage) < parseInt(HoldingsState.TOTALPAGES))  {          // safe to show Next Button
      $('.show-next').removeClass('next-link-hidden').addClass('next-link-visible');
    }
    // handle special case: current page is no longer the last one. Need to turn on display of "next button  again
    else {  // dont show "next previous" button anymore
      $('.show-next').removeClass('next-link-visible').addClass('next-link-hidden');
    }
  }
// end Ajax and helper functions for Holdings Tables - EQ and Fixed Income
// *******************************************************************