﻿function getjQueryObj(id) { return $("#ctl00_Main_" + id) }
function getCtrlId(id) { return "ctl00_Main_" + id }

$(document).ready(function() {
    initJsChartViewer();

    $(".startDate").datepicker({
        maxDate: '0d',
        numberOfMonths: 3,
        showButtonPanel: true,
        dateFormat: ' d-M-yy',
        stepMonths: 3
    });

    $(".endDate").datepicker({
        maxDate: '0d',
        numberOfMonths: 3,
        showButtonPanel: true,
        dateFormat: ' d-M-yy',
        stepMonths: 3
    });

    getjQueryObj("DateRange").bind("change",
                function() {
                    var endDate = new Date();
                    var startDate = addMonth(endDate, parseInt('-' + $(this).val()));
                    getjQueryObj("tbStartDate").val(startDate.format("d-MMM-yyyy"));
                    getjQueryObj("tbEndDate").val(endDate.format("d-MMM-yyyy"));

                    JsChartViewer.get(getCtrlId('WebChartViewer1')).partialUpdate();
                });

    $(".priceOverlay").change(setArg);
    $(".indicator").change(setArg);

    $(".priceOverlayArg").blur(setArgValidation);
    $(".indicatorArg").blur(setArgValidation);

    getjQueryObj("ddlMyTemplate").change(function() {
        $("#templateForm").hide();
        $("#chkSaveTemplate").attr('checked', false);
        setTemplateValue($(this).val());
    })

    $('.indicatorArg').attr('maxLength', 3);
    $('.priceOverlayArg').attr('maxLength', 3);

    getjQueryObj('tbSymbol_tbSymbol').blur(function() {
        if ($.trim($('#symbol').val()).toLowerCase() != $.trim($(this).val()).toLowerCase()) {
            window.location.href = siteUrl + '/chart/' + $(this).val();
        }
    });

    $('#myTemplateDiv img').click(function() {
        if (!confirm('Delete selected template ? ')) return false;

        var currentTemplate = getjQueryObj("ddlMyTemplate").find("option[selected]").text();
        PageMethods.DeleteTemplate(currentTemplate, function() {
            getjQueryObj("ddlMyTemplate").find("option[selected]").remove();
            if (getjQueryObj('ddlMyTemplate').find('option').length == 0)
                $('#myTemplateDiv').hide();
        });
    });

    getjQueryObj('DateRange').qtip({
        content: 'you can also drag chart to scroll left or right',
        position: { corner: { target: 'topMiddle', tooltip: 'bottomMiddle'} }
    });


    var watchListContent = '';
    if (!isLogin())
        watchListContent = 'Login to access your watchlist from here'
    else if ($('#watchListDetail a').length == 0)
        watchListContent = "You have not created a watchlist. <a href=\"\\members\\mywatchlist\">create a watchlist </a> and access the TA Chart from here.";
    else
        watchListContent = $('#watchListDetail');

    $('#myWatchList').qtip({
    content: watchListContent,
        position: { corner: { target: 'topRight', tooltip: 'topLeft'} , adjust: { x: -15, y: -50 } },
        hide: { when: 'mouseout', fixed: true }
    });

    $('#watchListDetail a').click(function() {
        window.location = siteUrl + "/chart/" + $(this).text();
    });

    _indicatorList = Sys.Serialization.JavaScriptSerializer.deserialize(_indicatorListJson);
    updatePermalink();

});                     // document ready end

function setArg() {
    var indicator;
    for (var i = 0; i < _indicatorList.length; i++) {
        if (_indicatorList[i].IndicatorID == $(this).val()) {
            indicator = _indicatorList[i]; break;
        }
    } //end for

    var args = $(this).parent().find("input")

    if (indicator) {
        if (args[0] && indicator.Arg1) args[0].value = indicator.Arg1;
        if (args[1] && indicator.Arg2) args[1].value = indicator.Arg2;
        if (args[2] && indicator.Arg3) args[2].value = indicator.Arg3;
    } else {
        if (args[0]) args[0].value = "";
        if (args[1]) args[1].value = "";
        if (args[2]) args[2].value = "";
    }
}

function setArgValidation() {
    var arg = $(this);
    if (arg.val() == "" || arg.val().match(/^[\d.]+$/)) {
        $("#msg").text("");
    } else {
        var timer = setTimeout("$('#" + arg.attr("id") + "').select();$('#" + arg.attr("id") + "').focus();", 20);
        var timer2 = setTimeout(" $('#msg').removeClass().addClass('errorMsg').text('positive numeric (1-500) only.');", 100);
    }
}

function addMonth(d, month) {
    t = new Date(d);
    t.setMonth(d.getMonth() + month);
    if (t.getDate() < d.getDate()) {
        t.setDate(0);
    }
    return t;
}

function saveTemplate() {
    if ($('uid').val() == '') return;

    if ($("#chkSaveTemplate").is(':checked')) {
        var currentTemplate = getjQueryObj("ddlMyTemplate").find("option[selected]").text();

        var tName = jQuery.trim($("#templateName").val());
        var tString = getTemplateValue();
        var tIsDefault = $("#chkDefaultTemplate").is(':checked');

        if (!$("#chkOverwrite").is(':checked') && (tName == '' || tName == 'enter a template name')) {
            alert("please enter a new template name \n or choose to update " + currentTemplate);
        }
        else {

            if ($("#chkOverwrite").is(':checked')) tName = currentTemplate;
            PageMethods.SaveTemplate(tName, tString, tIsDefault, onSaveTemplateCompleted);

            if ($("#chkOverwrite").is(':checked'))
                getjQueryObj("ddlMyTemplate").find("option[selected]").remove();

            getjQueryObj("ddlMyTemplate").append("<option value='" + tString + "' selected='selected'>" + tName + "</option>");
            $("#myTemplateDiv").show();
        }
    }
}

function onSaveTemplateCompleted(result) {
    if (result) {
        $("#msg").removeClass().addClass('statusMsg').text('template saved').fadeOut(2000);
    }
    else {
        $("#msg").removeClass().addClass('errorMsg').text('template not saved').fadeOut(2000);
    }
    $("#templateForm").hide();
    $("#chkSaveTemplate").attr('checked', false);
}

function getTemplateValue() {
    var t = "";
    t = getjQueryObj("ddlChartType").val() + "||"; // || for chart size to keep it consistent with old data
    t += "ind1," + getjQueryObj("Ind1").val() + "," + getjQueryObj("Ind1Arg1").val() + "," + getjQueryObj("Ind1Arg2").val() + "," + getjQueryObj("Ind1Arg3").val() + "|";
    t += "ind2," + getjQueryObj("Ind2").val() + "," + getjQueryObj("Ind2Arg1").val() + "," + getjQueryObj("Ind2Arg2").val() + "," + getjQueryObj("Ind2Arg3").val() + "|";
    t += "ind3," + getjQueryObj("Ind3").val() + "," + getjQueryObj("Ind3Arg1").val() + "," + getjQueryObj("Ind3Arg2").val() + "," + getjQueryObj("Ind3Arg3").val() + "|";
    t += "ind4," + getjQueryObj("Ind4").val() + "," + getjQueryObj("Ind4Arg1").val() + "," + getjQueryObj("Ind4Arg2").val() + "," + getjQueryObj("Ind4Arg3").val() + "|";
    t += "po1," + getjQueryObj("Pol1").val() + "," + getjQueryObj("Pol1Arg1").val() + "," + getjQueryObj("Pol1Arg2").val() + ",|";
    t += "po2," + getjQueryObj("Pol2").val() + "," + getjQueryObj("Pol2Arg1").val() + "," + getjQueryObj("Pol2Arg2").val() + ",|";
    t += "po3," + getjQueryObj("Pol3").val() + "," + getjQueryObj("Pol3Arg1").val() + "," + getjQueryObj("Pol3Arg2").val() + ",|";
    t += "po4," + getjQueryObj("Pol4").val() + "," + getjQueryObj("Pol4Arg1").val() + "," + getjQueryObj("Pol4Arg2").val() + ",|";
    t += getjQueryObj("DateRange").val() + "|";
    t += getjQueryObj('rblDataPeriod').find("input[checked]").val() + "|";
    t += getjQueryObj("ddlScale").val();
    return t;
}

function setTemplateValue(templateString) {

    var settings = templateString.split('|');
    getjQueryObj('ddlChartType').val(settings[0]);

    getjQueryObj('rblDataPeriod').find("input").each(function() {
        if ($(this).val() == settings[11]) $(this).attr("checked", true);
    })

    getjQueryObj('ddlScale').val(settings[12]);

    var ind1Setting = settings[2].split(','); getjQueryObj('Ind1').val(ind1Setting[1]);
    getjQueryObj('Ind1Arg1').val(ind1Setting[2]); getjQueryObj('Ind1Arg2').val(ind1Setting[3]); getjQueryObj('Ind1Arg3').val(ind1Setting[4]);

    var ind2Setting = settings[3].split(','); getjQueryObj('Ind2').val(ind2Setting[1]);
    getjQueryObj('Ind2Arg1').val(ind2Setting[2]); getjQueryObj('Ind2Arg2').val(ind2Setting[3]); getjQueryObj('Ind2Arg3').val(ind2Setting[4]);

    var ind3Setting = settings[4].split(','); getjQueryObj('Ind3').val(ind3Setting[1]);
    getjQueryObj('Ind3Arg1').val(ind3Setting[2]); getjQueryObj('Ind3Arg2').val(ind3Setting[3]); getjQueryObj('Ind3Arg3').val(ind3Setting[4]);

    var ind4Setting = settings[5].split(','); getjQueryObj('Ind4').val(ind4Setting[1]);
    getjQueryObj('Ind4Arg1').val(ind4Setting[2]); getjQueryObj('Ind4Arg2').val(ind4Setting[3]); getjQueryObj('Ind4Arg3').val(ind4Setting[4]);

    var pol1Settings = settings[6].split(',');
    getjQueryObj('Pol1').val(pol1Settings[1]);
    getjQueryObj('Pol1Arg1').val(pol1Settings[2]); getjQueryObj('Pol1Arg2').val(pol1Settings[3]);

    var pol2Settings = settings[7].split(',');
    getjQueryObj('Pol2').val(pol2Settings[1]);
    getjQueryObj('Pol2Arg1').val(pol2Settings[2]); getjQueryObj('Pol2Arg2').val(pol2Settings[3]);

    var pol3Settings = settings[8].split(',');
    getjQueryObj('Pol3').val(pol3Settings[1]);
    getjQueryObj('Pol3Arg1').val(pol3Settings[2]); getjQueryObj('Pol3Arg2').val(pol3Settings[3]);

    var pol4Settings = settings[9].split(',');
    getjQueryObj('Pol4').val(pol4Settings[1]);
    getjQueryObj('Pol4Arg1').val(pol4Settings[2]); getjQueryObj('Pol4Arg2').val(pol4Settings[3]);
}

function toggleTemplateForm() {
    $("#templateForm").toggle();
    if ($("#myTemplateDiv").is(":visible") == true) {
        $("#overwriteDiv").show();
        $("#currentTemplate").text(getjQueryObj("ddlMyTemplate").find("option[selected]").text());
    } else {
        $("#overwriteDiv").hide();
    }
}

function addToWatchList(watchListId) {
    TSService.AddToWatchList(watchListId, $('#symbol').val(), function(result) {
        $('#lnkAddToWatch').text('watching');
        $('#watchList').hide();
    });
}

function createWatchList() {
    var watchListName = $("#watchListName").val();
    TSService.AddToNewWatchList($('#uid').val(), $("#watchListName").val(), '', $('#symbol').val(), function(result) {
        $('#lnkAddToWatch').text('watching');
        $('#watchList').hide();
        $('#watchList').empty().append('<div onclick="addToWatchList(' + result + ')">' + watchListName + '</div>');
    });
}

function onCrossHairClick() {
    if ($("#chkCrosshair").is(":checked")) {
        $('#verticalLine').show();
        $('#horizontalLine').show();
        getjQueryObj('WebChartViewer1').bind('mousemove', function(e) { drawLine(e, this) });
    }
    else {
        $('#verticalLine').hide();
        $('#horizontalLine').hide();
        getjQueryObj('WebChartViewer1').unbind('mousemove', function(e) { drawLine(e, this) });
    }
}

function drawLine(event, obj) {
    if ($("#chkCrosshair").is(":checked")) {
        var verticalLeft = event.clientX - $('#column1').offset().left;
        $('#verticalLine').css({ left: verticalLeft, top: obj.style.top, height: obj.offsetHeight });
        $('#horizontalLine').css({ left: obj.style.left, top: event.clientY, width: obj.offsetWidth });
    }
}

function updatePermalink() {
    var host = siteUrl;
    var symbol = $('#symbol').val();
    var startdate = getjQueryObj("tbStartDate").val();
    var enddate = getjQueryObj("tbEndDate").val();
    var template = getTemplateValue();

    var permalink = host + "/chart/" + symbol + "?startdate=" + startdate + "&enddate=" + enddate + "&template=" + template;
    $("#permalinkUrl input").val(permalink);
}

// Initialize browser side Javascript controls
function initJsChartViewer() {
    // Check if the Javascript ChartViewer library is loaded
    if (!window.JsChartViewer)
        return;

    // Get the Javascript ChartViewer object
    var viewer = JsChartViewer.get(getCtrlId('WebChartViewer1'));    

    // Detect if browser is capable of support partial update (AJAX chart update)
    if (JsChartViewer.canSupportPartialUpdate()) {
        // Browser can support partial update, so connect the view port change event and
        // the submit button to trigger a partial update
        viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);
        document.getElementById(getCtrlId('SubmitButton')).onclick = function() {

            if ($.trim($('#symbol').val()).toLowerCase() == $.trim(getjQueryObj('tbSymbol_tbSymbol').val()).toLowerCase()) {
                saveTemplate();
                viewer.partialUpdate();
            }
            return false;
        };

        // For partial updates, we need to pass the start date / end date select boxes values to/from
        // the server via Javascript ChartViewer custom attributes
        var controlsToSync = [getCtrlId('tbStartDate'), getCtrlId('tbEndDate'), getCtrlId('ddlChartType'), getCtrlId('rblDataPeriod'), getCtrlId('ddlScale'),
                getCtrlId('Pol1'), getCtrlId('Pol2'), getCtrlId('Pol3'), getCtrlId('Pol4'),
                getCtrlId('Pol1Arg1'), getCtrlId('Pol1Arg2'), getCtrlId('Pol2Arg1'), getCtrlId('Pol2Arg2'),
                getCtrlId('Pol3Arg1'), getCtrlId('Pol3Arg2'), getCtrlId('Pol4Arg1'), getCtrlId('Pol4Arg2'),
                getCtrlId('Ind1'), getCtrlId('Ind2'), getCtrlId('Ind3'), getCtrlId('Ind4'),
                getCtrlId('Ind1Arg1'), getCtrlId('Ind1Arg2'), getCtrlId('Ind1Arg3'),
                getCtrlId('Ind2Arg1'), getCtrlId('Ind2Arg2'), getCtrlId('Ind2Arg3'),
                getCtrlId('Ind3Arg1'), getCtrlId('Ind3Arg2'), getCtrlId('Ind3Arg3'),
                getCtrlId('Ind4Arg1'), getCtrlId('Ind4Arg2'), getCtrlId('Ind4Arg3')];
        viewer.attachHandler("PreUpdate", function() { copyToViewer(viewer, controlsToSync); });
        viewer.attachHandler("PostUpdate", function() { copyFromViewer(viewer, controlsToSync); });
    }
}
// A utility to copy HTML control values to Javascript ChartViewer custom attributes
function copyToViewer(viewer, controlsToSync) {
    for (var i = 0; i < controlsToSync.length; ++i) {
        var obj = document.getElementById(controlsToSync[i]);
        if (obj && !{ "button": 1, "file": 1, "image": 1, "reset": 1, "submit": 1}[obj.type]) {
            if ((obj.type == "checkbox") || (obj.type == "radio"))
                viewer.setCustomAttr(obj.id, obj.checked ? 1 : 0);
            else if (obj.id == getCtrlId('rblDataPeriod'))
                viewer.setCustomAttr(obj.id, $("#" + obj.id).find("input[checked]").val());
            else
                viewer.setCustomAttr(obj.id, obj.value);
        }
    }
}
// A utility to copy Javascipt ChartViewer custom attributes to HTML controls
function copyFromViewer(viewer, controlsToSync) {
    for (var i = 0; i < controlsToSync.length; ++i) {
        var obj = document.getElementById(controlsToSync[i]);
        if (obj) {
            var value = viewer.getCustomAttr(obj.id);
            if (typeof value != "undefined") {
                if ((obj.type == "checkbox") || (obj.type == "radio"))
                    obj.checked = parseInt(value);
                else
                    obj.value = value;

                if (obj.validate)
                    obj.validate();
            }
        }
    }
    updatePermalink();
}

function onSymbolAutoCompleteSelected(source, eventArgs) {
    window.location.href = siteUrl + '/chart/' + eventArgs.get_value();
}