tibanna.actions = new Object();

tibanna.actions.openFile = function(openid) {
	// Call the read function in the Editor controller with the filepath from the clicked file.
	// store working tab
	if(tibanna.mine.active != "splash" && tibanna.mine.active != "preview") {
		tibanna.bespinworks.storeContents($(tibanna.util.esc("#"+tibanna.mine.active)));
	}
	var fileID = openid; // The id field stores filepaths
	var fileName = $(tibanna.util.esc("#"+openid+"")).text();
		var not_in_array = true;
		for (var i = 0; i < tibanna.mine.paths.length; i++){
			if (tibanna.mine.paths[i] == fileID){
				not_in_array = false;
				break;
			}
		}
		if (! (not_in_array)){ // A tab with this file is already open.
			// Simulate clicking on the tab.
			$(tibanna.util.esc("#"+fileID)+":not(.file)").click();
		}	
		
		else {
			$.post((jsurl+"editor/read"),	{'path': fileID, 'name':fileName}, tibanna.actions.openCallback);
			document.title = "[" +fileName + "] - Tibanna";	
	}
}

tibanna.actions.openCallback = function(file) {
	file = JSON.parse(file);
	$(".tab").removeClass("selected");
	tibanna.cloudcity.setContent(file.contents);
	tibanna.cloudcity.setLineNumber(1);
	tibanna.mine.paths.push(file.path);
	
	$("#tab-bar").append("<li class='tab' id=" + file.path + ">" + "<div class='tab-close'></div>" + file.name + "</li>");
	tibanna.mine.contents[file.path] = file.contents;
	tibanna.mine.positions[file.path] = {row:1,col:1}; 
	
	if (tibanna.mine.active == "splash"){
  		// Hide the splash buffer and display the Bespin editor component.
  		$("#splash-area").css("display","none");			
		$("#editor-area").css("display","block");
  	}
	if (tibanna.mine.active == "preview"){
  		// Hide the splash buffer and display the Bespin editor component.
  		$("#preview-area").css("display","none");
		$("#editor-area").css("display","block");
  	}
	
	// Deselect previous tab, select current one.
	tibanna.mine.active = file.path;
	var escaped_tabname = tibanna.util.esc("#"+tibanna.mine.active);
	$(escaped_tabname+":not(.file)").addClass("tab selected");

	filetype = file.path.split(".");
	filetype = filetype[filetype.length-1];
	tibanna.bespinworks.setLanguage(filetype);
	$("#canvas").focus();
}

/* 
 * Function saveFile(file);
 * Saves the file, defaults to active file. 
 * ToDo: Implement arbitrary file saving.
 */
tibanna.actions.saveFile = function(file) {
	if(typeof(file) == 'undefined') {
		file = tibanna.mine.active;
		contents = tibanna.cloudcity.getContent();
		
		if (tibanna.mine.active != "splash" && tibanna.mine.active != "preview") { 	
			$.post((jsurl+"editor/save"),{'path': file, 'data': contents}, tibanna.actions.saveResult);
		}
	}	
}

/* Function saveCallback(message);
 * Callback on file save. */
tibanna.actions.saveResult = function(message) {
	if (message == "saveError"){ 
		tibanna.ui.createBubble("Error", "Could not save file.");
	}
	else {
		tibanna.ui.createBubble("Normal", "Save successful"); 
		$('#preview-frame').each(function() { this.contentWindow.location.reload(true);});
	}
}

tibanna.actions.createFile = function() {
	var fldrpath = $(".file.selected,.folder.selected").attr("id");
	if ($(".file.selected,.folder.selected").hasClass("file")){
		fldrpath = $(".file.selected,.folder.selected").parent().prev("li").attr("id"); //get the path of the parent folder
	}
	if(typeof(fldrpath) == "undefined") { fldrpath = "/";} else { fldrpath += "/";}
		
	tibanna.ui.createDialog("Create New File", "<h3>File Name: <input type='textarea' id='createname'/></h3><p class='note'>Your file will be created at <strong id='createfolder'>"+ fldrpath +"</strong></p><div class='buttonset'><span class='button confirm'>Create File</span></div>", tibanna.actions.createConfirmation);
}

tibanna.actions.createConfirmation = function() {
	var folderpath = $("#createfolder").text();
	if (folderpath == "/"){
		folderpath = srcpath;
	}
	var filename = $("#createname").val();
	
	// Get the id of the element contained in the browser.
	var browserpath = folderpath+filename;
	// Validation for empty filenames.
	if (filename == ""){
		tibanna.ui.createBubble("Error", "You must specify a filename.");
	}
	// Check that this file doesn't already exist.
	else if ( $(tibanna.util.esc("#"+browserpath)).length>0 ){
		tibanna.ui.createBubble("Error", "File already exists.");
	}
	else{
		$.post((jsurl+"editor/create"),	{'folderpath': folderpath, 'name': filename}, tibanna.actions.createPostCallback);
		$(".popup").fadeOut("fast"); $(".popup").remove();
	}	
}

tibanna.actions.createPostCallback = function(file){	
	if (file == "createFailure"){ tibanna.ui.createBubble("Error", "Could not create file"); }
	else {	
		file = JSON.parse(file);
			
		if(file.path == srcpath) {
			$("#browser-list").append("<li class='file' id='"+srcpath+file.name+"'>"+file.name+"</li>");
		}
		else {
			$(".file.selected,.folder.selected").next("ul").append("<li class='file' id='"+file.path+file.name+"'>"+file.name+"</li>");
		}
		tibanna.ui.createBubble("Normal", "File "+file.name+" created successfully.");					
	}
}

/* Function deleteFile(event);
 * Used to delete a file. */
tibanna.actions.deleteFile = function(event) {
	event.stopPropagation();
	var filepath = $(".file.selected,.folder.selected").attr("id");
	
	if (typeof(filepath) == "undefined"){ tibanna.ui.createBubble("Error", "No file selected"); return false;} else
	if ($(".folder.selected").length == 1){ tibanna.ui.createBubble("Error", "Folders cannot be deleted"); return false;}
	else { $.post((jsurl+"editor/delete"),	{'path': filepath}, tibanna.actions.deleteCallback); }
	// TODO Should trigger dialog before post
}

/* Function deleteCallback(file);
 * Callback on file deletion. */
tibanna.actions.deleteCallback = function(file) {
	if (file == "deleteError"){
		tibanna.ui.createBubble("Error", "File could not be deleted.");
	}
	else {
		tibanna.ui.createBubble("Normal", "File deleted");
		$(tibanna.util.esc("#"+file)).remove();
		tibanna.ui.closeTab(file);		
	}
}

tibanna.actions.processCommandline = function(evt) {
	$.get(jsurl+"commandline/"+$("#commandline").val(), function(data){
	  	eval(data);
	});
	$("#commandline").val("");

	return false;
}