﻿var alertd = 1;
//Document.ready
//#region
$(document).ready(function() {
    
    GetScrollingStockData();        //Get the stock info for the scrolling ticker tape
    ShowChart();                    //Generate the charted stock info
    GetNewsFeed(moveOverRSSFeed);   //Retrieve current news feed and display in the "new" panel
    AutoPlayNewsFeedScroll();


    //Initialize some visual elements
    $('#chartMenu p:first').next('div.menu_body').slideDown(500);   //Open the first chart by default
    $('#chartMenu p:first').removeClass('menu_headClosed');
    $('#chartMenu p:first').addClass('menu_headOpen');

    //Register some event handlers

    //Wire up the mousehover event to open the "selected" chart and close any previously opened charts
    //We're using a timed action here to create a slight delay (hover intent) so that the charts don't open on random
    //fly-by hovers
    $('#chartMenu p').hover(function() {
        var p = $(this);
        var t = setTimeout(function() {
            //Close any open windows
            var openWindow = $('#chartMenu p.menu_headOpen:first');
            openWindow.next('div.menu_body').slideUp('slow');
            openWindow.addClass('menu_headClosed');
            openWindow.removeClass('menu_headOpen');

            p.addClass('menu_headOpen');
            p.removeClass('menu_headClosed');
            p.next('.menu_body').slideDown(500);
        }, 500);
        $(this).data('timeout', t);
    }, function() {
        //Clear the timed action when the mouse moves away from the item
        clearTimeout($(this).data('timeout'));
        var openContainer = $(this).siblings("div.menu_body .menu_headOpen");
    });

    //Wire up the mouseover event to stop the ticker tape from scrolling
    $('#tickerTape_Container').mouseover(function() {
        $('#tickerTape_Container ul').stop();
        animationToggle = 0;
    });

    //Wire up the mouseout event to restart the ticker tape scrolling
    $('#tickerTape_Container').mouseout(function() {
        animationToggle = 1;
    });
});
//#endregion

//LookupTickerAlias
//#region
//Certain indices have alias we want to display
function LookupTickerAlias(ticker) {
    var alias = ticker;
    switch (ticker) {
        case '^IXIC':
            alias = 'NASDAQ';
            break;
        case '^DJI':
            alias = 'DJIA';
            break;
        case 'RTH':
            alias = 'Retail Holders';
            break;
        case '^GSPC':
            alias = 'S&P 500';
            break;
        case '^FVX':
            alias = '5 YR TREAS';
            break;
        case '^TNX':
            alias = '10 YR TREAS';
            break;
        case '^TYX':
            alias = '30 YR TREAS';
            break;
        default:
            alias = ticker;
    }
    return alias;
}
//#endregion

//MakeWebRequest
//#region
//Initiates a web request and wires up the onCompleted event to the custom function
function MakeWebRequest(remoteURI, onCompletedFunction) {
    //using jQuery, make the remote WebRequest
    $.getJSON(
            proxyServiceURL,
            { URI: remoteURI },
            onCompletedFunction,
            function() { alert('error') }
            );
}
//#endregion

//Ticker Tape Stuff
//#region
//GetScrollingStockData - Starts the process of getting the stock info and creating the ticker tape elements
//#region
function GetScrollingStockData() {
    //Builds the web request, makes the request and creates a onCompleted function
    document.getElementById('tickerTape_Container').innerHTML = "";
    var fullURI = baseStockURL;
    for (var i = tickers.length - 1; i >= 0; i--) {
        fullURI += tickers[i] + ",";
    }
    fullURI.slice(0, fullURI.length - 1);
    fullURI += endStockURL;

    MakeWebRequest(fullURI, function(data) {
        GetScrollingStockData_Completed(data.d);
    });
}
//#endregion

//GetScrollingStockData _Completed
//#region
//Grabs the return data from the web request 
function GetScrollingStockData_Completed(resultData) {
    var stockData = ParseStockData(resultData);             //Parse the data
    ShowStockData(stockData);                               //Use the data to show the stock info
}
//#endregion

//ParseStockData - Reads the raw stock data for the ticker tape elements
//#region
//Parses the blob we get from the web request into individual anonymous items
function ParseStockData(rawData) {
    var rows = new Array(rawData.split('\n'))[0];           //parse the rows
    var dataSet = [];
    for (var i = rows.length - 1; i >= 0; i--) {            //iterate through each row
        //The split function does not ignore empty values
        if (rows[i].length > 0) {
            try {
                var fields = rows[i].split(/,(?=[^ ])/);                 //parse the fields
                if (fields.length == 11) {
                    fields.splice(1, 1);                    
                }
            dataSet[i] = {                                  //create an anonymous object
                "Name": fields[0].replace(/"/, ''),
                "Ticker": fields[1].replace(/['"']/g, ''),
                "LastTick": fields[2],
                "Change": fields[5]
            };
            }
            catch (ex) {                
                dataSet[i] = {                                  //create an anonymous error object
                    "Name": "error",
                    "Ticker": "error",
                    "LastTick": "error",
                    "Change": "error"
                };
            }
        }
    }
    return dataSet;
}
//#endregion

//ShowStockData - Creates the ticker tape list elements
//#region
//Create a 'ul' element with 'li' elements for each stock info item then add it to the ticker tape section
function ShowStockData(stockData) {
    var tickerTape = document.getElementById("tickerTape_Container");
    var tickerTape_ul = document.createElement('ul');
    tickerTape_ul.id = 'tickerTape_ul';

    for (var i = stockData.length - 1; i >= 0; i--) {
        var listItem = document.createElement('li');
        listItem.id = "i" + stockData[i].Ticker;

        var $tickerBox = $(document.createElement('span'));
        $tickerBox.text(stockData[i].Ticker);

        var $lastTickBox = $(document.createElement('span'));
        $lastTickBox.text(stockData[i].LastTick);

        var $changeBox = $(document.createElement('span'));
        $changeBox.text(stockData[i].Change);        
        

        listItem.appendChild(ApplyTickerTapeStyles($tickerBox.get(0), false, false));
        listItem.appendChild(ApplyTickerTapeStyles($lastTickBox.get(0), false, false));
        listItem.appendChild(ApplyTickerTapeStyles($changeBox.get(0), true, true));
        tickerTape_ul.appendChild(ApplyTickerTapeLIStyles(listItem, $changeBox.get(0)));
    }
    tickerTape.appendChild(tickerTape_ul);

    //We want the tickers to run across the whole screen so we'll have to create some empty elements 
    //This makes sure that if there are only a few tickers they don't pop up in the middle of the ticker tape on wrap around           
    var tapeWidth = $('#tickerTape_Container').outerWidth(true);
    var tickerWidth = $('#tickerTape_Container ul li').outerWidth(true);
    var numberOfTickersNeeded = parseInt(parseInt(tapeWidth) / parseInt(tickerWidth)) + 1;

    for (var extra = parseInt(numberOfTickersNeeded) - tickerTape_ul.childNodes.length; extra > 0; extra--) {
        var emptylistItem = document.createElement('li');
        emptylistItem.id = "iEmpty" + i;
        //emptylistItem.innerText = "test area";
        tickerTape_ul.appendChild(emptylistItem);
    }

    Scroll();       //Initiates the scrolling action
}
//#endregion

//Scroll - stock ticker tape
//#region
function Scroll() {
    var timer = setInterval('slide("left")', 1000);     //Calls the specified animation every 1 second
}
//#endregion

//Slide - stock ticker tape
//#region
function slide(where) {
    if (animationToggle == 1) {                                             //Make sure we want to run the animation
        var item_width = $('#tickerTape_Container ul li').outerWidth(true); //Get the width of the li elements

        if (where == 'left') {
            //Slide to the left 1 'li' element length
            var left_indent = parseInt($('#tickerTape_Container ul').css('left')) - item_width;
        }
        else {
            //Slide to the right 1 'li' element length
            var left_indent = parseInt($('#tickerTape_Container ul').css('left')) + item_width;
        }

        //Grab all 'li' elements that are not animating and start sliding them over 3 seconds.
        $('#tickerTape_Container ul:not(:animated)').stop().animate({ 'left': left_indent }, 3000,
                    "linear", function() {
                        //As the elements move off the screen we want to move them to the back of the list.  This
                        //creates the wrap-around effect.
                        if (where == 'right') {
                            $('#tickerTape_Container ul li:first').before($('#tickerTape_Container ul li:last'));
                        }
                        else {
                            $('#tickerTape_Container ul li:last').after($('#tickerTape_Container ul li:first'));
                        }

                        $('#tickerTape_Container ul:last').css({ 'left': '0px' });
                    });
    }
}
//#endregion

//ApplyTickerTape List Styles
//#region
//Apply a style to the 'li' elements so that negative and positive changes show up red and blue respectively
function ApplyTickerTapeLIStyles(liElement, changeBox) {    
    
    var text = $(changeBox).text();
    if (text.indexOf('-') == 1) {
        liElement.className = "stockNegative";
    }
    else {
        liElement.className = "stockPositive";
    }

    return liElement;
}
//#endregion

//ApplyTickerTapeStyles
//#region
//Style the span elements containing the ticker, last tick, and change values
function ApplyTickerTapeStyles(element, showSign, showParens) {    
    var text = $(element).text();
    if (parseFloat(text)) {
        if (parseFloat(text) < 0) {
            $(element).addClass("tickBoxNegative");
        }
        else {
            $(element).addClass("tickBoxPositive");
            if (showSign == true) {
                if (text.substring(0, 1) != ('+')) {
                    text = '+' + text;
                }
            }
        }
    }
    else {
        $(element).addClass("tickerBox");
    }

    if (showParens == true) {        
        $(element).text('(' + text + ')');
    }
    return element;
}
//#endregion
//#endregion

//Show Stock Charts
//#region
//Makes the web request for the stock charts, creates the charts and formats their headers
function ShowChart() {
    for (var i = 0, j = charts.length - 1; i < j; i++) {
        try {
            var par = document.createElement('p');
            par.className = "menu_headClosed";
            $(par).text(charts[i]);
            document.getElementById('chartMenu').appendChild(par);

            //Lookup stock info for header
            var requestURI = baseStockURL + charts[i] + endStockURL;
            
            MakeWebRequest(requestURI, function(data) {
                var rawData = data.d;
                var dataRecord = ParseStockData(rawData)[0];                

                var percentageChange = parseFloat(dataRecord.Change / (parseFloat(dataRecord.LastTick - dataRecord.Change))) * 100;
                var chartHeaderHTML = '<span id="chartLabelTicker">' + LookupTickerAlias(dataRecord.Ticker) +
                        '</span>&nbsp;&nbsp;&nbsp;<span id="chartLabelLastTick">' + '<b>' + dataRecord.LastTick + '</b>'
                        + '</span>&nbsp;&nbsp;&nbsp;<span id="chartLabelChange">' + dataRecord.Change
                        + '</span>&nbsp;&nbsp;&nbsp;';

                //This function is going to run asynchronously so we have to look for the right chartMenu item to update.                        
                var thisHeader = $('#chartMenu p:contains(' + dataRecord.Ticker + ')');
                if (percentageChange < 0) {
                    thisHeader.css('background-image', 'url(images/tz/SquareLabelGreenGradientArrowDown.png)');
                    chartHeaderHTML += '<span id="chartLabelPercentChange" style="color:red;font-weight:bold">' + '(' + percentageChange.toFixed(2) + '%)</span>';
                }
                else {
                    thisHeader.css('background-image', 'url(images/tz/SquareLabelGreenGradientArrowUp.png)');
                    chartHeaderHTML += '<span id="chartLabelPercentChange" style="color:black">' + '(' + percentageChange.toFixed(2) + '%)</span>';
                }

                thisHeader.html(chartHeaderHTML)

            });

            //Create the chart area
            var div = document.createElement('div');
            div.className = "menu_body"
            var chart = document.createElement('img');
            chart.src = "http://ichart.yahoo.com/t?t=1d&l=on&s=" + charts[i];       //This is the actual request for the charts
            div.appendChild(chart);
            document.getElementById('chartMenu').appendChild(div);
        }
        catch (Error) {
            alert(Error);
        }
    }
}
//#endregion

//Get News Feed
//#region
//Makes the web request for the news feed and formats the results
function GetNewsFeed(feedURI) {

    //Each time we run this function we want to clear out any old items
    $('#newsView').empty();

    //Indicate that we are loading news items
    newsViewPortLoading = 1;
    var p = 1;
    //Make the web request and create objects for each section of each news item
    MakeWebRequest(feedURI, function(results) {
        try {
            var xml = $.xmlDOM(results.d);
            $(xml).find('item').each(function() {
                var $item = $(this);
                var title = $item.find('title').text();
                var link = $item.find('link').text();
                var description = $item.find('description').text();
                var pubDate = $item.find('pubDate').text();

                if (description.toUpperCase() != "EXTRACT NOT AVAILABLE.") {        //Don't show incomplete news items
                    var li = document.createElement('li');
                    var sp = document.createElement('span');
                    sp.className = 'newsItemContainer';

                    var spT = document.createElement('span');
                    spT.className = 'postTitle';

                    var spP = document.createElement('span');
                    spP.className = 'date';

                    var spD = document.createElement('span');
                    spD.className = 'description';

                    var spL = document.createElement('span');                    
                    
                    var spLa = document.createElement('a');
                    spLa.href = link;
                    spLa.target = "_blank";
                    spLa.className = 'link';

                    $(spT).text(title);
                    $(spP).text(pubDate);
                    $(spD).text(description);
                    $('a.link').text('Read More >>');

                    sp.appendChild(spT);
                    sp.appendChild(document.createElement('br'));
                    sp.appendChild(spP);
                    sp.appendChild(document.createElement('br'));
                    sp.appendChild(spD);
                    sp.appendChild(document.createElement('br'));
                    spL.appendChild(spLa);
                    sp.appendChild(spL);

                    li.appendChild(sp);
                    $('#newsList').append(li);
                }
            });
        }
        catch (Error) {
            alert(Error);
        }
    });
}
//#endregion

//Scroll News Feed
//#region

//Scrolls through each news item, displaying one at a time
function ScrollNewsFeed(direction) {
    
    if (newsViewPortLoading == 1) {

        //Get a handle on the current first (read: currently displayed) news item
        var firstElement = $("#newsViewPort #newsList li:first");        
        
        firstElement.fadeOut(500);                              //Fade it out over 500ms
        setTimeout(function() {
            $("#newsViewPort #newsList li:first").remove();     //Remove the faded-out item when the animation finishes            
            if ($("#newsViewPort #newsList li").length < 1) {
                newsViewPortLoading = 0;
            }
        }, 500);
    }
    else {
        
        GetNewsFeed(moveOverRSSFeed);                           //Restart the news feed service getting new set of news items
    }

}
//#endregion

function AutoPlayNewsFeedScroll() {
    setInterval('ScrollNewsFeed("forward")', 15000);
}

//News Feed Manual Controls
//#region
//function PreviousPost() {
//    alert('previous');
//    return false;
//}

//function NextPost() {
//    ScrollNewsFeed("forward");
//    return false;
//}

//function TogglePlay() {
//    alert('toggle');
//    return false;    
//}

//#endregion

//Auto Play News Feed
//#region
//Scrolls to the next news item every 15 seconds

//#endregion

