
var ajaxHandler = [];
ajaxHandler[1] = '/portfolios/rank/1rank.php';
ajaxHandler[2] = '/funds/etf/cron/ajax_screens_data_handler.php';

// Attach click events to the up/down arrows
init_latestnews = function()
{
  js.event.add( document.getElementById('ln_scroll_down'), 'mousedown',     function(e){
    jsScroll.startScrolling('data_div', 'down');
  });

  js.event.add( document.getElementById('ln_scroll_up'), 'mousedown', function(e){
    jsScroll.startScrolling('data_div', 'up');
  });

  js.event.add( document.getElementById('ln_scroll_down'), 'mouseup',     function(e){
    jsScroll.stopScrolling();
  });

  js.event.add( document.getElementById('ln_scroll_up'), 'mouseup', function(e){
    jsScroll.stopScrolling();
  });
}


/**
* This method used for processing the data for each tab.
*
* The method takes in the tab id and the dc_page_id as the input parameter
* and fetches the data from the respective datasource based on the tab id.
* The dc_page_is is used for setting the highlighted tab based on the
* page. For example current business requirement is to have
* the latest stories tab highlighted for the home page and
* for every other page the most popular tab will be highlighted.
*
*
* @author Ekalabya Mukherjee<ekalabyam@zacksindia.com>
*
* @param  int  tabid  The tab for which the data is to be displayed
* @param  int  page_id The page identifier.
*
*
*
*/
function get_tab_data(tabid,page_id)
{

    var browserName = navigator.appName;
    var linkArr = new Array();
    linkArr[1] = "http://www.zacks.com/articles";
    linkArr[2] = "http://www.zacks.com/articles";

    nocache = Math.random();

    servername = _getservename();
    serverprotocol = getserverProtocol()
    var _param = new Array(2);
    // Create the param array
    _param = {'tab_id' : tabid, 'cache' : nocache};

  // Get data from the php handler.
   var _url= serverprotocol + "://"+ servername + '/top_commentary_module/header_tab_data_generator.php';

    //Generate the loading text
    var loadingText = "Loading Stories";

    setLoadingMessage('data_div',loadingText);

    // Using post for the data call
    jsAjaxNew = jsAjax;
    jsAjaxNew.init();
    jsAjaxNew.Request(returndataReply, _url, _param, 'POST');

    // Set the highlighted tab logic.
    if(page_id != '')
        {
            for(var i = 1; i <= 2; i++) // Currently two tabs are available.
                   {
                       if(i == tabid) // Highlighted the current selected tab
                       {
                           var tab = 'tab_'+tabid;
                           document.getElementById(tab).className = "select"; // Set the required class name to the selected tab.
                           document.getElementById('view_all_link').href = linkArr[parseInt(tabid)];
                       }
                       else
                       {
                            document.getElementById('tab_'+i).className = "";
                       }
                   }

        }


    function returndataReply()
    {
        if (jsAjaxNew.request.readyState == 4)
            {
            // Pull Object
            if( jsAjaxNew.request.responseText != "" )
                {
                var TableRef = document.getElementById('data_div') ;
                TableRef.innerHTML = '';
                response = jsAjaxNew.request.responseText ;

                TableRef.innerHTML = response;
            }
        }

    }
}

/**
* The function splits the uri into various parts.
* It is used to dynamically set the server path for various data calls.
*/
function _getservename()
{
    _getlocation            = String(window.location);                      //  The full location URI
    _serverprotocol_arr       = _getlocation.split('://'); //  upto http://
    _getlocation_servername = _serverprotocol_arr[1].split('/');                  //  upto widget_server
    _servername             =_getlocation_servername[0];                    //  get the server name for the split array

    return _servername;
}
/**
* The function splits the uri into various parts.
* It is used to dynamically set the server path for various data calls.
*/
function getserverProtocol()
{
    getlocation            = String(window.location);                      //  The full location URI
    serverprotocol_arr       = getlocation.split('://'); //  upto http://
    return serverprotocol_arr[0];
}

/**
* This function prepares the loading message text along with the loading bar
* while the strory is fetched.
*
* @param string  id  The div id
* @param string  loadingText  The text to be displayed while the stories are loaded.
*/
function setLoadingMessage(id,loadingText)
{
    var TableRef = document.getElementById(id) ;
serverprotocol = getserverProtocol();
  TableRef.innerHTML =  '<div style="padding:10px 0 0px 30px; text-align: center;"><span style="display:block;  text-align: center;">'+ loadingText +'</span><img src="'+ serverprotocol +'://staticzacks.net/images/icons/loaders/35.gif" /></div>';

}


/**
* This method is a standard method for calls that passes any ID as the main parameter
* for fetching the data.
*
* The method takes in parameters passed from any call that demands data
* based on a single ID.The second parameter is the php ajax handler file
* path which is a numeric value and based on that value the path is fetched
* from the ajaxHandler array.
*
* For Direct Ajax calls to widget from the widgets server we need the help of the proxy file.
*
* @author Abhijit Saha<abhijit.saha@zacksindia.com>
*
* @param  id  [The reference Id either industry or sector or message]
* @param  handlerId  [The id that maps to the php ajax handler path]
*
*
*/
function returndata(id,handlerId)
{    
    // The div to disable any user click by disabling the dispaly with a 1px background image
    document.getElementById('transparent_div').style.display = 'block';

    var browserName = navigator.appName;


    nocache = Math.random();


    serverprotocol = getserverProtocol();
    var _url= serverprotocol + "://"+ getServername() + ajaxHandler[handlerId] +"?reference_id=" + id +"&cache="+  nocache;

    //Generate the loading text
    var loadingText = "";

    setLoadingMessage('js_data',loadingText);

    //call the Request method of jsAjax Object with call back function, url to be parsed,
    //in MVC architecture paramter is being passed in the url so in this case _param variable is assigned
    //with null, the submission method is GET
    jsAjaxRank = jsAjax;
    jsAjaxRank.init();
    jsAjaxRank.Request(returndataRankReply, _url, null, 'GET');


    function returndataRankReply()
    {

        if (jsAjaxRank.request.readyState == 4)
            {
            // Pull Object
            if( jsAjaxRank.request.responseText != "" )
                {
                var TableRef = document.getElementById('js_data') ;
                TableRef.innerHTML = '';
                response = jsAjaxRank.request.responseText ;
                var _data = eval('(' + response + ')');
                Table_1 = new jsTable('Table_1');
                Table_1.loadData(app_data['ZacksTable']).attachTo('js_data').render();
                
                document.getElementById('transparent_div').style.display = 'none';               
                doDisplay();
                //Shadowbox.init();

            }
        }

    }
}



/**
* This method is specific to the ETF screens data.
*
* The method takes in parameters passed from any call that demands data
* based on a single ID.The second parameter is the php ajax handler file
* path which is a numeric value and based on that value the path is fetched
* from the ajaxHandler array. The method was created separarely for the column wise sorting
* and different pagination style need. It will be merged with the conventional returndata method as
* the same will be made more robust.
*
* For Direct Ajax calls to widget from the widgets server we need the help of the proxy file.
*
* @author Ekalabya Mukherjee<ekalabyam@zacksindia.com>
*
* @param  id  [The reference Id either industry or sector or message]
* @param  handlerId  [The id that maps to the php ajax handler path]
*
*
*/
function return_etf_screens_data(id,handlerId)
{    
    
    var column_name_label_mapping = [];
    column_name_label_mapping = {
        
                                    "monthly_volume" : {
                                    "label" : "Monthly Volume",
                                    "sort_type" : "desc"
                                    },
                                    "inst_value" : {
                                    "label" : "Zacks Market Value",
                                    "sort_type" : "desc"
                                    },
                                    "annual_operating_expense" : {
                                    "label" : "Total Operating Expenses",
                                    "sort_type" : "asc"
                                    },
                                    "monthly_low_price" : {
                                    "label" : "Monthly Low",
                                    "sort_type" : "asc"
                                    },
                                    "monthly_high_price" : {
                                    "label" : "Monthly High",
                                    "sort_type" : "desc"
                                    },
                                    "dividend_yield" : {
                                    "label" : "Dividend Yield",
                                    "sort_type" : "desc"
                                    }
                                };
    /*column_name_label_mapping['monthly_volume']             = 'Monthly Volume';
    column_name_label_mapping['q0_mktval']                  = 'Zacks Market Value';
    column_name_label_mapping['annual_operating_expense']   = 'Total operating expenses';
    column_name_label_mapping['monthly_low_price']          = 'Monthly Low';
    column_name_label_mapping['monthly_high_price']         = 'Monthly High';*/

    // The div to disable any user click by disabling the dispaly with a 1px background image
    document.getElementById('transparent_div').style.display = 'block';

    var browserName = navigator.appName;


    nocache = Math.random();


    serverprotocol = getserverProtocol();
   var _url= serverprotocol + "://"+ getServername() + ajaxHandler[handlerId] +"?reference_id=" + id +"&cache="+  nocache;

    //Generate the loading text
    var loadingText = "";


    setLoadingMessage('js_data',loadingText);

    //call the Request method of jsAjax Object with call back function, url to be parsed,
    //in MVC architecture paramter is being passed in the url so in this case _param variable is assigned
    //with null, the submission method is GET
    jsAjaxEtfScreens = jsAjax;
    jsAjaxEtfScreens.init();
    jsAjaxEtfScreens.Request(returndataEtfReply, _url, null, 'GET');


    function returndataEtfReply()
    {

        if (jsAjaxEtfScreens.request.readyState == 4)
        {  
            // Pull Object
            if( jsAjaxEtfScreens.request.responseText != "" )
            {
                
                var TableRef = document.getElementById('js_data') ;
                TableRef.innerHTML = '';
                response = jsAjaxEtfScreens.request.responseText ;
                var _data = eval('(' + response + ')');
                Table_1 = new jsTable('Table_1');
                Table_1.loadData(app_data['ZacksTable']).attachTo('js_data').setPagination([5,10,15,25,50,100],3,25).render();
                Table_1.sortBy( column_name_label_mapping[id]['label'], column_name_label_mapping[id]['sort_type'] );
                document.getElementById('transparent_div').style.display = 'none';               
                //doDisplay();
                //Shadowbox.init();

            }
        }

    }
}




function getServername()
{
    str1=String(window.location);
    str2=str1.substring(7,str1.length); //upto http://
    str3=str2.split('/'); //upto widget_server
    return servername=str3[0];
}

