// closes the message alert box
function closeMessageBox()
{
	var messageElement = document.getElementById('messageBox');
	messageElement.style.display = 'none';
}

function deleteConfirm(itemTitle,id)
{
	if(confirm('Are you sure you want to delete this ' + itemTitle + '? This action is irrevocable'))
	{
		window.location = '?method=delete&id='+id;
	}
}


/* Writen by John Resig: http://ejohn.org/projects/flexible-javascript-events/  */
function addEvent( obj, type, fn ) 
{
	if ( obj.attachEvent ) 
	{
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else
		obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) 
{
	if ( obj.detachEvent ) 
	{
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
		obj.removeEventListener( type, fn, false );
}



/* Written by Dustin Diaz: http://www.dustindiaz.com/top-ten-javascript/ */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function getElementsByClassRegexp(searchClass,node,tag) 
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp(searchClass);
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function debug(aMsg) {
   setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
}

function newEditSpanForm(e)
{
	if (this.firstChild.nodeName!='INPUT') // if its an input then its already been converted and we dont want to do it twice in a row
	{
		ajaxClass = getAjaxField(this.className);
		context = getClassContext(ajaxClass); 
		
		innerText = this.innerHTML;
		newText = '<input type="hidden" name="previousText" value="'+innerText+'" />';
		if(!context.match(/description/))
		{
			newText += '<input type="text" value="'+innerText+'" />';
		} else {
			newText += '<textarea>'+innerText+'</textarea>';
		}
		newText += '<input type="button" value="Save"/><input type="button" value="Cancel"/>';
		
		this.innerHTML = newText;
		
		addEvent( this.childNodes[2], 'click', saveFormInput ); // sets the event handler to save and send the new value
		addEvent( this.childNodes[3], 'click', cancelEdit ); // sets the event handler to cancel the edit, grabs the hidden field and restores the previous value
	}
}

function saveFormInput(e)
{
	innerText = this.previousSibling.value;
	
	ajaxClass = getAjaxField(this.parentNode.className);
	context = getClassContext(ajaxClass); 
	
	xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
"<request>"+
	"<action>edit</action>"+
	"<context>"+context+"</context>"+
	"<reference>"+currentPic+"</reference>"+
	"<value>"+innerText+"</value>"+
"</request>";
	
	ajax.object = this;
	ajax.onCompletion = finalizeFormEdit;
	ajax.runAJAX(xml);
}

function finalizeFormEdit()
{
	resetSpanText(ajax.object.parentNode,ajax.object.previousSibling.value);	
}

function cancelEdit(e)
{
	previousValue = this.parentNode.childNodes[0].value;
	resetSpanText(this.parentNode,previousValue);
}

function resetSpanText(obj,text)
{
	if (text=='')
	{
		text = '-';
	}
	obj.innerHTML = text;
}

function deleteListItem()
{
	ajaxClass = getAjaxField(this.className);
	context = getClassContext(ajaxClass);
	
	uPos = context.search(/_/);
	itemName = context.substr(uPos+1);
	context = context.substr(0,uPos);
	
	xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
"<request>"+
	"<action>delete</action>"+
	"<context>"+context+"</context>"+
	"<reference>"+currentPic+"</reference>"+
	"<value>"+itemName+"</value>"+
"</request>";

	ajax.object = this;
	ajax.onCompletion = finalizeDeleteListItem;
	ajax.runAJAX(xml);
}

function finalizeDeleteListItem()
{
	debug(ajax.response);
	
	list = ajax.object.parentNode.parentNode;
	list.removeChild(ajax.object.parentNode);
	
	debug(list.childNodes.length);
	if (list.childNodes.length==0)
	{
		newTag = document.createElement('li');
		newTag.innerHTML = 'This image has no tags';
		list.appendChild(newTag);
		
		list.className = 'empty';
	}
}

function addListItem()
{
	this.style.display = 'none';
	
	input = document.createElement('input');
	input.setAttribute('type','text');
	
	acceptButton = document.createElement('input');
	acceptButton.setAttribute('type','submit');
	acceptButton.setAttribute('value','Add');
	acceptButton.setAttribute('class','ajax_new_tag');
	
	cancelButton = document.createElement('input');
	cancelButton.setAttribute('type','submit');
	cancelButton.setAttribute('value','Cancel');
	
	paragraph = this.parentNode;
	paragraph.appendChild(input);
	paragraph.appendChild(acceptButton);
	paragraph.appendChild(cancelButton);
	
	addEvent(acceptButton,'click',addNewListItem);
	addEvent(cancelButton,'click',restoreNewListItemLink);
}

function addNewListItem() 
{
	ajaxClass = getAjaxField(this.className);
	context = getClassContext(ajaxClass);
	
	xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
"<request>"+
	"<action>new</action>"+
	"<context>"+context+"</context>"+
	"<reference>"+currentPic+"</reference>"+
	"<value>"+this.parentNode.childNodes[1].value+"</value>"+
"</request>";
	debug(xml);
	
	ajax.object = this;
	ajax.onCompletion = finalizeAddListItem;
	ajax.runAJAX(xml);
}

function finalizeAddListItem()
{
	debug(ajax.response);
	xml = ajax.responseXML;
	tagID = xml.getElementsByTagName('tagID')[0].childNodes[0].data;
	tagName = xml.getElementsByTagName('tagName')[0].childNodes[0].data;
	
	debug(ajax.object.value);
	list = ajax.object.parentNode.previousSibling;
	debug(list.innerHTML);
	
	if (list.className=='empty')
	{
		list.removeChild(list.firstChild);
		list.className = '';
	}
	
	debug('prehtml');
	newTag = document.createElement('li');
	newTag.innerHTML = '<a href="/photos/tags/'+tagName+'/">'+tagName+'</a><a href="#" class="ajax_delete_tag_'+tagID+'">[x]</a>';
	debug('posthtml');
	
	addEvent(newTag.childNodes[1],'click',deleteListItem);
	addEvent(newTag.childNodes[1],'click',function () { return false; });
	
	list.appendChild(newTag);
	
	restoreNewListItemLink(ajax.object);
}

function restoreNewListItemLink(obj)
{
	paragraph = obj.parentNode;
	
	for (i=paragraph.childNodes.length-1;i>0;i--)
	{
		paragraph.removeChild(paragraph.childNodes[i]);
	}
	
	paragraph.childNodes[0].style.display = 'inline';
}

var thumbDiv;

function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function showImageThumb()
{
	//thumbDiv = this.parentNode.parentNode.parentNode;
	thumbDiv = this.parentNode.parentNode.parentNode.parentNode.parentNode;
	
	ajaxClass = getAjaxField(this.className);
	context = getClassContext(ajaxClass);
	
	picID = context.replace(/details_/,'');
	
	for(i=0;i<photos.length;i++)
	{
		if (photos[i]['id']==picID)
		{
			photoNode = photos[i];
		}
	}
	
	floating = document.createElement('div');
	descText = '<div id="image"><img src="/photos/medium/'+ photoNode['id'] +'" /></div>';
	descText += '<p><strong>'+(photoNode['title'] ? photoNode['title'] : 'Untitled')+'</strong><br />';
	descText += '<small>['+photoNode['id']+']</small><br />';
	descText += '<small>'+photoNode['date']+'</small><br />';
	descText += photoNode['event']+'<br />';
	descText += photoNode['location']+'</p>';
	
	/*
	if(photoNode['tags'] != undefined)
	{
		if(photoNode['tags'][0]['tag'].length > 0)
		{
			descText += '<br />'+photoNode['description']+'<br />';
			for(i=0;i<photoNode['tags'].length;i++)
			{
				descText += photoNode['tags'][i]['tag']+', ';
			}
			descText = descText.substr(0,descText.length-2);
			descText += '</p>';
		}
	}*/
	
	floating.innerHTML = descText;
	floating.setAttribute('id','floatingPreview');
	
	thumbDiv.appendChild(floating);
	
	addEvent(thumbDiv,'mousemove',moveImageThumb);
	
	moveImageThumb(thumbDiv);
}

function getFloatingLayer()
{
	if (document.getElementById)
	{
		return document.getElementById("floatingPreview");
	} else if (document.all) {
		return document.all.trailimagid;
	}
}

function getFloatingLayerStyle()
{
	if (document.getElementById)
	{
		return document.getElementById("floatingPreview").style;
	} else if (document.all) {
		return document.all.trailimagid.style;
	}
}

function debugInfo(text)
{
	floating = getFloatingLayer();
	
	if(floating.childNodes.length==1)
	{
		newTag = document.createElement('p');
		newTag.innerHTML = text;
		
		floating.appendChild(newTag);
	} else {
		floating.lastChild.innerHTML = text;
	}
}

function moveImageThumb(e)
{
	mousePos = getMousePos(e);
	
	floatyLayer = getFloatingLayer();
	
	if (self.innerWidth)
	{
		vpWidth = self.innerWidth;
		vpHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		vpWidth = document.documentElement.clientWidth;
		vpHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		vpWidth = document.body.clientWidth;
		vpHeight = document.body.clientHeight;
	}
	
	var docWidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15;
	var docHeight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight);
	
	//debugInfo('vpWidth < (mousePos[0] + floatyLayer.offsetWidth)+40<br />'+vpWidth+' < ('+mousePos[0]+' + '+floatyLayer.offsetWidth+')+'+40+'<br />'+vpWidth+' < '+(mousePos[0] + floatyLayer.offsetWidth + 40));
	
	if (vpWidth < (mousePos[0] + floatyLayer.offsetWidth)+20)
	{
		xcord = mousePos[0] - floatyLayer.offsetWidth - 10;
	} else {
		xcord = mousePos[0] + 10;
	}
	
	// because IE considers mousePos relative to the viewport and FF relative to the document on IE we need to explicitly add the scroll distance
	extraHeight = 0;
	if (is_ie)
	{
		extraHeight = truebody().scrollTop;
	}
	
	//debugInfo('vpHeight + truebody().scrollTop < (mousePos[1] + getFloatingLayer().offsetHeight + extraHeight)+40<br />'+vpHeight+' + '+truebody().scrollTop+' < ('+mousePos[1]+' + '+getFloatingLayer().offsetHeight+' + '+extraHeight+')+'+40+'<br />'+(vpHeight + truebody().scrollTop)+' < '+((mousePos[1] + getFloatingLayer().offsetHeight + extraHeight)+40));
	
	if (vpHeight + extraHeight < (mousePos[1] + getFloatingLayer().offsetHeight + extraHeight)+20)
	{
		ycord = mousePos[1] - getFloatingLayer().offsetHeight + extraHeight - 10;
	} else {
		ycord = mousePos[1] + extraHeight + 10;
	}

	
	getFloatingLayerStyle().top = ycord+"px";
	getFloatingLayerStyle().left = xcord+"px";
}

function hideImageThumb()
{
	// div  = this.parentNode.parentNode.parentNode;
	div = this.parentNode.parentNode.parentNode.parentNode.parentNode;
	
	// element = document.getElementById('floatingPreview');
	element = getFloatingLayer();
	
	if(element)
		div.removeChild(element);
	
	removeEvent(div,'mousemove',moveImageThumb);
}

function getMousePos(e)
{
	if (e.pageX && e.pageY)
	{
		return new Array(e.pageX,e.pageY);
	} else 
	{
		if (event.clientX && event.clientY) 
				return new Array(event.clientX,event.clientY);
	}
}

function setupEvents()
{
	ef = getElementsByClassRegexp('ajax_');
	for (i=0;i<ef.length;i++)
	{
		ajaxClass = getAjaxField(ef[i].className);
		action = getClassAction(ajaxClass); // grabs the action to take
		context = getClassContext(ajaxClass); // grabs the reference to know what to apply the action to, this has to be hardcoded
		
		//debug('Ajax Class: '+ajaxClass);
		//debug('Action: '+action); 
		//debug('Context: '+context);
		
		switch(action)
		{
			case 'editable':
				addEvent(ef[i],'click',newEditSpanForm);
				break;
			case 'delete':
				addEvent(ef[i],'click',deleteListItem);
				addEvent(ef[i],'click',function () { return false; });
				break;
			case 'new':
				addEvent(ef[i],'click',addListItem);
				break;
			case 'show':
				addEvent(ef[i],'mouseover',showImageThumb);
				addEvent(ef[i],'mouseout',hideImageThumb);
			}
	}
	
	//addEvent(document,'mousemove',showMousePos);
}

function getAjaxField(className)
{
	results = className.split(/\s/);
	for(k=0;k<results.length;k++)
	{
		if (/^ajax_/.test(results[k]))
		{
			ajaxClass = results[k];
		}
	}	
	return ajaxClass.replace(/ajax_/,'');
}

function getClassAction(className)
{
	chunks = className.split('_');
	return chunks[0];
}

function getClassContext(className)
{
	chunks = className.split('_');
	context = '';
	for (l=1;l<chunks.length;l++)
	{
		context += chunks[l];
		if (l<chunks.length-1)
		{
			context += '_';
		}
	}
	return context;
}

// changes the password box from a text box to a password box
function switchPasswordBox()
{
	pwdSpan = document.getElementById('pwd');
	pwdSpan.innerHTML = '<input type="password" id="password" name="password" />';
	pwdSpan.firstChild.focus();
	pwdSpan.firstChild.focus();
}