/******* HIGHLIGHT INPUT FIELDS *******************************/
addEvent(window, "load", grub);

// Boot loader? :)
function grub()
{
	// Setup form highlights
	lastFocused = '';
	addHighlights();

	// Set opacity of loading indicator
	var loading = document.getElementById('loading');
	loading.style.opacity = '0.75';
	loading.style.filter = 'alpha(opacity=75)';

	// Fix PNG's for IE6
	if(document.body.style.filter!=undefined)
	{	
		var fixes = ['logo','fflogo','loading'];
		
		for (var i = 0; i < fixes.length; ++i)
		{
			var fixme = document.getElementById(fixes[i]);
			fixme.style.backgroundImage='none';
			fixme.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/images/'+fixes[i]+'.png", sizingMethod="scale")';
		}
	}
}

function addHighlights()
{
  	var inputs = document.getElementsByTagName("input");
	var textareas = document.getElementsByTagName("textarea");
	var selects = document.getElementsByTagName("select");

	var numInputs = inputs.length;
	var numTextAreas = textareas.length;
	var numSelects = selects.length;

	for ( i=0; i < numInputs; i++ )
	{
		var currentInput = inputs[i];
		currentInput.onfocus = onFocus;
		currentInput.onblur = onBlur;
		currentInput.onmouseover = onOver;
		currentInput.onmouseout = onOut;
	}

	for ( i=0; i < numTextAreas; i++ )
	{
		var currentTextArea = textareas[i];
		currentTextArea.onfocus = onFocus;
		currentTextArea.onblur = onBlur;
		currentTextArea.onmouseover = onOver;
		currentTextArea.onmouseout = onOut;
	}

	for ( i=0; i < numSelects; i++ )
	{
		var currentSelect = selects[i];
		currentSelect.onfocus = onFocus;
		currentSelect.onblur = onBlur;
		currentSelect.onmouseover = onOver;
		currentSelect.onmouseout = onOut;
	}
}
function onFocus()
{
	lastFocused = this;
	
	setFocus(this); // Use TurboTax animator.js
	//this.style.background = '#FFFFFF';
	//this.style.border = '1px solid #073A8D';
	//this.style.color = '#0000C0';
}
function onBlur()
{
	setBlur(this); // Use TurboTax animator.js
	//this.style.background = '#ECECEC';
	//this.style.border = 'solid 1px #B0B0B0';
	//this.style.color = '#000000';
}
function onOver()
{
	if (this != lastFocused)
	{
		this.style.background = '#F8F8F8';
		if (this.type == 'submit') this.style.cursor = 'pointer';
		if (this.type == 'button') this.style.cursor = 'pointer';
	}
}
function onOut()
{
	if (this != lastFocused)
	{
		this.style.background = '#ECECEC';
		this.style.border = 'solid 1px #B0B0B0';
		this.style.color = '#000000';
	}
}

////////////////////////////////////////////////////////
// Add event to window.onload
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}
////////////////////////////////////////////////////////
function getElementsByClassName(clsName,htmltag){
	var arr = new Array();
	var elems = document.getElementsByTagName(htmltag);
	for ( var cls, i = 0; ( elem = elems[i] ); i++ ){
		if ( elem.className == clsName ){
			arr[arr.length] = elem;
		}
	}
	return arr;
}
////////////////////////////////////////////////////////
/**************************************************************************************************************/
// Create xmlhttp object based on browsertype
function getHTTPObject() {
	if (window.XMLHttpRequest)
	{
		  // If IE7, Mozilla, Safari, etc: Use native object
		  var xmlHttp = new XMLHttpRequest();
	} else {
		if (window.ActiveXObject)
		{
		  // ...otherwise, use the ActiveX control for IE5.x and IE6
		  var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}
/**************************************************************************************************************/
function startOver()
{
	document.getElementById('results').innerHTML = '';

	// Determine how many images constitutes a page
	var windowsize = window.innerHeight || document.documentElement.clientHeight;
	limit = parseInt(windowsize / 45);

	readyForNext = true;
	poll = true;
	offset = 0;
	pollRate = 1000;
	endZone = 75; // amount of pixels to test for more

	//viewMore(); //
	smartScroll();
}
/**************************************************************************************************************/
function smartScroll()
{
	var scrollpos = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
	var windowsize = window.innerHeight || document.documentElement.clientHeight;
	var testend = document.body.clientHeight - (windowsize + scrollpos);
	//alert('document.body.clientHeight = ' + document.body.clientHeight + ' .. windowsize=' + windowsize + ' ... testend=' + testend);
	if ( (testend < endZone) && poll)
	{
		document.getElementById('loading').style.display = 'block';
		if (readyForNext)
		{
			viewMore();
			offset += limit;
			limit = parseInt(limit * 1.5); // Increase the limit each time we scroll to bottom
		}
	}
	if (poll)
		setTimeout('smartScroll()',pollRate);
}
/**************************************************************************************************************/
function viewMore()
{
	readyForNext = false;
	var album = escape(document.getElementById('album').value);
	var tags = escape(document.getElementById('tags').value);
	var description = escape(document.getElementById('description').value);
	var keyword = escape(document.getElementById('keyword').value);
	var rawsql = escape(document.getElementById('rawsql').value);

	var url = "/edits/viewMore.php?offset=" + offset + "&limit=" + limit + '&album=' + album + '&tags=' + tags + '&description=' + description + '&keyword=' + keyword + '&rawsql=' + rawsql;

	ajax = getHTTPObject();
	ajax.open("GET", url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.responseText.indexOf('invalid') == -1)
			{
				document.getElementById('results').innerHTML += ajax.responseText;
				document.getElementById('loading').style.display = 'none';
			
/*	minikit fade-ins (must set poll rate to 2000)
				var resultsDiv = document.getElementById('results');
				var newdiv = document.createElement('div');
				var divIdName = 'n' + Math.random();
				newdiv.setAttribute('id',divIdName);
				newdiv.style.height = '0';
				newdiv.style.visibility = 'hidden';
				newdiv.innerHTML = ajax.responseText;
				document.getElementById('loading').style.display = 'none';
				resultsDiv.appendChild(newdiv);

				var fx = new minikit.fx.Combo($(divIdName), {height: 200});
				fx.checkExec('toggle');
*/
				
				// When we see the flag signifying that we've reached the end, stop polling
				if (ajax.responseText.indexOf('|Flag No More Results|') > -1)
					poll = false;

				readyForNext = true;
			} // if index valid
		}	// End Readystate change
	};
	ajax.send(null);
}
/**************************************************************************************************************/
// Buttons image roll over
function imgSwap(obj, src)
{
	obj.src = '/images/' + src;
}
/**************************************************************************************************************/
function update(md5,obj,field,frontpage)
{
	if (frontpage) // Turn on the progress indicator
		document.getElementById('gif'+md5).style.display = 'block';
	else // Viewing a standalone image, echo 'Saving changes'
		document.getElementById('result'+md5).innerHTML = 'Saving changes... Please wait';

	var newVal = escape(obj.value);
	var url = "/includes/update.php?md5=" + md5 + "&new=" + newVal + '&field=' + field;

	ajax = getHTTPObject();
	ajax.open("GET", url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.responseText.indexOf('invalid') == -1)
			{
				// On the front page we have to turn off the progress indicator
				if (frontpage)
				{
					document.getElementById('gif'+md5).style.display = 'none';
					if (field == 'delete') document.getElementById('result'+md5).innerHTML = ajax.responseText;
				}
				else // Only echo results when we're not on the front page
				{
					// Give results in the display page table
					document.getElementById('result'+md5).innerHTML = ajax.responseText;

					// Stand alone photo deletion, any innerHTML alteration causes miniwidget to flipout
					if (field == 'delete')
					{
						document.getElementById('content').innerHTML = '<span style="color: red;">This image has been deleted!</span>';
					}
				}

				if (ajax.responseText.indexOf("I don't understand the date you entered.  Try again.") > -1)
				{
					alert('Sorry I do not understand the date: ' + obj.value + ', please enter it again in a different format');
					obj.value = '';
					obj.focus();
				}

			} // if index valid
		}	// End Readystate change
	};
	
	// Confirm deletion
	if (field == 'delete')
	{
		if(confirm('Are you sure you want to delete this photo?'))
		{
			ajax.send(null);
		}
		else
		{
			if(frontpage) // On the multi-edit view:
				document.getElementById('gif'+md5).style.display = 'none';
			else // On the standalone, 1 image view:
				document.getElementById('result'+md5).innerHTML = 'Waiting for changes...';
		}
	} // if we aren't deleting anything, send the update
	else
	{
		ajax.send(null);
	}
}/**************************************************************************************************************/
function deleteInline(md5)
{
	var url = "/includes/update.php?md5=" + md5 + "&new=none&field=delete";

	ajax = getHTTPObject();
	ajax.open("GET", url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.responseText.indexOf('invalid') == -1)
			{
				document.getElementById('n'+md5).innerHTML = '<span style="color: red;">This image has been deleted!</span>';
			} // if index valid
		}	// End Readystate change
	};
	
	// Confirm deletion
	if(confirm('Are you sure you want to delete this photo?'))
	{
		document.getElementById('n'+md5).innerHTML = 'Processing...';
		ajax.send(null);
	}
}
/**************************************************************************************************************/
function deleteAlbum(album,id)
{
	document.getElementById(id).innerHTML = '<img src="/images/thinking.gif" alt="Processing" />';
	var url = "/includes/deleteAlbum.php?album=" + album;

	ajax = getHTTPObject();
	ajax.open("GET", url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.responseText.indexOf('invalid') == -1)
			{
				// Fails if album name is blank
				try { document.getElementById(id).innerHTML = ajax.responseText; } catch(e) {};
			} // if index valid
		}	// End Readystate change
	};

	if(confirm('Do you really want to delete this album?'))
		ajax.send(null);
}
/**************************************************************************************************************/
function deleteThese()
{
	if(confirm('Are you sure you want to delete ALL photos? (Note: you may want to keep scrolling down to first see all the photos which are about to be deleted!!)'))
	{
		document.getElementById('loading').style.display = 'block';
		var album = document.getElementById('album').value;
		var tags = document.getElementById('tags').value;
		var description = document.getElementById('description').value;
		var keyword = escape(document.getElementById('keyword').value);
		
		var url = "/includes/delete.php?album=" + album + '&tags=' + tags + '&description=' + description + '&keyword=' + keyword;

		ajax = getHTTPObject();
		ajax.open("GET", url, true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
				if (ajax.responseText.indexOf('invalid') == -1)
				{
					document.getElementById('loading').style.display = 'none';
					var photos = getElementsByClassName('galleryItemLarge','div');

					for (var i = 0; i < photos.length; i++)
						document.getElementById(photos[i].id).innerHTML = 'Deleted.';
				} // if index valid
			}	// End Readystate change
		};
		ajax.send(null);
	}
}
/**************************************************************************************************************/
function tagThese()
{
	var newTag = prompt('Please enter the tag you would like to add to the photos which are now being displayed: (Note: you may want to keep scrolling down to first see all the photos will be tagged!!)',' ');
	if(newTag)
	{
		newTag = escape(newTag);
		document.getElementById('loading').style.display = 'block';
		var album = document.getElementById('album').value;
		var tags = document.getElementById('tags').value;
		var description = document.getElementById('description').value;
		var keyword = escape(document.getElementById('keyword').value);
		
		var url = "/includes/tag.php?album=" + album + '&tags=' + tags + '&description=' + description + '&newTag=' + newTag + '&keyword=' + keyword;

		ajax = getHTTPObject();
		ajax.open("GET", url, true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
				if (ajax.responseText.indexOf('invalid') == -1)
				{
					document.getElementById('loading').style.display = 'none';
					startOver();
				} // if index valid
			}	// End Readystate change
		};
		ajax.send(null);
	}
}
/**************************************************************************************************************/
function zipThese()
{
	var zip = confirm('Are you sure you want to download these as a single zip file? (Note: you may want to keep scrolling down to first see all the photos which will be sent)',' ');
	if(zip)
	{
		var album = escape(document.getElementById('album').value);
		var tags = escape(document.getElementById('tags').value);
		var description = escape(document.getElementById('description').value);
		var keyword = escape(document.getElementById('keyword').value);
		
		var url = "/images/zip.php?album=" + album + '&tags=' + tags + '&description=' + description + '&keyword=' + keyword;
		location.replace(url);
	}
}
/**************************************************************************************************************/
function loadPhotos()
{
	document.getElementById('loading').style.display = 'block';
	
	var album = escape(document.getElementById('album').value);
	var tags = escape(document.getElementById('tags').value);
	var description = escape(document.getElementById('description').value);
	var keyword = escape(document.getElementById('keyword').value);

	var url = 'loadPhotos.php?album=' + album + '&tags=' + tags + '&description=' + description + '&keyword=' + keyword;

	ajax = getHTTPObject();
	ajax.open("GET", url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.responseText.indexOf('invalid') == -1)
			{
				document.getElementById('results').innerHTML = ajax.responseText;
				document.getElementById('loading').style.display = 'none';
			} // if index valid
		}	// End Readystate change
	};
	ajax.send(null);
}