var prevDate = new Date();
var confirmationScheduleInProgress = false;

$(function() {
    $('#date').change(dateChanged);
    $('#scheduleid').change(reloadSchedule);
    $(window).resize(resize);
    resize();
});

function resize() {
    var h = $(window).height() - $('#header').height() - 30;
    if (h < 580) h = 580;
    $('#scheduleform #content').css('height', h);
    var tableHeight = h - $('#scheduleoptions').height() - $('#schedulenav').height() - 68;
    $('table.schedule').css('height', tableHeight);
    var cellHeight = tableHeight / $('table.schedule tr').length;
    $('table.schedule td').height(cellHeight);
}

function setDate(date) {
    $('#date').val(date);
    dateChanged();
    return false;
}

function dateChanged() {
    reloadSchedule();
}

///Перерисовывает календарь на текущую дату
function reloadSchedule() {
    var params = $('#scheduleform :input').serializeArray();
    params[params.length] = { name: 'timestamp', value: new Date().toString() };
    var $schedule = $('#schedule');
    $schedule.css('visibility', 'hidden');
    $schedule.load(base + 'schedule.ivp/' + $('#mode').val(), params, function() {
        resize();
        reloadTimeZoneSpan();
        reloadConfirmationDiv();
        $('#schedule').css('visibility', 'visible');
    });
}

function reloadConfirmationDiv()
{
    if ($('#confirmationstatus').length > 0 && $('#userschedule').size() > 0) {
        $.get(base + 'schedule.ivp/GetConfirmationStatus/' + $('#scheduleid').val(), function (result) {
            if (result) {
                $('#confirmationstatus').empty();
                $('#confirmationstatus').append(result);
            }
           
            return false;
        });
    }
}

function reloadTimeZoneSpan() {
    if ($('span#timezone').length > 0 && $('#scheduleid').length > 0) {
        $('#timezone').load(base + 'schedule.ivp/GetCurrentTimeZone/' + $('#scheduleid').val());
    }
}

//Обновляет список доступных календарей
function updateSchedules(id) {
    var select = $('#scheduleid').get(0);
    select.options.length = 0;
    $.getJSON(base + 'schedule.ivp/list', { json: true, timestamp: new Date().toString() }, function(schedules) {
        $(schedules).each(function(i, el) { select.options.add(new Option(el.Name, el.Id)); });
        $(select).val(id);
        reloadSchedule();
    });
}

function setMode(mode) {
    $('#mode').val(mode);
    reloadSchedule();
}

function createPeriod() {
    if (!parseInt($('#scheduleid').val(), 10)) {
        alert(ScheduleResources.ChooseSchedule); $('#scheduleid').focus(); return false;
    }
    var wnd = openDialog('scheduleperiod.ivp/create?' + $('#scheduleform :input').serialize(), 'schedule');
    wnd.focus();
    return false;
}

function editPeriod(id, timezone) {
    var wnd = openDialog('scheduleperiod.ivp/view/' + id, 'schedule');
    wnd.focus();
    return false;
}

function deletePeriod(id) {
    if (!confirm(ScheduleResources.SureDelete)) return false;

    var params = { id: id, nolayout: true, timestamp: new Date().toDateString(), json: true };
    var url = base + 'scheduleperiod.ivp/delete';

    $.getJSON(url, params, function(result) { if (result.hasOwnProperty('IsOK') && !result.IsOK) alert(result.Description); else reloadSchedule(); });
    return false;
}

function createDayException() {
    if (!parseInt($('#scheduleid').val(), 10)) {
        alert(ScheduleResources.ChooseSchedule); $('#scheduleid').focus(); return false;
    }
    var wnd = openDialog('scheduledayexception.ivp/create?' + $('#scheduleform :input').serialize(), 'schedule', { width: 650, height: 350 });
    wnd.focus();
    return false;
}

function editDayException(id, timezone) {
    var wnd = openDialog('scheduledayexception.ivp/view/' + id, 'schedule');
    wnd.focus();
    return false;
}

function deleteDayException(id) {
    if (!confirm(ScheduleResources.SureDelete1DaySchedule)) return false;

    var params = { id: id, nolayout: true, timestamp: new Date().toDateString(), json: true };
    var url = base + 'scheduledayexception.ivp/delete';

    $.getJSON(url, params, function(result) { if (result.hasOwnProperty('IsOK') && !result.IsOK) alert(result.Description); else reloadSchedule(); });
    return false;
}

function showDayDetails(td, date, timezone) {
    if ($('#readonlyform').size()>0) return false;
    td = $(td);
    $('#date').val(date);
    if (!parseInt($('#scheduleid').val(), 10)) return false;
    $('.daydetails').remove();
    td.append('<div class="popupwrapper daydetails"><div class="popup"></div></div>').find('.popup').load(base + 'schedule.ivp/daydetails/' + $('#scheduleid').val(), {sdate:date,timestamp:new Date().toDateString(), timezone: timezone}, function() { td.find('.popupwrapper').show().click(stopPropagation); td.find('.close').click(closePopup); });
    return false;
}

function closePopup(event) {
    $(event.target).parents('.popupwrapper').remove();
    stopPropagation(event);
    return false;
}

function stopPropagation(event) {
    event.stopImmediatePropagation(); return false;
}

//#region Календарь пользователя
function getConfirmationRequestForm() {
    var userId = $('#id').val();
    var scheduleId = $('#scheduleid').val();
    var url = base + 'schedule.ivp/GetConfirmationRequestForm';

    $.get(url, { userid: userId, scheduleId: scheduleId }, function (data) {
        $('body').append('<div id="confirmationrequestform"></div>');
        var $confirmationRequestForm = $('#confirmationrequestform');

        $confirmationRequestForm.dialog({
            autoOpen: false,
            width: '70%',
            height: 'auto',
            minHeight: 135,
            minWidth: 510,
            modal: true,
            resizable: true,
            title: ScheduleResources.ConfirmationFormTitle,
            close: closeConfirmationRequestForm
        });

        $confirmationRequestForm.html(data).show().dialog("open");
    }).fail(function (error) {
        alert(error.statusText);
    });
}

function sendNotificationSchedule() {
    $.post(base + "schedule.ivp/senduserschedulecard", { Recipient: $('#recipient').val(), Subject: $('#subject').val(), Body: $('#message').val() }, function (data) {
        var result = $.parseJSON(data);
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else
            alert(result.Description);
        closeConfirmationRequestForm();
    });
    return false;
}

function closeConfirmationRequestForm() {
    $('#confirmationrequestform').remove();
    return false;
}

function manualChangeConfirmationStatus() {
    if (confirmationScheduleInProgress) return false;

    confirmationScheduleInProgress = true;
    var userid = $('#id').val();
    var url = base + 'schedule.ivp/ManualChangeConfirmationStatus';
    $.get(url, { userid: userid }, function (data) {
        var $confirmationstatus = $('#confirmationstatus');
        $confirmationstatus.removeClass().empty().html(data);
        confirmationScheduleInProgress = false;
        reloadSchedule();
    });
    return false;
}
//#endregion
