$(function () {
    var tthid = setTimeout(function () { }, 0);
    $(document).on('click', '.context', showContext);
    $(document).on('mouseleave', '.combobox li', function () {
        tthid = setTimeout(hideContext, 500);
    });

    $(document).on('mouseover', '#comboholder ul.combobox li', function (event) {
        event.stopPropagation();
        $('#comboholder ul.combobox li a.context').hide();
        $(this).find('a.context:first').show();
    });
    $(document).on('mouseleave', '#comboholder ul.combobox li', function () { $('#comboholder ul.combobox li a.context').hide(); });

    $(document).on('click','#addcomboentry', function () {
        createEntry(true, 0);
        return false;
    });

    $(document).on('click', '.contextmenu', hideContext);

    $(document).on('intra:init.combobox.sortable', '#comboholder',function () {
        $(this).find('ul.sortable').sortable({ axis: "y", stop: saveComboOrder, handle: '.handle' });
    });

    $('#comboholder').trigger('intra:init.combobox.sortable');

    function showContext() {
        hideContext();
        clearTimeout(tthid);
        var $popup = $('<ul class="contextmenu"/>');
        var id = $(this).parent().attr('data-id');
        var $li = '';
        //$li = $('<li/>').text(TaskTypeFieldResources.AddChild).click(function () { createEntry(false, id); });
        //$popup.append($li);
        //$li = $('<li/>').html(($(this).parent().find('span#text:first b').length == 0 ? '' : '<img src="img/tick.gif"/> ') + TaskTypeFieldResources.DefaultValue).click(function () { defaultValue(id); });
        //$popup.append($li);
        $li = $('<li/>').text(TaskTypeFieldResources.Rename).click(function () { edit(id); });
        $popup.append($li);
        $li = $('<li/>').text(TaskTypeFieldResources.Localization).click(function () { selectFieldComboBoxLanguage(id); });
        $popup.append($li);
        $li = $('<li/>').text(TaskTypeFieldResources.Delete).click(function () { removeCombo($(this).parent()); });
        $popup.append($li);
        $popup.show();
        $($popup).mouseover(function () { clearTimeout(tthid); }).mouseleave(function () { tthid = setTimeout(function () { hideContext }, 500); });
        $(this).parent().prepend($popup);

        return false;
    }

    function hideContext() {
        $('.contextmenu').hide().remove();
    }

    function selectFieldComboBoxLanguage(id) {
        var tableName = $('#fieldcomboboxtablename').val();
        var url = 'fieldlanguage.ivp/load?table=' + tableName + '&required=true&field=NameXml&id=' + id;
        openDialog(url, 'selectlanguage', { width: 900, height: 650 });
        return false;
    }

    function saveComboOrder() {
        var ids = $(this).sortable('toArray');
        $.post(base + getFieldComboboxControllerName() + '/saveorder', {ids:ids});
    }

    function createEntry(isFirst, id) {
        var $wrapper = $('#comboholder');
        if (!isFirst)
            $wrapper = $('ul.combobox > li[data-id="' + id + '"]');
        var $childul = $wrapper.find('ul.combobox:first');
        if ($childul.length == 0) {
            $childul = $('<ul class="combobox sortable"/>');
            $childul.sortable({ axis: "y", stop: saveComboOrder, handle: '.handle' });
            $wrapper.append($childul);
        }
        $childul.append(createComboLi(id));

        $("#editname").focus();

    }

    function createComboLi(parentId) {
        var $li = $('<li data-id="0"/>');
        $li.append($('<span id="text"/>').append(createComboEdit('', parentId)));
        return $li;
    }

    function edit(id) {
        var $li = $('ul.combobox > li[data-id="' + id + '"]');
        var $span = $li.find('span#text:first');
        var text = $span.text();
        $span.empty().append(createComboEdit(text));
    }

    function createComboEdit(text, parentId) {
        $('#cancel').click();
        var $edit = $('<input id="editname" type="text"/>').attr('data-oldvalue', $.trim(text)).val($.trim(text));
        $edit.keyboard('enter', { preventDefault: true }, function () { $('#apply').click(); });
        var $apply = $('<img class="icons16"/>').attr('src', 'img/accept.png');
        var $cancel = $('<img class="icons16"/>').attr('src', 'img/delete.gif');
        $apply = $('<a id="apply" class="editbtn" href="#"/>').append($apply).click(function () {
            $.post(base + getFieldComboboxControllerName() + '/EditCombobox', { id: $('#apply').closest('li').attr('data-id'), name: $('#editname').val(), parentId: parentId, fieldId: $('#dialog').length > 0 ? $('#dialog').find('#id').val() : $('#id').val(), entityType: $('#comboholder').attr('entitytype') }, function (result) {
                //result = $.parseJSON(result);
                var $li = $('#apply').closest('li');
                if (result.IsNew) {
                    $li.attr('data-id', result.Id).attr('id', result.Id);
                    $li.find('span#text').before($('<div class="handlewrapper"/>').append($('<img class="handle"/>').attr('src', 'img/sort.gif')));
                    $li.find('span#text').after($('<a href="#" class="hover context"/>').append('<img src="img/contextmenu.gif"/>'));
                }
                var newtext = $edit.val();
                $('#apply').closest('span#text').empty().text(newtext);
            });
            return false;
        });
        $cancel = $('<a id="cancel" class="editbtn" href="#"/>').append($cancel).click(function () {
            if ($(this).closest('li').attr('data-id') == '0') { removeCombo($(this)); } else {
                var oldtext = $edit.attr('data-oldvalue');
                $(this).closest('span#text').empty().text(oldtext);
            }
            return false;
        });

        return $edit.after($('<span class="btnholder"/>').append($apply.after($cancel)));
    }

    function removeCombo($alink) {
        var $li = $alink.closest('li');
        if ($li.length > 0) {
            var dataid = $li.attr('data-id');
            var $ul = $li.parent();

            if (dataid != '0') {
                $.post(base + getFieldComboboxControllerName() + '/removecombovalue', { id: dataid, fieldId: $('#dialog').length > 0 ? $('#dialog').find('#id').val() : $('#id').val() });
            }
            $li.remove();
            if ($.trim($ul.html()).length == 0)
                $ul.remove();
        }
    }

    function getFieldComboboxControllerName() {
        return $('#fieldcomboboxcontrollername').val();
    }

    $('form').validate();
});