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

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

    if(!$('td.actions').is(':hidden')) $('td.actions').each(function(){fixOperateMenu($(this));});
    $('a.openEntry').click(function(){return openEntry($(this));});

    /* 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;
    }
});

/**
 * 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' data-module='" + (v.module || v.moduleName) + "'/>").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', 'module=' + $queryBox.data('module')), 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();
}

/**
 * Open link.
 *
 * @param  object $selector
 * @access public
 * @return void
 */
function openEntry($selector)
{
    var app  = '';
    var skip = false;
    var url  = $selector.prop('href') || $selector.data('url');
    if(!url) return true;

    if($selector.prop('target') == '_blank') skip = true;
    if($selector.data('toggle') == 'modal')  skip = true;
    if($selector.hasClass('deleter'))        skip = true;
    if($selector.hasClass('reloadDeleter'))  skip = true;
    if($selector.hasClass('switcher'))       skip = true;
    if(skip) return true;

    if(url.indexOf('/crm/')   != -1) app = 'crm';
    if(url.indexOf('/oa/')    != -1) app = 'oa';
    if(url.indexOf('/proj/')  != -1) app = 'proj';
    if(url.indexOf('/doc/')   != -1) app = 'doc';
    if(url.indexOf('/cash/')  != -1) app = 'cash';
    if(url.indexOf('/team/')  != -1) app = 'team';
    if(url.indexOf('/hr/')    != -1) app = 'hr';
    if(url.indexOf('/psi/')   != -1) app = 'psi';
    if(url.indexOf('/flow/')  != -1) app = 'flow';
    if(url.indexOf('/ameba/') != -1) app = 'ameba';
    if(url.indexOf('/sys/')   != -1) app = 'superadmin';
    if(url.indexOf('/sys/my')     != -1 || url.indexOf('/sys/index.php?' + config.moduleVar + '=my&'     + config.methodVar) != -1) app = 'dashboard';
    if(url.indexOf('/sys/todo')   != -1 || url.indexOf('/sys/index.php?' + config.moduleVar + '=todo&'   + config.methodVar) != -1) app = 'dashboard';
    if(url.indexOf('/sys/effort') != -1 || url.indexOf('/sys/index.php?' + config.moduleVar + '=effort&' + config.methodVar) != -1) app = 'dashboard';

    if($selector.data('app'))     app = $selector.data('app');
    if($selector.data('entryid')) app = $selector.data('entryid');

    if(!app) return true;

    $.openEntry(app, url);
    return false;
}

/**
 * Remove html tag.
 *
 * @param  str $str
 * @access public
 * @return void
 */
function removeHtmlTag(str)
{
    return str.replace(/<[^>]+>/g,"");
}

function initSlider()
{
    var sliderFlag = false;
    $(document).on('mousedown', '.slider-container .slider-btn', function()
    {
        sliderFlag = true;
        $(this).css('zIndex', '0');
    });

    $(document).on('mousemove', '.slider-container .slider-step-left, .slider-container .slider-step-right', function(event)
    {
        if(!sliderFlag) return false;
        var $slider = $($(this).parents('.slider-container')[0]);
        if($(this).hasClass('slider-step-left'))
        {
            var value = $(this).parent().data('value');
        }
        else
        {
            var value = $(this).parent().next().data('value');
        
        }
        moveSlider($slider, value)
    });
    
    $(document).on('mouseup', '.slider-container', function(event)
    {
        sliderFlag = false;
        $(this).find('.slider-btn').css('zIndex', '1');
    });

    $(document).on('input', '.slider-container .slider-input', function(event)
    {
        var $slider = $($(this).parents('.slider-container')[0]);
        var value = $(this).val();
        moveSlider($slider, value);
    });

    $(document).on('click', '.slider-container .slider-step-left, .slider-container .slider-step-right', function()
    {
        var $slider = $($(this).parents('.slider-container')[0]);
        if($(this).hasClass('slider-step-left'))
        {
            var value = $(this).parent().data('value');
        }
        else
        {
            var value = $(this).parent().next().data('value');
        }
        moveSlider($slider, value)
    })
}

function moveSlider($slider, value)
{
    var left = $slider.find("[data-value='" + value + "']").css('left');
    $slider.find('.slider-bar').css('width', left);

    if(left != '0px') left = (parseInt(left) - 10) + 'px';
    $slider.find('.slider-btn').css('left', left);

    $slider.find('input').val(value);
    $slider.find('input').change();
}
