/*
 * darkroom.js 
 * Contains all javascript functions I will ever use.
 * Some data is passed through from Perl in per-page variables.
 * E.g.
 *	var jsCounter = $counter;
 *	var jsAllfiles = $#allfiles;
 *	var firstFile = "$allfiles[0]";
 *	var nextFile = $allfiles[$counter];
 *	var prevFile = $allfiles[$counter - 2];
 *	var web_cgi_prefix = "$_webCGIPrefix";
 *	var photo_path = "$fullpath";
 *	var photo_img = "$filename";
 *	var acl_options = {$ACL_OPTIONS};
 *	var rotation = "$rotation";
 *
 *  v0.45 - April 8, 2008.
 */

var imgPreload = new Image();

/** Functions for albumoptions.cgi (group option setting page) **/

function aoptUpdateStatus(id,status) {
	switch(status) {
		case "clear":
			$(id + "_status").innerHTML = "";
			Element.removeClassName($(id + "_status"),"msg_fail");
			Element.removeClassName($(id + "_status"),"msg_success");
			break;
		case "processing":
			$(id + "_status").innerHTML = "Processing..."; break;
		case "success":
			$(id + "_status").innerHTML = "Success!";
			Element.addClassName($(id + "_status"),"msg_success");
			break;
		case "fail":
			$(id + "_status").innerHTML = "Set failed!";
			Element.addClassName($(id + "_status"),"msg_fail");
			break;
	}
	return true;
}

function aoptSet(id,name,content) {
	var params = 'id=' + name + '&path=' + photo_path + '&img=_GROUP&content=' + content;
	var ajax_req = new Ajax.Request(
		web_cgi_prefix + "/xmlwrite.cgi",
		{
			method: 'post',
			postBody: params,
			onSuccess: function(t) {aoptUpdateStatus(id,"success");},
			onFailure: function(t) {aoptUpdateStatus(id,"fail"); }
		}
	);
}

/** for keyboard rating control **/
function keyboardRating(rating) {
	if (authLoggedIn == "true") {
		var id = "editableRating";
		var params = 'id=' + id + '&path=' + photo_path + '&img=' + photo_img + '&content=' + rating;
		var ajax_req = new Ajax.Request(
			web_cgi_prefix + "/xmlwrite.cgi",
			{
				method: 'post',
				postBody: params,
				onSuccess: function(t) {
					if (jsCounter > jsAllfiles) {
						window.location= web_cgi_prefix + "/image.cgi?path=" + photo_path + firstFile;
					} else {
						window.location= web_cgi_prefix + "/image.cgi?path=" + photo_path + nextFile;
					}
				},
				onFailure: function(t) { window.alert("Failed to apply rating. Try logging in and check permissions on meta.xml."); }
			}
		);
	}
}

function arrowNavImg(event){
    switch(event.keyCode) {
    	/* First five are numerals for quick rating */
	    case 49:
	    	keyboardRating(1); return false; break;
	    case 50:
	    	keyboardRating(2); return false; break;
	    case 51:
	    	keyboardRating(3); return false; break;
	    case 52:
	    	keyboardRating(4); return false; break;
	    case 53:
	    	keyboardRating(5); return false; break;
		case 85: /* U for Up */
			window.location = web_cgi_prefix + "/index.cgi?path=" + photo_path;
			return false; break;
		case 63234: case 37: /* left arrow */
			window.location = web_cgi_prefix + "/image.cgi?path=" + photo_path + prevFile;
			return false; break;
		case 63235: case 39: /* right arrow */
			if (jsCounter > jsAllfiles) {
				window.location= web_cgi_prefix + "/image.cgi?path=" + photo_path + firstFile;
			} else {
				window.location= web_cgi_prefix + "/image.cgi?path=" + photo_path + nextFile;
			}
			return false; break;
	}
	return true;
}

function arrowNavIndex(event){
  switch(event.keyCode) {
	case 63234: case 37: /* left arrow */
		window.location = web_cgi_prefix + "/" + prevFile;
		return false; break;
	case 63235: case 39: /* right arrow */
		window.location = web_cgi_prefix + "/" + nextFile;
		return false; break;
  }
  return true;
}

function arrowNav(event){
	if (String(document.location).match(/image.cgi/)) {
		arrowNavImg(event);
	} else if (String(document.location).match(/index.cgi/)) {
		arrowNavIndex(event);
	}
}

function submitLoginOnEnter(event){
  switch(event.keyCode) {
	case 13: /* enter */
		var params = 'user=' + $F('user') + '&password=' + $F('password');
		new Ajax.Updater('logincontainer', web_cgi_prefix + '/login.cgi',
			{method: 'post', postBody: params, evalScripts: true }
		);
		return false; break;
  }
  return true;
}

// Make the tags clickable.
function swapTags() {
	var id = "editableTags";
	tags = $(id).innerHTML.split(" ");
	$(id).innerHTML = "";
	
	if (tags.length > 0) {
		for (var i=0; i<tags.length; i++) {
			$(id).innerHTML += '<a href=\"' + web_cgi_prefix + '/tagbrowser.cgi?tag=' + tags[i] + '" class="taglink">' + tags[i] + "</a>&nbsp;";
		}
		$(id).innerHTML += "Edit";
	} else {
		$(id).innerHTML += " No tags ";
	}
};

function prepareEditInPlace() {

	// Rudimentary security; also secured on server side
	if (authLoggedIn == "true") {

		// Override the default saving_text and add the animated GIF and saving message
		EditInPlace.defaults["saving_text"] = "<img src='../static/arrows.gif' /> <span class='" + EditInPlace.defaults["saving_class"] + "'>Saving changes, please wait.</span>";

		// Set the save_url to an ASP page (which simply returns the saved content as plain text)
		EditInPlace.defaults["save_url"] = web_cgi_prefix + "/xmlwrite.cgi";

		// Make the editableText <span> editable :-)
		EditInPlace.makeEditable({id:"editableTitle"});
		EditInPlace.makeEditable({id:"editableTags", type:"textarea", empty_text:"No tags"});
		EditInPlace.makeEditable({id:"editableComment", type:"textarea", empty_text:"Click to add comment"});
		EditInPlace.makeEditable({id:"editableACL", type:"select", options: acl_options});
		EditInPlace.makeEditable({id:"editableRating", type:"select",
			options: {
				5: "* * * * *",
				4: "* * * *",
				3: "* * *",
				2: "* *",
				1: "*",
				"no": "No rating"} });
		swapTags();
	}
}

function preloadImage(xloc, yloc) {
	$("loadingBigImage").style.display = "block";
	imgPreload.onload=function(){
		Element.removeClassName("mainimage", rotation);
		$("draggableFullSize").src = fullsizeImageSrc;
		$("loadingBigImage").style.display = "none";
		$("medimage").style.display = "none";
		$("dragThumb").style.display = "block";
		$("prevrect").style.display = "block";
		$("draggableFullSize").style.display = "block";
		
		initializeFullSize(xloc, yloc);
	}
	imgPreload.src = fullsizeImageSrc;
}

function initializeFullSize(xloc, yloc) {
	var scaleFactor = origwidth / Element.getDimensions($("medimage")).width;
	$("medimage").style.display = "none";
	$("dragThumb").style.display = "block";
	$("prevrect").style.display = "block";
	$("draggableFullSize").style.display = "block";

	if ($("draggableFullSize").state.left == "") {
//			$("draggableFullSize").state = {'left' : -1*0.3*origwidth + "px", 'top': -1*0.3*origheight + "px" };
		$("draggableFullSize").state = {'left' : ((-1 * scaleFactor * xloc) + 320) + "px", 'top': ((-1 * scaleFactor * yloc) + 213) + "px" };
	}
	$("draggableFullSize").width = origwidth;
	$("draggableFullSize").height = origheight;
	$("draggableFullSize").style.left = $("draggableFullSize").state.left;
	$("draggableFullSize").style.top = $("draggableFullSize").state.top;
	$("dragThumb").style.opacity = 0.5;
	$("prevrect").style.opacity = 0.5;

	updatePrevrect();
}

function stopLoading(event) {
	imgPreload.onload="";
	$("draggableFullSize").style.display = "none";
	$("dragThumb").style.display = "none";
	$("prevrect").style.display = "none";
	$("loadingBigImage").style.display = "none";
	$("medimage").style.display = "block";
	
}

function canvasToggleSize(event) {
	// This function gets called when the image is a portrait-orientation
	// image. We need to hide the canvas tag and restore to landscape orientation.

	Element.removeClassName("mainimage", rotation);
	toggleSize(event);
}

function toggleSize(event) {

	var needsPreload = 0;
	// preload image if necessary
	if ($("draggableFullSize").width == 0) {
		needsPreload = 1;
		preloadImage(event.layerX,event.layerY);
	}

	if ($("draggableFullSize").width == Element.getDimensions($("mainimage")).width) {
		// Zoom in
		if (needsPreload == 0) {
			initializeFullSize(event.layerX,event.layerY);
		}
		updatePrevrect();
} else {
		// Zoom out
		$("medimage").style.display = "block";
		$("dragThumb").style.display = "none";
		$("draggableFullSize").style.display = "none";
		$("draggableFullSize").width = Element.getDimensions($("mainimage")).width;
		$("draggableFullSize").height = Element.getDimensions($("mainimage")).height;
//		$("draggableFullSize").state.left = $("draggableFullSize").style.left;
//		$("draggableFullSize").state.top = $("draggableFullSize").style.top;
		$("draggableFullSize").state.left = "";
		$("draggableFullSize").state.top = "";
		$("draggableFullSize").style.left = "0px";
		$("draggableFullSize").style.top = "0px";
		$("dragThumb").style.opacity = 0;
		$("prevrect").style.opacity = 0;
		Element.addClassName("mainimage", rotation);
		
		if ((rotation == 'LeftHandBottom') || (rotation == 'RightHandTop')) {
			$("medimage").style.display = "none";
		}
	}
};

// These next two functions don't work for portrait-style images,
// but that's okay, because there's a CSS bug that hides the prevrect anyway.

function updatePrevrect() {
	var left = $("draggableFullSize").style.left;
	var top = $("draggableFullSize").style.top;
	var offset = [$("dragThumb").offsetLeft, $("dragThumb").offsetTop];

	// Strip 'px' and flip
	left = (left.substring(0, left.length - 2)) * -1;
	top = (top.substring(0, top.length - 2)) * -1;
	
	$("prevrect").style.left = (offset[0] + ((left / $("draggableFullSize").width) * $("dragThumb").width)) + "px";
	$("prevrect").style.top = (offset[1] + ((top / $("draggableFullSize").height) * $("dragThumb").height)) + "px";
}

function updatePrevrectThumb() {
	var left = $("prevrect").style.left;
	var top = $("prevrect").style.top;
	var offset = [$("dragThumb").offsetLeft, $("dragThumb").offsetTop];

	// Strip 'px'
	left = (left.substring(0, left.length - 2));
	top = (top.substring(0, top.length - 2));
	
	offset[0] = offset[0] - left;
	offset[1] = offset[1] - top;
	
	$("draggableFullSize").style.left = (offset[0] * $("draggableFullSize").width / $("dragThumb").width) + "px";
	$("draggableFullSize").style.top = (offset[1] * $("draggableFullSize").height / $("dragThumb").height) + "px";
}

function prepareDraggable() {
	/* prepare draggable 100% crop */
	var dragger = new Draggable($("draggableFullSize"), { starteffect: null, endeffect: null, change: updatePrevrect });
	var draggerThumb = new Draggable($("prevrect"), { starteffect: null, endeffect: null, change: updatePrevrectThumb });
	
	if ($("canvas"))
		Event.observe($("canvas"), 'dblclick', canvasToggleSize);
	Event.observe($("medimage"), 'dblclick', toggleSize);
	Event.observe($("loadingBigImage"), 'dblclick', stopLoading);
	Event.observe($("draggableFullSize"), 'dblclick', toggleSize);
	$("prevrect").style.width = ((Element.getDimensions($("mainimage")).width / origwidth) * prevrectWidth) + "px";
	$("prevrect").style.height = ((Element.getDimensions($("mainimage")).height / origheight) * prevrectHeight) + "px";
	
	$("draggableFullSize").state = {'left' : "0px", 'top': "0px" };

//	toggleSize();
	updatePrevrect();
	
}

if (String(document.location).match(/image.cgi/)) {
	Event.observe(window, "load", prepareEditInPlace, false);
	Event.observe(window, "load", prepareDraggable, false);
}

Event.observe(document, "keydown", arrowNav, false);


