﻿
var m_InstrumentInfoTimerInterval = 5000;
var m_OrderbookTable;
var m_OrderbookTableBody;
var m_OrderbookDiv;

var m_PerformanceDiv;
var m_PerformanceTable;
var m_PerformanceTableBody;

var m_TradesDiv;
var m_TradesTable;
var m_TradesTableBody;

var m_MaxOrderbookQuantity = 0;

var m_MobileVersion = false;

function InitializeInstrumentInfoTimer(mobileVersion) {
    m_MobileVersion = mobileVersion;
    setTimeout("GetInstrumentInfoDataFromInstrumentInfoService()", m_InstrumentInfoTimerInterval);
}

function GetInstrumentInfoDataFromInstrumentInfoService() {
    try {        
        var qs = new Querystring();
        var id = qs.get("id");

        var quoteService = new Marketmind.Web.Stocklink.Services.QuoteService();
        //get data from service

        quoteService.GetInstrumentData(id, OnInstrumentInfoSucceededCallback, OnInstrumentInfoFailedCallback, null);
        setTimeout("GetInstrumentInfoDataFromInstrumentInfoService()", m_InstrumentInfoTimerInterval);
    }
    catch (e) {
        //TODO                     
    }
}

function OnInstrumentInfoFailedCallback() {
    //TODO
}

function OnInstrumentInfoSucceededCallback(e) {
    try {           
        if (e.toString().length > 0) {
            //deserialize json string from service
            var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
            SetMainInstrumentInfoEntry(result.MainInstrumentInfoEntry);
            SetOrderbook(result.Bids, result.Asks, result.OrderbookSummaryEntry);
            if (!m_MobileVersion) {
                SetInstrumentPerformance(result.PerformanceEntries);
                SetInstrumentTrades(result.TradeEntries);
            }                        
        }
    }
    catch (exception) {
        //TODO
    }
}

function CalculateGraphWidth(noOfOrderbookEntriesToShow, bids, asks, bidGraphWidthArray, askGraphWidthArray) {
    
    var graphDefaultWidth;
    var graphMaxWidth;
    var graphMinWidth;

    if (m_MobileVersion) {
        graphDefaultWidth = 45;
        graphMaxWidth = 50;
        graphMinWidth = 40;
    }
    else {
        graphDefaultWidth = 90;
        graphMaxWidth = 100;
        graphMinWidth = 80;
    }              

    var currentGraphMaxWidth = 0;

    var regExp = /\D+/; //Removing non digit characters

    var tempAskGraphWidthArray = []; //need these as a workaround. Can only assign a value to a given index\position in js array once - the first assignment counts.
    var tempBidGraphWidhtArray = []; //need these as a workaround. Can only assign a value to a given index\position in js array once - the first assignment counts.

    if (m_MaxOrderbookQuantity == 0) {
        var tempQuantity = 0.0;
        for (var i = 0; i < noOfOrderbookEntriesToShow; i++) {
            tempQuantity = parseFloat(bids[i].Quantity.replace(regExp, ''));
            if(!isNaN(tempQuantity)){
                if (m_MaxOrderbookQuantity < tempQuantity) {
                    m_MaxOrderbookQuantity = tempQuantity;
                }
            }
            tempQuantity = parseFloat(asks[i].Quantity.replace(regExp, ''));
            if(!isNaN(tempQuantity)){
                if (m_MaxOrderbookQuantity < tempQuantity) {
                    m_MaxOrderbookQuantity = tempQuantity;
                }
            }
                       
        }
    }

    for (var i = 0; i < noOfOrderbookEntriesToShow; i++) {
        //calculate bid graph width
        var bidQuantity = parseFloat(bids[i].Quantity.replace(regExp, ''));
        if (isNaN(bidQuantity)) {
            tempBidGraphWidhtArray[i] = 0;
        }
        else {
            tempBidGraphWidhtArray[i] = Math.round((bidQuantity / m_MaxOrderbookQuantity) * graphDefaultWidth);
        }
        
        if (currentGraphMaxWidth < tempBidGraphWidhtArray[i]) {
            currentGraphMaxWidth = tempBidGraphWidhtArray[i];
        }

        //calculate ask graph width
        var askQuantity = parseFloat(asks[i].Quantity.replace(regExp, ''));
        if (isNaN(askQuantity)) {
            tempAskGraphWidthArray[i] = 0;
        }
        else {
            tempAskGraphWidthArray[i] = Math.round((askQuantity / m_MaxOrderbookQuantity) * graphDefaultWidth);
        }
        
        if (currentGraphMaxWidth < tempAskGraphWidthArray[i]) {
            currentGraphMaxWidth = tempAskGraphWidthArray[i];
        }

    }

    if (currentGraphMaxWidth < graphMinWidth || currentGraphMaxWidth > graphMaxWidth) {
        m_MaxOrderbookQuantity = 0; //causes the next run in CalculateGraphWidth to recalculate the m_MaxOrderbookQuantity -> will make the longest graph have value of 90 px.
        CalculateGraphWidth(noOfOrderbookEntriesToShow, bids, asks, bidGraphWidthArray, askGraphWidthArray);
    }
    else {
        for (var j = 0; j < tempBidGraphWidhtArray.length; j++) {
            bidGraphWidthArray[j] = tempBidGraphWidhtArray[j];
            askGraphWidthArray[j] = tempAskGraphWidthArray[j];
        }
    }
}

function SetOrderbook(bids, asks, orderbookSummaryEntry) {

    ClearOrderbookTable();

    var row;
    var cell;
    var txtContent;
    var imgElement;

    var bidGraphWidthArray = [];
    var askGraphWidthArray = [];
    
    var noOfOrderbookEntriesToShow = 5;

    if (bids.length < 5 && asks.length < 5) {
        if (bids.length > asks.length) {
            noOfOrderbookEntriesToShow = bids.length;
        }
        else {
            noOfOrderbookEntriesToShow = asks.length;
        }
    }
    
    //calculating width of each bid and ask graph
    CalculateGraphWidth(noOfOrderbookEntriesToShow, bids, asks, bidGraphWidthArray, askGraphWidthArray);

    for (var i = 0; i < noOfOrderbookEntriesToShow; i++) {
        row = document.createElement("tr");

        //bid Quantity
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(bids[i].Quantity);    
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //bid price
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(bids[i].Price);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //bid graph
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        imgElement = document.createElement("img");
        imgElement.setAttribute("src", "/images/bluepixel.gif");
        imgElement.setAttribute("width", bidGraphWidthArray[i].toString());
        imgElement.setAttribute("height", "10");
        cell.appendChild(imgElement);
        row.appendChild(cell);

        //ask graph
        cell = document.createElement("td");
        cell.setAttribute("align", "left");
        imgElement = document.createElement("img");
        imgElement.setAttribute("src", "/images/redpixel.gif");
        imgElement.setAttribute("width", askGraphWidthArray[i].toString());
        imgElement.setAttribute("height", "10");
        cell.appendChild(imgElement);
        row.appendChild(cell);

        //ask price
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(asks[i].Price);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //ask quantity
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(asks[i].Quantity);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        m_OrderbookTableBody.appendChild(row);
    }

    //add separator between orderbook graphs and summary
    row = document.createElement("tr");
    cell = document.createElement("td");
    cell.colSpan = 6;
    imgElement = document.createElement("img");
    imgElement.setAttribute("src", "/images/blackpixel.gif");
    imgElement.setAttribute("width", "100%"); //OPERA - FF etc compatible
    imgElement.style.width = "100%"; //IE
    imgElement.setAttribute("height", "3");
    cell.appendChild(imgElement);
    row.appendChild(cell);
    m_OrderbookTableBody.appendChild(row);

    ////////////////////////////////////////////////////////////////////////////
    //add summary:
    row = document.createElement("tr");
    //totalBidQuantity
    cell = document.createElement("td");
    cell.setAttribute("align", "right");
    txtContent = document.createTextNode(orderbookSummaryEntry.TotalBidQuantity);
    cell.appendChild(txtContent);
    row.appendChild(cell);

    //ratio
    cell = document.createElement("td");
    cell.setAttribute("align", "center");
    cell.colSpan = 4;
    txtContent = document.createTextNode("Ratio: " + orderbookSummaryEntry.Ratio);
    cell.appendChild(txtContent);
    row.appendChild(cell);

    //totalAskQuantity
    cell = document.createElement("td");
    cell.setAttribute("align", "right");
    txtContent = document.createTextNode(orderbookSummaryEntry.TotalAskQuantity);
    cell.appendChild(txtContent);
    row.appendChild(cell);

    m_OrderbookTableBody.appendChild(row);
    ////////////////////////////////////////////////////////////////////////////

}

function ClearOrderbookTable() {
    //find div containing orderbook table
    m_OrderbookDiv = document.getElementById("OrderbookDiv");
    CleanElement(m_OrderbookDiv); //need to remove all text children nodes from MostActiveDiv

    //finding table
    m_OrderbookTable = m_OrderbookDiv.firstChild;
    CleanElement(m_OrderbookTable);  //need to remove all text children nodes from mostActiveTable

    //finding table body
    m_OrderbookTableBody = m_OrderbookTable.firstChild;
    CleanElement(m_OrderbookTableBody); //need to remove all text children nodes from mostActiveTableBody

    //remove all rows apart from header
    while (m_OrderbookTableBody.childNodes.length > 1) {
        m_OrderbookTableBody.removeChild(m_OrderbookTableBody.lastChild);
    }
}

function SetMainInstrumentInfoEntry(result) {
    //find elements - give them new values\textnodes
    var textContext;

    //QuotesUpdatedTime
    var quotesUpdatedTimeDiv = document.getElementById("QuotesUpdatedTimeDiv");
    if (m_MobileVersion) {
        textContext = document.createTextNode("Sist oppdatert: " + result.MobileFormattedUpdatedTime);
    }
    else {
        textContext = document.createTextNode("Sist oppdatert: " + result.UpdatedTime);
    }
    quotesUpdatedTimeDiv.removeChild(quotesUpdatedTimeDiv.firstChild);
    quotesUpdatedTimeDiv.appendChild(textContext);

    //Last
    var lastDiv = document.getElementById("LastDiv");
    textContext = document.createTextNode(result.Last);
    lastDiv.removeChild(lastDiv.firstChild);
    lastDiv.appendChild(textContext);

    //Change
    var changeDiv = document.getElementById("ChangeDiv");
    if (changeDiv != null) {
        textContext = document.createTextNode(result.Change);
        changeDiv.removeChild(changeDiv.firstChild);
        changeDiv.appendChild(textContext);
    }

    //DirectionLink
    var directionLinkDiv = document.getElementById("DirectionLinkDiv");
    directionLinkDiv.innerHTML = result.DirectionLink;

    //PercentageChange
    var percentageChangeDiv = document.getElementById("PercentageChangeDiv");
    textContext = document.createTextNode(result.PercentageChange + "%");
    percentageChangeDiv.removeChild(percentageChangeDiv.firstChild);
    percentageChangeDiv.appendChild(textContext);

    //Bid
    var bidDiv = document.getElementById("BidDiv");
    textContext = document.createTextNode(result.Bid);
    bidDiv.removeChild(bidDiv.firstChild);
    bidDiv.appendChild(textContext);

    //Ask
    var askDiv = document.getElementById("AskDiv");
    textContext = document.createTextNode(result.Ask);
    askDiv.removeChild(askDiv.firstChild);
    askDiv.appendChild(textContext);
    

    //High
    var highDiv = document.getElementById("HighDiv");    
    textContext = document.createTextNode(result.High);
    highDiv.removeChild(highDiv.firstChild);
    highDiv.appendChild(textContext);
    

    //Low
    var lowDiv = document.getElementById("LowDiv");
    textContext = document.createTextNode(result.Low);
    lowDiv.removeChild(lowDiv.firstChild);
    lowDiv.appendChild(textContext);

    //Volume
    var volumeDiv = document.getElementById("VolumeDiv");
    textContext = document.createTextNode(result.Volume);
    volumeDiv.removeChild(volumeDiv.firstChild);
    volumeDiv.appendChild(textContext);

    //Turnover
    var turnoverDiv = document.getElementById("TurnoverDiv");
    if (turnoverDiv != null) {
        textContext = document.createTextNode(result.Turnover);
        turnoverDiv.removeChild(turnoverDiv.firstChild);
        turnoverDiv.appendChild(textContext);
    }
}

function SetInstrumentPerformance(performanceEntries) {
    ClearPerformanceTable();

    var row;
    var cell;
    var imgElement;
    var txtContent;
    var modCheck;

    for (var i = 0; i < performanceEntries.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");
        }

        //Period Quantity
        cell = document.createElement("td");
        cell.setAttribute("align", "left");
        //cell.setAttribute("nowrap", "nowrap");
        txtContent = document.createTextNode(performanceEntries[i].Period);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //High
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(performanceEntries[i].High);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //Low
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(performanceEntries[i].Low);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //Close
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(performanceEntries[i].Close);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //Change
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(performanceEntries[i].Change);
        cell.appendChild(txtContent);
        row.appendChild(cell);

        //DirectionLink
        cell = document.createElement("td");
        cell.setAttribute("valign", "top");
        cell.setAttribute("style", "padding:0; text-align:center; vertical-align:top;");

        if (performanceEntries[i].DirectionLink != "") {
            imgElement = document.createElement("img");
            imgElement.setAttribute("src", performanceEntries[i].DirectionLink);
            imgElement.setAttribute("alt", "directionUp");
            imgElement.setAttribute("width", "9");
            imgElement.setAttribute("height", "15");
            cell.appendChild(imgElement);
        }
        else {
            cell.innerHTML = "";
        }
               
        row.appendChild(cell);

        //PercentageChange
        cell = document.createElement("td");
        cell.setAttribute("align", "right");
        txtContent = document.createTextNode(performanceEntries[i].PercentageChange + "%");
        cell.appendChild(txtContent);
        row.appendChild(cell);

        m_PerformanceTableBody.appendChild(row);
    }
}

function ClearPerformanceTable() {
    //find div containing performace table
    m_PerformanceDiv = document.getElementById("PerformanceDiv");
    CleanElement(m_PerformanceDiv); //need to remove all text children nodes from MostActiveDiv

    //finding table
    m_PerformanceTable = m_PerformanceDiv.firstChild;
    CleanElement(m_PerformanceTable);  //need to remove all text children nodes from mostActiveTable

    //finding table body
    m_PerformanceTableBody = m_PerformanceTable.firstChild;
    CleanElement(m_PerformanceTableBody); //need to remove all text children nodes from mostActiveTableBody

    //remove all rows apart from header
    while (m_PerformanceTableBody.childNodes.length > 1) {
        m_PerformanceTableBody.removeChild(m_PerformanceTableBody.lastChild);
    }
}

function SetInstrumentTrades(tradeEntries) {
    ClearTradesTable();

    var row;
    var cell;
    var txtContent;
    var modCheck;

    if (tradeEntries.length == 0) {
        row = document.createElement("tr");
        //Buyer 
        cell = document.createElement("td");
        cell.setAttribute("align", "left");
        cell.setAttribute("colspan", "5");
        cell.colSpan = 5; //IE
        var iElement = document.createElement("i");
        txtContent = document.createTextNode("Ingen handler i listen.");
        iElement.appendChild(txtContent);
        cell.appendChild(iElement);
        row.appendChild(cell);

        m_TradesTableBody.appendChild(row);
    }
    else {
        for (var i = 0; i < tradeEntries.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");
            }

            //Buyer 
            cell = document.createElement("td");
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(tradeEntries[i].Buyer);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            //Seller 
            cell = document.createElement("td");
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(tradeEntries[i].Seller);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            //Price
            cell = document.createElement("td");
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(tradeEntries[i].Price);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            //Volume/Quantity
            cell = document.createElement("td");
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(tradeEntries[i].Volume);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            //Time
            cell = document.createElement("td");
            cell.setAttribute("align", "right");
            txtContent = document.createTextNode(tradeEntries[i].Time);
            cell.appendChild(txtContent);
            row.appendChild(cell);

            m_TradesTableBody.appendChild(row);
        }
    }
}

function ClearTradesTable() {
    m_TradesDiv = document.getElementById("TradesDiv");
    CleanElement(m_TradesDiv);

    m_TradesTable = m_TradesDiv.firstChild;
    CleanElement(m_TradesTable);

    m_TradesTableBody = m_TradesTable.firstChild;
    CleanElement(m_TradesTableBody);

    //remove all rows apart from header
    while (m_TradesTableBody.childNodes.length > 1) {
        m_TradesTableBody.removeChild(m_TradesTableBody.lastChild);
    }
}



function CleanElement(element) {
    if (element == null) return 0;
    var node = element.firstChild;
    while (node != null) {
        var tmp = node.nextSibling;
        if (node.nodeName == '#text') {
            element.removeChild(node);
        }
        node = tmp;
    }
}            
