﻿/// <reference path="~/scripts/main.js" />

/** row looks **/

var ATTR_ROW_STYLE = "EZStyle";
var ROW_REGULAR = 1;
var ROW_EXPIRING_DISABLED = 2;
var ROW_EXPIRING_SOON = 3;
var ROW_EXPIRED = 4;
var ROW_NOT_OPEN = 5;
var ROW_RATE_ESTABLISHED = 6;
var ROW_RATE_INVALID = 7;
var ROW_RATE_INVALID_LASTMIN = 8;
var ROW_RATE_INVALID_LOCKED = 9;
var ROW_SUSPENDED = 10;
var ROW_SUSPENDED_INVALID = 11;
var SELECTED_ICON_CLASS_PREFIX = "sel1_";
var BUTTON_CALL_FUNCTION = "StartInvestment($(this).parent().parent(),'call')"
var BUTTON_PUT_FUNCTION = "StartInvestment($(this).parent().parent(),'put')"
var TAB_OFF_CLASS = "smallTab_off";
var TAB_ON_CLASS = "smallTab_on";
var TAB_OVER_CLASS = "smallTab_over";
var STATE_DIV_BASE_CLASS = "size6";
var STATE_DIV_LAST_MIN_CLASS = "redclock";
var STATE_DIV_LOCKED_CLASS = "lock";
var STATE_DIV_ESTABALISHED_CLASS = "bell";
var STATE_DIV_ESTABALISHING_CLASS = "sand";
var STATE_DIV_UPDATING_CLASS = "Updating";
var MARKET_IMAGE_CLASS = "marketImage";
var CURRENT_QUOTE_TYPE = "currP";
var CALL_QUOTE_TYPE = "callP";
var PUT_QUOTE_TYPE = "putP";
var DELAY_QUOTE_TYPE = "delayP";
var INVESTMENTBOX_ID = "InvestmentBox";
var ReutersSessionId = null;
var m_firstTimeLoad = true;
var m_alterIndicator = 1;
var m_alternateRunning = false;
IS_TRADING_AREA = true;
var HIGH_BID_LIMIT = 300;
var USMARKETS = "NYSE;NASDAQ;CBOE;";
var LS_CMD_UPDATE = 'UPDATE';
var LS_CMD_ADD = 'ADD';
var LS_TABLE_CLASS = 'LsTable';

var MultiLang = {
    StatusLocked: 'Locked',
    StatusLastCall: 'Last Call!',
    StatusExpired: 'Expired',
    StatusExipring: 'Expiring',
    StatusOpening: 'Opening',
    StatusEstablishingRate: 'Establishing Rate',
    StatusRateEstablished: 'Rate Established',
    NoNews: 'No news found',
    TodayString: 'Today',
    TomorrowString: 'Tomorrow',
    LocalString: 'local',
    ChartLogin: "Please <u><a href='javascript:showSignInDialog()' >log in</a></u><br/>to view option chart",
    ChartLoading: "<b>Loading</b>"
}


LsOptionsTable = function(type, object) {

    object.hide();
    this.jObject = object;
    this.OptionsCount = 0;
    this.Type = type;
    this.Hide = function() {
        this.jObject.hide();
    };
    this.Show = function() {
        this.jObject.show();
    };

};
function DocReady() {
    $("." + TAB_OFF_CLASS).click(changeCategory);
    //    $("." + TAB_OFF_CLASS).mouseenter(onCategoryOver);
    //    $("." + TAB_OFF_CLASS).mouseleave(onCategoryOut);
    startNewsTicker();
    FillMultiLanguage();
    
    setTimeout("checkTradingEnabled()", 10000); /*** Enable/Disable trading ***/
    if (loggedIn) GetOpenTrades();
}
function checkTradingEnabled() {
    TradingService.checkTradingEnabled(checkTradingCallBack);
    setTimeout("checkTradingEnabled()", 10000);
}
function checkTradingCallBack(isEnabled) {
    if (isEnabled != isTradingEnabled) {
        window.location.reload(true)
    }
}
function FillMultiLanguage() {
    TradingService.GetTradingMessages(function(result) { MultiLang = result; });
}

function onCategoryOver() {


    $(this).removeClass(TAB_OFF_CLASS).removeClass(TAB_ON_CLASS).addClass(TAB_OVER_CLASS);

}
function onCategoryOut() {


    $(this).removeClass(TAB_OVER_CLASS).removeClass(TAB_ON_CLASS).addClass(TAB_OFF_CLASS);

}

function changeCategory() {


    var catTab = $(this);
    catTab.addClass("tabClicked");
    var DivOptions = $('#optionsWrapper');
    var DivLoading = $('#divLoadingLine');
    //    catTab.unbind('mouseenter', onCategoryOver);
    //    catTab.unbind('mouseleave', onCategoryOut);
    var catName = catTab.find('#catName').html();
    var prevCatTab = $("." + TAB_ON_CLASS);
    var id = catTab.attr('categoryID');
    catTab.unbind('click');
    catTab.removeClass(TAB_OFF_CLASS).removeClass(TAB_OVER_CLASS).addClass(TAB_ON_CLASS);
    prevCatTab.click(changeCategory);
    //    prevCatTab.mouseenter(onCategoryOver);
    //    prevCatTab.mouseenter(onCategoryOut);
    prevCatTab.removeClass(TAB_ON_CLASS).removeClass(TAB_OVER_CLASS).addClass(TAB_OFF_CLASS);
    m_firstTimeLoad = true;
    if (DivOptions.css('display') != 'none') {
        $('#optionsWrapper').hide('slide', { direction: 'right' }, 500, function() {

            DivLoading.show().find('b').html(catName);
            setCategoryTable(id);

        });
    }
    else {

        DivLoading.show().find('b').html(catName);
        setCategoryTable(id);
    }
    RemoveAllHighBids();

}

function SetLoggedInRates() {

    var DivOptions = $('#optionsWrapper');
    var DivLoading = $('#divLoadingLine');


    if (DivOptions.css('display') != 'none') {
        DivOptions.hide('slide', { direction: 'right' }, 500, function() {
            DivLoading.show();
            DivOptions.find("#optionRow").each(function() {
                var optionPanel = $(this);
                var investmentSpan = GetInvestmentSpan(optionPanel);
                if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan)
                else ShowQuote(GetQuoteSpan(optionPanel), CURRENT_QUOTE_TYPE);
            });
        });
    }
    else {
        DivLoading.show();
    }
    m_firstTimeLoad = true;

}

function AlternateRows() {
    var optionsWrapper = $('optionsWrapper');
    for (var i = 0; i < optionsWrapper.childNodes.length; i++) {
        var row = optionsWrapper.childNodes[i];
        if (row.className != undefined && row.className.substring(0, 17) == "tradeEntryWrapper") {
            if (m_alterIndicator < 0) {
                ChangeClass(row, "tradeEntryWrapper");
            }
            else {
                ChangeClass(row, "tradeEntryWrapperAlt");
            }
            m_alterIndicator *= -1;
        }
    }

    m_alternateRunning = false;
}

function formatValues(item, itemUpdate) {
    try {

        //item is the dom object of the entire line
        if (itemUpdate == null) {
            return;
        }
        window.status = "EZTrader.com!";
        if (m_firstTimeLoad) {
            //make the "loading..." line disappear
            m_firstTimeLoad = false;
            $('#divLoadingLine').hide('slide', { direction: 'right' }, 500, function() {
                $('#optionsWrapper').show('slide', { direction: 'up' }, 1000);
            });
        }

        var cmd = itemUpdate.getServerValue(2);
        var jqItem = $(item);
        if (jqItem.hasClass(LS_TABLE_CLASS)) {

            jqItem.removeClass(LS_TABLE_CLASS);
            //var option = new LsOptionsTable('w', open);
            var iType = itemUpdate.getServerValue(17);
            var tbl = OptionsTables.GetItem(iType);
            tbl.OptionsCount++;
            if (tbl.OptionsCount == 1) tbl.Show()
            else if (tbl.OptionsCount < 1) tbl.Hide()
        }
        
        
        
        var innerOptionPanel = $(item).find(".row");


        //flickering the stock upon change
        itemUpdate.setHotTime(500);
        itemUpdate.setStyle(4, "currentHot", "");
        itemUpdate.setStyle(20, "currentHot", "");
        itemUpdate.setStyle(18, "currentHot", "");
        itemUpdate.setStyle(19, "currentHot", "");
        itemUpdate.setStyle(5, "winReturnPrecHot", "winReturnPrec");

        //changing the quote color based on server decision
        GetQuoteWrapper(innerOptionPanel).css("color", itemUpdate.getServerValue(10));

        //update link to charts
        GetStockLink(innerOptionPanel).href = 'ExternalNews.aspx?O=' + itemUpdate.getServerValue(1);

        //update stock name
        var investmentSpan = GetInvestmentSpan(innerOptionPanel);
        var isInvetstmentClosed = investmentSpan.css("display") == 'none';
        var fullName = itemUpdate.getServerValue(13);
        investmentSpan.find(".StockName").html(fullName);


        //stock open?
        var biddingState = itemUpdate.getServerValue(12);
        var expirationTime = itemUpdate.getServerValue(7);

        //biddingState = 1;

        //**change the look based on how far we are from expiration
        var secondsLeftToNoMoreBids = Math.floor(itemUpdate.getServerValue(8));
        var secondsLeftToExpiration = Math.floor(itemUpdate.getServerValue(9));
        var closingPrice = Math.floor(itemUpdate.getServerValue(14));
        var currentPrice = itemUpdate.getServerValue(4);
       


        if (biddingState != 3 && investmentSpan.css("display") != 'none') UpdateChart(itemUpdate.getServerValue(1), innerOptionPanel, currentPrice);

        var isEstablishingRate = secondsLeftToExpiration <= 0 && closingPrice == 0;

        if (biddingState == "1" && isInvetstmentClosed && !isEstablishingRate) {

            var currentQuote = loggedIn ? CURRENT_QUOTE_TYPE : DELAY_QUOTE_TYPE;
            ShowQuote(GetQuoteSpan(innerOptionPanel), currentQuote);
        }

        //option suspended?
        var isSuspended = itemUpdate.getServerValue(21);


        var marketClass = itemUpdate.getServerValue(16);

        SetMarketImage(innerOptionPanel, marketClass);
        
//          var graphThumbImg = itemUpdate.getServerValue(17);

//        var graphDiv = GetGrafDiv(innerOptionPanel);

//        BindGraphs(graphDiv, graphImg, graphThumbImg);
        //get current row style
        var rowStyle = item.getAttribute(ATTR_ROW_STYLE);

        var market = itemUpdate.getServerValue(15);

        if (USMARKETS.indexOf(market) < 0) {
            var newsDiv = GetNewsDiv(innerOptionPanel);
            if (newsDiv.html() != '&nbsp;') newsDiv.html('&nbsp;');

        }

        if (biddingState == 2 || currentPrice.length == 0)   //stock not open
        {
            if (rowStyle != ROW_NOT_OPEN) {
                item.setAttribute(ATTR_ROW_STYLE, ROW_NOT_OPEN);
                MakeClosed(innerOptionPanel, itemUpdate.getServerValue(11));
            }
            else UpdateOpeningTime(innerOptionPanel, itemUpdate.getServerValue(11));
        }
        else if (secondsLeftToExpiration <= 0 && rowStyle != ROW_EXPIRED && closingPrice == 0) {
            //option expired - and we don't yet have the closing price
            item.setAttribute(ATTR_ROW_STYLE, ROW_EXPIRED);
            MakeExpiredEstablishingRate(innerOptionPanel);
        }
        else if (secondsLeftToExpiration <= 0 && rowStyle != ROW_RATE_ESTABLISHED && closingPrice > 0) {
            //rate established
            item.setAttribute(ATTR_ROW_STYLE, ROW_RATE_ESTABLISHED);
            MakeRateEstablished(innerOptionPanel);

        }
        else if (secondsLeftToNoMoreBids <= 0 && secondsLeftToExpiration > 0) {
            //no more bids - disabled
            if (biddingState != 3) {

                if (rowStyle != ROW_EXPIRING_DISABLED) {
                    item.setAttribute(ATTR_ROW_STYLE, ROW_EXPIRING_DISABLED);
                    MakeLocked(innerOptionPanel, secondsLeftToExpiration);
                }
                else UpdateCountdown(innerOptionPanel, secondsLeftToNoMoreBids);
            }
            else if (rowStyle != ROW_RATE_INVALID_LOCKED) {
                item.setAttribute(ATTR_ROW_STYLE, ROW_RATE_INVALID_LOCKED);
                MakeRowRateInvaildLocked(innerOptionPanel, secondsLeftToExpiration);
            }
        }
        else if (secondsLeftToNoMoreBids > 0 && secondsLeftToNoMoreBids <= 300) {
            //last 5 minutes for bidding
            if (biddingState != 3) {

                if (isSuspended == "False") {

                    if (rowStyle != ROW_EXPIRING_SOON) {
                        item.setAttribute(ATTR_ROW_STYLE, ROW_EXPIRING_SOON);
                        MakeLastMinutes(innerOptionPanel, secondsLeftToNoMoreBids);
                    }
                    else UpdateCountdown(innerOptionPanel, secondsLeftToNoMoreBids);
                }
                else {
                    if (rowStyle != ROW_SUSPENDED) {

                        item.setAttribute(ATTR_ROW_STYLE, ROW_SUSPENDED);
                        MakeSuspended(innerOptionPanel);
                    }
                }
            }
            else {
                if (isSuspended == "False") {
                    if (rowStyle != ROW_RATE_INVALID_LASTMIN) {

                        item.setAttribute(ATTR_ROW_STYLE, ROW_RATE_INVALID_LASTMIN);
                        MakeRowRateInvaildLastMinutes(innerOptionPanel, secondsLeftToNoMoreBids);
                    };
                } else {
                    if (rowStyle != ROW_SUSPENDED_INVALID) {

                        item.setAttribute(ATTR_ROW_STYLE, ROW_SUSPENDED_INVALID);
                        MakeSuspendedInvalid(innerOptionPanel);
                    }
                }
            }
        }
        else if (secondsLeftToNoMoreBids > 300) {
            //regular bidding
            if (biddingState != 3) {

                if (isSuspended == "False") {
                    if (rowStyle != ROW_REGULAR) {
                        item.setAttribute(ATTR_ROW_STYLE, ROW_REGULAR);
                        MakeRegularBidding(innerOptionPanel, expirationTime);
                    }
                }
                else {
                    if (rowStyle != ROW_SUSPENDED) {

                        item.setAttribute(ATTR_ROW_STYLE, ROW_SUSPENDED);
                        MakeSuspended(innerOptionPanel);
                    }
                }
            }
            else {

                if (isSuspended == "False") {
                    if (rowStyle != ROW_RATE_INVALID) {
                        item.setAttribute(ATTR_ROW_STYLE, ROW_RATE_INVALID);
                        MakeRowRateInvaild(innerOptionPanel, expirationTime);
                    }
                }
                else {
                    if (rowStyle != ROW_SUSPENDED_INVALID) {

                        item.setAttribute(ATTR_ROW_STYLE, ROW_SUSPENDED_INVALID);
                        MakeSuspendedInvalid(innerOptionPanel);
                    }
                }
            }

        }
    }
    catch (ex) {
        //not raising any erros for now
    }
}
function ItemUpdate(itemPos, Info, name) {


    var cmd = Info.getNewValue(2);   
    if (cmd == 'DELETE') {
       
        var iType = Info.getNewValue(17);
        var tbl = OptionsTables.GetItem(iType);
        tbl.OptionsCount--;
        if (tbl.OptionsCount < 1) tbl.Hide();
    }
}


///Change panel look to no more bids, waiting for expiration
function MakeLocked(optionPanel, secondsToExpiration) {

    var investmentSpan = GetInvestmentSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    expireDiv.hide();
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).hide();
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).show();

    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.addClass(STATE_DIV_LOCKED_CLASS);
    state.html(MultiLang.StatusLocked);
    state.show();
    StartCountdown(optionPanel, secondsToExpiration);

    ToggleClose(optionPanel, false, null);

}

function MakeLastMinutes(optionPanel, secondsLeft) {
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    var state = GetStateDiv(optionPanel);
    expireDiv.hide();
    EnableButtons(callButton, putButton);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    ToggleClose(optionPanel, false, null);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).hide();
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).show();
    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LOCKED_CLASS);
    state.addClass(STATE_DIV_LAST_MIN_CLASS);
    state.html(MultiLang.StatusLastCall);
    state.show();
    StartCountdown(optionPanel, secondsLeft);
}

function MakeRegularBidding(optionPanel, expirationTime) {
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var newsDiv = GetNewsDiv(optionPanel);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    var expireDiv = GetExpirationDiv(optionPanel);
    expirationTime = FixTime(expirationTime);
    expireDiv.html(expirationTime);
    expireDiv.show();
    state.hide();
    newsDiv.show();
    EnableButtons(callButton, putButton);
    ToggleClose(optionPanel, false, null);

    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).hide();
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).show();

    });
}

var m_debug = false;
function MakeClosed(optionPanel, openingTime) {
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var investmentSpan = GetInvestmentSpan(optionPanel);
    var state = GetStateDiv(optionPanel);
    var newsDiv = GetNewsDiv(optionPanel);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();

    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);

    DisableButtons(callButton, putButton);

    ToggleClose(optionPanel, true, openingTime);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();

    });
    state.hide();
}

function MakeRateEstablished(optionPanel) {

    var timeLeft = GetTimeLeftSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var investmentSpan = GetInvestmentSpan(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    var expired = GetExpiredSpan(optionPanel);
    var graf = GetGrafDiv(optionPanel);
    var finalSpan = GetFinalSpan(optionPanel);
    var qoute = GetQuoteWrapper(optionPanel);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();

    //expireDiv.show();
    expireDiv.hide();
    timeLeft.hide();
    expired.removeClass('expiring');
    expired.addClass('expired');
    expired.html(MultiLang.StatusExpired);
    expired.show();


    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);

    ToggleClose(optionPanel, false, null);

    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).hide();
            $(this).removeClass(STATE_DIV_ESTABALISHING_CLASS);
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).show();

    });
    graf.hide();
    finalSpan.show();
    qoute.addClass("finalQuote");

    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.removeClass(STATE_DIV_LOCKED_CLASS);
    state.addClass(STATE_DIV_ESTABALISHED_CLASS);
    state.html(MultiLang.StatusRateEstablished);
    state.show();



}

function MakeExpiredEstablishingRate(optionPanel) {
    var timeLeft = GetTimeLeftSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var investmentSpan = GetInvestmentSpan(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    var expired = GetExpiredSpan(optionPanel);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();

    expireDiv.hide();
    timeLeft.hide();
    expired.addClass('expiring');
    expired.removeClass('expired');
    expired.html(MultiLang.StatusEstablishingRate);
    expired.show();
    //expired.hide();

    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);

    ToggleClose(optionPanel, false, null);

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.removeClass(STATE_DIV_LOCKED_CLASS);
    state.addClass(STATE_DIV_ESTABALISHING_CLASS);
    state.html(MultiLang.StatusEstablishingRate);
    state.show();

    //hide the quote, so that customers don't get confused.
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            //$(this).addClass(STATE_DIV_ESTABALISHING_CLASS);
            $(this).addClass(STATE_DIV_LAST_MIN_CLASS);
            $(this).addClass("mart20");
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();
    });

}
function MakeRowRateInvaild(optionPanel, expirationTime) {

    var callButton = GetCallImage(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var investmentSpan = GetInvestmentSpan(optionPanel);
    var newsDiv = GetNewsDiv(optionPanel);
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    expirationTime = FixTime(expirationTime);
    expireDiv.html(expirationTime);
    expireDiv.show();
    state.hide();
    newsDiv.show();
    DisableButtons(callButton, putButton);
    ToggleClose(optionPanel, false, null);

    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            $(this).addClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();

    });

    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);

}
function MakeRowRateInvaildLastMinutes(optionPanel, secondsLeft) {

    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    var state = GetStateDiv(optionPanel);
    expireDiv.hide();
    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    DisableButtons(callButton, putButton);

    ToggleClose(optionPanel, false, null);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            if (!$(this).hasClass(STATE_DIV_UPDATING_CLASS)) $(this).addClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();
    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LOCKED_CLASS);
    state.addClass(STATE_DIV_LAST_MIN_CLASS);
    state.html(MultiLang.StatusLastCall);
    state.show();
    StartCountdown(optionPanel, secondsLeft);
    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    ToggleClose(optionPanel, false, null);
}
function MakeRowRateInvaildLocked(optionPanel, secondsToExpiration) {

    var investmentSpan = GetInvestmentSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    expireDiv.hide();

    var suspendMsg = optionPanel.find(".SuspendMessage").hide();
    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            if (!$(this).hasClass(STATE_DIV_UPDATING_CLASS)) $(this).addClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();

    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.addClass(STATE_DIV_LOCKED_CLASS);
    state.html(MultiLang.StatusLocked);
    state.show();
    StartCountdown(optionPanel, secondsToExpiration);

    ToggleClose(optionPanel, false, null);
}

function MakeSuspended(optionPanel) {

    var investmentSpan = GetInvestmentSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    expireDiv.hide();

    var suspendMsg = optionPanel.find(".SuspendMessage").show();
    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).hide();
            $(this).removeClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).show();

    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.addClass(STATE_DIV_LOCKED_CLASS);
    state.html(MultiLang.StatusLocked);
    state.show();

    ToggleClose(optionPanel, false, null);
}
function MakeSuspendedInvalid(optionPanel) {


    var investmentSpan = GetInvestmentSpan(optionPanel);
    var callButton = GetCallImage(optionPanel);
    var putButton = GetPutImage(optionPanel);
    var state = GetStateDiv(optionPanel);
    var expireDiv = GetExpirationDiv(optionPanel);
    expireDiv.hide();

    var suspendMsg = optionPanel.find(".SuspendMessage").show();
    if (investmentSpan.css("display") != 'none') CloseInvestmentPanel(investmentSpan);
    DisableButtons(callButton, putButton);
    optionPanel.find(".size2").each(function() {
        if ($(this).hasClass("spacer")) {
            $(this).show();
            if (!$(this).hasClass(STATE_DIV_UPDATING_CLASS)) $(this).addClass(STATE_DIV_UPDATING_CLASS);
        }
        else $(this).hide();

    });

    state.removeClass(STATE_DIV_ESTABALISHED_CLASS);
    state.removeClass(STATE_DIV_ESTABALISHING_CLASS);
    state.removeClass(STATE_DIV_LAST_MIN_CLASS);
    state.addClass(STATE_DIV_LOCKED_CLASS);
    state.html(MultiLang.StatusLocked);
    state.show();
    StartCountdown(optionPanel, secondsToExpiration);

    ToggleClose(optionPanel, false, null);

}

function ToggleClose(optionPanel, closed, openingTime) {

    var closedDiv;
    var regularDisplay, closedDisplay;
    openingTime = FixTime(openingTime);
    if (closed) {

        //var amPm = openingTime.slice(openingTime.length - 2, openingTime.length);
        //openingTime = openingTime.slice(0, openingTime.length - 2);
        optionPanel.find(".expires").hide();
        optionPanel.find(".size4").hide();
        closedDiv = optionPanel.find(".Closed");
        closedDiv.show();
        closedDiv.find(".opening").html(MultiLang.StatusOpening + ":");
        closedDiv.find(".openTime").html(openingTime);
        //closedDiv.find(".AmPm").html(amPm);


    }
    else {

        optionPanel.find(".expires").show();
        optionPanel.find(".size4").show();
        closedDiv = optionPanel.find(".Closed");
        closedDiv.hide();
        closedDiv.find(".opening").empty();
        closedDiv.find(".openTime").empty();
        closedDiv.find(".AmPm").empty();


    }
}
function UpdateOpeningTime(optionPanel, openingTime) {

    var closedDiv = optionPanel.find(".Closed");
    openingTime = FixTime(openingTime);
    closedDiv.find(".opening").html(MultiLang.StatusOpening + ":");
    closedDiv.find(".openTime").html(openingTime);

}
function FixTime(time) {

    if (time != null) {
        var i = time.indexOf("Today");
        if (i >= 0) time = time.replace(/Today/, MultiLang.TodayString);
        i = time.indexOf("Tomorrow");
        if (i >= 0) time = time.replace(/Tomorrow/, MultiLang.TomorrowString);
        i = time.indexOf("local");
        if (i >= 0) time = time.replace(/local/, MultiLang.LocalString);
    }
    return time;
}

//Button enable/disable
function DisableButtons(callButton, putButton) {


    if (!callButton.hasClass("size3callDis")) {

        callButton.removeClass("size3call");
        callButton.addClass("size3callDis");
    }
    if (!putButton.hasClass("size3putDis")) {

        putButton.removeClass("size3put");
        putButton.addClass("size3putDis");
    }
    callButton.unbind('click');
    putButton.unbind('click');
}

function EnableButtons(callButton, putButton) {
    if (!callButton.hasClass("size3call")) {

        callButton.removeClass("size3callDis");
        callButton.addClass("size3call");
    }
    if (!putButton.hasClass("size3put")) {

        putButton.removeClass("size3putDis");
        putButton.addClass("size3put");
    }
    callButton.click(StartCallInvestment);
    putButton.click(StartPutInvestment);
}


///Starting a countdown in the option panel
function StartCountdown(optionPanel, time) {

    var countdownSpan = GetTimeLeftSpan(optionPanel);
    countdownSpan.show();
    $(countdownSpan).countdown('destroy')
    $(countdownSpan).countdown({ until: +time, compact: true,
        format: 'MS', description: ''
    });

}
///Starting a countdown in the option panel
function UpdateCountdown(optionPanel, time) {

    $(countdownSpan).countdown({ until: +time });
}

/** end of row look **/
function StartCallInvestment() {

    optionPanel = $(this).parent().parent();
    StartInvestment(optionPanel, 'call');
    if (loggedIn && TradingCallPutEnabled) ShowQuote(GetQuoteSpan(optionPanel), CALL_QUOTE_TYPE);

}
function StartPutInvestment() {

    optionPanel = $(this).parent().parent();
    StartInvestment(optionPanel, 'put');
    if (loggedIn && TradingCallPutEnabled) ShowQuote(GetQuoteSpan(optionPanel), PUT_QUOTE_TYPE);
}
function ShowQuote(quoteSpan, type) {

    $(quoteSpan).parent().children().each(function() {
        elem = $(this)
        if (elem.hasClass(type)) {
            if (!elem.hasClass("current")) elem.addClass("current");
        }
        else {
            if (elem.hasClass("current")) elem.removeClass("current");
        }

    });
}

function StartInvestment(optionPanel, option) {

    var investmentSpan = GetInvestmentSpan(optionPanel);
    optionPanel.attr("CurrentOption", option);
    investmentSpan.show('slide', { direction: 'up' }, 500, function() {

        var FlashVersion = getFlashVersion().split(',').shift();
        if (FlashVersion >= 9) intializeGraph(GetOptionId(investmentSpan), GetChartObjectContainer(investmentSpan));
        else GetFlashGetImage(investmentSpan).show();
        var inputInvestment = $(this).find('input')
        inputInvestment.focus();
        inputInvestment.val('');
        inputInvestment.keyup(function() {
            CalculateReturns(inputInvestment, option);
        });
        CalculateReturns(inputInvestment, option)

    })

    var imgCallPut = GetSelectedIcon(investmentSpan);
    var txtInvestment = GetInvestmentTextField(imgCallPut);
    var iconClass = SELECTED_ICON_CLASS_PREFIX + option;
    var stringInvestment = option.substr(0, 1).toUpperCase() + option.substr(1, option.length);
    if (!imgCallPut.hasClass(iconClass)) {
        imgCallPut.removeClass();
        imgCallPut.addClass(iconClass);
    }
}

function EndInvestment(optionPanel) {

    var investmentSpan = GetInvestmentSpan(optionPanel);
    CloseInvestmentPanel(investmentSpan);

}

function CloseInvestmentPanel(investmentSpan)//check
{
    var optionPanel = investmentSpan.parent().parent();
    investmentSpan.find('.close').find('img').attr('src', 'images/x_2.gif');
    var investmentBtn = investmentSpan.find(".ExecuteBtn");
    var investmentLoader = investmentSpan.find(".amountBoxLoader");
    investmentSpan.find("#chartNote").hide();
    var id = GetOptionId(optionPanel);
    RemoveHighBid(id);
    var currentQuote = loggedIn ? CURRENT_QUOTE_TYPE : DELAY_QUOTE_TYPE;
    var rowStyle = optionPanel.attr(ATTR_ROW_STYLE);
    ShowQuote(GetQuoteSpan(optionPanel), currentQuote);
    investmentSpan.hide('slide', { direction: 'up' }, 500, function() {
        var inputInvestment = $(this).find('input');
        ClearInvestmentForm(inputInvestment, investmentBtn, investmentLoader)

    })

}
function ClearInvestmentForm(inputInvestment, investmentBtn, investmentLoader) {


    inputInvestment.val("");
    CalculateReturns(inputInvestment, 'reset');
    inputInvestment.blur();
    investmentBtn.show();
    investmentLoader.hide();

}

function CalculateReturns(txtInvestment, option) {


    try {
        amount = txtInvestment.val();
        if (isNaN(amount)) throw "Not a number";
    }
    catch (ex) {
        txtInvestment.val("");
        return;
    }
    var spanInvest = txtInvestment;
    while (spanInvest.attr('id') != INVESTMENTBOX_ID) spanInvest = spanInvest.parent();
    var optionPanel = spanInvest.parent().parent();
    var price = GetCurrentQuote(optionPanel);
    var id = GetOptionId(optionPanel);
    var winReturn = parseInt(optionPanel.find(".winReturnPrec").html()) + 100;
    var lossReturn = parseInt(optionPanel.find(".lossReturnPrec").html());
    var winAmount = Math.round(amount * winReturn / 100);
    var loseAmount = Math.round(amount * lossReturn / 100);
    var winner, loser;

    var spanAbove = spanInvest.find(".priceAbove");
    var spanBelow = spanInvest.find(".priceBelow");

    switch (option) {
        case 'call':
            //above is the winner
            winner = spanAbove;
            loser = spanBelow;
            break;

        case 'put':
            //below is the winner
            loser = spanAbove;
            winner = spanBelow;
            break;
        case 'reset':
            loser = spanAbove;
            winner = spanBelow;
            winAmount = loseAmount = 0;
            break;       
    }

    winner.html(CurrentCurrency + winAmount);
    loser.html(CurrentCurrency + loseAmount);

    if (option != 'reset') {
        if (amount >= HIGH_BID_LIMIT && amount <= 1500) {
            FlagHighBid(id, amount, GetPutCall(optionPanel), price);
        }
        else {
            RemoveHighBid(id);
        }
    }
}

function IfEnterThenInvest(evt, txtField) {

    var spanInvest = $(txtField);
    while (spanInvest.attr('id') != INVESTMENTBOX_ID) spanInvest = spanInvest.parent();
    if (evt.keyCode == 13) {

        MakeInvestment(spanInvest.parent());
    }
}

var m_currentOptionPanel;
function MakeInvestment(investmentSpan) {


    var optionPanel = investmentSpan.parent();
    m_currentOptionPanel = optionPanel;
    var optionId = GetOptionId(investmentSpan);
    var amount = GetAmount(investmentSpan);
    var investmentBtn = investmentSpan.find(".ExecuteBtn");
    var investmentLoader = investmentSpan.find(".amountBoxLoader");
    

    if (!loggedIn) {
        displayStaticMessage(StaticMessagesTemplates.Alert, 'Please <a onclick="goToSignInDialog()" >Login</a>, in order to invest', 300, 150, 5);
    }
    else if (isNaN(amount) || amount.indexOf('.') >= 0) {
        displayStaticMessage(StaticMessagesTemplates.Alert, 'Please enter a whole amount (integer)', 300, 150, 5);
    }
    else if (amount < 30) {
    displayStaticMessage(StaticMessagesTemplates.Alert, 'Minimum investment amount is ' + CurrentCurrency + '30', 300, 150, 5);
    }
    else if (amount > 1500) {
    displayStaticMessage(StaticMessagesTemplates.Alert, 'Maximum investment amount is ' + CurrentCurrency +'1500', 300, 150, 5);
    }
    else {
        investmentBtn.hide();
        investmentLoader.show();
        if (amount >= HIGH_BID_LIMIT) TradingService.UpdateBidPrice(optionId, GetCurrentQuote(optionPanel));
        var result = TradingService.MakeInvestment(amount, GetPutCall(optionPanel), optionId, GetCurrentQuote(optionPanel), TradingCallPutEnabled, InvestmentCallSuccess, InvestmentFailure);
    }
}
function goToSignInDialog() {
    closeStaticMessage();
    showSignInDialog();
}

//This method handles the return of the MakeInvestment webmethod. Due to a screwup on M$ part it has to handle both success in investing,
//and failures. See here: http://www.chrisbellini.com/2008/06/24/you-need-to-communicate-more/
function InvestmentCallSuccess(results, userContext, methodName) {

    
    var ALLOWED_INSTANCES = 4;
    var optionPanel = m_currentOptionPanel;
    var optionId = GetOptionId(optionPanel);
    var invsetmentSpan = GetInvestmentSpan(optionPanel);
    var investmentBtn = invsetmentSpan.find(".ExecuteBtn");
    var investmentLoader = invsetmentSpan.find(".amountBoxLoader");
    var inputInvestment = invsetmentSpan.find("input");

    if (results.indexOf("success") == 0) {
        var strike = GetStrikeData(results);
        addStrikeToChart(optionPanel, optionId, strike); 
        RefreshMyTrades();
        RefreshBalance();
        if (amount >= HIGH_BID_LIMIT) FlagHighBidSubmitted(optionId);
        ClearInvestmentForm(inputInvestment, investmentBtn, investmentLoader);
        var countTransactions = Math.floor(results.split(";")[1]) + 1;
        var transactionsLeft = ALLOWED_INSTANCES - countTransactions;
        if (countTransactions == 2) {
            var msg = 'Transaction performed successfully. Please note that you can own up to ' + ALLOWED_INSTANCES.toString() + ' instances of the same option, hence you can acquire this same option ' +
                    countTransactions.toString() + ' more time';
            if (transactionsLeft > 1) msg += "s";    //s for times
            displayStaticMessage(StaticMessagesTemplates.Success, msg, 350, 200, 5);
        }
        else {

            var msg = 'Transaction performed successfully';
            displayStaticMessage(StaticMessagesTemplates.Success, msg, 300, 150, 5);
        }
    }
    else {

        if (results.indexOf("disabled") >= 0) ShowDeactivatedMessage();
        displayStaticMessage(StaticMessagesTemplates.Alert, results, 300, 150, 5);
        investmentLoader.hide();
        investmentBtn.show();
        
    }

    m_currentOptionPanel = null;
}

StrikeObject=function(Value,Time,Type){

    this.value = Value;
    this.color= (Type=="Call") ? 0x0D8C05 : 0xA51009;
    this.time=Time;
    this.type=Type 

}

function GetStrikeData(results) {


    var data = results.split(';');
    var strike = new StrikeObject(parseFloat(data[2]), parseInt(data[3], 10), data[4]);

    return strike;
    

}


function SetMarketImage(innerOptionPanel, marketClass) {

    var dvStockName = innerOptionPanel.find(".StockName");
    if (!dvStockName.hasClass(MARKET_IMAGE_CLASS)) {

        dvStockName.addClass(MARKET_IMAGE_CLASS);
        dvStockName.addClass(marketClass); 
    }
    
    

}

function ToggleNews(obj) {

    var btn = $(obj);
    var newsDiv = btn.next();



    if (newsDiv.css("display") != 'none') {
        newsDiv.hide();
    }
    else {
        newsDiv.show();
        var optionPanel = btn.parent().parent();
        var investmentSpan = GetInvestmentSpan(optionPanel)
        var optionId = GetOptionId(investmentSpan);
        var successReturn = function(results, userContext, methodName) {
            if (results.length > 0) {
                newsDiv.html(results);
            }
            else {
                newsDiv.html(MultiLang.NoNews);
            }
        }

        var failureReturn = function GetNewsFailure(err) {
            newsDiv.html(err);
        }

        TradingService.GetNewsForIndex(optionId, successReturn, failureReturn);
    }
}

function onCloseOut(obj) {

    $(obj).find('img').attr('src', 'images/x_2.gif');
}
function onCloseOver(obj) {

    $(obj).find('img').attr('src', 'images/x_2_over.gif');
}

function InvestmentFailure(error) {

    displayStaticMessage(StaticMessagesTemplates.Alert, error.get_message(), 300, 150, 5);
    ReactivateButton(GetInvestmentSpan(m_currentOptionPanel));
    m_currentOptionPanel = null;
}

function ReactivateButton(investmentSpan) {

    var investmentBtn = investmentSpan.find(".amountBoxbtn");
    var investmentLoader = investmentSpan.find(".amountBoxLoader");
    investmentBtn.show();
    investmentLoader.hide();
}


function ChangeClass(ctrl, newClass) {
    ctrl.className = newClass;
}

/*High Bids*/

HighBids = new EzArray("optionId");
HighBid = function(optionId, callPut, amount, price) {

    this.optionId = optionId;
    this.callPut = callPut;
    this.amount = amount;
    this.price = price;
}

function FlagHighBid(id, amount, callPut, price) {
    TradingService.InsertHighBid(id, amount, callPut, price, function() {

        if (!HighBids.Contains(id)) HighBids.Add(new HighBid(id, callPut, amount, price));

    });
}
function FlagHighBidSubmitted(id) {

    TradingService.HighBidSubmitted(id, function() {
        HighBids.Remove(id);
    });
}
function RemoveHighBid(id) {

    if (HighBids.Contains(id)) {
        bid = HighBids.GetItem(id);
        TradingService.RemoveBid(id, function() {
            HighBids.Remove(id);
        });
    }
}
function RemoveAllHighBids() {

    if (!HighBids.isEmpty()) {
        for (i = 0; i < HighBids.Count(); i++) {
            bid = HighBids.items[i];
            TradingService.RemoveBid(bid.optionId);
        }
        HighBids.Clear();
    }

}


/**End High Bids**/

/*** Relative value getting ***/


function GetGrafDiv(optionPanel) { return optionPanel.find(".graf"); }
function GetFinalSpan(optionPanel) { return optionPanel.find(".final"); }
function GetUpdatingDiv(optionPanel) { return optionPanel.find(".Updating"); }
function GetAmount(investmentSpan) {
    var txtInvestment = investmentSpan.find('input');
    return txtInvestment.val();
}

function GetInvestmentSpan(optionPanel) { return optionPanel.find(".investmentDv"); }
function GetChartObjectContainer(investmentSpan) {
    return investmentSpan.find("#chartCnt").children();
}
function GetFlashGetImage(investmentSpan) {
    return investmentSpan.find("#chartCnt").children().find('a');
}
function GetPutCall(stockPanel) { return stockPanel.attr('CurrentOption'); }
function GetInvestmentTextField(investmentSpan) { return investmentSpan.find('a'); }
function GetCurrentQuote(optionPanel) {
    var quoteSpan = GetQuoteSpan(optionPanel);
    return quoteSpan.find("span").html();
}
function GetQuoteSpan(optionPanel) { return optionPanel.find(".current"); }
function GetQuoteWrapper(optionPanel) { return optionPanel.find(".quote"); }
function GetNewsDiv(optionPanel) { return optionPanel.find(".StockNews"); }
function GetCallImage(optionPanel) { return $(optionPanel.find(".size3").find("a").get(0)); }
function GetPutImage(optionPanel) { return $(optionPanel.find(".size3").find("a").get(1)); }
function GetOptionId(investmentSpan) { return investmentSpan.find('.optionId').html(); }
function GetStockLink(optionPanel) { return $(optionPanel.find(".stockLink")).get(0); }
function GetSelectedIcon(investmentSpan) { return investmentSpan.find('#selectedIcon'); }
function GetStateDiv(optionPanel) { return optionPanel.find(".size6"); }
function GetStateMsgSpan(optionPanel) { return optionPanel.find(".stateMsg"); }
function GetTimeLeftSpan(optionPanel) { return optionPanel.find('.countTime'); }
function GetExpirationDiv(optionPanel) { return optionPanel.find(".expiration"); }
function GetExpiredSpan(optionPanel) { return optionPanel.find(".statusTxt"); }

/*** end of relative value getting ***/
