var sid = 0;
var hid = 0;
var canedit = false;
var mode = $('#mode').val();

$(function() {
    canedit = ($('#canedit').val() == 'true');
    if (canedit && mode == 'NORMAL') { $('.node>a.link>span.cm').click(showContextMenu).mouseout(function() { clearTimeout(sid); hid = setTimeout('hideContextMenu()', 400); }); }
    $('#exportform input[type="radio"]').click(function() { if ($('#excelformatlist').attr('checked')) $('#assettypesfilter').show(); else $('#assettypesfilter').hide(); });
    $.cookies.set("assets_nodeid_excel",undefined);
});

//Перевод дерева в другой режим
function setMode(m) {
    switch (m) {
        case 'SELECTONE':
            mode = m;
            $('#popupcontainer').addClass('changed');
            break;
        default:
            mode = 'NORMAL';
            $('#popupcontainer').removeClass('changed');
            break;
    }
}

function expand(id, reload, skiptoggle) {
    var li = $('li#node_' + id);
    var params = '?parentid='+id+'&mode=' + mode + '&exclude=' + $('#exclude').val();
    var url = base + 'asset.ivp/node' + params;
    if (!reload && li.find('div.children').length > 0) {
        if(!skiptoggle) li.find('>div.children').toggle();
        syncImage(id);
    }
    else {
        $('li#node_' + id + '>.children').remove();
        li.append('<div class="children"></div>');
        var div = li.find('div.children');
        div.load(url, { timestamp: new Date().toString(), nolayout: true }, function() { syncImage(id); if (canedit && mode == 'NORMAL') { $('.node>a.link>span.cm', div).click(showContextMenu).mouseout(function() { clearTimeout(sid); hid = setTimeout('hideContextMenu()', 400); }); } });
    }
    return false;
}

function syncImage(id) {
    var li = $('li#node_' + id);
    var a = li.find('a.nodeicon:first');
    var img = a.find('img:first');
    var id = getId(a.parents('li.tn:first').attr('id'));
    
    //Есть дочки и они видны
    if (li.find('div.children .node').length > 0) {
        if (li.find('div.children').is(':visible'))
            img.attr('src', 'img/tree/minus.gif');
        else
            li.find('a.nodeicon:first > img').attr('src', 'img/tree/plus.gif');
    }
    else
        li.find('a.nodeicon:first > img').attr('src', 'img/_.gif');
}

function openCI(id) {
    $(parent.frames['ci']).attr('src', base + 'asset.ivp/view/' + id);
}

//Вызывается при клике на название актива
function select(link, skipexpand) {
    link = $(link);
    if (!skipexpand) expand(link.attr('nodeid'), false, true);

    $.cookies.set("assets_nodeid_excel", link.attr('nodeid'));
    
    switch (mode) {
        case 'SELECTONE':
            var parentname = link.attr('breadcrumbs');
            //remove all html tags from name of parentAsset
            parentname = parentname.replace(/<[^>]*>/g, '');
            if (parent.frames.ci.setParent(link.attr('nodeid'), link.attr('path'), parentname))
                setMode('NORMAL');
            return false;
        default:
            $('a.selected').removeClass('selected');
            link.addClass('selected').blur();
            return true;
    }
}

function addAsset(id) {
    var ids = [id];
    $('li#node_' + id).fadeOut('fast', function() { $('li#node_' + id).remove(); });
    var name = $('li#node_' + id + ' a.link').attr('breadcrumbs');
    try {
        if (getURLParameter('callback') != null && getURLParameter('callback') != '') {
            //second parameter is type for asset links
            eval('top.opener.' + getURLParameter('callback'))(id, 1, name);
        }
        else
            top.opener.assetSelected(ids, name);
        if (getURLParameter('selectmode') != null && getURLParameter('selectmode') != '' && getURLParameter('selectmode') == "SINGLE") {
            parent.parent.self.close();
        }
    } catch (e) { alert(e); }
    return false;
}

function hideContextMenu() {
    $('.contextmenu').hide();
}

function showContextMenu() {
    var id = getId($(this).parents('.tn:first').attr('id'));
    clearTimeout(hid);
    hideContextMenu();
    var nodeid = '#node_' + id;

    var link = $(nodeid).find('a.link:first').get(0);
    select(link,true);

    var popuppath = nodeid + '>.node>.contextmenu';
    var node = $(nodeid).children('.node');
    if ($(popuppath).length == 0) {
        var popup = node.append('<ul class="contextmenu"></ul>').children('.contextmenu');
        popup.append('<li onclick="return createChild(' + id + ')">' + AssetResources.CreateChildAsset + '</li>');
        popup.append('<li onclick="return deleteAsset(' + id + ')">' + AssetResources.DeleteAsset + '</li>');
        popup.append('<li onclick="return excel(' + id + ')">' + AssetResources.ExportExcel + '</li>');
        $(popuppath).mouseover(function() { clearTimeout(hid); }).mouseout(function() { hid = setTimeout('hideContextMenu()', 500); });
    }
    var offset = node.offset();
    $(popuppath).css('left', offset.left + 50).css('top', offset.top + 10).show();
    return false;
}

function createChild(id) {
    var url = base + 'asset.ivp/create?parentid=' + id;
    parent.frames.ci.document.location.href = url
    return false;
}

function deleteAsset(id) {
    if (!confirm(AssetResources.SureDelete)) return false;
    $.getJSON(base + 'asset.ivp/delete', { id:id, json: true, timestamp: new Date().toString() }, assetDeleted);
    return false;
}

function assetDeleted(result) {
    if (!result.IsOK) alert(result.Description);
    else {
        $('#node_' + result.Id).remove();
        parent.frames.ci.document.location.href = 'about:blank';
    }
}

function excel() {
    var id = $.cookies.get("assets_nodeid_excel");
    $('#rootid').val(null);
    $('.contextmenu').hide();
    $('#rootid').val(id);
    var left = 0;
    var top = 0;
    if ($('#node_' + id).offset()) {
        var offset = $('#node_' + id).offset();
        left = offset.left;
        top = offset.top;
    }
    $('#exportform').css('top', top + 20).css('left', left + 20).show();
    return false;
}

function initMultipleSelect() {
    if ($.multipleSelect)
        $.multipleSelect.initByClassName('.multipleselect', { init: true, pixelwidth: 600 });
}

function performExport() {
    var params = $('#exportform form').serializeArray();
    var url = base + 'asset.ivp/excel' + params['excelformat'] + '?rootid=' + params['rootid'] + '&typeids=' + params['typeids'];
    window.open(url, 'excel', null);
    $('#exportform').hide();
    return false;
}

var AssetTreeExport = {
    selectAssetType: function selectAssetType(url, msName) {
        if (url.indexOf('?') > -1) {
            url += "&";
        } else {
            url += "?";
        }

        url += ('msName=' + msName);
        url += '&cbmode=ServiceLevelRule';

        dlg = openDialog(url, 'selectassettypes', { width: 900, height: 650 });
        dlg.callback = ServiceLevelRule.assetTypesCallback;
        return false;
    },
    assetTypesCallback: function assetTypesCallback(result) {
        var msName = result['msName'];
        addSelectedValues(result, msName);
    }
}