var dlg = null;
$(function() {

$('form').validate({ ignore: '.ignore', submitHandler: function(form) {
    if (customValidate()) form.submit();
}
});
    
$('#addusers').autocomplete(base + 'task.ivp/findcoordinationusers/' + $('#id').val(), { minChars: 1 }).result(userAdded);
    
$('#addcoordinator').autocomplete(base + 'task.ivp/findcoordinationusers/' + $('#id').val(), { minChars: 1 }).result(coordinatorAdded);
    
$('#addexecutorAjax').autocomplete(base + 'task.ivp/findexecutors/' + $('#serviceid').val(), { minChars: 1 }).result(executorAdded);
    
$('#addobserverAjax').autocomplete(base + 'task.ivp/findexecutors/' + $('#serviceid').val(), { minChars: 1 }).result(observerAdded);
    
$('#addexecutorgroupAjax').autocomplete(base + 'task.ivp/findexecutorgroups/' + $('#serviceid').val(), { minChars: 1 }).result(executorGroupAdded);
   
});

//#region Группа исполнителей

function deleteExecutorGroup() {
    $.post(base + 'task.ivp/DeleteExecutorGroupAjax', { taskid: $('#id').val() });
    return false;
}

function addExecutorGroupAjax(id) {
    if (id)
        $.getJSON(base + 'task.ivp/AddExecutorGroupAjax', { taskid: $('#id').val(), executorGroupId: id });
    return false;
}

function executorGroupAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val('');
    executorGroupsSelectedOnCoordination(id, name);
}

function removeExecutorGroupOnCoordination(notext) {
    //return false;
    
    $('#executorgroupid').attr('changed', true).val('');
    $('#egroupholder').empty();
    if (notext == false) {
        var $nogroup = $('<div/>').addClass('details').attr('id', 'noexecutorgroup').text(TaskResources.ExecutorGroupNotAssigned);
        $('#egroupholder').append($nogroup);
    }
    deleteExecutorGroup($('#executorgroupid').val());
    return false;
}

function executorGroupsSelectedOnCoordination(id, name, canRemove) {
    removeExecutorGroupOnCoordination(true);
    addExecutorGroupAjax(id);
    $('#executorgroupid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline').text(name).attr('href', 'executorgroup/view/' + id).click(function () { return executorGroupDetails(id); });
    var $ar = $('<a href="#"/>').click(function () { return removeExecutorGroupOnCoordination(false); });
    $ar.append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
    $('#egroupholder').append(TaskResources.Group + ': ').append($ag);

    if (canRemove) {
        $('#egroupholder').append($ar);
    }

    if (canRemove === undefined)
        $('#egroupholder').append($ar);


    $('#egroupholder').removeClass("removed");
}

function selectExecutorGroupsOnCoordination() {
    var serviceid = $('#serviceid').val();
    dlg = openDialog('executorgroup/select?tb_mode=SERVICEGROUPS&tb_serviceid=' + serviceid);
    dlg.callback = executorGroupsCallback;
    return false;
}

function executorGroupsCallback(result) {
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    ___addExecutorGroups(ids, names);
}

function ___addExecutorGroups(ids, names) {
    var id = ids[0];
    var gn = names['id' + id];
    executorGroupsSelectedOnCoordination(id, gn);
}

//#endregion

//#region Наблюдатели

function deleteObserver(id) {
    $.post(base + 'task.ivp/DeleteObserverAjax', { taskid: $('#id').val(), observerId: id });
}

function addObserverAjax(id) {
    $.getJSON(base + 'task.ivp/AddObserverAjax', { taskid: $('#id').val(), observerId: id });
    return false;
}

function observerAdded(e, d) {
    var iid = '#participants';    
    var name = d[0];
    var company = d[1];
    var id = d[2];
    $(e.target).val('');
    addUserToList(id, name, company, iid, undefined, undefined);
}

function selectObserversOnCoordination() {    
    var url = 'user.ivp/select?cbmode=observers&reset=true&tb_mode=participants&tb_serviceid=' + $('#serviceid').val();
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var cbmode = result["callbackMode"];
    switch (cbmode) {
        case "observers": {
            var uids = result["selectedIds"];
            addSelectedObservers(uids);
            break;
        }
        case "executors": {
            var ids = result["selectedIds"];
            addSelectedExecutors(ids);
            break;
        }
        case "users": {
            var uids = result["selectedIds"];
            var names = result["selectedNames"];
            var companies = result["selectedCompanies"];
            var positions = result["selectedPositions"];
            addSelected(uids, names, companies, positions);
            break;
        }
    }
}

function addSelectedObservers(rawIds) {
    if (rawIds) {
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: base + 'task.ivp/getUsers',
            data: {
                ids: rawIds.join(',')
            },
            success: function (data) {
                if (data) {
                    $.each(data, function (index, user) {
                        addUserToList(user.Id, user.Name, user.CompanyName, '#participants', user.HashId);
                    });
                }
            }
        });
    }
}

function removeObserverAjax(a, id) {
    var $a = $(a);
    deleteObserver(id);
    $a.parents('li:first').remove();
    var wrapper = $('#participants');
    var $select = wrapper.find('select:first');
    $('option[value="' + id + '"]', $select).remove();

    return false;
}

function assignSelfObserverAjax() {
    $.getJSON(base + 'task.ivp/getuserelement', { json: "json" }, function (data) {
        addUserToList(data.id, data.name, data.company, "#participants");
    });
    return false;
}

//#endregion

//#region Ajax опреции с исполнителями

function selectExecutorsOnCoordination() {
    var url = 'user.ivp/select?cbmode=executors&reset=true&tb_mode=executors&tb_serviceid=' + $('#serviceid').val();
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function addSelectedExecutors(rawIds) {
    if (rawIds) {
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: base + 'task.ivp/getUsers',
            data: {
                ids: rawIds.join(',')
            },
            success: function (data) {
                if (data) {
                    $.each(data, function (index, user) {
                        addUserToList(user.Id, user.Name, user.CompanyName, '#executors', user.HashId);

                        var oneExecutorOnTicket = $('#oneexecutoronticket').val() == "True";
                        if (oneExecutorOnTicket) {
                            return false;
                        }
                    });
                }
            }
        });
    }
}

function assignSelfExecutorAjax() {
    $.getJSON(base + 'task.ivp/getuserelement', { json: "json" }, function (data) {
        addUserToList(data.id, data.name, data.company, "#executors");
    });
    return false;
}

function removeExecutorAjax(a,id) {
    var $a = $(a);
    deleteExecutor(id);
    $a.parents('li:first').remove();
    var wrapper = $('#executors');
    var $select = wrapper.find('select:first');
    $('option[value="' + id + '"]', $select).remove();

    return false;
}

function deleteExecutor(id) {
    $.post(base + 'task.ivp/DeleteExecutorAjax', { taskid: $('#id').val(), executorId: id });
}

function addExecutorsAjax(id) {
    $.getJSON(base + 'task.ivp/AddExecutorAjax', { taskid: $('#id').val(), executorId: id });
    return false;
}

//#endregion

function executorAdded(e, d) {
    var iid = '#executors';
    var name = d[0];
    var company = d[1];
    var id = d[2];
    $(e.target).val('');
    addUserToList(id, name, company, iid,undefined,undefined);
}

function addUserToList(id, name, company, type,hash, canRemove) {
    var wrapper = $(type);
    var $ul = wrapper.find('ul:first');
    var $select = wrapper.find('select:first');
    if ($('option[value="' + id + '"]:selected', $select).length > 0)
        return;

    if (hash) {
        addUserToListAction(hash, id, name, company, type, $ul, $select, canRemove);
    } else {
        $.getJSON(base + 'user.ivp/getuserhash', { userid: id, date: new Date().toString() }, function (hashid) {
            addUserToListAction(hashid, id, name, company, type, $ul, $select, canRemove);
        });
    }
}

function addUserToListAction(hashid, id, name, company, type, ul, select, canRemove) {
    var oneExecutorOnTicket = $('#oneexecutoronticket').val() == "True";

    if (oneExecutorOnTicket && $('option', select).length >= 1 && type == "#executors") {
        //Удаляем исполнителей
        deleteExecutor(select.val());

        select.find("option").remove();
        ul.find("li").remove();

        if (!$(".OnlyOneExecutor").length)
            $("#executors").prepend('<div class="warning OnlyOneExecutor">' + TaskResources.OnlyOneExecutor + '</div>');
    }

    if ($('option[value="' + id + '"]', select).length > 0)
        $('option[value="' + id + '"]', select).attr("selected", "selected");
    else
        select.append('<option selected value="' + id + '">' + name + '</option>');

    if (!ul.find('li[userid=' + id + ']').length) {

        var html = '<li userid="' + id + '"><a href="user.ivp/viewhash/' + hashid + '" onclick="return userDetails(' + "'" + hashid + "'" + ');" class="nounderline">' + name + '</a>';

        var removeAction = "removeObserverAjax";

        if (type == "#executors")
            removeAction = "removeExecutorAjax";
        
        if (canRemove) {
            if ((type === '#executors' && canRemove) || (type === '#participants' && canRemove)) {
                html += '<span class="hover"><a href="#" onClick="return ' + removeAction + '(this,' + id + ');"><img src="img/trash.gif" /></a></span>';
            }

        } else {
            html += '<span class="hover"><a href="#" onClick="return ' + removeAction + '(this,' + id + ');"><img src="img/trash.gif" /></a></span>';
        }

        html += '<div class="grey small">' + company + '</div></li>';
        ul.append(html);
        
        if (type == '#executors')
            addExecutorsAjax(id);

        if (type == '#participants')
            addObserverAjax(id);

        ul.find('.empty').hide();
    } else {
        removeUser(ul.find('li[userid=' + id + ']').find("a"), id);
    }
}

function closeCoordinationForm() {
    document.location.href = base + "task.ivp/view/"+ $('#id').val();
}

function customValidate() {
    if ($('#coordinators option:selected').length <= 0) {
        alert(TaskResources.SelectCoordinator);
        return false;
    }
    return true;
}

function deleteCoordinator(link) {
    var id = link.attr('id').substring(link.attr('id').indexOf('_')+1, link.attr('id').length);
    if (link.find('img').attr('src') == "img/trash.gif") {
        link.find('img').attr('src', 'img/trash_gray.gif');
        link.parent().addClass('archive');
        link.closest('ul').find('select option[value="' + id + '"]').removeAttr('selected');
        
    }
    else {
        link.parent().removeClass('archive');
        link.find('img').attr('src', 'img/trash.gif');
        link.closest('ul').find('select option[value="' + id + '"]').attr('selected', true);
    }
}

function userAdded(e, d) {
    var name = d[0];
    var company = d[1];
    var id = d[2];
    var position = d[3];
    addCoordinators(id, name, company, position);
	$(e.target).val('');
    return false;
}

function coordinatorAdded(e, d) {
    var name = d[0];
    var company = d[1];
    var id = d[2];
    var position = d[3];
    //addCoordinators(id, name, company, position);
	addCoordinatorsToDb(id);
	$(e.target).val('');
    return false;
}

function selectUsers() {
    var url = 'user.ivp/select?cbmode=users&reset=true&tb_mode=all&tb_serviceid=' + $('#serviceid').val();
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function addSelected(uids, names, companies, positions) {   
    uids.forEach(function(i, id) {
        var un = names['id' + id];
        var cn = companies['id' + id];
        var pn = positions['id' + id];
        var company = cn.substring((cn.indexOf('/') > 0) ? cn.indexOf('/')+1 : 0,cn.length-1);
        addCoordinators(id, un, company, pn);
    });
}

function addCoordinators(id, name, company, position) {
    if ($('select#coordinators option[value="' + id + '"]').length > 0) {return false;}
       else {
           var html = '<li><a id="a_'+id+'" href="#" onclick="deleteCoordinator($(this)); return false;"><img src = "img/trash.gif"></img></a>';
           html += '<span>'+name + ' (' + company + ' ' + position + ')';
           html += '</span><div class="spacer10"></div></li>';
           $('ul#coord').append(html);
       $('#coordinators').append($("<option></option>").attr("value", id).attr("selected", true).text(name)); 
    }
    return false;
}

function addCoordinatorsToDb(ids){
	$.getJSON(base + 'task.ivp/addcoordinators', { taskid: $('#id').val(), coordinatorids: ids }, function(result) {
		if (result.hasOwnProperty('IsOK') && !result.IsOK) {
			alert(result.Description);
        }
        else {	getTableOfCoordinators($('#id').val());getListOfCoordinators($('#id').val());	}
		});
	return false;	
}

function getListOfCoordinators(taskId){	
	$.getJSON(base + 'task.ivp/getcoordinators', { taskId: taskId }, function(result) {
		if (result.hasOwnProperty('IsOK') && !result.IsOK) {
			alert(result.Description);			
        }
        else {						
			$('#coordinator ul.users > li').remove();						
			$('#coordinator ul.users').html(result.Result);			
        }
        });
}