@{
    ViewData["Title"] = "Trader Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@model EForT.Models.ViewModel

<div class="app-content container center-layout pt-3" style="width:1400px;">
    <div class="content-header row">
        <div class="content-header-left col-12 mb-2">
            <h1 class="content-header-title mb-0">Empowered Forex Trader</h1>
            <div class="row breadcrumbs-top">
                <div class="breadcrumb-wrapper col-12">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item">
                            <a href="@Url.Action("Trader", "Home")">Trader Home</a>
                        </li>
                        <li class="breadcrumb-item active">
                            Home
                        </li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    <div id="trader-form" class="content-wrapper">
        <div class="content-body mb-1">
            <div class="row">
                <div class="col-lg-12 col-md-12 col-12">
                    <partial name="_AdvertisePublisher" model="Model.publisherModel" />
                    @if (Model.forexAccountModel.ForexAccountList.Count() > 0)
                    {
                        <div class="card">
                            <div class="card-header bottom-border">
                                <h4 class="card-title">Account Equity and Balance </h4>
                                <a class="heading-elements-toggle"><i class="fa fa-share-alt font-medium-3"></i></a>
                                <div class="heading-elements text-right font-medium-2">
                                    <ul class="list-inline mb-0">
                                        <li>
                                            <a href="javascript:void(0);" id="share-wa" class="sharer button" title="Share on Whatsapp"><i class="fa fa-whatsapp font-large-1"></i></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void(0);" id="share-fb" class="sharer button" title="Share on Facebook"><i class="fa fa-facebook-square font-large-1"></i></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void(0);" id="share-tw" class="sharer button" title="Share on Twitter"><i class="fa fa-twitter-square font-large-1"></i></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void(0);" id="share-li" class="sharer button" title="Share on LinkedIn"><i class="fa fa-linkedin-square font-large-1"></i></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void(0);" id="share-gp" class="sharer button" title="Share on Google+"><i class="fa fa-google-plus-square font-large-1"></i></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void(0);" title="Email" data-toggle="modal" data-target="#exampleModalLong"><i class="fa fa-envelope-square font-large-1"></i></a>
                                        </li>
                                    </ul>
                                </div>
                                <div class="row collapse mt-2 pt-1 top-border justify-content-end" id="share-email">
                                    <div class="col-12 col-md-6 col-lg-4">

                                    </div>
                                </div>
                            </div>
                            <div class="card-content">
                                <div class="card-body">
                                    <!-- Toolbar -->
                                    <div class="row">
                                        <div class="col-auto mb-1">
                                            <div class="btn-group btn-group-toggle" id="graphStyleTB">
                                                <label id="toolbarCandlestickButton" class="@("btn btn-outline-primary " + ((Model.forexAccountModel.Settings.GraphStyleGS == "candlestick") ? "active" : ""))">
                                                    <input type="radio" name="options" id="candlestickTB" autocomplete="off"> Candlestick
                                                </label>
                                                <label id="toolbarBarButton" class="@("btn btn-outline-primary " + ((Model.forexAccountModel.Settings.GraphStyleGS == "ohlc") ? "active" : ""))">
                                                    <input type="radio" name="options" id="barTB" autocomplete="off"> Bar
                                                </label>
                                                <label id="toolbarLineButton" class="@("btn btn-outline-primary " + ((Model.forexAccountModel.Settings.GraphStyleGS == "line") ? "active" : ""))">
                                                    <input type="radio" name="options" id="LineTB" autocomplete="off"> Line
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-auto mb-1">
                                            <div class="btn-group btn-group-toggle" id="timeIntervalTB">
                                                <label id="timeFrameM1TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 1) ? "active" : ""))">
                                                    <input type="radio" id="m1TB" autocomplete="off" name="timeFrameTB" value="1" /> 1 min
                                                </label>
                                                <label id="timeFrameM5TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 5) ? "active" : ""))">
                                                    <input type="radio" id="m5TB" autocomplete="off" name="timeFrameTB" value="5" /> 5 min
                                                </label>
                                                <label id="timeFrameM15TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 15) ? "active" : ""))">
                                                    <input type="radio" id="m15TB" autocomplete="off" name="timeFrameTB" value="15" /> 15 min
                                                </label>
                                                <label id="timeFrameH1TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 60) ? "active" : ""))">
                                                    <input type="radio" id="h1TB" autocomplete="off" name="timeFrameTB" value="60" /> 1 hr
                                                </label>
                                                <label id="timeFrameH4TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 240) ? "active" : ""))">
                                                    <input type="radio" id="h4TB" autocomplete="off" name="timeFrameTB" value="240" /> 4 hr
                                                </label>
                                                <label id="timeFrameW1TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 10080) ? "active" : ""))">
                                                    <input type="radio" id="w1TB" autocomplete="off" name="timeFrameTB" value="10080" /> 1 wk
                                                </label>
                                                <label id="timeFrameMN1TB" class="@("btn btn-secondary " + ((Model.forexAccountModel.Settings.TimeFrame == 43800) ? "active" : ""))">
                                                    <input type="radio" id="mn1TB" autocomplete="off" name="timeFrameTB" value="43800" /> 1 mon
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-auto mb-1">
                                            <div class="btn-group btn-group-toggle">
                                                <label id="toolbarExponentialMovingAverageButton" class="@("btn btn-outline-primary " + (Model.forexAccountModel.Settings.ExponentialMovingAverageInd ? "active" : ""))">
                                                <input type="checkbox" id="exponentialMovingAverageTB" @(Model.forexAccountModel.Settings.ExponentialMovingAverageInd ? "checked" : "")> Exponential Moving Average
                                                </label>
                                                <label id="toolbarMovingAverageButton" class="@("btn btn-outline-primary " + (Model.forexAccountModel.Settings.MovingAverageInd ? "active" : ""))">
                                                    <input type="checkbox" id="movingAverageTB" @(Model.forexAccountModel.Settings.MovingAverageInd ? "checked" : "")> Moving Average
                                                </label>
                                                <label id="toolbarVolumeButton" class="@("btn btn-outline-primary " + (Model.forexAccountModel.Settings.VolumeInd ? "active" : ""))">
                                                    <input type="checkbox" id="volumeTB" @(Model.forexAccountModel.Settings.VolumeInd ? "checked" : "")> Volume
                                                </label>
                                                <label id="toolbarCrosshairButton" class="@("btn btn-outline-primary " + (Model.forexAccountModel.Settings.CrosshairInd ? "active" : ""))">
                                                    <input type="checkbox" id="crosshairTB" @(Model.forexAccountModel.Settings.CrosshairInd ? "checked" : "")> Crosshair
                                                </label>
                                            </div>
                                            </div>
                                    </div>
                                    @if (Model.forexAccountModel.ForexAccountList.Count() > 1)
                                    {
                                        <nav>
                                            <ul class="nav nav-tabs" id="forex-tab" role="tablist">
                                                @for (int i = 0; i < Model.forexAccountModel.ForexAccountList.Count; i++)
                                                {
                                                    var fa = @Model.forexAccountModel.ForexAccountList[i];
                                                    <li class="nav-item">
                                                        <a class="nav-link @(i == 0 ? "active" : "")" title="Forex Account: @(fa.ForexId) Server: @(fa.Server)" id="@fa.ForexId" data-toggle="tab" href="#nav-@fa.ForexId" role="tab" aria-controls="nav-@fa.ForexId" aria-selected="true" onclick="updateAccount(this.id)">
                                                            @(fa.ForexId)
                                                        </a>
                                                    </li>
                                                }
                                            </ul>
                                        </nav>
                                        <div class="tab-content pt-2 px-2 pb-2">
                                            @*<div class="my-1" id="chartContainer" style="height: 400px; width: 100%;"></div>*@
                                            <div id="chartContainer" style="height: 400px; width: 100%;"></div>
                                        </div>
                                    }
                                    else
                                    {
                                        @*<div class="my-1" id="chartContainer" style="height: 400px; width: 100%;"></div>*@
                                        <div id="chartContainer" style="height: 400px; width: 100%;"></div>
                                    }
                                </div>
                            </div>
                            <div class="card-footer pb-0">
                                <div class="row mb-1">
                                    <div class="col-12" role="tabpanel">
                                        <ul class="nav nav-tabs" role="tablist">
                                            <li class="nav-item">
                                                <a id="openPrice-tab" class="nav-link active" data-toggle="tab" role="tab" href="#openPrice" aria-controls="openPrice" aria-selected="true">Open</a>
                                            </li>
                                            <li class="nav-item">
                                                <a id="highest-tab" class="nav-link" data-toggle="tab" role="tab" href="#highest" aria-controls="highest" aria-selected="false">Highest</a>
                                            </li>
                                            <li class="nav-item">
                                                <a id="lowest-tab" class="nav-link" data-toggle="tab" role="tab" href="#lowest" aria-controls="lowest" aria-selected="false">Lowest</a>
                                            </li>
                                            <li class="nav-item">
                                                <a id="closePrice-tab" class="nav-link" data-toggle="tab" role="tab" href="#closePrice" aria-controls="closePrice" aria-selected="false">Close</a>
                                            </li>
                                            <li class="nav-item">
                                                <a id="settingRules-tab" class="nav-link" data-toggle="tab" role="tab" href="#settingRules" aria-controls="settingRules" aria-selected="false">Setting Rules</a>
                                            </li>
                                        </ul>
                                        <div class="tab-content">
                                            <div class="container tab-pane fade active show p-2" id="openPrice" aria-labelledby="openPrice-tab">
                                                <div class="badge badge-pill bg-blue-grey px-1">Open price for the month: $0.00</div>
                                            </div>
                                            <div class="container tab-pane fade p-2" id="highest" aria-labelledby="highest-tab">
                                                <div class="badge badge-pill bg-blue-grey px-1">Highest price for the month: $0.00</div>
                                            </div>
                                            <div class="container tab-pane fade p-2" id="lowest" aria-labelledby="lowest-tab">
                                                <div class="badge badge-pill bg-blue-grey px-1">Lowest price for the month: $0.00</div>
                                            </div>
                                            <div class="container tab-pane fade p-2" id="closePrice" aria-labelledby="closePrice-tab">
                                                <div class="badge badge-pill bg-blue-grey px-1">Close price for the month: $0.00</div>
                                            </div>
                                            <div class="container tab-pane fade p-2" id="settingRules" aria-labelledby="settingRules-tab">
                                                1) Y-Margin percentage is applied for both upper y-axis margin and lower y-axis margin. <br />
                                                2) Axis limits are 0% to 25% <br />
                                                3) Volume limits are 5% to 40% <br />
                                                4) Max data points on the graph is 40 points. <br />
                                                5) If any overflow or underflow is inputted, the value will be rounded to the closest limit.
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12">
                                        <ul id="dateSearch" class="float-left float-md-right list-inline mb-1">
                                            <li>Go to date :</li>
                                            <li>
                                                <input class="form-control form-control-xs" type="text" id="minimumDate" placeholder="YYYY-MM-DD hh:mm">
                                            </li>
                                            <li>
                                                <div class="btn-group btn-group-sm align-baseline" role="group">
                                                    <button class="btn btn-primary" id="updateDate" onclick="updateDate()">Update</button>
                                                    <button class="btn btn-secondary" id="resetDate" onclick="resetDate()">Reset</button>
                                                </div>
                                            </li>
                                        </ul>
                                        <div class="float-right float-md-left mb-1">
                                            <a href="javascript:void(0);" class="font-medium-2" data-toggle="collapse" data-target="#settings"><i class="fa fa-cog"></i> Settings<i class="pl-1 fa fa-caret-down"></i></a>
                                        </div>
                                    </div>
                                </div>
                                @using (Html.BeginForm("AddTemplate", "Trader", FormMethod.Post))
                                {
                                    <div class="row collapse mb-2" id="settings">
                                        <div class="col-12">
                                            <ul class="nav nav-tabs" role="tablist">
                                                <li class="nav-item">
                                                    <a class="nav-link active" data-toggle="tab" href="#toolbar">Toolbar</a>
                                                </li>
                                                <li class="nav-item">
                                                    <a class="nav-link" data-toggle="tab" href="#indicators">Indicators</a>
                                                </li>
                                                <li class="nav-item">
                                                    <a class="nav-link" data-toggle="tab" href="#graphSettings">Graph</a>
                                                </li>
                                                <li class="nav-item">
                                                    <a class="nav-link" data-toggle="tab" href="#templates">Templates</a>
                                                </li>
                                            </ul>
                                            <div class="tab-content pt-2 px-2 pb-2">
                                                <div id="toolbar" class="container tab-pane fade active show">
                                                    <div class="row">
                                                        <div class="col-12">
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeIntTool" id="timeIntervalTBT" checked>
                                                                <label class="custom-control-label" for="timeIntervalTBT">Time Interval Toolbar Toggle</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.ExponentialMovingAverageTool" id="exponentialMovingAverageTBT" checked>
                                                                <label class="custom-control-label" for="exponentialMovingAverageTBT">Exponential Moving Average Toolbar Toggle</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.MovingAverageTool" id="movingAverageTBT" checked>
                                                                <label class="custom-control-label" for="movingAverageTBT">Moving Average Toolbar Toggle</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.VolumeTool" id="volumeTBT" checked>
                                                                <label class="custom-control-label" for="volumeTBT">Volume Toolbar Toggle</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.CrosshairTool" id="crosshairTBT" checked>
                                                                <label class="custom-control-label" for="crosshairTBT">Crosshair Toggle</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.GraphStyleTool" id="graphStyleTBT" checked>
                                                                <label class="custom-control-label" for="graphStyleTBT">Graph Styles</label>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.FindDateTool" id="dateSearchTBT" checked>
                                                                <label class="custom-control-label" for="dateSearchTBT">Date Search</label>
                                                            </fieldset>
                                                        </div>
                                                        <a href="javascript:void(0);" class="btn btn-primary mx-1" onclick="evaluateSettings()">Apply</a>
                                                        <a href="javascript:void(0);" class="btn btn-secondary" onclick="resetSettings()">Reset</a>
                                                    </div>
                                                </div>
                                                <div id="indicators" class="container tab-pane fade">
                                                    <div class="row">
                                                        <div class="col-12 col-md-6 col-lg-5">
                                                            <div class="row">
                                                                <div class="col-12">
                                                                    <fieldset class="form-group">
                                                                        <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.ExponentialMovingAverageInd" id="exponentialMovingAverage">
                                                                        <label class="custom-control-label" for="exponentialMovingAverage">Enable Exponential Moving Average</label>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.MovingAverageInd" id="movingAverage">
                                                                        <label class="custom-control-label" for="movingAverage">Enable Moving Average</label>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="movingAverageColor">Moving Average Line Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.MovingAverageColor" id="movingAverageColor">
                                                                            <option value="#4C9CA0" selected>Teal</option>
                                                                            <option value="#6D78AD">Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="blue">Blue</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="black">Black</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                            <option value="#6D78AD">Purple</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="movingAverageColor">Moving Average Options:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.MovingAverageOption" id="movingAverageApplyTo">
                                                                            <option value="median" selected>Median Price ((High+Low)/2)</option>
                                                                            <option value="close">Close</option>
                                                                            <option value="open">Open</option>
                                                                            <option value="high">High</option>
                                                                            <option value="low">Low</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.VolumeInd" id="volume">
                                                                        <label class="custom-control-label" for="volume">Enable Volume</label>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="volumeColor">Volume Bar Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.VolumeColor" id="volumeColor">
                                                                            <option value="#6D78AD" selected>Purple</option>
                                                                            <option value="green">Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="black">Black</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <input type="checkbox" class="custom-control-input" asp-for="forexAccountModel.Settings.CrosshairInd" id="crosshair" checked>
                                                                        <label class="custom-control-label" for="crosshair">Enable Crosshair</label>
                                                                    </fieldset>
                                                                </div>
                                                                <a href="javascript:void(0);" class="btn btn-primary mx-1" onclick="evaluateSettings()">Apply</a>
                                                                <a href="javascript:void(0);" class="btn btn-secondary" onclick="resetSettings()">Reset</a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="graphSettings" class="container tab-pane fade">
                                                    <div class="row">
                                                        <div class="col-12 col-md-6 col-lg-5">
                                                            <div class="row">
                                                                <div class="col-12">
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="graphStyle">Graph Style:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.GraphStyleGS" id="graphStyle">
                                                                            <option value="candlestick" selected>Candlestick</option>
                                                                            <option value="ohlc">Bar</option>
                                                                            <option value="line">Line</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="titleFontColor">Title Text Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.TitleColor" id="titleFontColor">
                                                                            <option value="black" selected>Black</option>
                                                                            <option value="green">Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="blue">Blue</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                            <option value="purple">Purple</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="labelFontColor">Label Text Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.LabelColor" id="labelFontColor">
                                                                            <option value="black" selected>Black</option>
                                                                            <option value="green">Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="blue">Blue</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                            <option value="purple">Purple</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="bullColor">Candlestick Bull Candle Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.BullColor" id="bullColor">
                                                                            <option value="#51CDA0" selected>Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="blue">Blue</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="black">Black</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                            <option value="purple">Purple</option>

                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label" for="bearColor">Candlestick Bear Candle Color:</label>
                                                                        <select class="form-control" asp-for="forexAccountModel.Settings.BearColor" id="bearColor">
                                                                            <option value="#51CDA0" selected>Green</option>
                                                                            <option value="red">Red</option>
                                                                            <option value="blue">Blue</option>
                                                                            <option value="orange">Orange</option>
                                                                            <option value="black">Black</option>
                                                                            <option value="white">White</option>
                                                                            <option value="yellow">Yellow</option>
                                                                            <option value="purple">Purple</option>
                                                                        </select>
                                                                    </fieldset>
                                                                    <fieldset class="form-group">
                                                                        <label class="label d-block" for="timeIntervalTB">Timeframe Intervals:</label>
                                                                        <div class="btn-group btn-group-toggle d-inline-flex">
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="m1s" value="1">
                                                                                <label class="custom-control-label" for="m1s"> M1</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="m5s" value="5">
                                                                                <label class="custom-control-label" for="m5s"> M5</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="m15s" value="15">
                                                                                <label class="custom-control-label" for="m15s"> M15</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="h1s" value="60">
                                                                                <label class="custom-control-label" for="h1s"> H1</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="h4s" value="240">
                                                                                <label class="custom-control-label" for="h4s"> H4</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="w1s" value="10080">
                                                                                <label class="custom-control-label" for="w1s"> W1</label>
                                                                            </div>
                                                                            <div class="custom-control custom-radio pr-1">
                                                                                <input type="radio" class="custom-control-input" asp-for="forexAccountModel.Settings.TimeFrame" id="mn1s" value="43800">
                                                                                <label class="custom-control-label" for="mn1s"> MN1</label>
                                                                            </div>
                                                                        </div>
                                                                    </fieldset>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="col-12 col-md-6 col-lg-5">
                                                            <fieldset class="form-group">
                                                                <label class="label" for="yAxisMargin">Y-Axis Margin (%):</label>
                                                                <input class="form-control" type="number" placeholder="5" min="0" max="25" asp-for="forexAccountModel.Settings.YAxisMargin" id="yAxisMargin" value="5">
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="volumeView">Volume View (%):</label>
                                                                <input class="form-control" type="number" placeholder="10" min="5" max="25" asp-for="forexAccountModel.Settings.VolumeViewPercentage" id="volumeView" value="10">
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="dataPointsView">Number of Data Points:</label>
                                                                <input class="form-control" type="number" placeholder="30" min="1" max="50" asp-for="forexAccountModel.Settings.DataPointsOnScreen" id="dataPointsView" value="30">
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="barColor">Bar Color:</label>
                                                                <select class="form-control" asp-for="forexAccountModel.Settings.BarColor" id="barColor">
                                                                    <option value="#51CDA0" selected>Green</option>
                                                                    <option value="red">Red</option>
                                                                    <option value="blue">Blue</option>
                                                                    <option value="orange">Orange</option>
                                                                    <option value="black">Black</option>
                                                                    <option value="white">White</option>
                                                                    <option value="yellow">Yellow</option>
                                                                    <option value="#6D78AD">Purple</option>
                                                                </select>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="lineColor">Line Color:</label>
                                                                <select class="form-control" asp-for="forexAccountModel.Settings.LineColor" id="lineColor">
                                                                    <option value="#51CDA0" selected>Green</option>
                                                                    <option value="red">Red</option>
                                                                    <option value="blue">Blue</option>
                                                                    <option value="orange">Orange</option>
                                                                    <option value="black">Black</option>
                                                                    <option value="white">White</option>
                                                                    <option value="yellow">Yellow</option>
                                                                    <option value="#6D78AD">Purple</option>
                                                                </select>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="foreground">Foreground Color:</label>
                                                                <select class="form-control" asp-for="forexAccountModel.Settings.ForegroundColor" id="foreground">
                                                                    <option value="green">Green</option>
                                                                    <option value="red">Red</option>
                                                                    <option value="blue">Blue</option>
                                                                    <option value="orange">Orange</option>
                                                                    <option value="black" selected>Black</option>
                                                                    <option value="white">White</option>
                                                                    <option value="yellow">Yellow</option>
                                                                    <option value="#6D78AD">Purple</option>
                                                                </select>
                                                            </fieldset>
                                                            <fieldset class="form-group">
                                                                <label class="label" for="background">Background Color:</label>
                                                                <select class="form-control" asp-for="forexAccountModel.Settings.BackgroundColor" id="background">
                                                                    <option value="green">Green</option>
                                                                    <option value="red">Red</option>
                                                                    <option value="blue">Blue</option>
                                                                    <option value="orange">Orange</option>
                                                                    <option value="black">Black</option>
                                                                    <option value="white" selected>White</option>
                                                                    <option value="yellow">Yellow</option>
                                                                    <option value="#6D78AD">Purple</option>
                                                                </select>
                                                            </fieldset>
                                                            <a href="javascript:void(0);" class="btn btn-primary mr-1" onclick="evaluateSettings()">Apply</a>
                                                            <a href="javascript:void(0);" class="btn btn-secondary" onclick="resetSettings()">Reset</a>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="templates" class="container tab-pane fade">
                                                    <div class="row">
                                                        <div class="col-12 col-md-6 col-lg-5 pb-1 pb-md-0">
                                                            <fieldset class="form-group">
                                                                <label class="label" for="loadTemplate">Load Template</label>
                                                                <select class="form-control" id="loadTemplate">
                                                                    @if (Model.forexAccountModel.SettingsTemplateList != null)
                                                                    {
                                                                        if (Model.forexAccountModel.SettingsTemplateList.Count > 0)
                                                                        {
                                                                            for (int i = 0; i < Model.forexAccountModel.SettingsTemplateList.Count; i++)
                                                                            {
                                                                                <option value="@Model.forexAccountModel.SettingsTemplateList[i].Id">@Model.forexAccountModel.SettingsTemplateList[i].TemplateName</option>
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            <option value="" selected disabled>Save a template to load later.</option>
                                                                        }
                                                                    }
                                                                </select>
                                                            </fieldset>
                                                            <a href="javascript:void(0);" onclick="loadSettings()" class="btn btn-primary">Load</a>
                                                            <a href="javascript:void(0);" onclick="deleteTemplate()" class="btn btn-secondary">Delete</a>
                                                        </div>
                                                        <div class="col-12 col-md-6 col-lg-5">
                                                            <fieldset class="form-group">
                                                                <label class="label">Save Template</label>
                                                                <input type="text" class="form-control" placeholder="Template Name" asp-for="forexAccountModel.Settings.TemplateName" value="" id="TemplateName">
                                                            </fieldset>
                                                            <button type="submit" name="save" class="btn btn-primary">Save</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                }
                            </div>
                        </div>
                    }
                    else
                    {
                        <div class="card">
                            <div class="card-header font-medium-2 bottom-border">
                                <h4 class="card-title">Account Equity and Balance</h4>
                            </div>
                            <div class="card-content">
                                <div class="card-body pt-0">
                                    <div class="row pt-2">
                                        <div class="col-12">
                                            <h5 class="mb-2"><i class="fa fa-warning warning"></i> It seems that you don't have a Forex Account linked yet.</h5>
                                            <p>Please, go to My Forex Accounts or click the button below to start linking and account with your EForT profile.</p>
                                            <a href="@Url.Action("MyForexAccounts", "Trader")" class="btn btn-primary">Link a Forex Account</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>
@using (Html.BeginForm("ShareEmail", "Trader", FormMethod.Post, Model))
{
    <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">Email Graph</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="emailform">
                        <h6 class="form-section">
                            <i class="fa fa-envelope-o"></i>Share Chart via Email
                        </h6>
                        <fieldset class="form-group">
                            <label for="FromName" class="control-label">Your Name:</label>
                            <input asp-for="LoggedUserFullName" id="FromName" class="form-control" type="text" required />
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="ToEmail" class="control-label">To:</label>
                            <input asp-for="ToEmail" id="ToEmail" placeholder="abc@hotmail.com" class="form-control" type="email" required />
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="Subject" class="control-label">Subject:</label>
                            <input asp-for="EmailFormat.Subject" id="Subject" class="form-control" type="text" required />
                        </fieldset>
                        <fieldset class="form-group">
                            <label for="Message" class="control-label">Message:</label>
                            <textarea rows="8" cols="50" asp-for="EmailFormat.Message" id="Message" class="form-control"></textarea>
                        </fieldset>
                    </div>
                    <div class="modal-footer">
                        <input name="Image" asp-for="Image" id="Image" type="hidden" value="">
                        <button type="submit" class="btn btn-primary">Send</button>
                        <a href="javascript:void(0);" class="btn btn-secondary" data-dismiss="modal">Close</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

<script type="text/javascript">
    const volume = 4;
    const close = 3;
    const low = 2;
    const high = 1;
    const open = 0;
    const maxNumberOfDataPoints = 40;
    const minNumberOfDataPoints = 1;
    const maxMarginPercentage = 25;
    const minMarginPercentage = 0;
    const maxVolumePercentage = 25;
    const minVolumePercentage = 5;
    var defaultTitleColor = document.getElementById("titleFontColor").options[0].value;
    var defaultLabelColor = document.getElementById("labelFontColor").options[0].value;
    var defaultBullColor = document.getElementById("bullColor").options[0].value;
    var defaultBearColor = document.getElementById("bearColor").options[0].value;
    var defaultForegroundColor = document.getElementById("foreground").options[0].value;
    var defaultBackgroundColor = document.getElementById("background").options[0].value;
    var defaultMovingAverageColor = document.getElementById("movingAverageColor").options[0].value;
    var defaultVolumeColor = document.getElementById("volumeColor").options[0].value;
    var defaultMovingAverageOption = document.getElementById("movingAverageApplyTo").options[0].value;
    var defaultGraphStyle = document.getElementById("graphStyle").options[0].value;
    var defaultLineColor = document.getElementById("lineColor").options[0].value;
    var defaultBarColor = document.getElementById("barColor").options[0].value;
    var defaultDataPoints = parseInt(document.getElementById("dataPointsView").placeholder);
    var defaultYAxisMargin = parseInt(document.getElementById("yAxisMargin").placeholder);
    var defaultVolumeView = parseInt(document.getElementById("volumeView").placeholder);
    var defaultTimeIntervalTBEnabled = true;
    var defaultExponentialMovingAverageTBEnabled = true;
    var defaultMovingAverageTBEnabled = true;
    var defaultVolumeTBEnabled = true;
    var defaultCrosshairTBEnabled = true;
    var defaultCrosshairEnabled = true;
    var defaultGraphStyleTB = true;
    var defaultDateSearchTB = true;
    var defaultExponentialMovingAverageEnabled = false;
    var defaultMovingAverageEnabled = false;
    var defaultVolumeEnabled = false;
    var oldestViewTime = null;
    var upperyAxisMargin = 0;
    var loweryAxisMargin = 0;
    var uppery2AxisMargin = 0;
    var lowery2AxisMargin = 0;
    var dataViewPercentage = 90;
    //dataViewPercentage is that value when volume is shown.
    var init = true;
    var timeFrame = 240;
    var graphPoints = [];
    var graphPointsBC = [];
    var graphPointsLine = [];
    var balancePoints = [];
    var balancePointsBarChart = [];
    var balancePointsLine = [];
    var volumePoints = [];
    var exponentialMovingPoints = [];
    var movingPoints = [];
    var partialArr = [];
    var chart; // global variable for the chart
    var max = null;
    var viewMax = null;
    var lowestLow = -1;
    var lowestLowBalance = -1;
    var lowestVolume = -1;
    var highestVolume = -1;
    var highestDataPoint = -1;
    var lowestDataPoint = -1;
    var highestDataPointBalance = -1;
    var lowestDataPointBalance = -1;
    var volumeRange = -1;
    var dataRange = -1;
    var balanceDataRange = -1;
    var yRange = -1;
    var y2Range = -1;
    var volumeMargin = -1;
    //Current Settings
    var titleFontColor = document.getElementById("titleFontColor").value;
    var labelFontColor = document.getElementById("labelFontColor").value;
    var bullColor = document.getElementById("bullColor").value;
    var bearColor = document.getElementById("bearColor").value;
    var foregroundColor = document.getElementById("foreground").value;
    var backgroundColor = document.getElementById("background").value;
    var movingAverageColor = document.getElementById("movingAverageColor").value;
    var volumeColor = document.getElementById("volumeColor").value;
    var graphStyle = document.getElementById("graphStyle").value;
    var barColor = document.getElementById("barColor").value;
    var lineColor = document.getElementById("lineColor").value;
    var numberOfDataPoints = parseInt(document.getElementById("dataPointsView").placeholder);
    var marginPercentage = parseInt(document.getElementById("yAxisMargin").placeholder);
    var volumeViewPercentage = parseInt(document.getElementById("volumeView").placeholder);
    var whichData = false;
    var updatedMinimum = false;
    var minimum;
    var exponentialMovingAverageEnabled = document.getElementById("exponentialMovingAverage").checked;
    var movingAverageEnabled = document.getElementById("movingAverage").checked;
    var applyTo = document.getElementById("movingAverageApplyTo").value;
    var volumeEnabled = document.getElementById("volume").checked;
    var crosshairEnabled = document.getElementById("crosshair").checked;
    var target = -1; // which Forex account
    var base64Image;//chart url

    var fa = 0;
    try { // try to get a tab <-> there is more than 1 FOREX account linked to it
        fa = document.getElementById("forex-tab").tabIndex;
    }
    catch (error) { // if there is only one account...
        fa = -1;
    }

    window.onload = function () {
        //Always Update Chart Data before creating chart to update timeFrame and graphPoints
        //For future features that require external searches (like DB) consider building functions
        //that update variables to be used by createChart.
        evaluateSettings();
    }

    function evaluateSettings() {
        var updateData = false;
        var justUpdateChart = false;
        if (init) {
            loadSettings();
            updateData = true;
            init = false;
        }
        //Update tool bar
        timeIntervalToolbarDisplay();
        exponentialMovingAverageToolbarDisplay();
        movingAverageToolbarDisplay();
        volumeToolbarDisplay();
        crosshairToolbarDisplay();
        graphStyleToolbarDisplay();
        dateSearchToolbarDisplay();
        if (titleFontColor != document.getElementById("titleFontColor").value ||
            labelFontColor != document.getElementById("labelFontColor").value ||
            bullColor != document.getElementById("bullColor").value ||
            bearColor != document.getElementById("bearColor").value ||
            foregroundColor != document.getElementById("foreground").value ||
            backgroundColor != document.getElementById("background").value ||
            movingAverageColor != document.getElementById("movingAverageColor").value ||
            volumeColor != document.getElementById("volumeColor").value ||
            crosshairEnabled != document.getElementById("crosshair").checked ||
            graphStyle != document.getElementById("graphStyle").value ||
            barColor != document.getElementById("barColor").value ||
            lineColor != document.getElementById("lineColor").value) {
            titleFontColor = document.getElementById("titleFontColor").value;
            labelFontColor = document.getElementById("labelFontColor").value;
            bullColor = document.getElementById("bullColor").value;
            bearColor = document.getElementById("bearColor").value;
            foregroundColor = document.getElementById("foreground").value;
            backgroundColor = document.getElementById("background").value;
            movingAverageColor = document.getElementById("movingAverageColor").value;
            volumeColor = document.getElementById("volumeColor").value;
            crosshairEnabled = document.getElementById("crosshair").checked;
            updateToolbarToggleState("toolbarCrosshairButton", crosshairEnabled);
            graphStyle = document.getElementById("graphStyle").value;
            updateGraphStyleToolbarToggleState(graphStyle);
            barColor = document.getElementById("barColor").value;
            lineColor = document.getElementById("lineColor").value;
            justUpdateChart = true;
        }
        // Margin Changes
        if (numberOfDataPoints != parseInt(document.getElementById("dataPointsView").value) ||
            marginPercentage != parseInt(document.getElementById("yAxisMargin").value) ||
            volumeViewPercentage != parseInt(document.getElementById("volumeView").value)) {
            //DataPoints validation
            if (!Number.isInteger(parseInt(document.getElementById("dataPointsView").value))) {
                document.getElementById("dataPointsView").value = document.getElementById("dataPointsView").placeholder;
            }
            else if (parseInt(document.getElementById("dataPointsView").value) < minNumberOfDataPoints) {
                document.getElementById("dataPointsView").value = minNumberOfDataPoints;
            }
            else if (document.getElementById("dataPointsView").value > maxNumberOfDataPoints) {
                document.getElementById("dataPointsView").value = maxNumberOfDataPoints;
            }
            numberOfDataPoints = parseInt(document.getElementById("dataPointsView").value);
            //Y-Axis Margin Percentage validation
            if (!Number.isInteger(parseInt(document.getElementById("yAxisMargin").value))) {
                document.getElementById("yAxisMargin").value = document.getElementById("yAxisMargin").placeholder;
            }
            else if (document.getElementById("yAxisMargin").value < minMarginPercentage) {
                document.getElementById("yAxisMargin").value = minMarginPercentage;
            }
            else if (document.getElementById("yAxisMargin").value > maxMarginPercentage) {
                document.getElementById("yAxisMargin").value = maxMarginPercentage;
            }
            marginPercentage = parseInt(document.getElementById("yAxisMargin").value);
            //Volume Percentage validation
            if (!Number.isInteger(parseInt(document.getElementById("volumeView").value))) {
                document.getElementById("volumeView").value = document.getElementById("volumeView").placeholder;
            }
            else if (document.getElementById("volumeView").value < minVolumePercentage) {
                document.getElementById("volumeView").value = minVolumePercentage;
            }
            else if (document.getElementById("volumeView").value > maxVolumePercentage) {
                document.getElementById("volumeView").value = maxVolumePercentage;
            }
            volumeViewPercentage = parseInt(document.getElementById("volumeView").value);
            updateData = true;
        }
        // Changes to Exponential Moving Average, Moving Average, or Volume
        if (exponentialMovingAverageEnabled != document.getElementById("exponentialMovingAverage").checked ||
            movingAverageEnabled != document.getElementById("movingAverage").checked ||
            volumeEnabled != document.getElementById("volume").checked ||
            applyTo != document.getElementById("movingAverageApplyTo").value) {
            exponentialMovingAverageEnabled = document.getElementById("exponentialMovingAverage").checked;
            updateToolbarToggleState("toolbarExponentialMovingAverageButton", exponentialMovingAverageEnabled);
            movingAverageEnabled = document.getElementById("movingAverage").checked;
            updateToolbarToggleState("toolbarMovingAverageButton", movingAverageEnabled);
            volumeEnabled = document.getElementById("volume").checked;
            updateToolbarToggleState("toolbarVolumeButton", volumeEnabled);
            applyTo = document.getElementById("movingAverageApplyTo").value
            updateData = true;
        }
        //Changes to time intervals
        if (document.getElementById("m1s").checked == true &&
            timeFrame != document.getElementById("m1s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameM1TB", true);
            document.getElementById("m1TB").checked = true;
            timeFrame = document.getElementById("m1TB").value;
            updateData = true;
        }
        else if (document.getElementById("m5s").checked == true &&
            timeFrame != document.getElementById("m5s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameM5TB", true);
            document.getElementById("m5TB").checked = true;
            timeFrame = document.getElementById("m5TB").value;
            updateData = true;
        }
        else if (document.getElementById("m15s").checked == true &&
            timeFrame != document.getElementById("m15s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameM15TB", true);
            document.getElementById("m15TB").checked = true;
            timeFrame = document.getElementById("m15TB").value;
            updateData = true;
        }
        else if (document.getElementById("h1s").checked == true &&
            timeFrame != document.getElementById("h1s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameH1TB", true);
            document.getElementById("h1TB").checked = true;
            timeFrame = document.getElementById("h1TB").value;
            updateData = true;
        }
        else if (document.getElementById("h4s").checked == true &&
            timeFrame != document.getElementById("h4s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameH4TB", true);
            document.getElementById("h4TB").checked = true;
            timeFrame = document.getElementById("h4TB").value;
            updateData = true;
        }
        else if (document.getElementById("w1s").checked == true &&
            timeFrame != document.getElementById("w1s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameW1TB", true);
            document.getElementById("w1TB").checked = true;
            timeFrame = document.getElementById("w1TB").value;
            updateData = true;
        }
        else if (document.getElementById("mn1s").checked == true &&
            timeFrame != document.getElementById("mn1s").value) {
            removeTimeFrameToolbarActiveButton();
            updateToolbarToggleState("timeFrameMN1TB", true);
            document.getElementById("mn1TB").checked = true;
            timeFrame = document.getElementById("mn1TB").value;
            updateData = true;
        }
        calcPercentages();
        if (updatedMinimum || updateData) {
            updateChart(timeFrame, exponentialMovingAverageEnabled, movingAverageEnabled, volumeEnabled, true, target);
        }
        else if (justUpdateChart) {
            createChart();
        }

        autoSaveUserTemplate();
    }

    function selectByValue(select, value) {
        for (option = 1; option < select.options.length; option++) {
            if (select.options[option].value == value) {
                select.selectedIndex = option;
            }
        }
    }

    function updateToolbarToggleState(buttonId, shouldBeActive) {
        let elem = document.getElementById(buttonId);
        if (shouldBeActive) {
            elem.classList.add("active");
        } else {
            elem.classList.remove("active");
        }
    }

    function removeTimeFrameToolbarActiveButton() {
        let timeFrameTBButtonIds = [
            "timeFrameM1TB", "timeFrameM5TB", "timeFrameM15TB", "timeFrameH1TB",
            "timeFrameH4TB", "timeFrameW1TB", "timeFrameMN1TB"];

        timeFrameTBButtonIds.forEach(buttonId => updateToolbarToggleState(buttonId, false));
    }

    function updateGraphStyleToolbarToggleState(graphStyle) {
        let graphStyleTBButtonMappings = {
            "candlestick": "toolbarCandlestickButton",
            "ohlc": "toolbarBarButton",
            "line": "toolbarLineButton",
        }

        Object.keys(graphStyleTBButtonMappings)
            .forEach(style => updateToolbarToggleState(graphStyleTBButtonMappings[style], false));

        updateToolbarToggleState(graphStyleTBButtonMappings[graphStyle], true);
    }

    function resetSettings() {
        selectByValue(document.getElementById("titleFontColor"), defaultTitleColor);
        selectByValue(document.getElementById("labelFontColor"), defaultLabelColor);
        selectByValue(document.getElementById("bullColor"), defaultBullColor);
        selectByValue(document.getElementById("bearColor"), defaultBearColor);
        selectByValue(document.getElementById("foreground"), defaultForegroundColor);
        selectByValue(document.getElementById("background"), defaultBackgroundColor);
        selectByValue(document.getElementById("movingAverageColor"), defaultMovingAverageColor);
        selectByValue(document.getElementById("volumeColor"), defaultVolumeColor);
        selectByValue(document.getElementById("movingAverageApplyTo"), defaultMovingAverageOption);
        selectByValue(document.getElementById("graphStyle"), defaultGraphStyle);
        selectByValue(document.getElementById("lineColor"), defaultLineColor);
        selectByValue(document.getElementById("barColor"), defaultBarColor);
        document.getElementById("dataPointsView").value = defaultDataPoints;
        document.getElementById("yAxisMargin").value = defaultYAxisMargin;
        document.getElementById("volumeView").value = defaultVolumeView;
        document.getElementById("crosshair").checked = defaultCrosshairEnabled;
        document.getElementById("exponentialMovingAverage").checked = defaultExponentialMovingAverageEnabled;
        document.getElementById("movingAverage").checked = defaultMovingAverageEnabled;
        document.getElementById("volume").checked = defaultVolumeEnabled;
        document.getElementById("timeIntervalTBT").checked = defaultTimeIntervalTBEnabled;
        document.getElementById("exponentialMovingAverageTBT").checked = defaultExponentialMovingAverageTBEnabled;
        document.getElementById("movingAverageTBT").checked = defaultMovingAverageTBEnabled;
        document.getElementById("volumeTBT").checked = defaultVolumeTBEnabled;
        document.getElementById("crosshairTBT").checked = defaultCrosshairTBEnabled;
        document.getElementById("graphStyleTBT").checked = defaultGraphStyleTB;
        document.getElementById("dateSearchTBT").checked = defaultDateSearchTB;
        var timeFrameRadioButtonId = "h4s";
        switch (timeFrame) {
            case 1:
                timeFrameRadioButtonId = "m1s";
                break;
            case 5:
                timeFrameRadioButtonId = "m5s";
                break;
            case 15:
                timeFrameRadioButtonId = "m15s";
                break;
            case 60:
                timeFrameRadioButtonId = "h1s";
                break;
            case 240:
                timeFrameRadioButtonId = "h4s";
                break;
            case 10080:
                timeFrameRadioButtonId = "w1s";
                break;
            case 43800:
                timeFrameRadioButtonId = "w1s";
                break;
            default:
                timeFrameRadioButtonId = "h4s";
        }
        document.getElementById(timeFrameRadioButtonId).checked = true;
        if (init) {
            init = false;
            return;
        }
        else {
            evaluateSettings();
        }
    }

    //Setting Template
    function deleteTemplate(templateId) {
        var templateId = document.getElementById("loadTemplate").value;
        $.ajax({
            type: "POST",
            url: '@Url.Action("DeleteTemplate", "Trader")',
            data: { templateId: templateId },
            cache: false,
            success: function (result) {
                if (result) {
                    location.reload();
                }
            },
            error: function () {
                console.log("Deleting template failed. Try again later.");
            }
        });
    }

    function loadSettings() {
        if (init) {
            defaultTimeIntervalTBEnabled = ("True" == '@Model.forexAccountModel.Settings.TimeIntTool');
            defaultExponentialMovingAverageTBEnabled = ("True" == '@Model.forexAccountModel.Settings.ExponentialMovingAverageTool');
            defaultMovingAverageTBEnabled = ("True" == '@Model.forexAccountModel.Settings.MovingAverageTool');
            defaultVolumeTBEnabled = ("True" == '@Model.forexAccountModel.Settings.VolumeTool');
            defaultCrosshairTBEnabled = ("True" == '@Model.forexAccountModel.Settings.CrosshairTool');
            defaultGraphStyleTB = ("True" == '@Model.forexAccountModel.Settings.GraphStyleTool');
            defaultDateSearchTB = ("True" == '@Model.forexAccountModel.Settings.FindDateTool');
            defaultExponentialMovingAverageEnabled = ("True" == '@Model.forexAccountModel.Settings.ExponentialMovingAverageInd');
            defaultMovingAverageEnabled = ("True" == '@Model.forexAccountModel.Settings.MovingAverageInd');
            defaultMovingAverageColor = '@Model.forexAccountModel.Settings.MovingAverageColor';
            defaultMovingAverageOption = '@Model.forexAccountModel.Settings.MovingAverageOption';
            defaultVolumeEnabled = ("True" == '@Model.forexAccountModel.Settings.VolumeInd');
            defaultVolumeColor = '@Model.forexAccountModel.Settings.VolumeColor';
            defaultCrosshairEnabled = ("True" == '@Model.forexAccountModel.Settings.CrosshairInd');
            defaultTitleColor = '@Model.forexAccountModel.Settings.TitleColor';
            defaultLabelColor = '@Model.forexAccountModel.Settings.LabelColor';
            defaultBullColor = '@Model.forexAccountModel.Settings.BullColor';
            defaultBearColor = '@Model.forexAccountModel.Settings.BearColor';
            defaultForegroundColor = '@Model.forexAccountModel.Settings.ForegroundColor';
            defaultBackgroundColor = '@Model.forexAccountModel.Settings.BackgroundColor';
            defaultGraphStyle = '@Model.forexAccountModel.Settings.GraphStyleGS';
            defaultLineColor = '@Model.forexAccountModel.Settings.LineColor';
            defaultBarColor = '@Model.forexAccountModel.Settings.BarColor';
            defaultDataPoints = '@Model.forexAccountModel.Settings.DataPointsOnScreen';
            defaultYAxisMargin = '@Model.forexAccountModel.Settings.YAxisMargin';
            defaultVolumeView = '@Model.forexAccountModel.Settings.VolumeViewPercentage';
            timeFrame = '@Model.forexAccountModel.Settings.TimeFrame';
            // resetSettings();
        }
        else {
            var templateId = document.getElementById("loadTemplate").value;
            $.ajax({
                type: "GET",
                url: "@Url.Action("LoadTemplate", "Trader")?tempId="+templateId,
                cache: false,
                success: function (result) {
                    if (result) {
                        location.reload();
                    }
                },
                error: function () {
                    console.log("Error loading template.");
                }
            });
        }
    }

    var limit = 50000;
    var y = [5198, 5629, 5159, 5385, 600];
    var data = [{ x: startDate, y: y }];
    var i = 0;
    var startDate = new Date();
    var day = 60 * 60 * 24 * 1000;
    while (i < limit) {
        y0 = y[0] + 100;
        y1 = y[1] + 100;
        y2 = y[2] + 100;
        y3 = y[3] + 100;
        y4 = y[4] + 50;
        data.push({ x: new Date(startDate.getTime() + i * 60000), y: [y0, y1, y2, y3, y4] });
        i++;
    }

    function createChart() {
        calcGraphView();
        var graphColor;
        if (graphStyle == "line") {
            graphPoints = graphPointsLine;
            balancePoints = balancePointsLine;
            graphColor = lineColor;
        }
        else {
            if (graphStyle == "candlestick") {
                graphColor = bearColor;
            }
            else {
                graphColor = barColor;
            }
            graphPoints = graphPointsBC;
            balancePoints = balancePointsBarChart;
        }

        if (graphPoints.length > 40) {
            partialArr = graphPoints.slice(0,42);
        }

        if (graphPoints.length > 40) {
            partialArr = graphPoints.slice(0,42);
        }

        var chart = new CanvasJS.Chart("chartContainer",
            {
                animationEnabled: true,
                theme: "light2",
                backgroundColor: backgroundColor,
                title: {
                    text: "Equity and Balance Graph",
                    fontFamily: "arial",
                    fontColor: titleFontColor
                },
                zoomEnabled: true,
                zoomType: "x",
                exportEnabled: true,
                exportFileName: "Equity and Balance Graph",
                axisY: {
                    includeZero: false,
                    title: "Prices",
                    fontFamily: "arial",
                    prefix: "$ ",
                    titleFontColor: titleFontColor,
                    labelFontColor: labelFontColor,
                    gridColor: foregroundColor,
                    gridThickness:0,
                    lineColor: foregroundColor,
                    maximum: upperyAxisMargin,
                    minimum: loweryAxisMargin,
                           crosshair:
                    {
                        enabled: crosshairEnabled,
                        color: foregroundColor,
                        snapToDataPoint: false,
                        labelFormatter: function(e) {
                            return "$" + CanvasJS.formatNumber(e.value, "##0.00");
                        }
                    }
                },
                axisX: {
                    scaleBreaks: {
                        type: "straight",
                        lineThickness: 0,
                        spacing: 20,
                        fillOpacity: 0.1,
                        customBreaks:[]
                    },
                    interval: timeFrame,
                    intervalType: "minute",
                    valueFormatString: "HH:mm",
                    titleFontColor: titleFontColor,
                    labelFontColor: labelFontColor,
                    gridThickness: 0,
                    labelAngle: -45,
                    gridDashType: "dot",
                    gridColor: foregroundColor,
                    lineColor: foregroundColor,
                    viewportMinimum: (whichData ? minimum : oldestViewTime),
                    maximum: max,
                    viewportMaximum: viewMax,

                    crosshair: {
                        enabled: crosshairEnabled,
                        color: foregroundColor,
                        snapToDataPoint: false
                    }
                },
                axisY2: {
                    includeZero: false,
                    title: "Balance",
                    fontFamily: "arial",
                    prefix: "$ ",
                    titleFontColor: titleFontColor,
                    labelFontColor: labelFontColor,
                    gridColor: foregroundColor,
                    gridThickness: 0,
                    lineColor: foregroundColor,
                    maximum: uppery2AxisMargin,
                    minimum: lowery2AxisMargin,
                    titleFontColor: "#C0504E", //red
                    labelFontColor: "#C0504E", 
                    lineColor: "#C0504E",
                    tickColor: "#C0504E",
                    crosshair:
                    {
                        enabled: crosshairEnabled,
                        color: foregroundColor,
                        snapToDataPoint: false,
                        labelFormatter: function (e) {
                            return "$" + CanvasJS.formatNumber(e.value, "##0.00");
                        }
                    }
                },
                dataPointMaxWidth: 12,
                data: [
                    {   // Volume
                        dataPointWidth: 5,
                        type: "column",
                        axisYIndex: 1,
                        color: volumeColor,
                        dataPoints: volumePoints,
                        toolTipContent: "Volume: {actual}"
                    },
                    {   // Graph Style Balance
                        name: "Balance",
                        dataPointWidth: 10,
                        type: graphStyle,
                        risingColor: "white",
                        axisYType: "secondary",
                        color: "#DF7970",//red
                        showInLegend: true,
                        dataPoints: balancePoints
                    },
                    {   // Graph Style Account Equity
                        dataPointWidth: 10,
                        type: graphStyle,
                        risingColor: bullColor,
                        color: graphColor,
                        dataPoints: graphPoints
                    },
                    {   // Moving Average
                        type: "spline",
                        axisYIndex: 0,
                        color: movingAverageColor,
                        name: "Moving Average",
                        showInLegend: true,
                        lineThickness: 1,
                        dataPoints: movingPoints
                    },
                    {  //Exponential Moving Average
                        type: "spline",
                        markerSize: 0,
                        name: "Exponential Moving Average",
                        color: "#AE7D99",//purple
                        yValueFormatString: "#,##0.00",
                        showInLegend: true,
                        dataPoints: exponentialMovingPoints,
                        lineThickness: 1
                    }
                ],
                subtitles: graphPoints.length === 0 ? [
                    {
                        text: "No data available",
                        verticalAlign: 'center',
                    }
                ] : []
            });

       
        var diff, startValue, endValue;

        var customBreaks = [];

        for (var i = 1; i < graphPoints.length; i++) {
            diff = graphPoints[i].x.getDate() - graphPoints[i - 1].x.getDate();
            if (diff == 1) {
                startValue = graphPoints[i - 1].x;
                endValue = graphPoints[i].x;
                customBreaks.push({startValue:startValue,endValue:endValue});
            }
        }
        chart.options.axisX.scaleBreaks.customBreaks = customBreaks;
        chart.render();
     
        setTimeout(function () {
            base64Image = chart.canvas.toDataURL();
            document.getElementById("Image").value = base64Image;
        }, chart.get("animationDuration") + 500);

        function toggleDataSeries(e) {
            if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                e.dataSeries.visible = false;
            } else {
                e.dataSeries.visible = true;
            }
            e.chart.render();
        }

    }

    function updateChart(_timeFrame, exponentialMovingAverageEnabled, movingAverage, volume, chart, forexAccount) {
        console.log("updating chart", _timeFrame);
        timeFrame = _timeFrame;
        highestDataPoint = -1;
        lowestDataPoint = -1;
        lowestLow = -1;
        highestDataPointBalance = -1;
        lowestDataPointBalance = -1;
        lowestLowBalance = -1;
        highestVolume = -1;
        dataRange = -1;
        balanceDataRange = -1;
        var date;
        var dateBalance;
        var formattedDate;
        var formattedDateBalance;
        graphPointsBC = [];
        graphPointsLine = [];
        balancePointsBarChart = [];
        balancePointsLine = [];

        Line = [];
        var forexAcc = "";
        if (forexAccount != null) {
            forexAcc = " &ForexAccount=" + forexAccount;
        }
        $.getJSON("@Url.Action("TimeFrames", "Trader")?timeFrame=" + _timeFrame + forexAcc, function (result) {
            if (result.data.length === 0) {
                graphPointsBC = [];
                graphPointsLine = [];
            }

            if (result.data2.length === 0) {
                balancePointsBarChart = [];
                balancePointsLine = [];
            }
            
            for (var c in result.data) {
                date = new Date(result.data[c].timeSlot);
                formattedDate = new Date(date.toISOString().replace('Z', '').replace('T', ' '));
                graphPointsBC.push({ x: formattedDate, y: [result.data[c].open, result.data[c].high, result.data[c].low, result.data[c].close, result.data[c].volume] });
                graphPointsLine.push({ x: formattedDate, y: result.data[c].close });
                //Used for volume scaling

                if (lowestLow == -1 || result.data[c].low < lowestLow) {
                    lowestLow = result.data[c].low;
                    //Used for max y-axis value
                    lowestDataPoint = lowestLow;
                }
                if (highestVolume == -1 || result.data[c].volume > highestVolume) {
                    highestVolume = result.data[c].volume;
                }
                if (lowestVolume == -1 || result.data[c].volume < lowestVolume) {
                    lowestVolume = result.data[c].volume;
                }
                //Used for max y-axis value
                if (highestDataPoint == -1 || result.data[c].high > highestDataPoint) {
                    highestDataPoint = result.data[c].high;
                }
            }

            dataRange = highestDataPoint - lowestDataPoint;

            //getting data for balance graph
            for (var c in result.data2) {
                dateBalance = new Date(result.data2[c].timeSlot);
                formattedDateBalance = new Date(dateBalance.toISOString().replace('Z', '').replace('T', ' '));
                balancePointsBarChart.push({ x: formattedDateBalance, y: [result.data2[c].open, result.data2[c].high, result.data2[c].low, result.data2[c].close, result.data2[c].volume] });
                balancePointsLine.push({ x: formattedDateBalance, y: result.data2[c].close });
                //Used for volume scaling
                if (lowestLowBalance == -1 || result.data2[c].low < lowestLowBalance) {
                    lowestLowBalance = result.data2[c].low;
                    //Used for max y-axis value
                    lowestDataPointBalance = lowestLowBalance;
                }
                //Used for max y-axis value
                if (highestDataPointBalance == -1 || result.data2[c].high > highestDataPointBalance) {
                    highestDataPointBalance = result.data2[c].high;
                }
            }
            
            balanceDataRange = highestDataPointBalance - lowestDataPointBalance;
            
            //callback;
            if (exponentialMovingAverageEnabled) {
                calculateExponentialMovingAverage(12);
            } else {
                exponentialMovingPoints = [];
            }
            if (movingAverage) {
                calcMovingAverage();
            }
            else {
                movingPoints = [];
            }
            if (exponentialMovingAverageEnabled) {
                calculateExponentialMovingAverage(12);
            } else {
                exponentialMovingPoints = [];
            }
            if (movingAverage) {
                calcMovingAverage();
            }
            else {
                movingPoints = [];
            }
            if (volume) {
                calcVolume();
            }
            else {
                volumePoints = [];
            }
            if (chart) {
                createChart();
            }
        });
    }

    function calculateExponentialMovingAverage(emaPeriod) {
        var currentEma = 0, prevEma = 0, temp = 0;
        exponentialMovingPoints = [];

        // Return if there are insufficient dataPoints
        if (graphPointsBC.length <= emaPeriod) return;

        for(var i = emaPeriod - 1; i < graphPointsBC.length; i++) {
            if(i === emaPeriod - 1) {
                // Calculate Simple average upto emaPeriod
                for (var j = 0; j < emaPeriod; j++) {
                    temp += graphPointsBC[j].y[3];
                }
                currentEma = temp / emaPeriod;
            } else {
                currentEma = graphPointsBC[i].y[3] * 2 / (emaPeriod + 1) + prevEma * (1 - 2 / (emaPeriod + 1));
            }

            exponentialMovingPoints.push({
                x: graphPointsBC[i].x,
                y: currentEma
            });
            prevEma = currentEma;
        }
    }

    function calcMACDLine() {

    }

    function calcMovingAverage() {
        var stick = 0;
        var numOfSticks = 5;
        var candleStickValues = [];
        var sum = 0.0;
        var average = 0;
        movingPoints = [];
        candleStickValues[0] = 0;
        for (var point in graphPointsBC) {
            if (applyTo == "close") {
                value = graphPointsBC[point].y[close];
            }
            else if (applyTo == "high") {
                value = graphPointsBC[point].y[high];
            }
            else if (applyTo == "open") {
                value = graphPointsBC[point].y[open];
            }
            else if (applyTo == "low") {
                value = graphPointsBC[point].y[low];
            }
            else if (applyTo == "median") {
                value = (graphPointsBC[point].y[high] + graphPointsBC[point].y[low])/2;
            }
            // Moving Average Calculations. Please check (https://introcs.cs.princeton.edu/java/15inout/MovingAverage.java.html)
            if (stick < numOfSticks) {
                candleStickValues[stick] = value;
                average = candleStickValues[stick];
                sum += candleStickValues[stick];
                average = sum / (stick+1); // first 5 values get the average of i-th previous terms
            }
            else {
                sum -= candleStickValues[stick % numOfSticks];
                candleStickValues[stick % numOfSticks] = value;
                sum += candleStickValues[stick % numOfSticks];
                average = sum / numOfSticks;
            }
            stick += 1;
            movingPoints.push({ x: graphPointsBC[point].x, y: average });
        }
    }

    function calcVolume() {
        var normalizedVolume = -1;
        var basePercentage = 3;
        var gapPercentage = 100 - marginPercentage - dataViewPercentage - volumeViewPercentage;
        var dataToVolumeGap = gapPercentage * dataRange / dataViewPercentage;
        var volumeCap = lowestDataPoint - dataToVolumeGap;
        var volumeFloor = -1 * ((((volumeViewPercentage - basePercentage) * dataRange) / dataViewPercentage) - volumeCap);
        volumeMargin = volumeFloor - ((basePercentage * dataRange) / dataViewPercentage);
        volumePoints = [];
        dataViewPercentage = 85;
        marginPercentage = 5;
        for (var point in graphPointsBC) {
            normalizedVolume = (((graphPointsBC[point].y[volume] - lowestVolume) * (volumeCap - volumeFloor)) / (highestVolume - lowestVolume)) + volumeFloor;
            volumePoints.push({ x: graphPointsBC[point].x, y: normalizedVolume, actual: graphPointsBC[point].y[volume] });
        }
    }

    // Go to a specific date
    function updateDate() {
        var d = document.getElementById("minimumDate").value;
        var date = new Date(d);
        var minMinutes = date.addMinutes(-1);
        updatedMinimum = true;
        whichData = true;
        if (minMinutes < oldestViewTime) {
            viewMax = minMinutes.addMinutes(timeFrame * numberOfDataPoints);
            max = null;
        }
        else {
            viewMax = null;
            max = minMinutes.addMinutes(timeFrame * numberOfDataPoints);
        }
        //chart.options.axisX.viewportMinimum = minMinutes;
        minimum = minMinutes;
        evaluateSettings();
    }

    function resetDate() {
        max = false;
        viewMax = false;
        whichData = false;
        evaluateSettings();
        updatedMinimum = false;
    }

    // Helper Function
    Date.prototype.addMinutes = function(min) {
        var date = new Date(this.valueOf());
        date.setDate(date.getMinutes() + min);
        return date;
    }

    Date.prototype.addMinutes = function(min) {
        var date = new Date(this.valueOf());
        return new Date(date.getTime() + min*60000);
    }

    function calcPercentages() {
        if (volumeEnabled && (volumeViewPercentage > marginPercentage)) {
            dataViewPercentage = 100 - volumeViewPercentage - marginPercentage;
        }
        else {
            dataViewPercentage = 100 - (2 * marginPercentage);
        }
    }

    function calcGraphView() {
        var showOnGraph = -1;
        //Points on graph
        if (numberOfDataPoints >= graphPointsBC.length) {
            showOnGraph = graphPointsBC.length;
        }
        else {
            showOnGraph = numberOfDataPoints;
        }

        if (graphPointsBC.length === 0) {
            oldestViewTime = new Date();
            upperyAxisMargin = 1;
            loweryAxisMargin = 0;
            return;
        }

        //Assumes date is in ascending order
        oldestViewTime = new Date((graphPointsBC[graphPointsBC.length - 1].x).getTime());
        //Assumption date in descending order
        //oldestViewTime = new Date((graphPointsBC[0].x).getTime());
        oldestViewTime.setTime(oldestViewTime.getMinutes() - timeFrame * showOnGraph);
        oldestViewTime.setMinutes(oldestViewTime.getMinutes() - timeFrame);
        //Margins
        console.log("data"+dataViewPercentage);
        var marginAmount = (marginPercentage * dataRange) / dataViewPercentage;
        var marginAmountBalance = (marginPercentage * balanceDataRange) / dataViewPercentage;

        upperyAxisMargin = highestDataPoint + marginAmount;
        uppery2AxisMargin = highestDataPointBalance + marginAmountBalance;
        if ((lowestDataPoint - marginAmount) < 0) {
            loweryAxisMargin = 0;
        }
       if ((lowestDataPointBalance - marginAmountBalance) < 0) {
          lowery2AxisMargin = 0;
       }
        else {
            lowery2AxisMargin = lowestDataPointBalance - marginAmountBalance;
            if (volumeEnabled && marginPercentage < volumeViewPercentage) {
                loweryAxisMargin = volumeMargin;
            }
            else {
                loweryAxisMargin = lowestDataPoint - marginAmount;
            }
        }
        yRange = (highestDataPoint + upperyAxisMargin) - (lowestDataPoint - loweryAxisMargin);
        y2Range = (highestDataPointBalance + uppery2AxisMargin) - (lowestDataPointBalance - lowery2AxisMargin);
    }

    function timeIntervalToolbarDisplay() {
        var timeIntervalTB = document.getElementById("timeIntervalTB");
        var timeIntervalTBEnabled = document.getElementById("timeIntervalTBT").checked;
        if (timeIntervalTBEnabled) {
            timeIntervalTB.style.display = "inline-flex";
        }
        else {
            timeIntervalTB.style.display = "none";
        }
    }

    function exponentialMovingAverageToolbarDisplay() {
        var exponentialMovingAverageTBEnabled = document.getElementById("exponentialMovingAverageTBT").checked;
        if (exponentialMovingAverageTBEnabled) {
            exponentialMovingAverageTB.style.display = "block";
        }
        else {
            exponentialMovingAverageTB.style.display = "none";
        }
    }

    function movingAverageToolbarDisplay() {
        var movingAverageTBEnabled = document.getElementById("movingAverageTBT").checked;
        if (movingAverageTBEnabled) {
            movingAverageTB.style.display = "block";
        }
        else {
            movingAverageTB.style.display = "none";
        }
    }

    function volumeToolbarDisplay() {
        var volumeTBEnabled = document.getElementById("volumeTBT").checked;
        if (volumeTBEnabled) {
            volumeTB.style.display = "block";
        }
        else {
            volumeTB.style.display = "none";
        }
    }

    function crosshairToolbarDisplay() {
        var crosshairTBEnabled = document.getElementById("crosshairTBT").checked;
        if (crosshairTBEnabled) {
            crosshairTB.style.display = "block";
        }
        else {
            crosshairTB.style.display = "none";
        }
    }

    function graphStyleToolbarDisplay() {
        var graphStyleTBEnabled = document.getElementById("graphStyleTBT").checked;
        if (graphStyleTBEnabled) {
            graphStyleTB.style.display = "inline-flex";
        }
        else {
            graphStyleTB.style.display = "none";
        }
    }

    function dateSearchToolbarDisplay() {
        var dateSearchTBEnabled = document.getElementById("dateSearchTBT").checked;
        if (dateSearchTBEnabled) {
            dateSearch.style.display = "block";
        }
        else {
            dateSearch.style.display = "none";
        }
    }

    function exponentialMovingAverageToolbarAction() {
        document.getElementById("exponentialMovingAverage").checked = !exponentialMovingAverageEnabled;
        evaluateSettings();
    }

    function movingAverageToolbarAction() {
        document.getElementById("movingAverage").checked = !movingAverageEnabled;
        evaluateSettings();
    }

    function crosshairToolbarAction() {
        document.getElementById("crosshair").checked = !crosshairEnabled;
        evaluateSettings();
    }

    function volumeToolbarAction() {
        document.getElementById("volume").checked = !volumeEnabled;
        evaluateSettings();
    }

    function graphStyleToolbarAction(style) {
        if ("candlestick" == style) {
            document.getElementById("graphStyle").selectedIndex = "0";
        }
        else if ("ohlc" == style) {
            document.getElementById("graphStyle").selectedIndex = "1";
        }
        else {
            document.getElementById("graphStyle").selectedIndex = "2";
        }
        evaluateSettings();
    }

    var target = -1;
    function updateAccount(id) {
        target = id;
        init = true;
        evaluateSettings();
    }

    function updateCharts() {
        resetDate();
        updateChart(timeFrame, exponentialMovingAverageEnabled, movingAverageEnabled, volumeEnabled, true, target);
    }

    function autoSaveUserTemplate() {
        $.ajax({
            type: "POST",
            url: '@Url.Action("SaveAutoGeneratedUserTemplate", "Trader")',
            data: { 
                graphTemplate: {
                    TemplateName: "__AutoGenTemplate", 
                    TimeIntTool: document.getElementById("timeIntervalTBT").checked,
                    ExponentialMovingAverageTool: document.getElementById("exponentialMovingAverageTBT").checked,
                    MovingAverageTool: document.getElementById("movingAverageTBT").checked,
                    VolumeTool: document.getElementById("volumeTBT").checked,
                    CrosshairTool: document.getElementById("crosshairTBT").checked,
                    GraphStyleTool: document.getElementById("graphStyleTBT").checked,
                    FindDateTool: document.getElementById("dateSearchTBT").checked,
                    ExponentialMovingAverageInd: document.getElementById("exponentialMovingAverage").checked,
                    MovingAverageInd: document.getElementById("movingAverage").checked,                   
                    MovingAverageColor: document.getElementById("movingAverageColor").value,
                    MovingAverageOption: document.getElementById("movingAverageApplyTo").value,
                    VolumeInd:document.getElementById("volume").checked,
                    VolumeColor: document.getElementById("volumeColor").value,
                    CrosshairInd: document.getElementById("crosshair").checked,
                    GraphStyleGS: document.getElementById("graphStyle").value,
                    TimeFrameGS: "h4s",
                    TimeFrame: timeFrame,
                    TitleColor: document.getElementById("titleFontColor").value,
                    LabelColor: document.getElementById("labelFontColor").value,
                    BullColor: document.getElementById("bullColor").value,
                    BearColor: document.getElementById("bearColor").value,
                    BarColor: document.getElementById("barColor").value,
                    LineColor: document.getElementById("lineColor").value,
                    ForegroundColor: document.getElementById("foreground").value,
                    BackgroundColor: document.getElementById("background").value,
                    YAxisMargin: document.getElementById("yAxisMargin").value,
                    VolumeViewPercentage: document.getElementById("volumeView").value,
                    DataPointsOnScreen: document.getElementById("dataPointsView").value,
                }
            },
            cache: false,
            success: function (result) {},
            error: function () {
                console.log("Auto saving user template failed. Try again later.");
            }
        });
    }
</script>

