/**
 * Copyright 2008 Alex Corscadden
 * 
 * This script may be used on other sites if desired.  You will, however, need 
 * to write your own backend code.  The formats of the JSON data are fairly 
 * simple.  I've tried, where possible to make this fail gracefully.  You'll
 * need to support standard links everywhere you use this if you'd like to 
 * preserve that functionality.
 * 
 * No warranty is expressed or implied.  If you use this, you're
 * on your own.
 **/

var loaded = false;
var req = false;
var md5;
var str;
var d = document;
var w = window;
var v = false;
var set;
var currHandle;

var root = "";

function killEvent(evt) 
{
	if (!evt) evt = w.event;
	evt.cancelBubble = true;
	if (evt.stopPropogation) evt.stopPropogation();
}

function md5sc()
{
	if (req.readyState == 4)
	{
		if (req.status == 200)
		{
			loaded = true;
			str = req.responseText;  
			finishLogin();
		}
	}
}

function finishLogin(r)
{
	var p = d.getElementById("pass");
	var s = d.getElementById("sPass");
	var f = d.getElementById("loginform");
	eval(r.responseText);
	s.value = hex_md5(p.value);
	p.value = "";
	f.submit();
}

function login() 
{
	if (!loaded) 
	{
		sendRequest(root + "/admin/md5.js", finishLogin);
	}
	else
	{
		finishLogin();
	}
}

function logout()
{
	var f = d.getElementById("loginform");
	f.submit();
}

function resizeCover(d1, d2)
{
	var height = Math.max(d.body.parentNode.scrollHeight, d.body.scrollHeight) + "px"; 
	d1.style.height = height; 
	d2.style.height = height;
}

function viewImage(handle, set, tag, evt)
{
	if (!v) {
		
		var height = d.body.scrollHeight + "px";
		var div = d.createElement("div");
		div.id = "cover";
		div.style.height = height;
		div.style.backgroundImage = "url(" + root + "/img/load.gif)";
		d.body.appendChild(div);
		
		var div2 = d.createElement("div");
		div2.id = "image_c";
		div2.style.height = height;
		d.body.appendChild(div2);
		
		div2.onclick = function () {
			d.body.removeChild(div);
			d.body.removeChild(div2); 
			v = false;
			div2.onclick = null;
		};

		resizeCover(div, div2);
		
		try {
			sendRequest(root + "/gallery/jsonimg/" + handle, displayImage);
			sendRequest(root + "/gallery/jsonset/" + set, processSet);
		}
		catch (ex) {
			return true;
		}
		killEvent(evt);
		v = true;
		currHandle = handle;
	}
	return false;
}

function displayImage(r)
{
   var image;
   eval(r.responseText);
	buildImage(image)
}

function processSet(r) 
{
	eval(r.responseText);
}

function nextImage(evt) 
{
	if (changeImage(1)) {
		killEvent(evt);
		return false;
	}
	return true;
}

function previousImage(evt)
{
	if (changeImage(-1)) {
		killEvent(evt);
		return false;
	}
	return true;
}

function changeImage(inc)
{
	var index, i, handle;
	for (i in set) {
		if (set[i] == currHandle) {
			index = parseInt(i);
			break;
		}
	}
	index = (index + inc) % set.length;
	while (index < 0) {
		index = set.length + index;
	}
	handle = set[index];
	currHandle = handle;
	try {
		sendRequest(root + "/gallery/jsonimg/" + handle, displayImage);
	} catch (ex) {
		return false;
	}
	return true;
}

function buildImage(image)
{
	var div = d.getElementById("cover");
	var div2 = d.getElementById("image_c");
	
	while (div2.hasChildNodes()) {
		div2.removeChild(div2.firstChild);
	}

	div.style.backgroundImage = "";
	
	var f = function () {
		resizeCover(div, div2); 
	};
	window.onscroll = f;

	var div3 = d.createElement("div");
	var div4 = d.createElement("div");

	div3.id = "image";
	div4.id = "image_data";

	div2.appendChild(div3);

	var h1 = d.createElement("h1");
	h1.innerHTML = image.name;
	div3.appendChild(h1);

	div3.appendChild(div4);

	var img = d.createElement("img");
	img.src = root + image.large;
	img.alt = image.description;
	img.title = image.description;
	div3.appendChild(img);
	
	buildImageData(image, div4);

   f();
}

function buildImageData(img, target) 
{
	if (!img.data) { 
		return; 
	}
	data = [];
	for (tag in img.data) {
		data.push(tag + " = " + img.data[tag] + "; ");
	}
	target.innerHTML = "<span class=\"highlight\">{</span>"+
							 data.join("") +
							 buildControls() +
							 "<span class=\"highlight\">}</span>";
}

function buildLink(toCall, onFail, content) 
{
	return "<a href=\"" + onFail + "\" onclick=\"return " + toCall + "\">"+ content + "</a>";  
}

function buildControls() 
{
	return	buildLink("previousImage(event)", "#", "previous();") + " " +
				buildLink("nextImage(event)", "#", "next();") + " ";
}

// From Quirksmode at http://www.quirksmode.org/js/xmlhttp.html
function sendRequest(u,c,d) 
{
	var req = createXmlRequest();
	var m = (d) ? "POST" : "GET";
	req.open(m,u,true);
	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (d)
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');

	req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
			alert('HTTP error ' + req.status);
			return;
		}
		c(req);
		c = null;
	}

	if (req.readyState == 4) return;
	req.send(d);
}

var xf = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

var wf = false;
function createXmlRequest() 
{
   if (wf) return wf();
	var x = false;
	for (var i=0;i<xf.length;i++) {
		try {
			x = xf[i]();
			wf = xf[i];
		}
		catch (e) {
			continue;
		}
		break;
	}
	if (!x) { throw new Error("XHR unsupported"); }
	return x;
}
