// QST Documentor
// (c) Quali-Soft
// Developed by persei


var g_docData = new Object();

var g_foldName = '';
var g_foldId = 0;

var cur_doc = undefined;


var g_folder = 0; 
function sendAdminLogin()
{
	function loginResult(data)
	{
		setAdmin(data == 1 ? true : false);		
		hideForm('adminLogin');
	}
			
	var password = $("#admin_password").attr('value');
	
	$.post('/documents/ajax/', {'action' : 'login', 'password' : password}, loginResult);
}

function makeMove(source, destination, pos)
{
	$.post('/documents/ajax/', {'action' : 'move', 'source' : source, 'destination' : destination, 'pos': pos});
}

function newFolder()
{
	var foldid = TreeCollection.get(0).getSelected().attr('id') == undefined ? '0' : TreeCollection.get(0).getSelected().attr('id');
	
	if(foldid.indexOf('/') != -1)
		foldid = foldid.split('/')[0];

	g_foldId = foldid;
	
	showForm('newFolder');
}

function editFolder(foldid)
{
	g_foldId = foldid;
	g_foldName = $("li#" + foldid + " span:first").text();
	
	showForm('editFolder');
}

function newDocument()
{
	if (TreeCollection.get(0).getSelected().attr('id') == undefined)
		g_folder = 0;
	else
	{
		g_folder = TreeCollection.get(0).getSelected().attr('id');
	}
	
	showForm('newDocument');
}

function editDocument()
{
	if (TreeCollection.get(0).getSelected().attr('id') == undefined && cur_doc == undefined)
		return false;

	var docid = TreeCollection.get(0).getSelected().attr('id') == undefined ? cur_doc : TreeCollection.get(0).getSelected().attr('id');
	
	if(docid.indexOf('/') == -1)
		return editFolder(docid);
	
	$.ajax({
		   type  : 'GET',
		   url   : '/documents/ajax/',
		   async : false,
		   data  : {'action' : 'getdocument', 'id' : docid},
		   dataType : 'json',
		   success : function(data){g_docData = data},
		   error : function(data,status,e){alert(status)}
		  });
					  
	showForm('editDocument');
}

function deleteDocument()
{
	if (TreeCollection.get(0).getSelected().attr('id') == undefined && cur_doc == undefined)
		return false;
		
	var docid = TreeCollection.get(0).getSelected().attr('id') == undefined ? cur_doc : TreeCollection.get(0).getSelected().attr('id');
	
	if(docid.indexOf('/') != -1)
	{
		if(!confirm('Вы действительно хотите удалить документ "' + $("li#" + docid  + " span.active:first").text() + '"?'))
			return false;
	}
	else
	{
		if(!confirm('Вы действительно хотите удалить папку документов "'+$("li#" + docid  + " span.active:first").text() +'"?  Вместе с папкой будут удалены и содержащиеся в ней документы!'))
			return false;		
	}
		
	
	$.post('/documents/ajax/', {'action' : 'delete', 'id' : docid}, function(data){if(data) {var div = document.getElementById(docid); div.parentNode.removeChild(div); window.location.reload();}});
}

function processNewFolder()
{
	newFoldName = $("#folder_name").attr('value');
	
	function newFolderResult(data)
	{
		if(data)
		{
			hideForm('newFolder');
			window.location.reload();
		}
	}
	
	$.post('/documents/ajax/', {'action' : 'newfold', 'parent' : g_foldId, 'name' : newFoldName}, newFolderResult);	
}

function processEditFolder()
{
	newFoldName = $("#folder_name").attr('value');
	
	function editFolderResult(data)
	{
		if(data)
		{
			$("li#" + g_foldId + " span:first").text(newFoldName);
			hideForm('editFolder');
		}
	}
	
	$.post('/documents/ajax/', {'action' : 'editfold', 'id' : g_foldId, 'name' : newFoldName}, editFolderResult);
}

function processAddDocument()
{
	function addResult(data)
	{
		hideForm('newDocument');
		var name = g_folder ? $("li#" + g_folder + " span:first").text() : 'корень';
		alert('Документ успешно создан и помещен в папку "' + name + '"');
		window.location.reload();
	}
	
	var name = document.getElementById('document_name').value;
	var descr = document.getElementById('document_desc').value;
	var date = document.getElementById('document_date').value;
	var htmldata = document.getElementById('document_html').value;
	var tmpid = document.getElementById('document_id').value;

	if(name.length < 3)
	{
		alert('Название слишком короткое');
		return false;
	}

	if(descr.length < 3)
	{
		alert('Описание слишком короткое');
		return false;
	}
	
	if(date.length < 3)
	{
		alert('Выберите дату');
		return false;
	}
		
	$.post('/documents/ajax/', {'action' : 'new', 'name' : name, 'descr' : descr, 'date' : date, 'htmldata' : htmldata, 'folder' : g_folder, 'tmpid' : tmpid}, addResult);
}

function processEdtDocument()
{
	function editResult(data)
	{
		hideForm('editDocument');
		window.location = window.location;
	}
	
	var name = document.getElementById('document_name').value;
	var descr = document.getElementById('document_desc').value;
	var date = document.getElementById('document_date').value;
	var htmldata = document.getElementById('document_html').value;
	var id = document.getElementById('document_id').value;
	
	if(name.length < 3)
	{
		alert('Название слишком короткое');
		return false;
	}

	if(descr.length < 3)
	{
		alert('Описание слишком короткое');
		return false;
	}

	if(date.length < 3)
	{
		alert('Выберите дату');
		return false;
	}
		
	$.post('/documents/ajax/', {'action' : 'edit', 'name' : name, 'descr' : descr, 'date' : date, 'htmldata' : htmldata, 'folder' : g_folder, 'id' : id}, editResult);	
}

function addFileToForm(data)
{
	document.getElementById('document_attached').innerHTML += data;
}

function uploadFile()
{
	var id = document.getElementById('document_id').value;
	
	$.ajaxFileUpload({
						url : '/documents/ajax/?action=uploadfile&id=' + id,
						secureuri : false,
						fileElementId : 'document_upload',
						dataType : 'html',
						success : function (data, status)
						{
							addFileToForm(data);
						},
						error : function (data, status, e)
						{
							alert(data.responseText);
							alert('Во время загрузки произошла ошибка. Возможно файл слишком большой');
						}
					});
}

function deleteFile(name, id)
{	
	function deleteFileResult(data)
	{
		var div = document.getElementById(name + '_' + id);
		div.parentNode.removeChild(div);
	}
	
	if(!confirm('Вы действительно хотите удалить файл? Действие нельзя будет отменить!'))
		return false;
	
	$.post('/documents/ajax/', {'action' : 'deletefile', 'name' : name, 'id' : id}, deleteFileResult);
}

function htmlSave()
{
	document.getElementById('document_html').value = FCKeditorAPI.GetInstance('document_html_editor').GetXHTML(true);
}

function logout()
{
	setAdmin(0);
	$.post('/documents/ajax/', {'action' : 'logout'});
}
