var httpRequest = false;

function getCloseButtonHTML ()
{
	return '<div id="close-button" onClick="javascript:closeEmail();" ><span class="red"><span class="small">(Close)&nbsp;&nbsp;</span></span></div>';
}

// needs to use onMouseDown event to get clientX and clientY
function email(destination, title, objId)
{
		var bodyElement = (document.getElementsByTagName("body"))[0];
		if (document.getElementById("email-link-to-friend"))	{ //we need to remove any old email boxes
			var emailBox = document.getElementById("email-link-to-friend");
			var removedNode = bodyElement.removeChild(emailBox);
		}
		// fade body
		for (i=0; i<bodyElement.childNodes.length; i++){
			if (bodyElement.childNodes[i].style) {
				bodyElement.childNodes[i].style.opacity = ".5";
				bodyElement.childNodes[i].style.filter = "alpha(opacity=50)";
			}
		}
		
		if (destination.substr(0,4) != "http") {
			destination = 'http://www.ptsem.edu' + destination;
		}
		var emailbox = document.createElement("div");
		emailbox.setAttribute("id", "email-link-to-friend");
		var boxHTML = getCloseButtonHTML();
		boxHTML += '<h3 class="center" id="email-message"><span class="red">Share this link with a friend or collegue!</span></h3>';
		boxHTML += '<div id="email-status-bar" style="display:none; text-align:center;"><img src="/iym/images/new/emailing/loading.gif" /></div>'
		boxHTML += '<form id="email-link-form" name="email-link-form" action="" ><table>';
		boxHTML += '<tr>	<td class="bold" id="toname-label">Recipient\'s Name:</td><td><input type="text" maxlength="50" size="20" name="toname" id="toname" /></td></tr>';
		boxHTML += '<tr><td class="bold" id="toemail-label">Recipient\'s Email Address:</td><td><input type="text" maxlength="50" size="20" name="toemail" id="toemail" /></td></tr>';
		boxHTML += '<tr><td class="bold" id="fromname-label">Your Name:</td><td><input type="text" maxlength="50" size="20" name="fromname" id="fromname" /></td></tr>';
		boxHTML += '<tr><td class="bold" id="fromemail-label">Your Email Address:</td><td><input type="text" maxlength="50" size="20" name="fromemail" id="fromemail" /></td></tr>';
		boxHTML += '<tr><td class="bold" id="usermessage-label" colspan="2"><br />Message: <span class="small">(optional)</span></td><td></td></tr>';
		boxHTML += '<tr><td colspan="2"><textarea name="usermessage" id="usermessage" cols="40" rows="2"></textarea></td></tr>'
		boxHTML += '<tr><td><input type="text" name="link" id="link" value="' + destination + '" style="display:none" /><input type="text" name="linktitle" id="linktitle" value="' + title + '" style="display:none" /></td><td><br /><input  class="bold" type="button" name="button" id="button" value="Send Email" onClick="javacript:submitEmail();" /></td></tr>';

		var linkref = document.getElementById(objId);
		emailbox.innerHTML += boxHTML;
		//place box in center of page
		emailbox.style.left = ((xClientWidth()/2)-163) + "px";
		emailbox.style.top = ((xClientHeight()/2)-143) + "px";
		var bodyElement = (document.getElementsByTagName("body"))[0];
		bodyElement.appendChild(emailbox);
}

function closeEmail()
{
		var bodyElement = (document.getElementsByTagName("body"))[0];
		var emailBox = document.getElementById("email-link-to-friend");
		var removedNode = bodyElement.removeChild(emailBox);	
		
		for (i=0; i<bodyElement.childNodes.length; i++){
			if (bodyElement.childNodes[i].style) {
				bodyElement.childNodes[i].style.opacity = "1";
				bodyElement.childNodes[i].style.filter = "alpha(opacity=100)";
			}
		}
}

function addEmailLinks()
{
	var spantags = document.getElementsByTagName("span");
	emailLinkCounter = 0;
	for (i=0; i<spantags.length; i++)
	{
		if (spantags[i].getAttribute("title") == 'emailme')
		{
			var originallinks = spantags[i].getElementsByTagName("a");
			if (originallinks[0]) // this should always be true, but incase the html is malformed, we don't want the script to die
			{
				var linkId = "emailLink" + emailLinkCounter;
				var destination = originallinks[0].getAttribute("href");
				var title = originallinks[0].getAttribute("title");
				var emaillink = document.createElement("a");
				emaillink.setAttribute("href", "javascript:email('" + destination + "', '" + title + "', '" + linkId + "')");
				emaillink.setAttribute("id", linkId);
				emaillink.setAttribute("class", "email-me");
				var linkImg = document.createElement("img");
				linkImg.setAttribute("alt", "Email link");
				linkImg.setAttribute("src", "/iym/images/new/emailing/email_edit.gif");
				emaillink.appendChild(linkImg);
				var space = document.createTextNode(" ");
				spantags[i].appendChild(space);
				spantags[i].appendChild(emaillink);
				emailLinkCounter++;
			}
		}
	}
	// display notice about email link, should be embedded in actual page, but only turned on if the Javascript gets this far
	emailNotice = document.getElementById("email-notice"); 
	if (emailNotice) {
		emailNotice.style.display = "block";
	}
}

function makeRequest(url, parameters)
{
	httpRequest = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) { //IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {} 
		}
	}
	if (!httpRequest) {
		// need to handle this case better
		alert('Error, cannot send email due to browser settings');
		return false;
	}
	httpRequest.onreadystatechange = alertResult;
	httpRequest.open('POST', url, true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader("Content-length", parameters.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(parameters);
//httpRequest.open('GET', url + parameters, true);
//	httpRequest.send(null);
}

function alertResult() {
	try {
    	if (httpRequest.readyState == 4) {
        	if (httpRequest.status == 200) {
				var xmlDoc = httpRequest.responseXML;
            	var resultNode = xmlDoc.getElementsByTagName('result').item(0);
				if (resultNode.getAttribute("success") == "true")
				{
					formDiv = document.getElementById('email-link-to-friend');
					formDiv.innerHTML = getCloseButtonHTML(); // clear out the old element except for close button
					var messageContainer = document.createElement("h3");
					messageContainer.setAttribute("class", "center");
					var message = document.createElement("span");
					message.setAttribute("class", "red");
					var messageText = document.createTextNode("Your email has been sent.");
					message.appendChild(messageText);
					messageContainer.appendChild(message);
					formDiv.appendChild(messageContainer);
				}
				else
				{
					document.getElementById('email-link-form').style.display = "block";
					document.getElementById('email-status-bar').style.display = "none";
					
					errorNode = xmlDoc.getElementsByTagName('error').item(0);
					formDiv = document.getElementById('email-link-to-friend');
					// get and format the error message
					var message = document.createElement("span");
					message.setAttribute("class", "red");
					var messageText = document.createTextNode(errorNode.getElementsByTagName("message").item(0).firstChild.data);
					message.appendChild(messageText);
					var element = errorNode.getElementsByTagName("element").item(0).firstChild.data;
					
					// if it was a user entry problem, indicate the problem	
					if (errorNode.getAttribute("type") == "input")	{
						document.getElementById("email-message").innerHTML = ""
						document.getElementById("email-message").appendChild(message);
						var labelId = element + '-label';
						document.getElementById(labelId).innerHTML = '<span class="red">' + document.getElementById(labelId).innerHTML + '</span>';
					}
					// some other sort of problem, just die as gracefully as possible
					else {
						formDiv.innerHTML = ""; // clear out the old element
						var messageContainer = document.createElement("h3");
						messageContainer.setAttribute("class", "center");
						messageContainer.setAttribute("id", 'email-link-to-friend');
						messageContainer.appendChild(message);
						formDiv.appendChild(messageContainer);
					}
				}
            } else {
				alert('There was a problem with the request.');
			}
		}
	}
	catch( e ) {
		alert('Caught Exception: ' + e);
	}
}

function submitEmail()

{
	var form = document.getElementById('email-link-form');
	var poststr = "";
	var inputtags = form.getElementsByTagName("input");
	textarea = form.getElementsByTagName("textarea")[0];
	for (i=0; i<inputtags.length; i++)
	{
		if (inputtags[i].type == "text")
		{
			poststr += inputtags[i].name + '=' + encodeURI( inputtags[i].value ) + '&';
		}
	}
	poststr += textarea.name + '=' + encodeURI( textarea.value );
	
	document.getElementById("email-message").innerHTML = ""
	document.getElementById("email-message").innerHTML = '<span class="red">Please wait, sending email...</span>';
	// messsage user to wait
	document.getElementById('email-link-form').style.display = "none";
	document.getElementById('email-status-bar').style.display = "block";
	
	makeRequest('/iym/emailing/sendemail.php', poststr);
}