/******************************************************************************************************************/
/** GENERAL FUNCTIONS *********************************************************************************************/
/******************************************************************************************************************/

String.prototype.replaceAll = function(toRemove, replaceWith) {
	var newString = this.toString()
	while(newString.indexOf(toRemove) != -1)
	{
		newString = newString.replace(toRemove, replaceWith);
	}
	return newString;
}

function setCookie(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 getCookie(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 deleteCookie(name)
{
	setCookie(name,"",-1);
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function addLoadFunction(newFunction)
{
	if(typeof window.onload == "function")
	{
    	var previousOnload = window.onload;
		window.onload = function()
		{
			previousOnload();
			newFunction();
		}
	}
	else
		window.onload = newFunction;
}

/******************************************************************************************************************/
/** ANTONINSUITE CODE *********************************************************************************************/
/******************************************************************************************************************/

function highlightRow(obj, state)
{
	if(state == 'over')
	{
		obj.className = 'highlighted';
		// For the highlight to work, we want to remove the background color from child cells.
		// Before we do this, though, we save the background color as a custom attribute to snag on mouseoff.
		for(i=0;i<obj.childNodes.length;i++)
		{
			if(obj.childNodes[i].nodeType == 1)
			{
				// for IE, errors otherwise
				if(obj.childNodes[i].style)
				{
					if(typeof obj.childNodes[i].style.backgroundColor == 'string')
					{
						obj.childNodes[i].setAttribute('previousBackgroundColor', obj.childNodes[i].style.backgroundColor);
						obj.childNodes[i].style.backgroundColor = '';
					}
				}
			}
		}
	}
	else
	{
		obj.className = '';
		// Re-set the custom background color of any child nodes that have it.
		for(i=0;i<obj.childNodes.length;i++)
		{
			if(obj.childNodes[i].nodeType == 1)
			{
				if(typeof obj.childNodes[i].getAttribute('previousBackgroundColor') == 'string')
				{
					obj.childNodes[i].style.backgroundColor = obj.childNodes[i].getAttribute('previousBackgroundColor');
				}
			}
		}
	}
}

function checkAll(checkboxes)
{
	if(checkboxes)
	{
		for(i=0;i<checkboxes.length;i++)
			checkboxes[i].checked = true;
	}
}
function checkNone(checkboxes)
{
	if(checkboxes)
	{
		for(i=0;i<checkboxes.length;i++)
			checkboxes[i].checked = false;
	}
}
function checkSome(checkboxes, kind)
{
	if(checkboxes)
	{
		checkNone(checkboxes);
		for(i=0;i<checkboxes.length;i++)
		{
			if(checkboxes[i].getAttribute('kind').indexOf(kind) != -1)
				checkboxes[i].checked = true;
		}
	}
}

var curTextInput = false;
function setTextInputClasses()
{
	var inputObjs = document.getElementsByTagName('input');
	for(i=0;i<inputObjs.length;i++)
	{
		if((inputObjs[i].type == 'text' || inputObjs[i].type == 'password') && inputObjs[i].getAttribute('nohighlight') != 'true')
		{
			if(typeof inputObjs[i].getAttribute('oldUsername') == 'string')
				var isUsernameField = true;
			else
				var isUsernameField = false

			inputObjs[i].className = 'text';

			if(isUsernameField)
				inputObjs[i].onkeyup = function() { checkUsernameTimeout(this); };

			inputObjs[i].onfocus = function() {
				if(curTextInput)
					curTextInput.className = 'text';
				this.className = 'textActive'
				curTextInput = this;
				if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
				{
					if(this.parentNode.parentNode.className == '')
						this.parentNode.parentNode.className = 'highlighted';
				}
			}

			inputObjs[i].onblur = function() {
				if(typeof this.getAttribute('oldUsername') == 'string')
					checkUsernameTimeout(this);

				this.className = 'text';
				if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
				{
					if(this.parentNode.parentNode.className == 'highlighted')
						this.parentNode.parentNode.className = '';
				}
			}
		}
	}
	var inputObjs = document.getElementsByTagName('textarea');
	for(i=0;i<inputObjs.length;i++)
	{
		inputObjs[i].className = 'text';
		inputObjs[i].onfocus = function() {
			if(curTextInput)
				curTextInput.className = 'text';
			this.className = 'textActive'
			curTextInput = this;
			if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
			{
				if(this.parentNode.parentNode.className == '')
					this.parentNode.parentNode.className = 'highlighted';
			}
		}
		inputObjs[i].onblur = function() {
			this.className = 'text';
			if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
			{
				if(this.parentNode.parentNode.className == 'highlighted')
					this.parentNode.parentNode.className = '';
			}
		}
	}
	var inputObjs = document.getElementsByTagName('select');
	for(i=0;i<inputObjs.length;i++)
	{
		inputObjs[i].className = 'text';
		inputObjs[i].onfocus = function() {
			if(curTextInput)
				curTextInput.className = 'text';
			this.className = 'textActive'
			curTextInput = this;
			if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
			{
				if(this.parentNode.parentNode.className == '')
					this.parentNode.parentNode.className = 'highlighted';
			}
		}
		inputObjs[i].onblur = function() {
			this.className = 'text';
			if(this.parentNode.parentNode.tagName.toLowerCase() == 'tr')
			{
				if(this.parentNode.parentNode.className == 'highlighted')
					this.parentNode.parentNode.className = '';
			}
		}
	}
}

function formatHTTPval(obj)
{
	obj.value = obj.value.replaceAll('\\', '/');
	if(obj.value.length > 7)
	{
		if(obj.value.substr(0, 7).toLowerCase() != 'http://' && obj.value.substr(0, 8).toLowerCase() != 'https://')
			obj.value = 'http://' + obj.value;
		if(obj.value.substr(obj.value.length - 1, 1) != '/')
			obj.value = obj.value + '/';
	}
	obj.value = obj.value.replace('http://', '[http]');
	obj.value = obj.value.replace('https://', '[https]');
	obj.value = obj.value.replaceAll('//', '/');
	obj.value = obj.value.replace('[http]', 'http://');
	obj.value = obj.value.replace('[https]', 'https://');
}
function formatFSOval(obj)
{
	obj.value = obj.value.replaceAll('/', '\\');
	obj.value = obj.value.replaceAll('\\\\', '\\');
	if(obj.value.length > 3)
	{
		if(obj.value.substr(1, 2).toLowerCase() != ':\\')
			obj.value = 'c:\\' + obj.value;
		if(obj.value.substr(obj.value.length - 1, 1) == '\\')
			obj.value = obj.value.substr(0, obj.value.length - 1);
	}
}

var ajaxLocked = false;
var usernameObj = null;
function checkUsernameTimeout(obj)
{
	usernameObj = obj;
	setTimeout("checkUsername()", 500);
}
function checkUsername()
{
	var usernameValidText = document.getElementById('usernameValidText');
	if(usernameObj)
	{
		if(usernameObj.value.length > 0)
		{
			if(!ajaxLocked)
			{
				ajaxLocked = true;
				var xmlhttp =  new XMLHttpRequest();
				if(xmlhttp)
				{
					qsData = 'new_username=' + usernameObj.value + '&old_username=' + usernameObj.getAttribute('oldUsername');
					xmlhttp.open("GET", "js-checkusername.asp?" + qsData, true);
					xmlhttp.onreadystatechange = function() {
						if (xmlhttp.readyState == 4) {
							if(xmlhttp.status == 200) {
								var response = xmlhttp.responseText;
								if(usernameValidText)
								{
									if(response == 'available')
									{
										usernameValidText.className = 'success';
										usernameValidText.innerHTML = 'Username available!';
									}
									else if(response == 'taken')
									{
										usernameValidText.className = 'error';
										usernameValidText.innerHTML = 'Username taken!';
									}
									else if(response == 'bad-char')
									{
										usernameValidText.className = 'error';
										usernameValidText.innerHTML = 'Invalid character in username';
									}
									else if(response == 'same')
									{
										usernameValidText.className = '';
										usernameValidText.innerHTML = '';
									}
								}
							}
							ajaxLocked = false;
						}
					}
					xmlhttp.send(null);
				}
			}
		}
		else
		{
			usernameValidText.className = '';
			usernameValidText.innerHTML = '';
		}
	}
}

/******************************************************************************************************************/
/** PHOTO GALLERY *************************************************************************************************/
/******************************************************************************************************************/

function goPhoto(direction)
{
	var photoObj = document.getElementById('photo');
	if(photoObj)
	{
		var curId = photoObj.getAttribute('photoId') - 1 + 1;
		if(curId + direction > photoAlbum.length - 1)
			var newId = 0;
		else if(curId + direction < 0)
			var newId = photoAlbum.length - 1;
		else
			var newId = curId + direction;
		photoObj.src = albumName + '/' + photoAlbum[newId][0];
		photoObj.onload = function(evt) {
			hideGalleryLoader();
			this.height = photoAlbum[newId][2];
			this.width = photoAlbum[newId][3];
		}
		showGalleryLoader();
		photoObj.setAttribute('photoId', newId);
		document.getElementById('photoTitle').innerHTML = '<b>' + photoAlbum[newId][1] + '</b> (' + (newId + 1) + ' of ' + photoAlbum.length + ')';
		var thumbContainer = document.getElementById('thumbContainer');
		if(thumbContainer)
		{
			// scroll to the thumb, eventually
			//thumbContainer.style.left = (thumbContainer.style.left.replace('px', '') - 1 + 1 + -50) + 'px';
		}
	}
	else
	{
		alert('Strange...  photo object not found!');
	}
}

var allowScroll = false;
var thumbScroll;
function scrollThumbs(distance)
{
	if(allowScroll)
	{
		var thumbContainer = document.getElementById('thumbContainer');
		var newPos = thumbContainer.style.left.replace('px', '') - 1 + 1 - distance;
		var thumbTable = document.getElementById('thumbTable');
		var firstThumb = document.getElementById('firstThumb');
		if(newPos < 0)
		{
			if(thumbTable.offsetWidth > 700)
			{
				if( newPos > (0 - (thumbTable.offsetWidth - 700)) )
					newPos = newPos;
				else
					newPos = 0 - (thumbTable.offsetWidth - 700);
				try {
					thumbContainer.style.left = (newPos) + 'px';
				}
				catch (e) {
					//alert(newPos);
				}
			}
		}
		else
			thumbContainer.style.left = '0px';
			
	}
	else
	{
		clearInterval(thumbScroll);
	}	
}
function scrollThumbsLeft()
{
	allowScroll = true;
	var thumbContainer = document.getElementById('thumbContainer');
	if(thumbContainer)
	{
		thumbScroll = setInterval("scrollThumbs(-5)", 1)
	}
}
function scrollThumbsRight()
{
	allowScroll = true;
	var thumbContainer = document.getElementById('thumbContainer');
	if(thumbContainer)
	{
		thumbScroll = setInterval("scrollThumbs(+5)", 1);
	}
}
function stopScroll()
{
	allowScroll = false;
}

function showGalleryLoader()
{
	var imageGalleryLoader = document.getElementById('galleryLoader');
	var photoObj = document.getElementById('photo');
	if(imageGalleryLoader && photoObj)
	{
		imageGalleryLoader.style.display = 'block';
		imageGalleryLoader.style.top = findPosY(photoObj) + 'px';
		imageGalleryLoader.style.left = findPosX(photoObj) + 'px';
	}
}

function hideGalleryLoader()
{
	var imageGalleryLoader = document.getElementById('galleryLoader');
	if(imageGalleryLoader)
	{
		imageGalleryLoader.style.display = 'none';
	}
}

/******************************************************************************************************************/
/** UPLOAD PROGRESS ***********************************************************************************************/
/******************************************************************************************************************/

var ajaxLocked = false;
var uploadComplete = false;

function hideUpload()
{
	document.getElementById('upload').style.display = 'none';
}
function hideProgress()
{
	//document.getElementById('progress').style.display = 'none';
	//document.getElementById('upload').style.display = 'block';
	uploadComplete = false;
	location = './';
}

function loadProgress(progressData)
{
	var progressDataSplit = progressData.split('?');
	// taken from a query string function, changed to use ? instead of &
	function GetProgressValue(key)
	{
		for(i=0;i<progressDataSplit.length;i++)
		{
			var curQS = progressDataSplit[i].split('=');
			if(curQS[0].toLowerCase() == key.toLowerCase())
				return curQS[1];
		}
		//return '';
	}
	document.getElementById('progress_bytesReceived').innerHTML = GetProgressValue('bytesReceived');
	document.getElementById('progress_totalBytes').innerHTML = GetProgressValue('totalBytes');
	document.getElementById('progress_timeStarted').innerHTML = GetProgressValue('timeStarted');
	document.getElementById('progress_timeElapsed').innerHTML = GetProgressValue('timeElapsed');
	document.getElementById('progress_timeRemaining').innerHTML = GetProgressValue('timeRemaining');
	document.getElementById('progress_timeLastActive').innerHTML = GetProgressValue('timeLastActive');
	document.getElementById('progress_percentComplete').innerHTML = GetProgressValue('percentComplete') + '%';
	document.getElementById('progress_bar').style.width = GetProgressValue('percentComplete') + "%";
	if(GetProgressValue('percentComplete') == '100')
		uploadComplete = true;
}

function getProgress()
{
	var xmlhttp = false;
	var xmlhttp = new XMLHttpRequest();
	if(!ajaxLocked && !uploadComplete)
	{
		ajaxLocked = true;
		if(xmlhttp)
		{
			qsData = 'Session=' + UploadSession;
			xmlhttp.open("GET", "../fileman/fileops/upload/getprogress.asp?" + qsData, true);
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4) {
					if(xmlhttp.status == 200) {
						loadProgress(xmlhttp.responseText);
						setTimeout('getProgress()', 15 * 5);
					}
					else {
						alert('The server returned status code ' + xmlhttp.status);
					}
					ajaxLocked = false;
				}
			}
			xmlhttp.send(null);
			// to allow post content
			//xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			//xmlhttp.send(data)
		}
		else
		{
			alert('XMLHTTP not supported in your browser!');
		}
	}
	else if(uploadComplete)
	{
		hideProgress();
	}
}

var UploadSession = new String();

function submitUpload()
{
	uploadComplete = false;
	// Create a random session identifier.
	UploadSession = Math.floor(Math.random() * 0xFFFFFF).toString(16);

	if(!document.getElementById('sneakyFrame'))
	{
		var newIframe = document.createElement('iframe');
		newIframe.id = 'sneakyFrame';
		newIframe.name = 'sneakyFrame';
		newIframe.style.height = '1px';
		newIframe.style.position = 'absolute';
		newIframe.style.bottom = '0px';
		newIframe.style.zIndex = '2';
		newIframe.style.display = 'none';
		document.body.appendChild(newIframe);
	}
	var sneakyFrame = document.getElementById('sneakyFrame');

	// set session ID to our upload form
	document.uploadForm.target = "sneakyFrame";
	document.uploadForm.action = document.uploadForm.getAttribute('baseAction') + '&Session=' + UploadSession;
	hideUpload();
	document.getElementById('progress').style.display = 'block';

	getProgress();

	return true;
}

/******************************************************************************************************************/
/** EVENT BUBBLING ************************************************************************************************/
/******************************************************************************************************************/

function stopBubble(e)
{
	if (!e)
		var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation)
		e.stopPropagation();
	return false;
}

/******************************************************************************************************************/
/** PAGE LOADERS **************************************************************************************************/
/******************************************************************************************************************/

addLoadFunction(setTextInputClasses);
