/* open view page. */
function viewTodo(obj)
{
    $.zui.modalTrigger.show($.extend({backdrop: 'static'}, $(obj).data()));
}

$(document).ready(function()
{
    $('#todoCalendar').droppable(
    {
        selector: '.event',
        target: '.trash',
        drop : function(e)
        {
            url = createLink('todo', 'delete', 'id=' + e.element.data('id'));
            $.get(url, function(response)
            {
                if(response.result == 'success')
                {
                    if(response.message) $.zui.messager.success(response.message);
                    updateCalendar();
                }
            }, 'json');
        }
    });

    /* dropable setting. */
    $('#todoLists').droppable(
    {
        selector: '[data-toggle="droppable"]',
        container: '#todoLists',
        target: function()
        {
            return $('#todoCalendar .cell-day');
        },
        drop: function(event)
        {
            if(event.target)
            {
                var from   = event.element;
                var to     = event.target.find('.day');
                var toDate = new Date(to.data('date'));
                if(from.data('action') == 'edit' && to.data('date') != '1970-01-01')
                {
                    var data = {
                    'date': toDate.format('yyyy-MM-dd'),
                    'name': from.data('todoName'),
                    'type': from.data('type'),
                    'begin': from.data('begin'),
                    'end': from.data('end')
                    }
                    var url = createLink('todo', 'edit', 'id=' + from.data('id'), 'json');
                }
                else if(from.data('action') != 'edit' && to.data('date') != '1970-01-01')
                {
                    var data = {
                    'date': toDate.format('yyyy-MM-dd'),
                    'type': from.data('type'),
                    'idvalue': from.data('id'),
                    'name': from.data('todoName'),
                    'begin': '',
                    'end':''
                    }
                    var url = createLink('todo', 'create', '', 'json');
                }
                else if(from.data('action') == 'edit' && to.data('date') == '1970-01-01')
                {
                    var data = {}
                    var url = createLink('todo', 'delete', 'id=' + from.data('id'), 'json');
                }
                else if(from.data('action') != 'edit' && to.data('date') == '1970-01-01')
                {
                    return false;
                }

                $.post(url, data, function(response)
                {
                    if(response.result == 'success')
                    {
                        if(response.message) $.zui.messager.success(response.message);
                        updateCalendar();
                        from.hide();
                        from.prop('data-remove', '1')
                        updateBoard(from.data('type'));
                    }
                }, 'json');
            }
        }
    });

    // Sidebar toggle
    var toggleSidebar = function(toggle)
    {
        var $mainRow = $('#mainRow');
        if(toggle === undefined) toggle = $mainRow.hasClass('hide-side');
        $mainRow.toggleClass('hide-side', !toggle);
        $('#sidebarToggleBtn .icon').toggleClass('icon-collapse-full', !!toggle).toggleClass('icon-expand-full', !toggle);
        $.cookie('todoCalendarSide', toggle ? 'show' : 'hide', {path: config.webRoot});

        tryFixedHeader();
    };

    $('#sidebarToggleBtn').click(function(){toggleSidebar();});

    /* Add pager of board list. */
    var recPerPage = 10;
    function addPager(selecter)
    {
        var $tab   = $(selecter);
        var $list  = $tab.find('.todo-list');
        var $items = $list.children('li');
        var count  = $items.length;
        var $pager = $tab.find('.pager');
        if(!$pager.length)
        {
            var updateListItems = function(state)
            {
                $(selecter).find('.todo-list>li').each(function(index)
                {
                    index += 1;
                    $(this).toggle(index >= state.start && index <= state.end);
                });
            };
            $pager = $('<ul class="pager"></ul>').pager(
            {
                page: 1,
                recPerPage: recPerPage,
                recTotal: count,
                elements: 'prev_icon,page_text,<div class="pager-label">/</div>,total_page_text,next_icon',
                onPageChange: updateListItems
            }).appendTo($tab);
            updateListItems({start: 1, end: 10});
        }
        else
        {
            $pager.data('zui.pager').set(1, count, recPerPage);
        }
        $pager.toggle(count > recPerPage);
    }

    /* load board list. */
    function updateBoard(type)
    {
        var param = 'account=&id=&type=board';
        var link = createLink('task', 'ajaxGetTodoList', param);
        if(type == 'all' || type == 'task') $('#tab_task').load(link, function(){addPager('#tab_task');});
        var link = createLink('crm.order', 'ajaxGetTodoList', param);
        if(type == 'all' || type == 'order') $('#tab_order').load(link, function(){addPager('#tab_order');});
        var link = createLink('crm.customer', 'ajaxGetTodoList', param);
        if(type == 'all' || type == 'customer') $('#tab_customer').load(link, function(){addPager('#tab_customer');});
        for(i = 0; i < v.zentaoEntryList.length; i++)
        {
            var code = v.zentaoEntryList[i];
            if(type == 'all' || type == code)
            {
                var link = $("a[href='#tab_" + code + "']").data('url');
                $('#tab_' + code).load(link, function(){addPager('#tab_' + code);});
            }
        }
    }
    addPager('#tab_custom');
    addPager('#tab_undone');
    updateBoard('all');

    updateWeekendAndHoliday();
    var lastUpdateHolidayRequest;
    $('#todoCalendar').on('display.zui.calendar', function()
    {
        if(lastUpdateHolidayRequest)
        {
            clearTimeout(lastUpdateHolidayRequest);
            lastUpdateHolidayRequest = null;
        }
        lastUpdateHolidayRequest = setTimeout(function()
        {
            lastUpdateHolidayRequest = null;
            updateWeekendAndHoliday();
        }, 300);
    });

    var menuHeight     = $('#mainNavbar').outerHeight() + $('#menu').outerHeight();
    var windowScrollUp = $(window).scrollTop();

    // Fixed calendar header
    var tryFixedHeader = function()
    {
        var fixed = windowScrollUp > 0;
        var $calendar = $('#todoCalendar');
        var $calendarHeader = $calendar.find('.calender-header').css(fixed ? {
            position: 'fixed',
            top: menuHeight,
            width: $('#mainRow>.main-col').width(),
            transition: 'none',
            left: 'auto',
            marginLeft: -10,
            padding: 10,
            zIndex: 10,
            background: '#fff'
        } : {
            position: 'relative',
            top: 'auto',
            left: 'auto',
            marginLeft: 0,
            padding: 0,
            width: '100%',
            zIndex: 1,
            background: 'none'
        });
        var headerHeight = $calendarHeader.outerHeight();
        $calendar.css('padding-top', fixed ? (headerHeight - 16) : 0);
        var $tableFixedHeader = $calendar.find('.table-fixed-header');
        if(fixed)
        {
            if(!$tableFixedHeader.length)
            {
                var $tableHeader = $calendar.find('.calendar-view>table>thead');
                $tableFixedHeader = $('<div class="table-fixed-header"><table class="table"></table></div>');
                $tableFixedHeader.find('table').append($tableHeader.clone());
                $tableFixedHeader.prependTo($calendar.find('.calendar-view'));
            }
            $tableFixedHeader.css(
            {
                display: 'block',
                position: 'fixed',
                top: menuHeight + headerHeight,
                width: $('#mainRow>.main-col').width(),
                transition: 'none',
                left: 'auto',
                marginTop: -5,
                marginLeft: -10,
                padding: '0 10px',
                zIndex: 10,
                background: '#fff'
            });
        }
        else
        {
            $tableFixedHeader.hide();
        }
    };

    $(window).on('scroll', function()
    {
        windowScrollUp = $(window).scrollTop();
        tryFixedHeader();
    }).scroll();
    $(window).on('resize', tryFixedHeader);
});

function updateWeekendAndHoliday()
{
    var dates = $('.calendar .cell-day .day').map(function(){return $(this).data('date').toDateString();}).get();
    $.post(createLink('todo', 'ajaxGetWeekendAndHoliday'), {dates: dates}, function(response)
    {
        if(response.status == 'success')
        {
            if(response.dates)
            {
                for(var date in response.dates)
                {
                    var label = response.dates[date];
                    if($(".cell-day .day[data-date='" + date + "'] .heading").find('.label-rest').length) $(".cell-day .day[data-date='" + date + "'] .heading").find('.label-rest').remove();
                    $(".cell-day .day[data-date='" + date + "'] .heading").prepend("<div class='label-rest'>" + label + "</div>");
                }
            }
        }
        else
        {
            if(response.message) bootbox.alert(response.message);
        }
    }, 'json');
}
