var startStack=function() { };  // A stack of functions to run onload/domready
registerOnLoad = function(func) 
{
	var origOnLoad = startStack;
	startStack = function () 
	{
		origOnLoad();
		func();
		return;
	}
}
var ranOnload=false; // Flag to determine if we've ran the starting stack already.
if (document.addEventListener) 
{
	// Mozilla actually has a DOM READY event.
	document.addEventListener("DOMContentLoaded", function()
	{
		if (!ranOnload) 
		{
			ranOnload=true; 
			startStack();
		}
	}, false);
}  
else if (document.all && !window.opera) 
{
	// This is the IE style which exploits a property of the (standards defined) defer attribute
	document.write("<scr" + "ipt id='DOMReady' defer=true " + "src=//:><\/scr" + "ipt>");  
	document.getElementById("DOMReady").onreadystatechange = function()
	{
		if (this.readyState=="complete"&&(!ranOnload))
		{
			ranOnload=true;
			startStack();
		}
	}
}
var origOnLoad=window.onload;
window.onload=function() {
	if (typeof(origOnLoad)=='function') 
	{
		origOnLoad();
	}
	if (!ranOnload) 
	{
		ranOnload=true;
		startStack();
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function curryFunc(func,args,space) 
{
    var n  = func.length - args.length; //arguments still to come
    var sa = Array.prototype.slice.apply(args); // saved accumulator array
    function accumulator(moreArgs,sa,n) 
    {
        var saPrev = sa.slice(0); // to reset
        var nPrev  = n; // to reset
        for(var i=0;i<moreArgs.length;i++,n--) 
        {
            sa[sa.length] = moreArgs[i];
        }
        if ((n-moreArgs.length)<=0) 
        {
            var res = func.apply(space,sa);
            // reset vars, so curried function can be applied to new params.
            sa = saPrev;
            n  = nPrev;
            return res;
        } 
        else 
        {
            return function ()
            {
                // arguments are params, so closure bussiness is avoided.
                return accumulator(arguments,sa.slice(0),n);
            }
        }
    }
    return accumulator([],sa,n);
}

function rot47(input)
{
	var ret_str = "";
	for(var n = 0; n < input.length; ++n)
	{
		var ch = input.charCodeAt(n);
		if (ch + 47 >= 126)
			ret_str += String.fromCharCode(" ".charCodeAt(0) + (ch + 47) % 126);
		else
			ret_str += String.fromCharCode(ch + 47);
	}
	return ret_str;
}

function cursor_wait() 
{
	document.body.style.cursor = 'wait';
}

function cursor_clear() 
{
	document.body.style.cursor = 'default';
}

function processMenubar()
{
	if (document.all&&document.getElementById) // test for IE 5+
	{
		navRoot = document.getElementById("menubar_root");
		for (i=0; i<navRoot.childNodes.length; i++) 
		{
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") 
			{
				node.onmouseover=function() 
				{
					this.className+=" over";
				}
				node.onmouseout=function() 
				{
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}
registerOnLoad(processMenubar);

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser does not support AJAX!");
				return false;
			}		
        }
	}
	return xmlHttp;
}

function ExecuteAjaxRequest(xmlHttp, reqType, pageUrl, pageArgs, finishFunction, failFunction)
{
	xmlHttp.onreadystatechange=function()
	{
		if (xmlHttp.readyState==4)
		{
			cursor_clear();
			if (xmlHttp.status==200)
			{
				finishFunction(xmlHttp);
				return;
			}
			else if (failFunction);
			{
				failFunction(xmlHttp);
				return;
			}
		}
		else
		{
			cursor_wait();
		}
	}
	
	if (reqType != "GET" && reqType != "POST")
	{
		alert("Bad reqType: " + reqType);
		return;
	}

//	alert("Opening ajax page: " + pageUrl);

	xmlHttp.open(reqType,pageUrl,true);

	if (reqType == "POST")
	{
		//Send the proper header information along with the request
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", pageArgs.length);
		xmlHttp.setRequestHeader("Connection", "close");
	}
	else
		pageArgs = null;
	
	xmlHttp.send(pageArgs);
}

function PrintXmlHttp(divID, xmlHttp)
{
    if (arguments.length < 1) 
    {
        return PrintXmlHttp;
    } 
    else if (arguments.length < 2) 
    {
        return function(c) { return PrintXmlHttp(divID,c); }
    } 
    else 
    {
		document.getElementById(divID).innerHTML = xmlHttp.responseText;
    }
}

function prependChild(parent, node)
{
	parent.insertBefore(node, parent.firstChild);
}

function printAjaxEditForm(photoID, EditValueType)
{
	var formElem = document.createElement('form');
	formElem.action = "javascript:submitNew" + EditValueType + "('" + photoID + "')";
	var textElem = document.createElement('input');
	textElem.type = "text";
	textElem.id = "edit_field_text_" + photoID;
	textElem.className = "editFieldBox";
	textElem.size = "40";
	var submitElem = document.createElement('input');
	submitElem.type = "submit";
	submitElem.className = "editFieldBox";
	submitElem.value = "Submit";
	var buttonElem = document.createElement('input');
	buttonElem.type = "button";
	buttonElem.onclick = function(){setTimeout("hideEditField('"+photoID+"');", 00);};
	buttonElem.className = "editFieldBox";
	buttonElem.value = "Cancel Edit";
	var feedbackElem = document.createElement('div');
	feedbackElem.style.display = "inline";
	feedbackElem.id = "edit_feedback_" + photoID;

	var editFieldDiv = document.getElementById('edit_field_' + photoID);
	formElem.appendChild(textElem);
	formElem.appendChild(submitElem);
	formElem.appendChild(buttonElem);
	editFieldDiv.appendChild(formElem);
	editFieldDiv.appendChild(feedbackElem);
}

function showEditField(photoID, isAlbum)
{
	var textFieldDiv = document.getElementById('text_field_' + photoID);
	var editFieldDiv = document.getElementById('edit_field_' + photoID);
	
	var textFieldStyle = textFieldDiv.style;
	var editFieldStyle = editFieldDiv.style;
	editFieldStyle.display = "inline";
	textFieldStyle.display = "none";
	
	printAjaxEditForm(photoID, isAlbum);
	var newTitleInput = document.getElementById('edit_field_text_' + photoID);
	newTitleInput.value = textFieldDiv.textContent;
	newTitleInput.focus();
	newTitleInput.select();
}

function hideEditField(photoID)
{
	var textFieldDiv = document.getElementById('text_field_' + photoID);
	var editFieldDiv = document.getElementById('edit_field_' + photoID);
	
	var textFieldStyle = textFieldDiv.style;
	var editFieldStyle = editFieldDiv.style;
	textFieldStyle.display = "inline";
	editFieldStyle.display = "none";
	
	setTimeout("document.getElementById('edit_field_" + photoID + "').innerHTML = '';", 100);
}

function showTextField(photoID, xmlHttp)
{
	if (arguments.length < this.showTextField.length) 
	{
		return curryFunc(this.showTextField,arguments,this);
	}  

	document.getElementById('text_field_' + photoID).innerHTML = xmlHttp.responseText;
	hideEditField(photoID);
}

function showNewTag(photoID, xmlHttp)
{
	if (arguments.length < this.showNewTag.length) 
	{
		return curryFunc(this.showNewTag,arguments,this);
	}  

	var newTagElem = document.createElement('span');
	newTagElem.className = "photo_tag";
	newTagElem.innerHTML = xmlHttp.responseText + " ";

	var photoTagsDiv = document.getElementById('photo_tags_' + photoID);
	photoTagsDiv.appendChild(newTagElem);
}

function showAllTags(photoID, xmlHttp)
{
	if (arguments.length < this.showAllTags.length) 
	{
		return curryFunc(this.showAllTags,arguments,this);
	}
	
	var photoTagsDiv = document.getElementById('photo_tags_' + photoID);
	photoTagsDiv.innerHTML = xmlHttp.responseText;
	
	hideEditField(photoID);
}

function loadNewAlbumName(xmlHttp)
{
	document.location.href = xmlHttp.responseText;
}

function showErrorFeedback(photoID, xmlHttp)
{
	if (arguments.length < this.showErrorFeedback.length) 
	{
		return curryFunc(this.showErrorFeedback,arguments,this);
	}  

	document.getElementById('edit_feedback_' + photoID).innerHTML = xmlHttp.responseText;
}

function findAllPhotosWithTag(tagID)
{
	if (tagID == 0)
		return [];
	var retArr = [];
	var imgs = document.getElementsByTagName('img');
	for (var n = 0; n < imgs.length; ++n)
	{
		if (imgs[n].className != "photo")
			continue;
		var tag_attrib = imgs[n].getAttribute('tag_' + tagID);
		if (tag_attrib != null)
			retArr.push(imgs[n]);
	}
	return retArr;
}

function findAllPhotosWithoutTag(tagID)
{
	var retArr = [];
	var imgs = document.getElementsByTagName('img');
	for (var n = 0; n < imgs.length; ++n)
	{
		if (imgs[n].className != "photo")
			continue;
		var tag_attrib = imgs[n].getAttribute('tag_' + tagID);
		if (tag_attrib == null)
			retArr.push(imgs[n]);
	}
	return retArr;
}

function highlightAllPhotosWithTag(tagID)
{
	var highlightPhotos = findAllPhotosWithoutTag(tagID);
	for (var n = 0; n < highlightPhotos.length; ++n)
	{
		var style = highlightPhotos[n].style;
		style.borderColor = "#000000";
		//style.backgroundColor = "#000000";
		//style.padding = "0px";
	}
	var highlightPhotos = findAllPhotosWithTag(tagID);
	for (var n = 0; n < highlightPhotos.length; ++n)
	{
		var style = highlightPhotos[n].style;
		style.borderColor = "#ffffff";
		//style.backgroundColor = "#ffffff";
		//style.padding = "1px";
	}
}

function getWindowSize() 
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) 
  {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } 
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
  {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } 
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
  {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {x: myWidth, y: myHeight};
}

function sizeElementHelper(eID, reserveWidth, reserveHeight)
{
	var elem = document.getElementById(eID);
	var windowSize = getWindowSize();
	if (reserveWidth >= 0)
		elem.style.width = reserveWidth + "px";
	else
		elem.style.width = (windowSize.x - ((-reserveWidth) + elem.offsetWidth - elem.clientWidth)) + "px";
	if (reserveHeight >= 0)
		elem.style.height = reserveHeight + "px";
	else
		elem.style.height = (windowSize.y - ((-reserveHeight) + elem.offsetHeight - elem.clientHeight)) + "px";
}

function sizeElement(eID, reserveWidth, reserveHeight)
{
	sizeElementHelper(eID, reserveWidth, reserveHeight);
	
	var origResize = window.onresize;
	window.onresize = function()
	{
		sizeElementHelper(eID, reserveWidth, reserveHeight);
		if (origResize)
			origResize();
	};
}

function positionElement(eID, leftPos, topPos, rightPos, bottomPos)
{
	var elem = document.getElementById(eID);
	elem.style.position = "absolute";
	if (leftPos >= 0)
		elem.style.left = leftPos + "px";
	if (topPos >= 0)
		elem.style.top = topPos + "px";
	if (rightPos >= 0)
		elem.style.right = rightPos + "px";
	if (bottomPos >= 0)
		elem.style.bottom = bottomPos + "px";
}

