function initTreelineButtonsElnProjects(treeId) {
	initTreelineMoreOptionsDeleteFolder(treeId, "/eln/workspace/{id}/isEmpty", "/eln/workspace/{id}/delete");
}

function initTreelineButtonsTextTemplates(treeId) {
		initTreelineMoreOptionsDeleteFolder(treeId, "/eln/workspace/{id}/isEmpty", "/eln/workspace/{id}/delete");
}

var TreeElement = {

		createNew: function(item, elType, group, callback) {

			var saveCallback = 	function(formData) {
				var formObj = convertFormArrayToObject(formData);
				TreeElement.saveNew(item, elType, formObj, callback);
			};

			var isTemplate = (elType == "TEMPLATE");
			var itemName = isTemplate ? "template" : "project";

			var options = {
					templateName: "jsTemplate_workspace_create_project_dialog",
					treeId: "project_popup",
					treeUrl: "/eln/workspace/treeInPopup",
					template: isTemplate,
					showTreeFoldersOnly: true,
					treeFolderSelectable: true,
					treeItemSelectable: false,
					selectedTreelineCallback: function(formData){
						saveCallback(formData);
					}
			};

			if(item == "item"){
				openSelectTreelineDialog("Create " + itemName, options);

			}else if(item == "folder"){
				options.templateName= "jsTemplate_workspace_create_folder_dialog";
				openSelectTreelineDialog("Create folder", options);
			}
		},

		saveNew: function(item, elType, formObj, fCallback){

			var formData = {
				name: formObj.name,
				groupId: formObj.selectedTreelineGroupId,
				parentId: formObj.selectedTreelineObjectId,
				csrfToken: getCSRFToken(),
				type: elType
			};

			var callback;

			var postUrl;

			if(item == "item"){

				postUrl = "/eln/workspace/createProject";

				callback = function(data, textStatus, jqXHR){

					if(data.status == 0) {
						if (data.dataObj.groupId > 0 && data.dataObj.shareable) {
							Group.projects.shareEdit(data.dataObj.id, data.dataObj.groupId);

						} else if(fCallback) {
							fCallback(data);

						} else {
							Dialog.close();
							location.reload(true);
						}

					} else {
						Dialog.showError(data.errorMessageList);
					}

				}
			}
			else if(item == "folder"){

				postUrl = "/eln/workspace/createFolder";

				callback = function(data, textStatus, jqXHR){

					if(data.status == 0) {

						Dialog.close();

						var itemName = (elType == "TEMPLATE") ? "templates" : "projects";

						var targetFolder = $("#treeline_eln_" + itemName +"_" + formObj.selectedTreelineGroupId + "_" + formObj.selectedTreelineObjectId).next();

						var shareSettings = "";
						if(data.dataObj.shareable) {
							shareSettings = "<div class='more_options_item buttonShareSettings'>" +
											"<span aria-hidden='true' class='icon-conf'></span> Share settings" +
											"</div>";
						}

						var newFolder =	$("<a id='treeline_eln_" + itemName + "_" + formObj.selectedTreelineGroupId + "_"
										+ data.dataObj.id + "' data-groupid='" + formObj.selectedTreelineGroupId + "' "
										+ "data-objectid='" + data.dataObj.id + "' class='treeline is_folder is_open_folder'>")
										.append("<span class='updateTS'>"+ data.dataObj.createTS + "</span>")
										.append("<div class='tree_button more_options in_tree'>"
					+"<button class='more_options_button_tree'><span aria-hidden='true' class='wheel-img'></span></button>"
					+"<div class='more_options_panel in_tree' style='display: none;'>"

						+"<span class='menu_arrow-img'></span>"
						+"<ul>"
						+"<li class='more_options_item buttonRename'>Rename folder<span class='edit-img'></span></li>"
						+"<li class='more_options_item treelineButtonDeleteFolder'>Delete folder<span class='trash_dark-img'></span></li>"
						+"</ul>"
						+"</div>"
						+"</div>")
										.append("<span class='folder_dn-img'></span>")
										.append("<span class='name'> " + formObj.name + "</span>");

						makeDroppable(newFolder);
						makeDraggable(newFolder);

						var newChildren = $("<div class='treeline_children'><div class='treeline_children_empty'>empty folder</div></div>");
						newFolder.after(newChildren).hide();

						targetFolder.append(newFolder).children(".treeline_children_empty").slideUp(300,function(){
							this.remove();
						});

						newFolder.eq(0).css("background", "rgb(236, 240, 243)");

						newFolder.show(300, function() {
							$(newFolder.parents(".treeline_children").siblings(".is_folder")).each(function(){
								openTreelineFolder($(this));
							});
							newFolder.eq(0).css("overflow", "visible");
							setTimeout(function(){
									// TODO we should have exactly 1 main element in all pages
									// in all projects page we have #eln_main_content
									// in group projects page we have #eln_project_content
									$("#eln_main_content, #eln_project_content").animate({
										scrollTop: $(newFolder).offset().top-200
									}, 500);
								},500);
						});

					} else {
						Dialog.showError(data.errorMessageList);
					}
				}
			}

			$.post(postUrl, formData, function(data, textStatus, jqXHR){
				callback(data, textStatus, jqXHR);
			});

		}
}



function initTreelineMoreOptionsDeleteFolder(treeId, isEmptyUrl, deleteUrl) {
	$("body").on("click", ".treelineButtonDeleteFolder", function(){
		var treeline = $(this).closest("a.treeline");
		var objectId = treeline.attr("data-objectId");

		var isEmptyUrlReplaced = isEmptyUrl.replace("{id}", objectId);
		$.get(isEmptyUrlReplaced, {}, function(data, textStatus, jqXHR){
			if(data.status == 0) {
				if(data.dataObj == true) {

					var templateData = { treeline_name: treeline.find("span.name").text() };
					var content = $.jsTemplate("jsTemplate_basic_delete_folder_dialog", templateData);

					var confirmButtonCallback = function() {
						var deleteUrlReplaced = deleteUrl.replace("{id}", objectId);
						$.post(deleteUrlReplaced, {csrfToken: getCSRFToken()}, function(data, textStatus, jqXHR){
							if(data.status == 0) {
								var parentLine = treeline.parent();
								treeline.next().andSelf().slideUp(300, function(){
									this.remove();
									if(parentLine.children().length == 0){
										var emptyChildren = $("<div class='treeline_children_empty' style='display:none'>empty folder</div>");
										parentLine.append(emptyChildren);
										emptyChildren.slideDown(300);
									}
								});
								Dialog.close();
							} else {
								Dialog.showError(data.errorMessageList);
							}
						});
					};
					Dialog.confirm("Delete folder", content, {text: "Delete", callback: confirmButtonCallback});

				} else {
					Dialog.alert("Delete folder");
					Dialog.showError("This folder is not empty. Please delete all of its content first, then you can delete the folder itself");
				}
			} else {
				return ;
			}
		});

		$(".more_options_panel").hide();
		return false;
	});
}


function selectTreeline(treeId, groupId, objectId) {
	$("#tree_" + treeId + " input[name=selectedTreelineGroupId]").val(groupId);
	$("#tree_" + treeId + " input[name=selectedTreelineObjectId]").val(objectId);
	$("#tree_" + treeId + " .treeline").removeClass("selected");
	$("#treeline_" + treeId + "_" + groupId + "_" + objectId).addClass("selected");
}



function openSelectTreelineDialog(dialogTitle, options) {

	var content = $.jsTemplate(options.templateName, null);

	var confirmButtonCallback = function() {
		var groupId = $("#tree_" + options.treeId + " input[name=selectedTreelineGroupId]").val();
		var objectId = $("#tree_" + options.treeId + " input[name=selectedTreelineObjectId]").val();

		if(groupId == "" || objectId == "") {
			if(dialogTitle == "Use template"){

				Dialog.showError("Please select a template that you would like to use");

			} else if(dialogTitle == "Save as new template"){

				Dialog.showError("Please select a template folder");

			}else if(dialogTitle == "Create a new entry"){

				setTimeout(function(){Dialog.showError("Please select a project");}, 300);
			}

		} else {
			var formData = $("#my_popup_content form").serializeArray();
			options.selectedTreelineCallback(formData);
		}
	};

	var loadedCallback = function() {
		$.get(options.treeUrl,
				{
					treeId: options.treeId,
					template: options.template,
					showTreeFoldersOnly: options.showTreeFoldersOnly,
					treeFolderSelectable: options.treeFolderSelectable,
					treeItemSelectable: options.treeItemSelectable
				},
				function(data, textStatus, jqXHR){
					var selectTree = $(data);

					$("#my_popup_content .spinner").fadeOut(300, function(){
						$("#my_popup_content .treeInPopupContainer").html(selectTree).slideDown(300, function(){
							var firstLine = $("#tree_project_popup a").first();
							selectTreeline(options.treeId, firstLine.attr("data-groupid"), firstLine.attr("data-objectid"));
							Dialog.center();
							initTreelineFolders(options.treeId);
						});
					});
				}
		);

		$("#my_popup_content input:first").focus();
		$("#my_popup_content form").submit(function(){
			confirmButtonCallback();
			return false;
		});

	};

	Dialog.confirm(dialogTitle, content, {text: dialogTitle, callback: confirmButtonCallback}, {}, {}, loadedCallback);
}

function moveProject(objectId, groupId, parentId){
	$.post("/eln/workspace/" + objectId + "/move",
			{
				"csrfToken": getCSRFToken(),
				"parentId": parentId
			},
			function(data){
				if(data.status != 0) {
					Dialog.showError(data.errorMessageList);
				}
			}
	);
}

function bindTreeUI(){
	//Hacky hack to fix jquery bug in 1.8.2 that adds overflow hidden when animating hide and show
	$('body').on('mouseover', '.treeline, .treeline_children', function(){
		if($(this).css('overflow') == "hidden" ) $(this).css("overflow", "visible");
	});

	var droppableScope = $("a.is_folder");
	makeDroppable(droppableScope);

	var draggableScope = $("a.is_folder, a.is_item").not($("[data-objectid='0']"));
	makeDraggable(draggableScope);
}

function makeDroppable(elements){

	elements.droppable({
		accept: function(el){
			if(el.hasClass("is_item")){
				return (el.attr("data-groupid") == $(this).attr("data-groupid"));
			}
			else {
				var notOwnChild = (el.next().find($(this)).length == 0);
				if(el.hasClass("is_folder") && notOwnChild) return (el.attr("data-groupid") == $(this).attr("data-groupid"));
			}
		},
		activeClass: "droppable_folder",
		drop: function(event, ui){

			var el = this;
			var siblings = $(el).next().children("a");
			var inserted = false;
			var originSiblings = ui.draggable.siblings("a").length;
			var parent = ui.draggable.parent();

			for(var i = 0; i < siblings.length; i++){

				if(ui.draggable.hasClass("is_item")){
					if(siblings.eq(i).hasClass("is_folder")){
				 		ui.draggable.hide(300,function(){
				 			siblings.eq(i).before(ui.draggable.show(300));
				 		});
				 		inserted = true;
				 		break;
					} else if(siblings.eq(i).hasClass("is_item")){
						if(ui.draggable.find("span.name").text().trim().toLowerCase() < siblings.eq(i).find("span.name").text().trim().toLowerCase()){
					 		ui.draggable.hide(300,function(){
					 			siblings.eq(i).before(ui.draggable.show(300));
					 		});
					 	inserted = true;
					 	break;
						}
					}
				} else if(ui.draggable.hasClass("is_folder")){
					if(siblings.eq(i).hasClass("is_folder")){
						if(ui.draggable.find("span.name").text().trim().toLowerCase() < siblings.eq(i).find("span.name").text().trim().toLowerCase()){
					 		ui.draggable.next().andSelf().hide(300,function(){
					 			siblings.eq(i).before(ui.draggable.next().andSelf());
								if (ui.draggable.hasClass("is_open_folder")){
									ui.draggable.next().andSelf().show(300);
								}
								else ui.draggable.show(300);
					 		});
					 	inserted = true;
					 	break;
						}
					}
				}
			}

			if(!inserted){
				if(ui.draggable.hasClass("is_folder")){
			 		ui.draggable.next().andSelf().hide(300,function(){
			 			 $(el).next().append(ui.draggable.next().andSelf());
			 			 if (ui.draggable.hasClass("is_open_folder")){
			 				 ui.draggable.next().andSelf().show(300);
			 			 }
			 			 else ui.draggable.show(300);
			 		});
				}
				else if(ui.draggable.hasClass("is_item")){
			 		ui.draggable.hide(300,function(){
			 			 $(el).next().append(ui.draggable.show(300));
			 		});
				}
			}

			if(originSiblings == 0){
				parent.append("<div class='treeline_children_empty'>empty folder</div>");
			}

			$(el).next().children(".treeline_children_empty").hide("fast", function(){
				$(this).remove();
			});

			var objectId = ui.draggable.attr("data-objectid");
			var groupId = ui.draggable.attr("data-groupid");
			var parentId = $(el).attr("data-objectid");

			moveProject(objectId, groupId, parentId);

		},
		hoverClass: "hover_droppable_folder"
	});
}

function makeDraggable(elements){

	elements.draggable({
		appendTo: '.eln_scroll-y',
		cursorAt: { bottom: 15, left: 45 },
		distance: 25,
		revert: "invalid",
		revertDuration: 200,
		helper: function(){
			var helper = $(this).clone();
			helper.addClass("dragging_helper").css({
				"height": "auto",
				"line-height": "0",
				"color": "#69bfee"
			}).find(".tree_button, span.updateTS").remove();
			return helper;
		},
		drag: function(event, ui){
			$(this).css("z-index", 20);
		},
		stop: function(event, ui){

			$(this).next().andSelf().css({
				'position': 'relative',
	            'top': '',
	            'left': '',
	            'z-index': ''
	        });

			$(this).next().css('position', '');

			$(".hover_droppable_folder").removeClass("hover_droppable_folder");
		}
	});
}

function getCookieNameForTree(el) {
	var treeId = el.parents(".tree_top_level").attr("data-treeid");
	return "tree_" + treeId + "_open_folders";
}

function initTreelineFolders(treeId) {
	var cookieName = "tree_" + treeId + "_open_folders";
	var curValue = getCookieValue(cookieName);
	if(curValue) {
		var arr = curValue.split(",");
		for(var i=0; i<arr.length; i++) {
			var treeNode = $("#treeline_" + treeId + "_" + arr[i] + ".is_closed_folder");
			var treeNodeChildren = treeNode.next(".treeline_children");
			treeNode.removeClass("is_closed_folder").addClass("is_open_folder");
			treeNodeChildren.css("display", "block");
		}
	}

	$("a.is_closed_folder").children("span.folder_dn-img").removeClass("folder_dn-img").addClass("folder_up-img");
	$("a.is_open_folder").children("span.folder_up-img").removeClass("folder_up-img").addClass("folder_dn-img");
}

function openTreelineFolder(treeNode) {
	var treelineId = treeNode.attr("data-groupId") + "_" + treeNode.attr("data-objectId");
	var treeNodeChildren = treeNode.next();

	if(treeNode.hasClass("is_closed_folder")){
		treeNodeChildren.slideDown();
		treeNode.removeClass("is_closed_folder").addClass("is_open_folder");
		treeNode.find("span.icon-arrow_right").removeClass("icon-arrow_right").addClass("icon-arrow_down");
	}
}

$(document).ready(function() {

	if(Global.viewname == "WORKSPACE_INDEX") {
		var treeId = "eln_projects";
		initTreelineFolders(treeId);
		initTreelineButtonsElnProjects(treeId);
		bindTreeUI();
	} else if(Global.viewname == "TEMPLATE_INDEX") {
		var treeId = "eln_templates";
		initTreelineFolders(treeId);
		initTreelineButtonsTextTemplates(treeId);
		bindTreeUI();
	}

	$("body").on("click", "a.is_folder", function(event){

		if($(event.target).hasClass("icon-conf_drop") || $(event.target).hasClass("default_button")) {
			return;
		}

		var treeNode = $(this);
		var treeNodeChildren = treeNode.next();

		if(treeNode.hasClass("is_closed_folder")) {
			treeNodeChildren.slideDown();
			treeNode.removeClass("is_closed_folder").addClass("is_open_folder");
			treeNode.find("span.folder_up-img").removeClass("folder_up-img").addClass("folder_dn-img");
		} else {
			treeNodeChildren.slideUp();
			treeNode.removeClass("is_open_folder").addClass("is_closed_folder");
			treeNode.find("span.folder_dn-img").removeClass("folder_dn-img").addClass("folder_up-img");
		}
	});

});

