var dlg = null;

$(function () {
    $('.saveandresume').attr("title", "[alt+shift+s]");
    //автоинкремент инвентарного номера
    if ($('#assetsaved').size()) {
        alert($('#assetsaved').val());
        var newname = $('#inventorynumber').val();
        var match = /([\d]+$)/.exec(newname);
        if (match && parseInt(match[0], 10)) {
            var num = parseInt(match[0], 10)+1;
            newname = newname.replace(/([\d]+$)/, String(num));
        } else {
            newname = newname + ' new';
        }
        $('#inventorynumber').val(newname);
        blinkbg($('#inventorynumber'));
    }

    $.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;
    }

    $('#typeid').change(function () { loadAttr($(this).val()); });

    if ($('#chooseowner').length) $('#chooseowner').autocomplete(base + 'asset.ivp/findowners/', { minChars: 1 }).result(ownerSelected);
    if ($('#chooseparent').length) $('#chooseparent').autocomplete(base + 'asset.ivp/findparents/' + $('#id').val(), { minChars: 1 }).result(parentAutocompleted);
    if ($('#postback').length > 0) {
        if ($('#parentid').val()) {
            parent.frames.tree.expand($('#parentid').val(), true);
            if ($('#oldparentid').val()) {
                if ($('#oldparentid').val() > 0)
                    parent.frames.tree.expand($('#oldparentid').val(), true);
                else
                    $(parent.frames.tree.document.getElementById('node_' + $('#id').val())).hide();
                $('#oldparentid').val('');
            }
        }
        else {
            parent.frames['tree'].location.href = base + 'asset.ivp/node';
        }
    }
    
    $("#exportTemplate").click(function () {
        $('#actionholder').toggle();
    });
});

$(document).ready(function() {
    //многоуровневое меню "Действия"
    if (typeof liMenuVert == 'function')
        $('.menu_vert').liMenuVert();
});

function setTab(id) {
    if (!documentReady) return;

    $('#tab').val(id);
    $('.tab').each(function(i, el) { if (el.id == id) $(el).show(); else $(el).hide(); });
    $('#tabid').val(id);
    $('#tabs>ul>li>a').each(function(i, el) { if (el.id == 'a' + id) $(el).addClass('selected'); else $(el).removeClass('selected'); });
    $('.rm').hide();
    $('#' + id + 'menu').show();

    if (id == 'links' || id == 'tasks') {
        $('.save').attr('disabled', true);
        $('.saveandreturn').attr('disabled', true);
    }
    else {
        $('.save').attr('disabled', false);
        $('.saveandreturn').attr('disabled', false);
    }

    return false;
}

function selectLinkType() {
    $('#linktype').css('left', $('li > #alinks').position().left).show();
    return false;
}

function loadLinks(id) {
    $('#linktype').hide();
    $('#linktypeid').val(id);
    DisableSaveButtons();
    $('#links > #tableholder').load(base + 'assetlinkdetails.ivp/list', { partial: true, tb_asset_id: $('#id').val() }, function () {
        if ($('#istable').val() == "True")
            loadFilterMenu();
        setTab('links');
        initCluetip();
        initTable();
    });
    
    return false;
}

function initCluetip() {
    $('img.link').cluetip({
        arrows: false,
        dropShadow: false,
        cluetipClass: 'jtipnew',
        showTitle: false
    });
    $('span.assetlink').cluetip({
        arrows: false,
        dropShadow: false,
        cluetipClass: 'jtipnew',
        showTitle: false
    });
}

function applySavedAjaxFilter(stateid) {
    $('#links > #tableholder').load(base + tableController() + tableAction() + '?stateid=' + stateid, { partial: true, tb_asset_id: $('#id').val(), timestamp: new Date().toString() }, function () {
        initTable();
        loadFilterMenu();
        initCluetip();
    });

}

function loadFilterMenu() {
    $('.assetlinks').load(base + 'assetlinkdetails.ivp/loadrightmenu');
    $('#filterholder').remove();
    $('.assetlinks').show();
}

function loadTasks() {
    DisableSaveButtons();
    if (!$.trim($('#tasks').html())) {
        $('#tasks').load(base + 'asset.ivp/loadtasks/' + $('#id').val(), { timestamp: new Date().toDateString() }, function() { setTab('tasks'); $('.assetlinks').hide(); });
    }
    else setTab('tasks');
    return false;
}

function loadAttr(id) {  
    $('#attributeholder').load(base + 'assettable.ivp/gettypefields/' + id);
    if (id != '') {
        $.getJSON(base + 'assettable.ivp/displayproperyasset/', { typeid: id }, function (result) {
            if (result.success) {                
                if (!result.isDisplayInventoryNumber) {
                    $('#inventorynumber').removeClass('required')
                    $('#inventorynumber').closest('.field').hide();
                }                   
                else {
                    $('#inventorynumber').closest('.field').show();
                }
                if (!result.isDisplayParentField)
                    $('#parentid').closest('.field').hide();
                else
                    $('#parentid').closest('.field').show();
            }
        });
    }
    else {
        $('#inventorynumber').closest('.field').show();
        $('#parentid').closest('.field').show();
    }
}

function addSelected(uids, names) {	
    var id = uids[0];
    var un = names['id' + id];
    _ownerSelected(id, un);
}

function ownerSelected(e, d) {
    var id = d[1];
    var name = d[0];

    $(e.target).val('');
    _ownerSelected(id, name);
}

function _ownerSelected(id, name) {
    $('#owner ul li').remove();
    var hashid = getuserhash(id);
    var html = '<li class="changed"><a href="user.ivp/viewhash/' + hashid + '" onclick="return userDetails(' + "'" + hashid + "'" + ');" class="nounderline">' + name + '</a></li>';
    $('#owner ul').append(html);
    $('#ownerid').val(id);
}
//#endregion

//#region parent
function changeParent() {
    $('#parentadvice').show();
    parent.frames.tree.setMode('SELECTONE');
    return false;
}

function setParent(id, path, breadcrumbs) {
    if (id < 0) {
        parent.frames.tree.setMode('NORMAL');
        $('#parentadvice').hide();
        return false;
    }

    var oldpath = $('#path').val();
    if (oldpath.length > 0 && (path == oldpath || (path.length > oldpath.length && path.substr(0, oldpath.length) == oldpath))) {
        alert(AssetResources.CantMoveToChild);
        return false;
    }

    if (!$('#oldparentid').val()) {
        var pid = $('#parentid').val();
        $('#oldparentid').val(pid? pid : '0');
    }
    
    if( !$('#oldparentid').val())
        $('#oldparentid').val($('#parentid').val());
        
    $('#parentid').val(id);
    $('#breadcrumbs').addClass('changed').text(breadcrumbs);
    $('#parentadvice').hide();
    return true;
}

var Asset = {
    selectParent: function selectParent() {
        var url = 'assettable.ivp/select?cbmode=Asset&reset=true&tb_select_mode=assetparents&tb_asset_id=' + $("#id").val() + '&selectmode=SINGLE';
        dlg = openDialog(url, 'selectassets', { width: 900, height: 650 });
        dlg.callback = Asset.assetsCallback;
        return false;
    },
    assetsCallback: function assetsCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        parentSelected(ids, names);
    },

    selectOwner: function selectOwner() {
        var url = 'user.ivp/select?cbmode=Asset&reset=true&tb_mode=assetowners&tb_serviceid=0';
        dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
        dlg.callback = Asset.usersCallback;
        return false;
    },
    usersCallback: function usersCallback(result) {
        var uids = result["selectedIds"];
        var names = result["selectedNames"];
        addSelected(uids, names);
        return false;
    }
}

function parentAutocompleted(e, d) {
    var id = d[1];
    var name = d[0];

    $(e.target).val('');
    _parentSelected(id, name);
}

function parentSelected(ids, names) {
    var parentId = ids[0];
    var parentName = $.trim(names['id' + parentId]);
    _parentSelected(parentId, parentName);
    return false;
}

function _parentSelected(id, name) {
    $('#parentid').val(id);
    $('#parentlink').attr('onclick', 'assetDetails(event,' + id + '); return false').empty().html('<span class="normal">' + name + '</span>');
    $('#deleteparent').show();
}

function removeParrent() {
    $('#parentid').val('');
    $('#parentlink').attr('onclick', 'return false;').empty().html('<span class="normal">' + AssetResources.NotAssigned + '</span>');
    $('#deleteparent').hide();
    return false;
}
//#endregion

function removeFile(fieldid, link) {
    //if (!confirm(CommonResources.SureDeleteFile)) return false;

    //$('#filedeleted').val('true');
    //Пополняем коллекцию удаляемых файлов новым идентификатором
    var elems = $('#deletingfileids').val() != '' ? ($('#deletingfileids').val()).split('|') : [];
    elems.push(fieldid);
    $('#deletingfileids').val(elems.join('|'));
    
    var link = $(link);
    link.next('a').next('.changed').show().find('input').attr('disabled', false);
    link.next('a').hide();
    link.prev('a').hide();
    link.hide();
    
//    var link = $(link);
//    $.getJSON(base + 'asset.ivp/removefile/' + assetid + '/' + fieldid, { timestamp: new Date().toString() }, function(result) {
//        if (!result.IsOK) alert(result.Description);
//        else {
//            link.next('a').next('.changed').show().find('input').attr('disabled', false);
//            link.next('a').hide();
//            link.prev('a').hide();
//            link.hide();
//        }
//    });
    return false;
}

function changeFile(fieldid, link) {

    //Удаляем идентификатор из коллекции удаляемых файлов
    var elems = ($('#deletingfileids').val()).split('|');
    var newelems = [];
    for (var i = 0; i <= elems.length - 1; i++) {
        if (elems[i] != fieldid) newelems.push(elems[i]);
    }
    $('#deletingfileids').val(newelems.join('|'));

    var link = $(link);
    link.next('.changed').show().find('input').attr('disabled', false);
    link.hide();
    $('#filedeleted').val('true'); 
    return false;
}

function assetHistory() {
    openDialog('assethistory.ivp/list/' + $('#id').val(), 'History');
    return false;
}

function changeZabbixHost(currentid) {
    $('#changebtn').hide();
    $('#changebtn').parent().text(AssetResources.ZabbixHost);
    $('#externalidholder').empty();
    var select = $('<select id="externalid" name="externalid"/>');
    $.getJSON(base + 'asset.ivp/getzabbixhosts', { typeid: $('#typeid').val() }, function(result) {
        $(result).each(function(i, e) { var option = $('<option/>').val(e.Id).text(e.Name); if (e.Id == currentid) option.attr('selected', true); select.append(option); });
        $('#externalidholder').append(select);
    });
    
    return false;
}


function removeAssetLink() {
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toDateString() };
    var url = base + tableController() + 'DeleteLinksFromForm';
    selectedIds.length = 0;
    $(tableRootDiv).load(url, params, initTable);
    return false;
}

function openAssetLinkPanel(link, linkid) {
    $('#assetlinkform').remove();
    var $link = $(link);
    var $popupwrapper = $('<div id="assetlinkform" class="popupwrapper"/>');
    $('body').append($popupwrapper);
    
    var offset = $link.offset();
    $popupwrapper.load(base + 'assetlink.ivp/createfromform', { typeid: $('#linktypeid').val(), linkassetid: $('#id').val(), linkid: linkid, from:'asset' }, function() {
        $popupwrapper.css('top', offset.top + $link.height() + 5).css('left', offset.left);
        autoComplete();
        afterLinkFormCreated();
        $popupwrapper.show();
        
    });
    return false;
}

function saveAssetLink() {
    if ($("#linkform").valid() && $('#addsecondobject').valid()) {        
        $('#assetlinkform').hide();
        $.post(base + 'assetlink.ivp/save/', $('#linkform').serializeArray(), function() { loadLinks($('#linktypeid').val()) });
        $('#assetlinkform').remove();
    }
    return false;
}

function assetDescription(e, id) {
    if (!e)
        e = window.event;

    if (e.cancelBubble)
        e.cancelBubble = true;
    else if (e.stopPropagation)
        e.stopPropagation();

    openDialog('assettable.ivp/view/' + id + '?popup=true&read=true', 'asset', { width: 980, height: 650 });
    return false;
}

function changeFieldFile(fieldid, link) {
    return changeFile(fieldid, link);
}
