﻿/// <reference path="fitsystems-global-values.js" />
/// <reference path="fitsystems-editwatch.js" />
/// <reference path="jquery-1.5.1-vsdoc.js" />



$(document).ready(function () {
    SetDisabled('body');
    EditWatchSetup('body');
    SetupJQueryForm('body');
});

/*
-------------------------------------------------
Setup jQuery Form helpers, datepicker etc
-------------------------------------------------
*/
function getDateYymmdd(value) {
    if (value == null)
        return null;
    return $.datepicker.parseDate("yy/mm/dd", value);
}

function SetupJQueryForm(container) {
    if (fitsystems_debug)
        console.log("SetupJQueryForm: container: " + container);
    // DateTimePicker    
    $(container).find('.DateTimePicker').each(function () {
        var minDate = getDateYymmdd($(this).data("val-rangedate-min"));
        var maxDate = getDateYymmdd($(this).data("val-rangedate-max"));
        $(this).datetimepicker({
            dateFormat: "dd/mm/yy",  // hard-coding uk date format, but could embed this as an attribute server-side (based on the current culture)
            minDate: minDate,
            maxDate: maxDate
        });
        //$(this).datetimepicker();
    });

    if (fitsystems_debug)
        console.log("SetupJQueryForm: outside Find .ModalTarget..");
    $(container).find('.ModalTarget').each(function () {
        if (fitsystems_debug)
            console.log("SetupJQueryForm: Find .ModalTarget..");
        var modalTargetId = this.id;
        var modalId = modalTargetId + "_Modal";
        var modalTextAreaId = modalId + "_TextArea";
        var modalPreviewAreaId = modalId + "_PreviewArea";
        var modalInjectButtonId = modalId + "_InjectButton";

        if (fitsystems_debug)
            console.log("SetupJQueryForm: Find .Modal: modalTargetId: " + modalTargetId + " modalId: " + modalId + " modalTextAreaId: " + modalTextAreaId);

        var html = "<div id='" + modalId + "' class='Modal'>";

        html += "<div id='" + modalId + "_Tabs'>";
        html += "<ul>";
        html += "<li><a href='#" + modalId + "_Tabs-1'>Input</li>";
        html += "<li><a href='#" + modalId + "_Tabs-2'>Preview</li>";
        html += "</ul>";

        html += "<div id='" + modalId + "_Tabs-1'>";
        html += "<textarea id='" + modalTextAreaId + "'>" + $(this).val() + "</textarea>";
        html += "</div>";

        html += "<div id='" + modalId + "_Tabs-2'>";
        html += "<iframe id='" + modalPreviewAreaId + "'></iframe>";
        html += "</div>";

        html += "</div>";

        html += "<div class='ModalButtons'>";
        html += "<img id='" + modalInjectButtonId + "' class='Button Save' src='/Content/images/icons/55x55/file_create.png' title='Inject Data' alt='Inject Data'>";
        html += "<img class='Button Exit' onclick='$(\"#" + modalId + "\").dialog(\"close\");' src='/Content/images/icons/55x55/file_exit.png' title='Cancel' alt='Cancel'>";
        html += "</div>";

        html += "</div>";
        $(this).after(html);

        $("#" + modalId + "_Tabs").tabs({
            selected: 2
        });

        var delay;
        var myCodeMirror = CodeMirror.fromTextArea(document.getElementById(modalTextAreaId), {
            mode: 'text/html',
            tabMode: 'indent',
            lineNumbers: true,
            onChange: function () {
                clearTimeout(delay);
                delay = setTimeout(updatePreview, 300);
            }
        });

        function updatePreview() {
            var preview = document.getElementById(modalPreviewAreaId).contentDocument;
            preview.open();
            preview.write(myCodeMirror.getValue());
            preview.close();
        }
        setTimeout(updatePreview, 300);

        $('#' + modalId).dialog({
            autoOpen: false,
            modal: true,
            width: 800,
            height: 600
        });

        $('#' + modalInjectButtonId).click(function () {
            $('#' + modalTargetId).val(myCodeMirror.getValue());
            $('#' + modalId).dialog('close');
        });

        $(this).click(function () {
            myCodeMirror.setValue($('#' + modalTargetId).val());
            $('#' + modalId).dialog('open');
            myCodeMirror.refresh();
        });
    });
}

/*
-------------------------------------------------
Post Download Disable Inputs/Selects
-------------------------------------------------
*/
function SetDisabled(container) {
//    if (fitsystems_debug)
//        console.log("Disable: container: " + container);
    $(container).find('.Disabled').each(function() {
        $(this).attr('disabled', true);
    });
    $(container).find('.Locked').each(function () {
        $(this).attr('disabled', true);
    });
}

/*
-------------------------------------------------
Enable and Disable
-------------------------------------------------
*/
function UnlockForm(FormId) {
    UnlockFormIcons(FormId);
    UnlockFormInputs(FormId);
}
function LockForm(FormId) {
    CancelHighlightInputContainer(FormId);
    LockFormIcons(FormId);
    LockFormInputs(FormId);
}

function UnlockFormIcons(FormId) {
    if (fitsystems_debug)
        console.log("UnlockFormIcons: FormId: " + FormId);
    $(FormId + "_Locked").fadeOut('fast', function () {
        $(FormId + "_Unlocked").fadeIn('fast');
    });
}
function LockFormIcons(FormId) {
    if (fitsystems_debug)
        console.log("LockFormIcons: FormId: " + FormId);
    $(FormId + "_Unlocked").fadeOut('fast', function () {
        $(FormId + "_Locked").fadeIn('fast');
    });
}

function UnlockFormInputs(FormId) {
    if (fitsystems_debug)
        console.log("UnlockFormInputs: FormId: " + FormId);
    $(FormId).find('.Locked').each(function () {
        $(this).attr('disabled', false);
        $(this).removeClass('Locked');
        $(this).addClass('Unlocked');
    });
}
function LockFormInputs(FormId) {
    if (fitsystems_debug)
        console.log("LockFormInputs: FormId: " + FormId);
    $(FormId).find('.Unlocked').each(function () {
        $(this).attr('disabled', true);
        $(this).removeClass('Unlocked');
        $(this).addClass('Locked');
    });
}





/*
-------------------------------------------------
FetchList
-------------------------------------------------
*/
function FetchList(controller, returnElementId, previousCommandResultData, formIdOfPreviousCommandResult) {
    if(fitsystems_debug)
        console.log("FetchList: controller: " + controller + ", returnElementId: " + returnElementId);
    jQuery.ajax({
        type: 'POST',
        url: controller + "/_List",
        data: {},
        beforeSend: function () {
            if (fitsystems_debug)
                console.log("AjaxHelper: Before:");
            // this is where we append a loading image
            $(returnElementId + "Loading").show();
        },
        success: function (data) {
            if (fitsystems_debug)
                console.log("AjaxHelper: Success:");
            $(returnElementId).html(data);
            SetDisabled(returnElementId);
            EditWatchSetup(returnElementId);
            SetupJQueryForm(returnElementId);
            $(returnElementId + "Loading").hide();
            PostFetchDisplay(previousCommandResultData, formIdOfPreviousCommandResult);
        },
        error: function () {
            // failed request; give feedback to user
            if (fitsystems_debug)
                console.log("AjaxHelper: Error:");
            alert(data);
            $(returnElementId).html(data);
            SetDisabled(returnElementId);
            EditWatchSetup(returnElementId);
            SetupJQueryForm(returnElementId);
            $(returnElementId + "Loading").hide();
            PostFetchDisplay(previousCommandResultData, formIdOfPreviousCommandResult);
        }
    });
}
function PostFetchDisplay(previousCommandResultData, formIdOfPreviousCommandResult) {
    LockForm(formIdOfPreviousCommandResult);

    $(formIdOfPreviousCommandResult).find('.FormMessage').each(function () {
        $(this).slideUp('slow', function () {
            $(this).html(JsonCommandResultToHTMLString(previousCommandResultData));
            $(this).slideDown('slow', function () {
                $(this).delay(1000).slideUp('slow');
            });
        });
    });

    $(formIdOfPreviousCommandResult).animate({ backgroundColor: "#DDFFDD" }, 500, function () {
        $(this).animate({ backgroundColor: "#FFFFFF" }, 500, function () {
            $(this).css('background-color', '');
        });
    });
}

/*
-------------------------------------------------
Delete
-------------------------------------------------
*/
// bug prevents row animation, so animates td then removes tr
function DeleteForm(formId) {
    if (fitsystems_debug)
        console.log("Delete:");
    var split = formId.toString().split("_");
    var controller = split[0].toString().substring(1, split[0].length);
    var id = split[1];
    if (fitsystems_debug)
        console.log("Delete: controller: " + controller + " formId: " + formId + "id: " + id);
    jQuery.ajax({
        type: 'POST',
        url: controller + "/Delete",
        data: { id: id },
        beforeSend: function () {
            // this is where we append a loading image
            if (fitsystems_debug)
                console.log("beforeSend");
        },
        success: function (data) {
            // successful request; do something with the data
            if (fitsystems_debug)
                console.log("Success");
            if (data.Success) {
                if (fitsystems_debug)
                    console.log("The operation was a success, controller: " + controller + " id: " + id);
                $(formId).effect("highlight", { color: "#e33535" }, 500).fadeOut(500, function () { $(this).remove(); });
            }
            else {
                if (fitsystems_debug)
                    console.log("The operation was a failure, controller: " + controller + " id: " + id);
                $(formId).effect("highlight", { color: "#e33535" }, 500);
                alert(data.Title + ": " + data.Message);
            }
        },
        error: function () {
            // failed request; give feedback to user
            if (fitsystems_debug)
                console.log("Error");
            alert("Failed to delete reccord");
        }
    });
}

/*
-------------------------------------------------
Success and Failure
-------------------------------------------------
*/
function OnSuccess(data, formId, refreshList) {
    if (fitsystems_debug)
        console.log("OnSuccess: formId: " + formId + " data.Success: " + data.Success);
    if (data.Success) {
        SetDefaultValues(formId);
        var split = formId.toString().split("_");
        var controller = split[0].toString().substring(1, split[0].length);
        if(refreshList)
            FetchList(controller, "#" + controller + "_List", data, formId);
        LockForm(formId);
    }
    else {
        OnFailure(data, formId);
    }
}

function OnFailure(data, formId) {
    if (fitsystems_debug)
        console.log("OnFailure: formId: " + formId + " data.Success: " + data.Success);

    $(formId).find('.FormMessage').each(function () {
        $(this).slideUp('slow', function () {
            $(this).html(JsonCommandResultToHTMLString(data));
            $(this).slideDown();
        });
    });

    $(formId).animate({ backgroundColor: "#FFDDDD" }, 500, function () {
        $(this).animate({ backgroundColor: "#FFFFFF" }, 500, function () {
            $(this).css('background-color', '');    
        });
    });
}

function SetDefaultValues(formId) {
        if (fitsystems_debug)
            console.log("SetDefaultValues: FormId: " + formId);
        $(formId).find('input').each(function () {
            $(this).data('default', this.value);
        });
        $(formId).find('select').each(function () {
            $(this).data('default', this.value);
        });
}
