/**
 * Convert a plain-text password into one encrypted using MD5 hashing.
 * 
 * @return true always.
 */
function encryptPwd() {
	document.forms["credentials"]["encPwd"].value = hex_md5(document
			.getElementById("password").value);
	document.forms["credentials"]["password"].value = "";
	return true;
}

/**
 * Verify the user has entered all the required fields and that the new
 * passwords match each other, then encrypt both the existing password and the
 * new passwords.
 * 
 * @return true if all fields are present and correct, false otherwise.
 */
function verifyAndEncryptPwd() {
	if (document.forms["credentials"]["newpassword1"].value != document.forms["credentials"]["newpassword2"].value) {
		alert("Passwords don't match");
		return false;
	}
	document.forms["credentials"]["oldpassword"].value = hex_md5(document.forms["credentials"]["oldpassword"].value);
	document.forms["credentials"]["newpassword1"].value = hex_md5(document.forms["credentials"]["newpassword1"].value);
	document.forms["credentials"]["newpassword2"].value = hex_md5(document.forms["credentials"]["newpassword2"].value);
	return true;
}

var hideTimeout = new Array();
var hideTimeoutFrames = new Array();

/**
 * Returns the index into the array that will match the timer for the frame we
 * want to hide.
 * 
 * @param frame
 *            the frame we want to hide
 * @return the index for the timer for when this frame should be hidden
 */
function getTimerForFrame(frame) {
	timer = -1;
	for (i = 0; i < hideTimeoutFrames.length; i++) {
		if (hideTimeoutFrames[i] == frame) {
			timer = i;
		}
	}
	if (timer == -1) {
		timer = hideTimeoutFrames.length;
		hideTimeoutFrames[timer] = frame;
	}
	return timer;
}

/**
 * Requests that a DIVision be hidden after a short delay based on its ID. The
 * delay exists to stop flickering in Internet Explorer.
 * 
 * @param frame
 *            the frame who's border we want to set to the background color.
 * @param contents
 *            the data to be hidden.
 * @return nothing.
 */
function hidediv(frame, contents) {
	timer = getTimerForFrame(frame);
	hideTimeout[timer] = setTimeout('hidedivDelay(\'' + frame + '\', \''
			+ contents + '\')', 20);
}

/**
 * Hides a DIVision based on its ID, and makes it's frame the same as the
 * background (hides it without causing screen shimmer).
 * 
 * @param frame
 *            the frame who's border we want to set to the background color.
 * @param contents
 *            the data to be hidden.
 * @return nothing.
 */
function hidedivDelay(frame, contents) {
	document.getElementById(contents).style.visibility = 'hidden';
	document.getElementById(frame).style.border = '2px solid #a5cae5';
}

/**
 * Shows a DIVision based on its ID, and makes it's frame the same as the
 * borders within this particular layout.
 * 
 * @param frame
 *            the frame who's border we want to see.
 * @param contents
 *            the data to be shown.
 * @return nothing.
 */
function showdiv(frame, contents) {
	timer = getTimerForFrame(frame);
	if (hideTimeout[timer] != null) {
		clearTimeout(hideTimeout[timer]);
		hideTimeout[timer] = null;
	}
	document.getElementById(contents).style.visibility = 'visible';
	document.getElementById(frame).style.border = '2px solid #245882';
}

/**
 * Creates a visible email address that should be otherwise hidden from spiders.
 * 
 * @param username the name of the user who will get the email.
 * @param tld the top level domain for the host
 * @param hostname the server that hosts the email.
 * @return nothing (output is put directly into the document).
 */
function generate_address(username, tld, hostname) {
	var atsign = "&#64;";
	var addr = username + atsign + hostname + '.' + tld;
	document.write("<" + "a" + " " + "href=" + "mail" + "to:" + addr + ">"
			+ addr + "<\/a>");
}

/**
 * Ensures that all required fields are filled in before allowing the user to
 * submit a contact-us request.
 * 
 * @param errorMessage
 *            the language-specific error message if fields are missing
 * @return true if all required fields are present, false otherwise.
 */
function validate() {
	var reqd = new Array("name", "email", "comment");
	for (i in reqd) {
		if (!document.forms["contactUs"][reqd[i]].value.match(/.+/)) {
			alert("You need to enter a valid " + reqd[i]);
			setTimeout("focusElement('contactUs', '" + reqd[i] + "')", 0);
			return false;
		}
	}
	if (!echeck(document.forms["contactUs"]["email"].value)) {
		setTimeout("focusElement('contactUs', 'email')", 0);
		return false;
	}
	return true;
}

/**
 * Moves focus to a specific element within a specified form. Allows us to put
 * the cursor back to any fields that are missing.
 * 
 * @param formName
 *            the form containing the field we want focused.
 * @param elemName
 *            the name of the field we want focused
 * @return nothing
 */
function focusElement(formName, elemName) {
	var elem = document.forms[formName].elements[elemName];
	elem.focus();
	elem.select();
}

/**
 * DHTML email validation script. Courtesy of SmartWebby.com
 * (http://www.smartwebby.com/dhtml/)
 */
function echeck(str) {
	var at = "@";
	var dot = ".";
	var lat = str.indexOf(at);
	var lstr = str.length;
	var ldot = str.indexOf(dot);
	var valid = true;
	
	if (str.indexOf(at) == -1) {
		valid = false;
	}

	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
		valid = false;
	}

	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
		valid = false;
	}

	if (str.indexOf(at, (lat + 1)) != -1) {
		valid = false;
	}

	if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
		valid = false;
	}

	if (str.indexOf(dot, (lat + 2)) == -1) {
		valid = false;
	}

	if (str.indexOf(" ") != -1) {
		valid = false;
	}
	
	if (valid == false) {
		alert("Invalid E-mail ID")
	}

	return valid;
}

var commentXmlHttp;
var photoXmlHttp;


/**
 * Creates an AJAX request for a new comment to display on the website.
 */
function getNewComment() {
	commentXmlHttp = GetXmlHttpObject();
	if (commentXmlHttp == null) {
		alert("Browser does not support HTTP Request");
		return;
	}
	var url = "singleComment.php";
	url = url + "?sid=" + Math.random();
	commentXmlHttp.onreadystatechange = receivedComment;
	commentXmlHttp.open("GET", url, true);
	commentXmlHttp.send(null);
}


/**
 * Updates the comment in the comment area with the latest comment sent from
 * the server.
 */
function receivedComment() {
	if (commentXmlHttp.readyState == 4) {
		document.getElementById("comment").innerHTML = commentXmlHttp.responseText;
		setTimeout("getNewComment()", 3000);
	}
}


/**
 * Creates an AJAX request for a new photo to display on the website.
 */
function getNewPhoto() {
	photoXmlHttp = GetXmlHttpObject();
	if (photoXmlHttp == null) {
		alert("Browser does not support HTTP Request");
		return;
	}
	var url = "singlePhoto.php";
	url = url + "?sid=" + Math.random();
	photoXmlHttp.onreadystatechange = receivedPhoto;
	photoXmlHttp.open("GET", url, true);
	photoXmlHttp.send(null);
}


/**
 * Updates the photo in the photo area with the latest photo sent from
 * the server.
 */
function receivedPhoto() {
	if (photoXmlHttp.readyState == 4) {
		document.getElementById("photo").innerHTML = photoXmlHttp.responseText;
		setTimeout("getNewPhoto()", 3000);
	}
}


/**
 * Creates an XmlHttp object no matter what type of browser we are using, which
 * we can then use in our Ajax requests.
 * 
 * @return a browser independent XmlHttp object.
 */
function GetXmlHttpObject() {
	if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject) { // IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}


/**
 * Kick off our Ajax requests for comments and photos.
 */
setTimeout("getNewComment()", 100);
setTimeout("getNewPhoto()", 1500);
