﻿
var m_TimerInterval = 5000; //interval - uc polls data every 5000 ms.
var m_ImageRefreshInterval = 60000;
var m_QuoteService;
var m_DummyQuerystring = ""; //needed to prevent the image of OSEBX graph to cache in client browser

var m_MobileVersion = false;

var m_MainIndexPreviousChange = null;
var m_MainIndexPreviousPercentageChange = null;
var m_MainIndexPreviousLast = null;

//Initializes timer for polling new market overview data from server.
function InitializeMarketOverviewTimer(count, mobileVersion) {
    m_MobileVersion = mobileVersion;
    setTimeout("GetMarketOverviewDataFromQuoteService(" + count + ")", m_TimerInterval);
}

//Initializes timer for image refresh
function InitializeImageTimer() {
    setTimeout("RefreshImage()", m_ImageRefreshInterval)
}

//Refreshes the Main Index picture (OSEBX)
function RefreshImage() {
    var img = document.getElementById("OSEBXImg");

    var url = new String(img.getAttribute("src"));

    url = url.substr(0, url.length - m_DummyQuerystring.length);

    //get new dummy querystring
    var now = new Date();
    var milliseconds = now.getTime();
    m_DummyQuerystring = "?" + milliseconds.toString();

    url = url + m_DummyQuerystring;

    img.setAttribute("src", url.toString());

    setTimeout("RefreshImage()", m_ImageRefreshInterval);
}

function GetMarketOverviewDataFromQuoteService(count) {
    try {
        m_QuoteService = new Marketmind.Web.Stocklink.Services.QuoteService();
        m_QuoteService.GetWinnersAndLosers(count, OnMarketOverviewSucceededCallback, OnMarketOverviewFailedCallback, null);
        setTimeout("GetMarketOverviewDataFromQuoteService(" + count + ")", m_TimerInterval);
    }
    catch (e) {
        //Nothing - this is expected when the Scriptmanager is not loaded.
    }
}

function OnMarketOverviewFailedCallback() {
    //TODO
}

function OnMarketOverviewSucceededCallback(e) {
    try {
        if (e.toString().length > 0) {
            //deserialize json result string
            var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);

            //finding winners and losers
            var winners = [];
            var losers = [];

            var winnerIndex = 0;
            var loserIndex = 0;

            for (var i = 0; i < result.QuoteServiceEntries.length; i++) {
                if (result.QuoteServiceEntries[i].EntryType == "W") {
                    winners[winnerIndex] = result.QuoteServiceEntries[i];
                    winnerIndex++;
                }
                else {
                    losers[loserIndex] = result.QuoteServiceEntries[i];
                    loserIndex++;
                }
            }

            UpdateTable(winners, "WinnersDiv", "Ingen vinnere registrert.");

            UpdateTable(losers, "LosersDiv", "Ingen tapere registrert.");

            UpdateStatistics(result.StatisticsEntry);

            UpdateMainIndex(result.MainIndexEntry);
        }
    }
    catch (e) {
        //todo
    }
}

///Updates table with new winners\losers list
function UpdateTable(result, ParentDivTagID, emptyStringResource) {
    var parentDiv = document.getElementById(ParentDivTagID);
    CleanElement(parentDiv); //need to remove all text children nodes from MostActiveDiv

    //finding table
    var table = parentDiv.firstChild;
    CleanElement(table);  //need to remove all text children nodes from mostActiveTable

    //finding table body
    var tableBody = table.firstChild;
    CleanElement(tableBody); //need to remove all text children nodes from mostActiveTableBody

    //remove all rows, except header and empty gif
    if (!m_MobileVersion) {
        while (tableBody.childNodes.length > 2) {
            tableBody.removeChild(tableBody.lastChild);
        }
    }
    else {
        while (tableBody.childNodes.length > 1) {
            tableBody.removeChild(tableBody.lastChild);
        }
    }

    var row;
    var cell;
    var modCheck;

    if (result.length == 0) {
        //no result returned (no winners)
        row = document.createElement("tr");
        cell = document.createElement("td");
        cell.setAttribute("colspan", "3"); //FF etc.
        cell.colSpan = 3; //IE         
        cell.setAttribute("align", "left");
        var iElement = document.createElement("i");
        txtContent = document.createTextNode(emptyStringResource);
        iElement.appendChild(txtContent);
        cell.appendChild(iElement);
        row.appendChild(cell);

        tableBody.appendChild(row);
    }
    else {
        //add new rows
        //the result is deserialized into an object with the same properties as QuoteServiceEntry.        
        for (var i = 0; i < result.length; i++) {
            row = document.createElement("tr");

            modCheck = i + 1;
            if (modCheck % 2 == 0) {
                row.setAttribute("class", "quoteListEven");
                row.setAttribute("className", "quoteListEven");
            }
            else {
                row.setAttribute("class", "quoteListOdd");
                row.setAttribute("className", "quoteListOdd");
            }

            //KeyAndSymbolHref
            cell = document.createElement("td");
            cell.setAttribute("align", "left");
            var ahrefContent = document.createElement("a");
            if (m_MobileVersion) {
                ahrefContent.setAttribute("href", "/mobile/InstrumentInfo.aspx?id=" + result[i].Key);
            }
            else {
                ahrefContent.setAttribute("href", "/InstrumentInfo.aspx?id=" + result[i].Key);
            }

            var txtContent;
            if (!m_MobileVersion) {
                txtContent = document.createTextNode(result[i].Name);
            }
            else {
                txtContent = document.createTextNode(result[i].Symbol);
            }
            ahrefContent.appendChild(txtContent);
            cell.appendChild(ahrefContent);
            row.appendChild(cell);

            //Last
            cell = document.createElement("td");
            cell.setAttribute("nowrap", "nowrap"); //FF && Opera
            cell.setAttribute("noWrap", "true"); //IE
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(result[i].Last);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            //PercentageChange
            cell = document.createElement("td");
            cell.setAttribute("nowrap", "nowrap"); //FF && Opera
            cell.setAttribute("noWrap", "true"); //IE
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(result[i].PercentageChange);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            tableBody.appendChild(row);
        }
    }


}

//Updates all statistics- How many securities have moved "Up", moved "Down", unchanged and their ratio.
function UpdateStatistics(result) {
    var textContent;

    var securitiesUpDiv = document.getElementById("SecuritiesUpDiv");
    textContent = document.createTextNode(result.SecuritiesUp);
    securitiesUpDiv.removeChild(securitiesUpDiv.firstChild);
    securitiesUpDiv.appendChild(textContent);

    var securitiesDownDiv = document.getElementById("SecuritiesDownDiv");
    textContent = document.createTextNode(result.SecuritiesDown);
    securitiesDownDiv.removeChild(securitiesDownDiv.firstChild);
    securitiesDownDiv.appendChild(textContent);

    var securitiesUnchangedDiv = document.getElementById("SecuritiesUnchangedDiv");
    textContent = document.createTextNode(result.SecuritiesUnchanged);
    securitiesUnchangedDiv.removeChild(securitiesUnchangedDiv.firstChild);
    securitiesUnchangedDiv.appendChild(textContent);

    var securitiesChangeRatioDiv = document.getElementById("SecuritiesChangeRatioDiv");
    textContent = document.createTextNode(result.SecuritiesChangeRatio);
    securitiesChangeRatioDiv.removeChild(securitiesChangeRatioDiv.firstChild);
    securitiesChangeRatioDiv.appendChild(textContent);

    var turnOverDiv = document.getElementById("TurnOverDiv");
    textContent = document.createTextNode(result.TurnOver);
    turnOverDiv.removeChild(turnOverDiv.firstChild);
    turnOverDiv.appendChild(textContent);
}

//updates all data from MainIndex (OSEBX)
function UpdateMainIndex(result) {
    var textContext;
    var str;

    var updatedTimeDiv = document.getElementById("UpdatedTimeDiv");
    textContext = document.createTextNode("Kurser sist oppdatert: " + result.UpdatedTime);
    updatedTimeDiv.removeChild(updatedTimeDiv.firstChild);
    updatedTimeDiv.appendChild(textContext);

    var mainIndexLastDiv = document.getElementById("MainIndexLastDiv");
    //get previous value on last if this is the first time UpdateMainIndex is called:
    if (m_MainIndexPreviousLast == null) {
        str = mainIndexLastDiv.innerHTML;
        if (str.replace(/-/, "").length > 0) {
            //previous last is not empty - can cast it to a Number
            m_MainIndexPreviousLast = new Number(str.replace(",", "."));
        }
    }
    textContext = document.createTextNode(result.Last);
    mainIndexLastDiv.removeChild(mainIndexLastDiv.firstChild);
    mainIndexLastDiv.appendChild(textContext);

    str = result.Last;
    var last = null;
    if (str.replace(/-/, "").length > 0) {
        //last is not empty - can cast it to a Number
        last = new Number(str.replace(",", "."));
        if (m_MainIndexPreviousLast != null) {
            if (last > m_MainIndexPreviousLast) {
                //current change higher
                mainIndexLastDiv.setAttribute("class", "bluecell");
                mainIndexLastDiv.setAttribute("className", "bluecell");
            }
            else if (last < m_MainIndexPreviousLast) {
                //current change lower
                mainIndexLastDiv.setAttribute("class", "redcell");
                mainIndexLastDiv.setAttribute("className", "redcell");
            }
            else {
                //no change
                mainIndexLastDiv.removeAttribute("class");
                mainIndexLastDiv.removeAttribute("className");
            }
        }
    }
    m_MainIndexPreviousLast = last;

    var mainIndexHighDiv = document.getElementById("MainIndexHighDiv");
    textContext = document.createTextNode(result.High);
    mainIndexHighDiv.removeChild(mainIndexHighDiv.firstChild);
    mainIndexHighDiv.appendChild(textContext);

    var mainIndexLowDiv = document.getElementById("MainIndexLowDiv");
    textContext = document.createTextNode(result.Low);
    mainIndexLowDiv.removeChild(mainIndexLowDiv.firstChild);
    mainIndexLowDiv.appendChild(textContext);

    var mainIndexChangeDiv = document.getElementById("MainIndexChangeDiv");
    //get previous value on change if this is the first time UpdateMainIndex is called:        
    if (m_MainIndexPreviousChange == null) {
        str = mainIndexChangeDiv.innerHTML;
        if (str.replace(/-/, "").length > 0) {
            //previous change is not empty - can cast it to a Number
            m_MainIndexPreviousChange = new Number(str.replace(",", "."));
        }
    }
    textContext = document.createTextNode(result.Change);
    mainIndexChangeDiv.removeChild(mainIndexChangeDiv.firstChild);
    mainIndexChangeDiv.appendChild(textContext);

    str = result.Change;
    var change = null;

    if (str.replace(/-/, "").length > 0) {
        //change is not empty - can cast it to a Number
        change = new Number(str.replace(",", "."));
        if (m_MainIndexPreviousChange != null) {
            if (change > m_MainIndexPreviousChange) {
                //current change higher
                mainIndexChangeDiv.setAttribute("class", "bluecell");
                mainIndexChangeDiv.setAttribute("className", "bluecell");
            }
            else if (change < m_MainIndexPreviousChange) {
                //current change lower
                mainIndexChangeDiv.setAttribute("class", "redcell");
                mainIndexChangeDiv.setAttribute("className", "redcell");
            }
            else {
                //no change
                mainIndexChangeDiv.removeAttribute("class");
                mainIndexChangeDiv.removeAttribute("className");
            }
        }
    }
    m_MainIndexPreviousChange = change;

    var mainIndexPercentageChangeDiv = document.getElementById("MainIndexPercentageChangeDiv");
    //get previous value on percentage change if this is the first time UpdateMainIndex is called:
    if (m_MainIndexPreviousPercentageChange == null) {
        str = mainIndexPercentageChangeDiv.innerHTML;
        str = str.replace(/%/, ""); //remove %
        if (str.replace(/-/, "").length > 0) {
            //previous percentagechange is not empty - can cast it to a Number
            m_MainIndexPreviousPercentageChange = new Number(str.replace(",", "."));
        }
    }
    textContext = document.createTextNode(result.PercentageChange + "%");
    mainIndexPercentageChangeDiv.removeChild(mainIndexPercentageChangeDiv.firstChild);
    mainIndexPercentageChangeDiv.appendChild(textContext);

    str = result.PercentageChange;
    var percentageChange = null;

    if (str.replace(/-/, "").length > 0) {
        //change is not empty - can cast it to a Number
        percentageChange = new Number(str.replace(",", "."));
        if (m_MainIndexPreviousPercentageChange != null) {
            if (percentageChange > m_MainIndexPreviousPercentageChange) {
                //current change higher
                mainIndexPercentageChangeDiv.setAttribute("class", "bluecell");
                mainIndexPercentageChangeDiv.setAttribute("className", "bluecell");
            }
            else if (percentageChange < m_MainIndexPreviousPercentageChange) {
                //current change lower
                mainIndexPercentageChangeDiv.setAttribute("class", "redcell");
                mainIndexPercentageChangeDiv.setAttribute("className", "redcell");
            }
            else {
                //no change
                mainIndexPercentageChangeDiv.removeAttribute("class");
                mainIndexPercentageChangeDiv.removeAttribute("className");
            }
        }
    }
    m_MainIndexPreviousPercentageChange = percentageChange;

    setTimeout("ClearMarketOverviewFlashElements()", 1000);
}

function ClearMarketOverviewFlashElements() {
    //clear flashing in MainIndexLastDiv                  
    var mainIndexLastDiv = document.getElementById("MainIndexLastDiv");
    mainIndexLastDiv.removeAttribute("class");
    mainIndexLastDiv.removeAttribute("className");

    //clear flashing in MainIndexChangeDiv.
    var mainIndexChangeDiv = document.getElementById("MainIndexChangeDiv");
    mainIndexChangeDiv.removeAttribute("class");
    mainIndexChangeDiv.removeAttribute("className");

    //clear flashing in MainIndexPercentageChangeDiv
    var mainIndexPercentageChangeDiv = document.getElementById("MainIndexPercentageChangeDiv");
    mainIndexPercentageChangeDiv.removeAttribute("class");
    mainIndexPercentageChangeDiv.removeAttribute("className");
}



