var dlg = null;
var sid = 0;
var hid = 0;
var showtd = true;

$(function () {
    $('form').validate();
    $('#executors').autocomplete(base + 'executorgroup/findexecutors/', { minChars: 1 }).result(executorSelected);
    $('#observers').autocomplete(base + 'executorgroup/findobservers/', { minChars: 1 }).result(observerSelected);
    $('#companies').autocomplete(base + 'executorgroup/findcompanies/', { minChars: 1 }).result(ecompanySelected);
    $('.delexec').click(removeExecutorStroke);
    $('.del-observer').click(removeObserverStroke);
    $('.delcompany').click(removeCompanyStroke);
    $('.execlink').mouseover(showGroupLeaderChange).mouseout(function () {
        showtd = false;
        clearTimeout(sid);
        hid = setTimeout('hideGroupLeaderChange()', 400);
    }).click(function () { showtd = false; });
});
function observerSelected(e, d) {
    var name = d[0];
    var company = d[2];
    var id = d[1];
    $(e.target).val('');
    _addObserverToList(id, name, company);
}

function ecompanySelected(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    $.getJSON(base + 'company.ivp/getcompanyhash', { companyid: id }, function (hashid) {
        _addCompanyToList(id, name, hashid);
    });
}

function executorSelected(e, d) {
    var name = d[0];
    var company = d[2];
    var id = d[1];
    $(e.target).val('');
    _addUserToList(id, name, company);
}

var ExecutorGroup = {
    chooseCompany: function chooseCompany() {
        var url = 'company.ivp/select?cbmode=ExecutorGroup&tb_custom_mode=NOTARCHIVE';
        dlg = openDialog(url, 'selectcompanies', { width: 980, height: 650 });
        dlg.callback = ExecutorGroup.companiesCallback;
        return false;
    },
    companiesCallback: function companiesCallback(result) {
        var ids = result["selectedIds"];
        companySelected(ids);
    },

    chooseServices: function chooseServices() {
        var url = 'service.ivp/select?cbmode=ExecutorGroup&tb_custom_mode=user&tb_executorgroupid=' + $('#Id').val();
        dlg = openDialog(url, 'selectservice', { width: 980, height: 650 });
        dlg.callback = ExecutorGroup.servicesCallback;
        return false;
    },
    servicesCallback: function servicesCallback(result) {
        var serviceids = result["selectedIds"];
        addSelectedServices(serviceids);
    }
}

var ExecutorGroupExecutors = {
    chooseExecutors: function chooseExecutors() {
        var url = 'user.ivp/select?cbmode=ExecutorGroupExecutors&tb_mode=ALLUSERS&tb_serviceid=-1';
        dlg = openDialog(url, 'selectusers', { width: 980, height: 650 });
        dlg.callback = ExecutorGroupExecutors.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        var companies = result["selectedCompanies"];
        userSelected(uids, names, companies);
    }
}

var ExecutorGroupObservers = {
    chooseObservers: function chooseObservers() {
        var url = 'user.ivp/select?cbmode=ExecutorGroupObservers&tb_mode=ALLUSERS&tb_serviceid=-1';
        dlg = openDialog(url, 'selectusers', { width: 980, height: 650 });
        dlg.callback = ExecutorGroupObservers.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        var companies = result["selectedCompanies"];
        observerMultipleSelected(uids, names, companies);
    }
}

function userSelected(uids, names, companies) {
    uids.forEach(function (id) {
        var un = names['id' + id];
        var cn = companies['id' + id];
        _addUserToList(id, un, cn);
    });
}

function observerMultipleSelected(uids, names, companies) {
    uids.forEach(function (id) {
        var un = names['id' + id];
        var cn = companies['id' + id];
        _addObserverToList(id, un, cn);
    });
}

function _addObserverToList(id, name, company) {
    if ($('#observerscontainer td[entity-id="' + id + '"]').length == 0) {
        var hashid = getuserhash(id);
        var $a = $('<a/>').addClass('nounderline execlink').attr('data-id', id).attr('href', 'user.ivp/viewhash/' + hashid).click(function () { return userDetails(hashid); }).append(' ' + $.trim(name));
        var $td = $('<td/>').append($a).attr('entity-id', id);
        var $delA = $('<a href="#"/>').addClass('del-observer noul mright9').click(removeObserver).append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
        $td.prepend($delA).append($('<div/>').addClass('grey small ucompany').text($.trim(company)));
        var $tr = $('<tr/>').append($td);
        $('#observerscontainer').append($tr);
    }
    if ($('select#oids option[value="' + id + '"]').length == 0) {
        var $option = $('<option/>').val(id).text($.trim(name)).attr('selected', true);
        $('select#oids').append($option);
    }
    else {
        $('select#oids option[value="' + id + '"]').attr('selected', true);
    }
}

function removeObserver() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');
    $('select#oids option[value="' + id + '"]').remove();
    $li.remove();
    return false;
}

function _addUserToList(id, name, company) {
    var url = base + 'ExecutorGroup/checkexecutorscount';
    $.getJSON(url, { userid: id, }, function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alertDialog(CommonResources.Error, result.Description);
        else {
            if ($('#selexecutors td[entity-id="' + id + '"]').length == 0) {
                var hashid = getuserhash(id);
                var $a = $('<a/>').addClass('nounderline execlink').data('isoperator', false).attr('data-id', id).attr('href', 'user.ivp/viewhash/' + hashid).click(function () { return userDetails(hashid); }).append($.trim(name));
                $a.mouseover(showGroupLeaderChange).mouseout(function () {
                    showtd = false;
                    clearTimeout(sid);
                    hid = setTimeout('hideGroupLeaderChange()', 400);
                }).click(function () { showtd = false; });

                var $td = $('<td/>').append($a).addClass('selexec').attr('entity-id', id);
                var $delA = $('<a href="#"/>').addClass('delexec noul mright9').click(removeExecutor).append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
                $td.prepend($delA).append($('<div/>').addClass('grey small ucompany').text($.trim(company)));
                var $tr = $('<tr/>').append($td).append($('<td/>').addClass('groupleaderholder')).append($('<td/>').addClass('groupoperatorholder'));
                $('#selexecutors').append($tr);
            }
            if ($('select#eids option[value="' + id + '"]').length == 0) {
                var $option = $('<option/>').val(id).text($.trim(name)).attr('selected', true);
                $('select#eids').append($option);
            }
            else {
                $('select#eids option[value="' + id + '"]').attr('selected', true);
            }
        }
    });    
}

function removeExecutor() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');
    $('select#eids option[value="' + id + '"]').remove();
    $li.remove();
    return false;
}

function companySelected(ids) {
    $.getJSON(base + 'company.ivp/getcompaniesname', { ids: ids.join(',') }, function (result) {
        $(result).each(function () {
            var cid = this.Id;
            var cname = this.Name;
            $.getJSON(base + 'company.ivp/getcompanyhash', { companyid: cid }, function (hashid) {
                _addCompanyToList(cid, cname, hashid);
            });
            
        });
    });
}

function _addCompanyToList(id, name, hash) {
    if ($('ul#selcompanies li[entity-id="' + id + '"]').length == 0) {
        var $li = $('<li/>').append($('<a/>').addClass('nounderline').attr('href', '#').click(function () { return companyDetailsHash(hash); }).append($.trim(name))).addClass('selcompany').attr('entity-id', id);
        var $delA = $('<a href="#"/>').addClass('delcompany noul mright9').click(removeCompany).append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
        $li.prepend($delA);
        $('ul#selcompanies').append($li);
    }
    if ($('select#cids option[value="' + id + '"]').length == 0) {
        var $option = $('<option/>').val(id).text(name).attr('selected', true);
        $('select#cids').append($option);
    }
    else {
        $('select#cids option[value="' + id + '"]').attr('selected', true);
    }
}

function removeCompany() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');
    $('select#cids option[value="' + id + '"]').remove();
    $li.remove();
    return false;
}

function removeCompanyStroke() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');

    if (!$li.hasClass('removed')) {
        $li.addClass('removed');
        $('select#cids option[value="' + id + '"]:selected').removeAttr('selected');
    }
    else {
        $li.removeClass('removed');
        $('select#cids option[value="' + id + '"]').attr('selected', true);
    }
    return false;
}

function removeObserverStroke() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');
    if (!$li.hasClass('removed')) {
        $li.addClass('removed');
        $('select#oids option[value="' + id + '"]:selected').removeAttr('selected');
    }
    else {
        $li.removeClass('removed');
        $('select#oids option[value="' + id + '"]').attr('selected', true);
    }
    return false;
}

function removeExecutorStroke() {
    var $li = $(this).parent();
    var id = $li.attr('entity-id');
    if (!$li.hasClass('removed')) {
        $li.addClass('removed');
        $('select#eids option[value="' + id + '"]:selected').removeAttr('selected');
    }
    else {
        $li.removeClass('removed');
        $('select#eids option[value="' + id + '"]').attr('selected', true);
    }
    return false;
}

function addSelectedServices(serviceids) {
    $.ajaxSettings.traditional = true;
    $('#services').load(base + 'ExecutorGroup/AddServices', {
        id: $('#Id').val(),
        serviceIds: serviceids
    },
        function () {
            $('#selectservices').hide();
            $('#addservices').show(),
                function () { date: new Date().toString(); },
                function () { $('#availableservices').fadeIn('fast'); };
        });

    return false;
}

function deleteSelectedServices() {
    var selected = new Array();
    $('#services table td input:checked').each(function (i, el) { selected.push(el.value); });
    $.ajaxSettings.traditional = true;
    $('#services').load(base + 'ExecutorGroup/DeleteServices', {
        id: $('#Id').val(),
        serviceIds: selected
    });

    return false;
}

/*function companyDetails(id) {
    window.open(base + 'company.ivp/view/' + id);
    // openDialog('company.ivp/view/' + id + '?popup=true', 'company' + id);
    return false;
}*/

//Показать/скрыть описание заявки
function showGroupLeaderChange() {
    var id = $(this).attr('data-id');
    showtd = true;
    sid = setTimeout('_showGroupLeaderChange("' + id + '")', 300);
    clearTimeout(hid);
}
function hideGroupLeaderChange() {
    $('.gleaderchange').hide();
}
function _showGroupLeaderChange(tid) {
    if (!showtd) return;
    var id = tid;
    if ($('[data-id="' + id + '"]').length == 0) return;

    var tdkey = '#gleaderchange_' + id;
    $('.gleaderchange').hide();

    var offset = $('[data-id="' + id + '"]').offset();
    var h = $('[data-id="' + id + '"]').height();
    var w = 280;

    if ($(tdkey).length > 0) {
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left).css('width', w);
        $(tdkey).fadeIn('fast');
    }
    else {
        $('body').append('<div id="gleaderchange_' + id + '" class="gleaderchange popupwrapper"><div class="popup"></div></div>');
        $(tdkey).css('top', offset.top + h + 5).css('left', offset.left + 40).css('width', w);
        $(tdkey).mouseover(function () { clearTimeout(hid); }).mouseout(function () { hid = setTimeout('hideGroupLeaderChange()', 300); });

        var $a = $('<a href="#"/>').click(function () { return handleGroupLeader(id); }).text(ExecutorGroupResources.Leader);
        $('.popup', $(tdkey)).empty().append($a);

        var $b = $('<a class="handleGroupOperator" href="#"/>').click(function () { return handleGroupOperator(id); }).text($('[data-id="' + id + '"]').data("isoperator").toString().toLowerCase() == 'true' ? ExecutorGroupResources.UnsetOperator : ExecutorGroupResources.SetOperator);
        $('.popup', $(tdkey)).append($b);

        if (!showtd) return;
        $(tdkey).show();
    }
}

function handleGroupLeader(id) {
    var $link = $('[data-id="' + id + '"]');
    var $gh = $link.closest('tr').find('td.groupleaderholder');
    $('.groupleaderholder').addClass('changed');
    if ($.trim($gh.html()).length > 0) {
        if (!$gh.hasClass('newleader')) {
            if (!$gh.hasClass('linethrough')) {
                $gh.addClass('linethrough');
                $('#groupleader').val('');
            }
            else {
                $('.groupleaderholder.newleader').empty();
                $gh.removeClass('linethrough');
                $('#groupleader').val(id);
            }
        }
        else {
            $gh.empty();
            $('#groupleader').val('');
        }
    }
    else {
        $('.groupleaderholder.newleader').empty();
        $('.groupleaderholder.saved').addClass('linethrough');
        $gh.addClass('newleader').text(' - ' + ExecutorGroupResources.TeamLeader);
        $('#groupleader').val(id);
    }
    return false;
}

function handleGroupOperator(id) {
    var $link = $('[data-id="' + id + '"]');
    var $oh = $link.closest('tr').find('td.groupoperatorholder');
    $('.groupoperatorholder').addClass('changed');

    if ($link.data("isoperator").toString().toLowerCase() == 'true') {
        $oh.html('');
        $link.data("isoperator", false);
        $("#groupoperators [value='" + id + "']").remove();
        $("#gleaderchange_" + id + " a.handleGroupOperator:first").text(ExecutorGroupResources.SetOperator);
    }
    else {
        $link.data("isoperator", true);
        $oh.html("(" + ExecutorGroupResources.GroupOperator + ")");
        var $selectList = $('#groupoperators');
        if ($selectList.find('[value="' + id + '"]').length < 1) {
            $selectList.append($("<option></option>")
                              .attr("value", id)
                              .text(id));
        }
        $("#groupoperators [value='" + id + "']").attr("selected", "selected");
        $("#gleaderchange_" + id + " a.handleGroupOperator:first").text(ExecutorGroupResources.UnsetOperator);
    }

    return false;
}

function loadServices(reload) {
    if (reload || $.trim($('#services').html()).length == 0) {
        var params = new Array();
        params.push({ name: 'timestamp', value: new Date().toString() });
        if ($('#popup').length > 0) params.push({ name: 'popup', value: true });
        $('#services').load(base + 'executorgroup/services/' + $('#Id').val(), params, function () { setTab('services'); });
    }
    else setTab('services');
}