var tthid = 0;
$(function() {
    $(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(); });

    $('#addcomboentry').click(function() {
        createEntry(true, 0);
        
        return false;
    });
    if ($('#parameters.autogrow'))
        $('#parameters.autogrow').elastic();
    $(document).on('click', '.contextmenu', hideContext);
    $('ul.sortable').sortable({ axis: "y", stop: saveComboOrder, handle: '.handle' });
    $('#fieldtypeid').change(function() {
        $('#defaultvaluefield').load(base + 'tasktypefield.ivp/getdefaultvaluefield/' + this.value, { timestamp: new Date().toString() }, function() {
            //Инициализируем textareas
            $('#defaultvaluefield textarea.autogrow').elastic();
            $('#parameters.autogrow').elastic();
        });

        var isrequired = this.value != 9;
        if (isrequired)
        {
            $("#isrequired").closest(".field").show();
            //$("#isrequired").attr("checked", true);
        }
        else
        {
            $("#isrequired").closest(".field").hide();
            $("#isrequired").attr("checked", false);
        }

        var typelocked = this.value == 9;
        if (typelocked)
        {
            $('#typelocked').val('True');
        }
        else
        {
            $('#typelocked').val('False');
        }

        if (this.value == 5) { // dropdown
            $('#comboholder').show();
            $('#selectistreevalue').show();
            $('#defaultvaluefield').hide();
            $('#filepermissioneditname').hide();
            $('#filepermissioninputname').hide();
            $('#commonpermissioninputname').show();
            $('#commonpermissioneditname').show();
            $("#cvadditionals").hide();
        }
        else if (this.value == 6) { // file
            $('#comboholder').hide();
            $('#selectistreevalue').hide();
            $('#defaultvaluefield').hide();
            $('#unitfield').hide();
            $('#filepermissioneditname').show();
            $('#filepermissioninputname').show();
            $('#commonpermissioninputname').hide();
            $('#commonpermissioneditname').hide();
            $("#cvadditionals").hide();
        } else if (this.value == 9) { // custom html
            $('#comboholder').hide();
            $('#selectistreevalue').hide();
            $('#defaultvaluefield').hide();
            $('#defaultvaluefield').val('');
            $('#unitfield').hide();
            $("#name").val($("#name").val() ? $("#name").val() : "HtmlElement");
            $('#filepermissioneditname').hide();
            $('#filepermissioninputname').hide();
            $('#commonpermissioninputname').show();
            $('#commonpermissioneditname').show();
            $("#cvadditionals").show();
        }
        else {
            $('#comboholder').hide();
            $('#selectistreevalue').hide();
            $('#defaultvaluefield').show();
            $('#unitfield').show();
            $('#filepermissioneditname').hide();
            $('#filepermissioninputname').hide();
            $('#commonpermissioninputname').show();
            $('#commonpermissioneditname').show();
            $("#cvadditionals").hide();
        }
    });

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


function afterSave() {
    opener.loadFields(true);
}

function selectAll(radio, cb) {
    cb.removeAttr('checked');
    $('input.permission').each(function(i, e) { $(e).attr('checked', false); });
    radio.each(function(i, e) { $(e).attr('checked', true); });
    return false;
}

function selectAllcb() {
    if ($('#selallcbs').prop('checked'))
        $('input.ipermission').attr('checked', true);
    else $('input.ipermission').removeAttr('checked');
    /*
    $('input.ipermission').each(function() {
        if ($(this).prop('checked')) {
            $(this).removeAttr('checked');
        } else {
            $(this).attr('checked', true);
        }
    });
    */
    return false;
}

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

function selectTaskTypeFieldDefaultLanguage() {
    var url = 'fieldlanguage.ivp/load?table=TaskTypeFields&field=DefaultValueXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectTaskTypeFieldDefaultAreaLanguage() {
    var url = 'fieldlanguage.ivp/load?textarea=true&table=TaskTypeFields&field=DefaultValueXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectTaskTypeFieldUnitLanguage() {
    var url = 'fieldlanguage.ivp/load?table=TaskTypeFields&field=UnitXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}


function selectTaskTypeFieldHintLanguage() {
    var url = 'fieldlanguage.ivp/load?table=TaskTypeFields&field=HintXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

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

function saveComboOrder() {
    var ids = $(this).sortable('toArray'); 
    $.ajax({
        type: 'post',
        dataType: "json",
        url: base + 'tasktypefield.ivp/saveorder',
        data: { ids: ids },
    });
}

function showContext() {
    hideContext();
    clearTimeout(tthid);
    var $popup = $('<ul class="contextmenu"/>');
    var id = $(this).parent().attr('data-id');
    var $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() { selectTaskTypeFieldComboBoxLanguage(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('hideContext()', 500); });
    $(this).parent().prepend($popup);
    
    return false;
}

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

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 defaultValue(id) {
    $('#cancel').click();
    $.post(base + 'tasktypefield.ivp/defaultcombovalue', { id: id, fieldId: $('#id').val() }, function(result) {
        result = $.parseJSON(result);
        var $lispan = $('li[data-id="' + id + '"] span#text:first');
        var text = $lispan.text();
        if ($lispan.find('b').length > 0)
            text = $lispan.find('b').contents().unwrap().text();
        $('li span#text b').contents().unwrap();
        $lispan.empty();
        if (result.IsDefault) {
            $lispan.append('<b>' + text + '</b>');
        } else {
            $lispan.text(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 + 'tasktypefield.ivp/editcombo', { id: $('#apply').closest('li').attr('data-id'), name: $('#editname').val(), parentId: parentId, fieldId: $('#id').val() }, 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 + 'tasktypefield.ivp/removecombovalue', { id: dataid, fieldId: $('#id').val() });
        }
        $li.remove();
        if ($.trim($ul.html()).length == 0)
            $ul.remove();
    }
}