$(document).ready(function()
{
    fixNavbar();
    setRequiredFields();

    /* Enable default ajax options. */
    $.setAjaxForm('#ajaxForm');
    $.setAjaxDeleter('.deleter');
    $.setReload('.reload');
    $.setReloadDeleter('.reloadDeleter');
    $.setAjaxLoader('.loadInModal', '#ajaxModal');
    $.setAjaxJSONER('.jsoner');

    /* run code if desktop. */
    if(typeof $.ipsStart != 'undefined')
    {
        /* Set ping keep online. */
        setInterval(ping, 1000 * config.pingInterval);
        ping();
    }
    else
    {
        /* bind app-btn events. */
        $(document).on('click', '.app-btn', function(event)
        {
            if($(this).attr('data-id'))
            {
                $.openEntry($(this).attr('data-id'), $(this).data('url') || $(this).attr('href'));
                return false;
            }
        });
    }

    /* Enable tooltip */
    $('body').tooltip({html: true,selector: "[data-toggle='tooltip']",container: "body"});

    condensedForm();
    setPageActions();

    /* Reload modal. */
    $(document).on('click', '.reloadModal', function(){$.reloadAjaxModal(1000, $(this).data('width'))});

    /* Support iframe modal shortcut */
    $(document).on('click', 'a.iframe', function(e)
    {
        var $this = $(this);
        if (!$this.data('zui.modaltrigger'))
        {
            var modalWidth  = '';
            var modalHeight = '';
            if($this.attr('width') != 'undefined')  modalWidth = $this.attr('width');
            if($this.attr('height') != 'undefined') modalHeight = $this.attr('width');

            $this.modalTrigger(
            {
                width: modalWidth,
                height: modalHeight,
                show: true
            });
        }
        else
        {
            $this.trigger('.toggle.' + 'zui.modaltrigger');
        }
        e.preventDefault();
    });

    $(document).on('click', '#mainNavbar #searchbox .searchBtn', function()
    {
        var $words = $('#mainNavbar #searchbox #words');
        var  words = $.trim($words.val());
        if(!words) return false;

        var link = createLink('sys.my', 'search') + (config.requestType == 'GET' ? '&' : '?') + 'words=' + window.btoa(encodeURI(words));
        $('#mainNavbar #searchModal').load(link, function()
        {
            fixSearchPanel();

            $words.val('');
        });

        return false;
    });

    $('#mainNavbar #searchbox #words').focus(function()
    {
        $(this).val('');
    });

    // setMenu();
    initSearch();

    $(document).on('click', '#noticeAttend .close', function()
    {
        $.get(createLink('oa.attend', 'read'));
    });
});

$(document).on('keyup', function(e)
{
    if(e.keyCode == '37')
    {
        /* left, go to pre object. */
        if($('#ajaxModal').css('display') == 'block') return false;
        if($('input,textarea').is(':focus')) return false;
        preLink = ($('#pre').attr("href"));
        if(typeof(preLink) != 'undefined') location.href = preLink;
    }
    if(e.keyCode == '39')
    {
        /* right, go to next object. */
        if($('#ajaxModal').css('display') == 'block') return false;
        if($('input,textarea').is(':focus')) return false;
        nextLink = ($('#next').attr("href"));
        if(typeof(nextLink) != 'undefined') location.href = nextLink;
    }
});

/**
 * Show or hide more items.
 *
 * @access public
 * @return void
 */
function switchMore()
{
    $('#search').width($('#search').width()).focus();
    $('#moreMenu').width($('#defaultMenu').outerWidth());
    $('#searchResult').toggleClass('show-more');
}

/**
 * Init search form
 *
 * @access public
 * @return void
 */
function initSearch()
{
    $searchTab = $('#bysearchTab');
    if($searchTab.data('initSearch')) return;

    if(!$searchTab.closest('#menu').length)
    {
        $('#menu>.container>.nav:first').append($searchTab);
    }

    var $queryBox = $('#querybox');
    if(!$queryBox.length)
    {
        $queryBox = $("<div id='querybox' class='hidden'/>").insertAfter($('#menu'));
    }

    if(v && v.mode == 'bysearch')
    {
        $('#menu > ul > li.active').removeClass('active');
        ajaxGetSearchForm($queryBox);
        $searchTab.addClass('active').find('a').attr('href', '#bysearch');
        $queryBox.removeClass('hidden');
    }

    $searchTab.on('click', function()
    {
        var isSearchTabActive = $searchTab.hasClass('active');
        if(isSearchTabActive)
        {
            var $oldTab = $searchTab.data('oldTab');
            if($oldTab)
            {
                $oldTab.addClass('active');
            }
            else
            {
                $searchTab.addClass('selected');
            }
        }
        else
        {
            $(window).scrollTop(0);
            $searchTab.data('oldTab', $('#menu > ul > li.active').removeClass('active'));
            ajaxGetSearchForm($queryBox, function()
            {
                if(!$queryBox.hasClass('hidden')) $queryBox.trigger('querybox.toggle', true);
            });
        }
        $searchTab.toggleClass('active', !isSearchTabActive);
        $queryBox.toggleClass('hidden', isSearchTabActive).trigger('querybox.toggle', !isSearchTabActive);
    });

    $searchTab.data('initSearch', true);
}

/**
 * Ajax get search form
 *
 * @param  string   $queryBox
 * @param  callback $callback
 * @access public
 * @return void
 */
function ajaxGetSearchForm($queryBox, callback)
{
    if(!$queryBox) $queryBox = $('#querybox');
    if($queryBox.html() == '')
    {
        $.get(createLink('search', 'buildForm'), function(data)
        {
            $queryBox.html(data);
            callback && callback();
        });
    }
}

// /**
//  * Set menu
//  *
//  * @access public
//  * @return void
//  */
// function setMenu()
// {
//     $menuTitle = $('#menuTitle');
//     $menu = $('#menu');
//     if($menu.length && $menuTitle.length)
//     {
//         $menu.children('ul.nav:not(.pull-right)').hide();
//         $menu.prepend($menuTitle.addClass('nav'));
//     }
// }

/* Remove 'ditto' in first row when batch create or edit. */
function removeDitto()
{
    $firstTr = $('.table').find('tbody tr:first');
    $firstTr.find('td select').each(function()
    {
        $(this).find("option[value='ditto']").remove();
        $(this).trigger("chosen:updated");
    });
}

/**
 * Start cron.
 *
 * @access public
 * @return void
 */
function startCron()
{
    $.ajax({type:"GET", timeout:100, url:createLink('cron', 'ajaxExec')});
}

/**
 * Set mailto list from a contact group.
 *
 * @param  string $mailto
 * @param  int    $contactID
 * @access public
 * @return void
 */
function setMailto(mailto, contactID)
{
    link = createLink('usercontact', 'ajaxGetContactMembers', 'id=' + contactID);
    $.get(link, function(users)
    {
        $('#' + mailto).replaceWith(users);
        $('#' + mailto + '_chosen').remove();
        $('#' + mailto).chosen();
    });
}

/**
 * Fix search panel's height.
 *
 * @access public
 * @return void
 */
function fixSearchPanel()
{
    var windowHeight = $(window).height();

    $('#searchModal .panel-body .list .items').css('height', windowHeight - 115);

    $('#searchModal').show();
}
