/* AJAH QUERY / RESPONSE
---------------------------------------------------------------*/
function closeAll() {
	$("#content ul ul").remove();
	$("#content a.open").set("class", "dir");
}
function getPageSize() {
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;

	arrayPageSize = new Array(w,h)
	return arrayPageSize;
}
function getHeight(adjustment) {
	adjustment += 20;
	var page_size = getPageSize();
	var nav_height = (page_size[1] - adjustment) + "px";
	return nav_height;
}
function setDimensions() {
	var page_size = getPageSize();
	var nav_height = (page_size[1] - 80) + "px";

	$("#left_col #job_nav").css({height:getHeight(147), visibility:"visible"});
	$("#content").css({height:getHeight(80), visibility:"visible"});
}

/* TOOL TIP
-----------------------------------------------------------------------------------*/
var tip_extension = /\.jpg|\.jpeg|\.png|\.gif|\.mov|\.mp4|\.mp3|\.mpg|\.mpeg|\.aif|\.wav|\.txt/g;
function tipShow(o)
{
	$("#tool_tip").empty();
	var link = o.href.toLowerCase();
	var loadable = link.match(tip_extension);
	var action = (loadable == null) ? "" : "Click to preview";

	switch(o.className)
	{
		case "head":
		$("#tool_tip").empty();
		break;

		case "open":
		var contents = "<p>Click to close</p>";
		$("#tool_tip").append(contents);
		break;

		case "dir_link":
		var contents = "<p><em>Directory:</em>" + o.innerHTML + "</p>";
		contents += "<p><em>Action:</em>Click to view contents</p>";
		contents += "<p><em>Updated:</em>" + o.name + "</p>";
		$("#tool_tip").append(contents);
		break;

		case "thickbox":
		var len = 25;
		var file = o.innerHTML
		file = (file.length >= len) ? file.substring(0, len - 5) + "..." : file;
		var contents = "<p><em>File:</em>" + file + "</p>";
		contents += "<p><em>Action:</em>" + action + "</p>";
		contents += "<p><em>Updated:</em>" + o.name + "</p>";
		$("#tool_tip").append(contents);
		break;

		default:
		var contents = "<p><em>File:</em>" + o.innerHTML + "</p>";
		contents += "<p><em>Action:</em>Click to download</p>";
		contents += "<p><em>Updated:</em>" + o.name + "</p>";
		$("#tool_tip").append(contents);
		break;
	}
	$("#tool_tip").css("height", "auto");
	delete file;
	delete contents;
}
function tipHide() {
	$("#tool_tip").empty();
}

/* FOLDER CONTENTS
-----------------------------------------------------------------------------------*/
var contentURL = "php/getFiles.php";
var jobDetailsURL = "php/getJobDetails.php"
var active_contents;
var admin_info;
var job_array = new Array();

var load_msg = "<p id='load_txt'>Retrieving files...</p>";

function getAdminContent()
{
	// Get details of all jobs in db
	$.get(jobDetailsURL, function(json) {
		var jobs_raw = eval('(' + json + ')');
		var all_jobs = jobs_raw.jobs;
		var links = "";

		// populate job_array with objects containing details of each job:
		// title, login details, date created, date updated
		for (var i = 0; i < all_jobs.length; i++)
		{
			var job_obj = all_jobs[i];
			var job_ref = job_obj.job_ref;
			job_array[job_ref] = job_obj;
			links += "<div class=\"job\"><a href=\"javascript:;\" id=\""+job_ref+"\">"+job_ref+"</a></div>";
		}

		// create html
		$("#left_col").append("<h1 class=\"heading\">CURRENT JOBS</h1>");
		$("#left_col").append("<div id=\"job_nav\"></div>");
		$("#left_col #job_nav").append(links);
		$("#left_col").append("<div id=\"job_add\"><a class=\"thickbox\" href=\"snippets/job_add.html?width=300&amp;height=190\">Click to add new job</a></div>");

		setDimensions();

		// bind events
		$(".job a").click(function(){ checkJob(this.id); });
		TB_init();

		// clean up
		delete json;
		delete jobs_raw;
		delete all_jobs;
	});
}

function refreshJobsArray(all_jobs)
{
	job_array = [];
	for (var i = 0; i < all_jobs.length; i++)
	{
		var o = all_jobs[i];
		var ref = o.job_ref;
		job_array[ref] = o;
	}
	return job_array;
}

function reloadAdminContent(job_ref)
{
	$("a.thickbox").unclick();
	$.get(jobDetailsURL, function(json){
		var jobs_raw = eval('(' + json + ')');

		// recreate the array of job details
		job_array = refreshJobsArray(jobs_raw.jobs);

		// add the last-generated link and automatically open it
		var link = "<div class=\"job\"><a href=\"javascript:;\" id=\""+job_ref+"\">"+job_ref+"</a></div>";
		$("#job_nav").prepend(link);
		$("#job_nav " + job_ref).click(function(){ checkJob(this.id); });
		checkJob(job_ref);
	});
}

function checkJob(f_id)
{
	// reset elements
	$("a.thickbox").unclick();
	$("#content").empty();
	$("#job_info").empty();

	if (userID == "admin")
	{
		// reset
		$("#job_info").empty();
		$("#job_nav .open_job").set("class","job");
		$("#job_nav .open_a").set("class","closed_a");

		// get active job details
		var activeJob_obj = job_array[f_id]
		var job_title = activeJob_obj.job_title;
		var admin_info = "<p><em>Username:</em><div class='edit_inline' id='username'>" + activeJob_obj.username + "</div></p>\n";
			admin_info += "<p><em>Director pass:</em><div class='edit_inline' id='director_pass'>" + activeJob_obj.director_pass + "</div></p>\n";
		admin_info += "<p><em>Client pass:</em><div class='edit_inline' id='client_pass'>" + activeJob_obj.client_pass + "</div></p>\n";
		admin_info += "<p><em>Created:</em>" + activeJob_obj.job_created + "</p>\n";
		admin_info += "<p><em>Updated:</em>" + activeJob_obj.job_updated + "</p>\n";
		$("#job_info").append(admin_info);
		$("#content").prepend("<h1 class='edit_inline' id='job_title'>" + job_title + "</h1>");

		var el = (window.ActiveXObject) ? $("#job_nav #" + f_id) : $(document.getElementById(f_id).parentNode);
		var el_class = (window.ActiveXObject) ? "open_a" : "open_job";
		el.set("class", el_class);

		$(".edit_inline").editable("php/updateJobDetails.php", {
			saving: "<img src='images/arrow_prog_tiny.gif'>",
			extraParams: { job_id:activeJob_obj.job_id, username:activeJob_obj.username },
			callback: function(){
				$.get(jobDetailsURL, function(json){
					var jobs_raw = eval('(' + json + ')');
					var all_jobs = jobs_raw.jobs;

					// recreate the array of job details
					refreshJobsArray(all_jobs);
				});
			}
		});
	}
	else
	{
		$("#content").append("<h1 id='job_title'>'" + title + "'</h1>");
	}
	
	$.post(contentURL, { job_dir:f_id, level:"job", view:"thumb" }, function(response){
		$("#load_txt").remove();
		$("#content").css({height:getHeight(77)}).append(response);
		TB_init();

		delete response;
	})
}

function checkFolder(a, f_name, f_id)
{
	// reset functions
	$("a.thickbox").unclick();

	// check whether subnode is already open: close if so
	var folder = $(a).siblings(0);
	var folder_open = folder.is("div");
	if (folder_open) {
		var sub_folder =folder.cur[1];
		$(sub_folder).hide("normal", function(){ $(sub_folder).remove(); });
		$(a).set("class","dir_link");
	} else {
		var active_folder = "#" + f_id;
		$.post(contentURL, { job_dir:f_name, level:"folder", view:"thumb" }, function(response) {
			$(a).set("class","open");
			$(active_folder).append(response);
			TB_init();
			delete response;
		})
	}
}

/* CREATE JOB
-----------------------------------------------------------------------------------*/
function createJob()
{
	var job_form = document.getElementById("job_form");
	var u_name  = job_form.username.value;
	var j_title	= job_form.job_title.value;
	var j_ref	= job_form.job_ref.value;
	var d_pass  = job_form.director_pass.value;
	var c_pass  = job_form.client_pass.value;

	// only proceed if all elements have been filled
	if (u_name != "" && j_title != "" && j_ref != "" && d_pass != "" && c_pass != "")
	{
		// check that the director-level and client-level passwords not the same
		// to allow for differentiated access
		if (d_pass == c_pass)
		{
			job_form.client_pass.value = "passwords must differ";
			job_form.client_pass.onfocus = function(){ this.value = ""; };
		}
		else
		{
			job_form.username.value = "creating job folder";
			job_form.job_title.value = "";
			job_form.job_ref.value = "";
			job_form.director_pass.value = "";
			job_form.client_pass.value = "";

			var job_vars = { username:u_name, director_pass:d_pass, client_pass:c_pass, job_title:j_title, job_ref:j_ref };

			$.post("php/createJob.php", job_vars, function(server_reply) {
				var response = eval('(' + server_reply + ')');
				if (response.status == "failure")
				{
					job_form.username.value = u_name
					job_form.job_title.value = j_title;
					job_form.job_ref.value = j_ref;
					job_form.director_pass.value = "";
					job_form.client_pass.value = "";

					var el = response.el;
					job_form[el].value = response.msg;

					job_form.username.onfocus = function(){ this.value = ""; };
					job_form.job_title.onfocus = function(){ this.value = ""; };
					job_form.job_ref.onfocus = function(){ this.value = ""; };
					job_form.director_pass.onfocus = function(){ this.value = ""; };
					job_form.client_pass.onfocus = function(){ this.value = ""; };
				}
				else
				{
					$("#TB_window").fadeOut("normal", function(){
						$("#TB_window").empty();
						$('#TB_window,#TB_overlay').remove();
						reloadAdminContent(response.job_ref);
					})
				}
				delete server_reply;
				delete response;
			})
		}
	}
	else
	{
		job_form.username.value = "Please enter all details";
		job_form.username.onfocus = function(){ this.value = ""; };
	}
	delete response;
}
