$(function() {
    if ($('#postback').length > 0) {
        if ($('#parentid').val()) {
            parent.frames.tree.expand($('#parentid').val(), true);
            if ($('#oldparentid').val()) {
                parent.frames.tree.expand($('#oldparentid').val(), true);
                $('#oldparentid').val('');
            }
        }
        else {
            parent.frames['tree'].location.href = base + 'kb.ivp/node';
        }
    } else {
        parent.frames['tree'].location.href = base + 'kb.ivp/node';
    }

    resize();
    $(window).resize(resize);

    //загружаем при необходимости список документов для выбранного раздела
    if ($('#kbdocumentholder').length > 0)
        $('#kbdocumentholder').load(base + $('#kbdocumentholder').attr('src'), { timestamp: new Date().toDateString(), nolayout: true });
});

function resize() {
    var h = $(window).height() - $('#header').height() - $('#footer').height() - 30;
    $('#content').css('height', h);
	$('#kbdocumentholder').css('height', h - 30);
}

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

function getKbDocumentHolder() {
	return $('#kbdocumentholder');
}

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

    var oldpath = $('#path').val();
    if (path == oldpath || (path.length > oldpath.length && path.substr(0, oldpath.length) == oldpath)) {
        return false;
    }
    
    if( !$('#oldparentid').val())
        $('#oldparentid').val($('#parentid').val());
    
    $('#parentid').val(id);
    $('#breadcrumbs').addClass('changed').text(breadcrumbs);
    $('#parentadvice').hide();
    return true;
}

/**************permissions***********************/

function changePermission(link) {
    var link = $(link);
    var td = link.parent();
    $('.popupwrapper').hide();
    if (td.find('.popupwrapper').length > 0)
        td.find('.popupwrapper').show();
    else {
        var html = '<div class="popupwrapper"><div class="popup">' + $('#selectpermissiontemplate').html() + '</div></div>';
        td.append(html).find('.popupwrapper').css({left:td.position().left + 10, top: td.position().top + 10}).show();
    }
    return false;
}

function hidePermission(link) {
    $(link).parents('.popupwrapper').hide();
    return false;
}

function setPermission(link, permissionid) {
    var dd = $(link).parents('dd');
    $(link).parents('.popupwrapper').remove();
    var url = base +'kb.ivp/changepermission';

    $.getJSON(url, {permissionid: permissionid, kbfpermissionid: getId(dd.find('a:first').attr('id')), timestamp: new Date().toString() }, function(result) {		
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
			dd.find('a:first').text($(link).text());
			//dd.addClass('changed');
			//var color = dd.parent().hasClass('odd') ? '#f3f7fc' : '#fff';
			//dd.animate({ backgroundColor: color }, 1500).removeClass('changed');      
        }
    });
    return false;
}

/****************delete ******************************/
function deletePermission(link, permissionId) {
    if (!confirm(CommonResources.SureDeletePermission)) return false;
	var groupName = $(link).parents('div:first').attr('id');
    $.getJSON(base + 'kbfolderpermission.ivp/delete', { id:permissionId, json: true, timestamp: new Date().toString() }, function() {reload(groupName);});
    return false;
}

function reload(groupName) {
	$('#permissionsholder').load(base + 'kb.ivp/ReloadPermissions/' + $('#id').val(), {timestamp: new Date().toString(), nolayout: true}, function() {reloadComplete(groupName);});
	return false;
}

function reloadComplete(groupName) {
	toggle($('#'+groupName).prev().prev(), '#'+groupName);
	return false;
}

/*****************choose members***************************/

/******users******/
function chooseUser(folderid) {
    var url = 'user.ivp/select?tb_mode=kbfolder&tb_serviceid=0&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectusers', { width: 980, height: 650 });
    dialog.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var uids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedUsers(uids, pid);
}

function addSelectedUsers(uids, pid) {
	var folderId = $('#id').val();
	$.post(base + 'kb.ivp/addpermissions', { folderId: folderId, permissionid: pid, uids: uids.join(','), timestamp: new Date().toString(), nolayout: true}, function() {reload('Users');});
}

/******companies******/
function chooseCompany(folderid) {
    var url = 'company.ivp/select?tb_custom_mode=kbfolder&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectcompanies', { width: 980, height: 650 });
    dialog.callback = companiesCallback;
    return false;
}

function companiesCallback(result) {
    var ids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedCompanies(ids, pid);
};

function addSelectedCompanies(cids, pid) {
	var folderId = $('#id').val();
	$.post(base + 'kb.ivp/addpermissions', { folderId: folderId, permissionid: pid, cids: cids.join(','), timestamp: new Date().toString(), nolayout: true}, function() {reload('Departments');});
}

/******services******/
function chooseService(folderid) {
    var url = 'service.ivp/select?tb_custom_mode=kbfolder&tb_kbfolderid=' + folderid;
    var dialog = openDialog(url, 'selectservices', { width: 980, height: 650 });
    dialog.callback = servicesCallback;
    return false;
}

function servicesCallback(result) {
    var ids = result["selectedIds"];
    var pid = result["permissionId"];
    addSelectedServices(ids.join(','), pid);
}

function addSelectedServices(sids, pid) {
	var folderId = $('#id').val();
	$.post(base + 'kb.ivp/addpermissions', { folderId: folderId, permissionid: pid, sids: sids, timestamp: new Date().toString(), nolayout: true}, function() {reload('_Services');});
}

/******distribution********/
function openDistributionForm(id) {
    var allVals = [];
    $("input:checkbox[name='distributionids']:checked:enabled").each(function() {
       allVals.push($(this).val());
   });
   if (allVals.length <= 0) {
       alert(KBResources.SelectAnyDocument);
       return false;
   }
   $('body').append('<form action="' + base + 'kb.ivp/runnewsletter" id="distributionform" method="post" enctype="multipart/form-data"></form>');
   var distributionform = $('#distributionform');
   distributionform.append('<input id="documentids" name="documentids" type="hidden" value="' + allVals + '"/>');
   distributionform.append('<input id="id" name="id" type="hidden" value="' + id + '"/>');
   distributionform.submit();
   return false;
}

function selectAll() {
    $("input:checkbox[name='usersemails']").each(function() {
        $(this).attr("checked", true);
    });
}

function deselectAll() {
    $("input:checkbox[name='usersemails']").each(function() {
        $(this).attr("checked", false);
    });
}

function preview() {
    var userid = $("input:checkbox[name='usersemails']").val();
    var message = $('#message').val();
    var subject = $('#subject').val();
    $.post(base + 'kb.ivp/preview', { userid: userid, message: message, subject: subject, preview: true, timestamp: new Date() }, function(result) {
        var html = $.parseJSON(result);
        $('body').append('<div id="loadingdiv" class="loadingdiv" style="height:100%;"></div><div id="previewform" class="popuppreview"></div>');
        $('#previewform').append(html);
        $('#previewform').show();
        $('#previewform').css('left', '10%').css('top', 100);
    }, "html");
}

function send() {
    var allVals = [];
    $("input:checkbox[name='usersemails']:checked:enabled").each(function() {
        allVals.push($(this).val());
    });
    if (allVals.length <= 0) {
        alert(KBResources.SelectAnyUser);
        return;
    }
    $('.send').attr("disabled", true);
    $('.preview').attr("disabled", true);
    $.ajax({
      url: base + 'kb.ivp/send',
      type: "POST",
      data: ({ users: allVals, subject: $('#subject').val(), message: $('#message').val() }),
      dataType: "json",
      success: function (result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
          $('.send').attr("disabled", false);
          $('.preview').attr("disabled", false);
          $('#errorholder').empty().css("background-color", "#ffd8d8").css("border-color", "#fca6a6").html("<div id='error'><div class='kberror'>" + result.Description + "</div></div>").show();
          $('#errorholder').css("height", $('#error').height() + 20);
        }
        else {
          $('.send').attr("disabled", false);
          $('.preview').attr("disabled", false);
          $('#errorholder').empty().css("background-color", "#e3ffd8").css("border-color", "#96e577").html("<div id='error'><div class='kberror'>" + KBResources.Success + "</div></div>").show();
          $('#errorholder').css("height", $('#error').height() + 20);
        }
      }
  });
}

function selectKbDescriptionLanguage() {
    var url = 'fieldlanguage.ivp/load?textarea=true&table=KBFolders&field=DescriptionXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectKbNameLanguage() {
    var url = 'fieldlanguage.ivp/load?required=true&table=KBFolders&field=NameXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function inheritKbFolderPermissions() {
    var params = {
        id: $('#id').val(),
        users: $('#inheritusers').is(':checked'),
        departments: $('#inheritdepartments').is(':checked'),
        services: $('#inheritservices').is(':checked')
    };
    $.ajax({
        type: 'POST',
        url: base + 'KBFolderPermission.ivp/InheritPermissions',
        data: params,
        success: function () {
            alert(KBResources.InheritPermissionsSuccess);
            $('#inheritprop').hide();
        },
        error: function (request, status, error) {
            alert(error);
        }
    });
}