var dlg = null;

$(function () {
autoComplete();
$('.saveandresume').attr("title", "[alt+shift+s]");
if ($('#linksaved').size()) {
    alert($('#linksaved').val());
}

$.keyboard('Alt+Shift+s');
$(document).keyboard('Alt+Shift+s');
$('form input').keyboard('Alt+Shift+s');
$('form textarea').keyboard('Alt+Shift+s');
$.keyboard('Alt+Shift+s', saveandresume);

function saveandresume() {
    $('.saveandresume').focus();
    if ($('form:first').size() > 0 && $('form:first').valid() && !$('.save[disabled="true"]').length) {
        $('.saveandresume').click();
    }
    return false;
}
});

var dlg;


function autoComplete() {
    $('#addsecondobject').autocomplete(base + 'assetlink.ivp/findsecondobject/', { minChars: 1, extraParams: { typeid: function () { return $('#linkform #typeid').val() } } }).result(secondObjectAdded);
    $('#addasset').autocomplete(base + 'assetlink.ivp/findassets/', { minChars: 1 }).result(assetAdded);
}

function changeType() {
    $('a.link').text($('#typeid option:selected').text());
    autoComplete();
    $.getJSON(base + 'assetlink.ivp/getlinktypes/' + $('#linkform #typeid option:selected').val(), {}, function(result) {
        $('#linktypeid').empty();
        $('#addsecondobject').val('');
        $('#secondobjectholder').empty();
        var option = $('<option/>').val('');
        $('#linktypeid').append(option);
        $(result).each(function(i, e) { var option = $('<option/>').val(e.Id).text(e.Name); $('#linktypeid').append(option); });
    });
}

function afterLinkFormCreated() {
    $('#linkform').validate({
        errorPlacement: function (error, element) {
            if ($(element).attr('replaceerrorelementafter')) {
                error.insertAfter($($(element).attr('replaceerrorelementafter')));
            }
            else {
                error.insertAfter(element);
            }
        }
    });
    $('#linkform select#linktypeid').on('change', function () {
        if ($(this).val() != '' && $(this).val() != 0) {
            if ($('#typesDictionary')) {
                $('label[for="addsecondobject"][class!="error"]').text($('#typesDictionary option[value="' + $('option:selected', this).attr('typeid') + '"]').text());
            }
            $('#linkTypeSecondObject').removeClass('hidden');
            $('#addsecondobject').val("");
        }
        else {
            $('#linkTypeSecondObject').addClass('hidden');
            $('#secondobject').val("");
            $('#addsecondobject').val("");

        }
        $('#linkform #typeid').val($('option:selected', this).attr('typeid'));
    });
}

function assetAdded(e, d) {
    var name = d[0];
    var id = d[1];
    $(e.target).val(name);
    assetSelected(id, name, true);
}

function secondObjectAdded(e, d) {
    var name = d[3];
    var id = d[2];
    var type = d[1];
    $(e.target).val(name);
    secondObjectSelected(id, type, name);
}

function secondObjectSelected(id, type, name) {
    $('#secondobject').val(id + '|' + type);
    name = name.replace(/<[^>]+>/ig, "").replace(/\s/g, "");
    $('#addsecondobject').val(name);
}

function assetsSelected(ids, names) {
    ids.forEach(function (id) {
        var name = names['id' + id];
        assetSelected(id, name);
    });
}

function assetSelected(id, name) {
    $('#firstassetid').val(id);
    $('#addasset').val(name.replace(/<[^>]+>/ig, "").replace(/\s/g, ""));    
}

function secondAssetSelected(ids, names) {
    var id = ids[0];
    secondObjectSelected(id, 1, names['id' + id]);
}

function userSelected(ids, names) {
    var id = ids[0];
    var un = names['id' + id];
    secondObjectSelected(id, 2, un);
}

function assetLinkCompanySelected(id, name) {
    secondObjectSelected(id, 3, $.trim(name));
}

function assetDetails(id) {
    openDialog('asset.ivp/view/' + id + '?popup=true&readonly=true', 'asset' + id);
    return false;
}

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

var AssetLinkFirst = {
    selectAssets: function selectAssets() {
        dlg = openDialog('assettable.ivp/select?cbmode=AssetLinkFirst&selectmode=SINGLE&tb_select_mode=none');
        dlg.callback = AssetLinkFirst.assetsCallback;
        return false;
    },
    assetsCallback: function (result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        assetsSelected(ids, names);
    }
}

var AssetLinkSecond = {
    selectSecondObject: function selectSecondObject() {
        if ($('#linkform #typeid').val() == "1") {
            dlg = openDialog('assettable.ivp/select?cbmode=AssetLinkSecond&selectmode=SINGLE');
            dlg.callback = AssetLinkSecond.assetsCallback;
        }
        if ($('#linkform #typeid').val() == "2") {
            dlg = openDialog('user.ivp/select?cbmode=AssetLinkSecond&tb_mode=all&tb_serviceid=-1&selectmode=SINGLE');
            dlg.callback = AssetLinkSecond.usersCallback;
        }
        if ($('#linkform #typeid').val() == "3") {
            dlg = openDialog('company.ivp/select?cbmode=AssetLinkSecond&tb_custom_mode=NOTARCHIVE&selectmode=SINGLE');
            dlg.callback = AssetLinkSecond.companiesCallback;
        }
        return false;
    },
    assetsCallback: function assetsCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        secondAssetSelected(ids, names);
    },
    usersCallback: function usersCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        userSelected(ids, names);
    },
    companiesCallback: function companiesCallback(result) {
        var id = result["selectedIds"][0];
        var name = result["selectedNames"]['id' + id];
        assetLinkCompanySelected(id, name);
    }
}

//function selectSecondObject() {
//    openDialog('assetlink.ivp/selectsecondobject');
//    return false;
//}

function setType(id) {
    $('#linkpopupholder').hide();
    $('#linkform #typeid').val(id);
    changeType();
    return false;
}