﻿var URL = '';
var URL = '';
var Command = null;
var locale = 'en';
var WaitMessage = "<h2>" + localizedStrings['PleaseWait'] + "</h2><a class='stopRequest' style='text-decoration:none;font-weight:bold;float:right' href='javascript:void(0)' onclick='StopRequest()'>" + localizedStrings['Stop'] + "</a>";
var request;
var $dialog;
var cnt = -1;


function SetSettings(url, locale) {
    URL = url;
    locale = locale;
}

function BlockUIWait() {
    BlockUI(WaitMessage);
}

function BlockUIWaitRequest(r) {
    request = r;
    BlockUIWait();
}

function BlockUI(message) {
    $.blockUI({ css: {
        border: 'none',
        padding: '15px',
        backgroundColor: '#000',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: .9,
        color: '#fff',
        zIndex: 5001
    },
        overlayCSS: { zIndex: 5000 },
        message: message
    });
    return false;
}


function AjaxPostRequest(Url, onSuccess) {
    return AjaxRequest(Url, "POST", null, onSuccess, OnError);
}

function AjaxRequest(Url, type, data, onSuccess, onError) {
    var request = $.ajax({
        type: type,
        url: Url,
        data: data,
        success: onSuccess,
        error: onError
    });
    return request;
}


function GlowUI(resourceName, error) {
    $.unblockUI();
    if (error) {
        $.growlUI(localizedStrings['Error'], localizedStrings[resourceName], 5000, null, 'background: url(/UserControlsAdmin/MeetingService/css/img/error48.png) no-repeat 10px 10px');
    } else {
        $.growlUI(localizedStrings['Success'], localizedStrings[resourceName], 5000);
    }
}

function Reply(id) {
    cnt = -1;
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=reply&to=" + id + "&locale=" + locale, OnReplySuccess);
    return false;
};



function Contact(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=contact&to=" + id + "&locale=" + locale, OnSuccess);
    return false;
};

function Message(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=message&to=" + id + "&locale=" + locale, OnMessageSuccess);
    return false;
};


function OnMessageSuccess(res) {
    $.unblockUI();
    var go = localizedStrings['Go'];
    var buttons = {};
    buttons[go] = function () {
        var to = $("#to"),
			subject = $("#subject"),
			message = $("#message");

        BlockUIWait();

        request = AjaxRequest("/MeetingSender.ashx", "POST", { message: message.val(), type: "message", subject: subject.val(), to: to.val(), locale: locale },
        function (res) {
            $.unblockUI();
            if (res != 'true') {
                updateTips(localizedStrings['ServerError']);
            } else {
                $dialog.dialog('close');
                GlowUI("Sended", false);
            }
        },
            function () {
                $.unblockUI();
                updateTips(localizedStrings['ServerError']);
            }
        );
    };
        ShowWindow("SendMessage", res, buttons, false, 500, 450);
}

function Edit(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=edit&to=" + id + "&locale=" + locale, OnEditSuccess);
    return false;
}

function OnEditSuccess(res) {
    $.unblockUI();
    var save = localizedStrings['Save'];
    var buttons = {};
    buttons[save] = function () {
        var subject = $("#subject"),
			time = $('#start option:selected').val() + "-" + $('#end option:selected').val(),
			day = $('#modal-form input:radio:checked'),
            to = $("#to");

        BlockUIWait();

        if (subject.val() == null || subject.val() == '' || day.val() == null || day.val() == '' || time == null || time == '') {
            updateTips(localizedStrings['FillRequiredFields']);
            $.unblockUI();
            return false;
        } else {
            $(".ui-state-error").css('display', 'none');
        }

        $.ajax({
            type: "POST",
            url: "/MeetingUtils.ashx",
            data: { type: "checkschedule", day: day.val(), time: time, id: to.val() },
            success: function (res) {
                if (res != 'true') {
                    $("#checkschedule").css('color', 'red');
                    $("#checkschedule").toggle('pulsate', {}, 500, function () { $("#checkschedule").css('display', '').css('opacity', ''); });
                } else {
                    $("#checkschedule").html(localizedStrings['CheckSchedule']).css('color', '');
                    $.ajax({
                        type: "POST",
                        data: { cmd: "editok", subject: subject.val(), time: time, day: day.val(), locale: locale, to: to.val() },
                        url: "/MeetingModal.ashx",
                        success: function (res) {
                            $.unblockUI();
                            if (res != 'true') {
                                updateTips(localizedStrings['ServerError']);
                            } else {
                                $dialog.dialog('close');
                                LoadSchedule("#schedule-cont", locale);
                                setTimeout(function () { GlowUI('Edited', false) }, 1000);
                            }
                        },
                        error: OnError
                    });
                }
            },
            error: OnError
        });
        $.unblockUI();
    };

    ShowWindow("Edit", res, buttons, true, 500, 390);
    return false;
}

function Custom(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=customevent&to=" + id + "&locale=" + locale, OnCustomSuccess);
    return false;
};

function SendCustomEvent(day, time, subject) {
    BlockUIWait();

    request = AjaxRequest("/MeetingUtils.ashx", "POST", { type: "checkschedule", day: day, time: time }, function (res) {
        if (res != 'true') {
            GlowUI("ScheduleConflict", true);
        } else {
            AjaxRequest("/MeetingSender.ashx", "POST", { type: "customevent", subject: subject, time: time, day: day },
            function (res) {
                $.unblockUI();
                if (res != 'true') {
                    updateTips(localizedStrings['ServerError']);
                } else {
                    setTimeout(function () { GlowUI("EventAdded", false) });
                }
            }, OnError);
        }
    }, OnError);
}

function OnCustomSuccess(res) {
    $.unblockUI();
    var go = localizedStrings['Go'];
    var buttons = {};
    buttons[go] = function () {
        var subject = $("#subject"),
			time = $('#start option:selected').val() + "-" + $('#end option:selected').val(),
			day = $('#modal-form input:radio:checked');

        BlockUIWait();

        if (subject.val() == null || subject.val() == '' || day.val() == null || day.val() == '' || time == null || time == '') {
            updateTips(localizedStrings['FillRequiredFields']);
            $.unblockUI();
            return false;
        } else {
            $(".ui-state-error").css('display', 'none');
        }

        $.ajax({
            type: "POST",
            url: "/MeetingUtils.ashx",
            data: { type: "checkschedule", day: day.val(), time: time },
            success: function (res) {
                if (res != 'true') {
                    var s = '<span class=\'scheduleSpan\'>' + localizedStrings['ScheduleConflict'] + '</span>';
                    $("#checkschedule").html(s).css('color', 'red');
                    $("#checkschedule").toggle('pulsate', {}, 500, function () { $("#checkschedule").css('display', '').css('opacity', ''); });
                } else {
                    $("#checkschedule").html(localizedStrings['CheckSchedule']).css('color', '');
                    $.ajax({
                        type: "POST",
                        data: { type: "customevent", subject: subject.val(), time: time, day: day.val(), locale: locale },
                        url: "/MeetingSender.ashx",
                        success: function (res) {
                            $.unblockUI();
                            if (res != 'true') {
                                updateTips(localizedStrings['ServerError']);
                            } else {
                                $dialog.dialog('close');
                                LoadSchedule("#schedule-cont", locale);
                                setTimeout(function () { GlowUI('EventAdded', false) }, 1000);
                            }
                        },
                        error: OnError
                    });
                }
            },
            error: OnError
        });
        $.unblockUI();
    };

    ShowWindow("AddCustomEvent", res, buttons, true, 500, 390);
    return false;
}


function OnReplySuccess(res) {
    $.unblockUI();
    var go = localizedStrings['Go'];
    var buttons = {};
    buttons[go] = function () {
        var to = $("#to"),
			subject = $("#subject"),
			message = $("#message");

        BlockUIWait();

        request = AjaxRequest("/MeetingSender.ashx", "POST", { message: message.val(), type: "message", subject: subject.val(), to: to.val(), locale: locale },
        function (res) {
            $.unblockUI();
            if (res != 'true') {
                updateTips(localizedStrings['ServerError']);
            } else {
                $dialog.dialog('close');
                GlowUI("Sended", false);
            }
        },
            function () {
                $.unblockUI();
                updateTips(localizedStrings['ServerError']);
            }
        );
    };
        ShowWindow("ReplyMessage", res, buttons, false, 500, 420);
}


function SuggestAmend(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=suggest&to=" + id + "&locale=" + locale, OnSuccess);
}

function StopRequest() {
    if (request != null) {
        request.abort();
    }
    $.unblockUI();
}

function updateTips(t) {
    $(".ui-state-error").css('display', '');
    $("#error-text").css('display', 'inline').html(t).toggle('pulsate', {}, 500, function () { $("#error-text").css('display', 'inline').css('opacity', ''); });
    $(".ui-state-error").addClass('ui-state-highlight');
    setTimeout(function () {
        $(".ui-state-error").removeClass('ui-state-highlight', 1500);
    }, 500);
}


function OnAccessForbiden() {
    GlowUI("AccessForbiden", true);
}


function OnError() {
    GlowUI("ServerError", true);
}

function Accept(id) {
    BlockUIWait();
    request = AjaxPostRequest(URL + "?cmd=accept&to=" + id + "&locale=" + locale, OnAcceptSuccess);
    return false;
}

function OnAcceptSuccess(res) {
    if (res == 'false') {
        GlowUI("ScheduleConflict", true);
    } 
    else {
        $.unblockUI();
        var go = localizedStrings['Accept'];
        var canc = localizedStrings['Cancel'];
        var buttons = {};
        buttons[go] = function () {
            var to = $("#to"),
			subject = $("#subject"),
			message = $("#message");

            BlockUIWait();
            AcceptOk(to.val(), message.val());
            $.unblockUI();
        }
        buttons[canc] = function () {
            $('#dialog-form').remove();
        }
        ShowWindow("AcceptMessage", res, buttons, true, 500, 450);
    }
}

function AcceptOk(id, message) {
    BlockUIWait();
    request = AjaxRequest("/MeetingModal.ashx?cmd=acceptok&to=" + id, "POST", { message: message }, function (res) {
        UpdateStatus(id);
        $.unblockUI();
        $dialog.dialog('close');
        GlowUI("Accepted", false);
    },
    OnError);
}

function UpdateStatus(id) {
    request = AjaxRequest("/MeetingUtils.ashx", "POST", { type: "status", meeting: id, locale: locale }, function (res) { $("#" + id + "-cmd").html(res); }, OnError);
}

function Reject(id) {
    BlockUIWait();
    request = AjaxPostRequest("/MeetingModal.ashx?cmd=reject&to=" + id, OnRejectSuccess);
    return false;
}

function RejectOk(id,message) {
    BlockUIWait();
    request = AjaxRequest("/MeetingModal.ashx?cmd=rejectok&to=" + id, "POST", { message: message }, function (res) {
        UpdateStatus(id);
        $.unblockUI();
        if (res != 'true') {

        } else {
            UpdateStatus(id);
            $.unblockUI();
            $dialog.dialog('close');
            GlowUI("Rejected", false);
        }
    },
    OnError);
}

function OnRejectSuccess(res) {
    $.unblockUI();
    var go = localizedStrings['Decline'];
    var canc = localizedStrings['Cancel'];
    var buttons = {};
    buttons[go] = function () {
        var to = $("#to"),
		subject = $("#subject"),
		message = $("#message");

        BlockUIWait();
        RejectOk(to.val(), message.val());
        $.unblockUI();
    }
    buttons[canc] = function () {
        $('#dialog-form').remove();
    }

    ShowWindow("DeclineMessage", res, buttons, true, 500, 410);
}

function OnSuccess(res, code) {    
    $.unblockUI();
    var go = localizedStrings['Go'];
    var buttons = {};
    buttons[go] = function () {
        var to = $("#to"),
			subject = $("#subject"),
			time = $('#start option:selected').val() + "-" + $('#end option:selected').val(),
			message = $("#message"), 
            day = $('#modal-form input:radio:checked');

        if (day.val() == null || day.val() == '' || time == null || time == '') {
            updateTips(localizedStrings['FillRequiredFields']);
            return;
        } else {
            $(".ui-state-error").css('display', 'none');
        }

        BlockUIWait();

        $.ajax({
            type: "POST",
            url: "/MeetingUtils.ashx",
            data: { type: "checkschedule", day: day.val(), time: time },
            success: function (res) {
                if (res != 'true') {
                    var s = '<span class=\'scheduleSpan\'>' + localizedStrings['ScheduleConflict'] + '</span>';
                    $("#checkschedule").html(s).css('color', 'red');
                    $("#checkschedule").toggle('pulsate', {}, 500, function () { $("#checkschedule").css('display', '').css('opacity', ''); });
                } else {
                    $("#checkschedule").html(localizedStrings['CheckSchedule']).css('color', '');
                    var url = "/MeetingSender.ashx?" + "message=" + message.val() + "&subject=" + subject.val() + "&time=" + time + "&to=" + to.val() + "&day=" + day.val() + "&locale=" + locale;
                    $.ajax({
                        type: "POST",
                        data: { type: "meeting" },
                        url: url,
                        success: function (res) {
                            $.unblockUI();
                            if (res != 'true') {
                                updateTips(localizedStrings['ServerError']);
                            } else {
                                $dialog.dialog('close');
                                GlowUI("Sended", false);
                            }
                        },
                        error: OnError
                    });
                }
            },
            error: OnError
        });
        $.unblockUI();
    };
    ShowWindow("MakeAppointment", res, buttons, true, 500, 620);
}

function getAbsolutePosition(el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    if (el.offsetParent) {
        var tmp = getAbsolutePosition(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;
    }
    return r;
}

function ShowWindow(titleKey, code, buttons, time, width, height) {

    $dialog = $(code).dialog({
        autoOpen: false,
        title: localizedStrings[titleKey],
        modal: true,
        resizable: false,
        height: height,
        width: width,
        close: function () {
            $('#dialog-form').remove();
        },
        open: function () {
            var buttons = $dialog.dialog("option", "buttons");
            var d = 0;
        },
        buttons: buttons
    });

    $dialog.dialog('open');
    var dialogForm = document.getElementById("dialog-form");
    if (dialogForm != null) {
        var absolutePosition = getAbsolutePosition(dialogForm);
        scroll(0, absolutePosition.y - 50);
    }
    if (time) {
        $('#time').ptTimeSelect({ hoursLabel: localizedStrings['Hour'], minutesLabel: localizedStrings['Minutes'], setButtonLabel: localizedStrings['Select'], popupImage: "<img src='/UserControlsAdmin/MeetingService/css/img/clock.png'/>" });
        $("#modal-form input:radio").checkbox();
    }

    $('select#start, select#end').selectToUISlider({ labels: 0 });
    var txt = '<p class=\'smallText\'>' + localizedStrings['SliderDescription'] + '</p>';
    $("#ms-slider").append(txt);
}

function checkLength(Object, MaxLen) { return (Object.value.length <= MaxLen); }

function textCounter(field, countfield, maxlimit, cntadd) {
    if (cntadd > 0) {
        if (cnt == -1) {
            cnt = cntadd;
        }
    }
    else {
        cnt = cntadd;
    }
    if (field.value.length > maxlimit + cnt) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit + cnt);
    // otherwise, update 'characters left' counter
    else {
        if (maxlimit + cnt - field.value.length > 350)
            cnt = field.value.length;
        countfield.value = maxlimit + cnt - field.value.length;
    }
}
