var xmlHttp; // for the ajax object
// if you need multiple ajax calls, create different ajax objects for each call here
var projectXmlHttp; 
var contactXmlHttp; 
var rssXmlHttp; 

var anchorId; // this needs to be a global so my processing scripts can toggle onclicks 
var anchorEvent; // save this?

// process_email() is the mail client call
function send_email() {
	if (!validate_email_addresses())
	{
		// put an error message inside the status label
		pushError("Invalid Email Address");
		updateBuffer();
		document.getElementById("status").focus();		
		return false;
	}
	send_request();
	return false;
}

function join_project() {
	send_join_request();
	return false;
}

function contact_us() {
	contactXmlHttp = GetXmlHttpObject();
	var from = document.getElementById('from').value;
	var sendername = document.getElementById('sender-name').value;
	var comment = document.getElementById('comment').value;
	var subjectline = document.getElementById('subject').value;
	var message = document.getElementById('message').value;
	// get the parameters
	if (contactXmlHttp == null)
	{
		alert("Your browser does not support AJAX!");
		return;
	}
	var url = "http://urban.cens.ucla.edu/ajax-processing/contact_us.php";
	url += "?from="+from;
	url += "&sendername="+sendername;
	url += "&comment="+comment;
	url += "&message="+message;
	url += "&subjectline="+subjectline;
	url += "&sid="+Math.random();
	contactXmlHttp.onreadystatechange=process_contactUs;
	contactXmlHttp.open("GET",url,true); 
	contactXmlHttp.send(null);
	return false;
}

function validate_email_addresses() {
	// check from / to and check if they are valid
	var from = document.getElementById('from').value;
	var to = document.getElementById('to').value;
	if (from.length == 0 || to.length == 0)
		return false;
	else 
		return true;
}

// send_request sends the request, does some processing too
function send_request()
{
	xmlHttp=GetXmlHttpObject();
	var from = document.getElementById('from').value;
	var to = document.getElementById('to').value;
	var comment = document.getElementById('comment').value;
	var target = document.getElementById('target').value;
	// get the parameters
	if (xmlHttp == null)
	{
		alert("Your browser does not support AJAX!");
		return;
	}
	var url = "http://urban.cens.ucla.edu/ajax-processing/email_friend.php";
	url += "?to="+to;
	url += "&from="+from;
	url += "&comment="+comment;
	url += "&target="+target;
	url += "&sid="+Math.random();
	xmlHttp.onreadystatechange=process_request;
	xmlHttp.open("GET",url,true); 
	xmlHttp.send(null);
	return false;
}

// grab an rss feed
function send_rss_request(content,folder)
{
	rssXmlHttp=GetXmlHttpObject();
	// get the parameters
	if (rssXmlHttp == null)
	{
		alert("Your browser does not support AJAX!");
		return;
	}
	var url = "http://urban.cens.ucla.edu/ajax-processing/grab_rss.php";
	url += "?content="+content;
	url += "&folder="+folder;
	url += "&sid="+Math.random();
	rssXmlHttp.onreadystatechange=process_rss_request;
	rssXmlHttp.open("GET",url,true); 
	rssXmlHttp.send(null);
	return false;
}

// send the join request
function send_join_request()
{
	projectXmlHttp=GetXmlHttpObject();
	var email = document.getElementById('email').value;
	var project = document.getElementById('project-name').value;
	var message = document.getElementById('message').value;
	// get the parameters
	if (projectXmlHttp == null)
	{
		alert("Your browser does not support AJAX!");
		return;
	}
	var url = "http://urban.cens.ucla.edu/ajax-processing/project_join.php";
	url += "?message="+message;
	url += "&email="+email;
	url += "&project-name="+project;
	url += "&sid="+Math.random();
	projectXmlHttp.onreadystatechange=process_join_request;
	projectXmlHttp.open("GET",url,true); 
	projectXmlHttp.send(null);
	return false;
}

function process_contactUs()
{
	if (contactXmlHttp.readyState==4)
	{
		flushStatus('status-success-label');
		var newP = document.createElement('p');
		// did we have sucess?
		if (contactXmlHttp.responseText=='true')
		{
			var newText = document.createTextNode('Your email has been sent');
			newP.className='success';
		}
		else
		{
			var newText = document.createTextNode('There was an error sending your email ' + contactXmlHttp.responseText);
			newP.className='error';		
		}
		newP.appendChild(newText);
		document.getElementById("status-success-label").appendChild(newP);
		// try this to update the JAWS buffer
		// updateBuffer();
		// if this works, set the focus to the success label
		// you can move focus with the 'focus()' method, however it only works on certain elements (not labels)
		document.getElementById("status").focus();
		
		// debug
		return false; // because we don't want the form to go anywhere
	}
}

function process_request()
{
	if (xmlHttp.readyState==4)
	{
		flushStatus('friend-success-label');
		flush('popupDiv');
		var newP = document.createElement('p');
		// did we have sucess?
		if (xmlHttp.responseText=='true')
		{
			var newText = document.createTextNode('Your email has been sent');
			newP.className='success';
		}
		else
		{
			var newText = document.createTextNode(xmlHttp.responseText);
			//var newText = document.createTextNode('There was an error sending your email');
			newP.className='error';		
		}
		newP.appendChild(newText);
		var popupDiv = document.getElementById('popupDiv');
		popupDiv.insertBefore(newP,document.getElementById('close-popup-form'));
		// var closeForm = makeCloseForm();
		// popupDiv.appendChild(closeForm);
		// document.getElementById("friend-success-label").appendChild(newP);
		// try this to update the JAWS buffer
		// updateBuffer();
		// if this works, set the focus to the success label
		// you can move focus with the 'focus()' method, however it only works on certain elements (not labels)
		// document.getElementById("status").focus();
		// what is the xmlHttp status?
		
		// debug
		// document.getElementById('debug').innerHTML = xmlHttp.responseText;
		return false; // because we don't want the form to go anywhere
	}
}

function process_join_request()
{
	if (projectXmlHttp.readyState==4)
	{
		flushStatus('join-status');
		var newP = document.createElement('p');
		// did we have sucess?
		if (projectXmlHttp.responseText=='true')
		{
			var newText = document.createTextNode('Thank you for signing up. You should be receiving a confirmation shortly.');			
			newP.className='success';		
		}
		else
		{
			var newText = document.createTextNode('There was an error signing up for this project: ' + projectXmlHttp.responseText);			
			newP.className='error';		
		}
		newP.appendChild(newText);
		document.getElementById("join-status").appendChild(newP);
		
		// debug
		return false; // because we don't want the form to go anywhere
	}
}

function process_rss_request() {
	// for now, i just wanna see the response text
	if (rssXmlHttp.readyState==4)
	{
		var popupDiv = document.getElementById('popupDiv');

		// flush anything after the close button
		for (var i = 1; i < popupDiv.childNodes.length; i++)
			popupDiv.removeChild(popupDiv.childNodes[i]);
		
		var rss = eval(rssXmlHttp.responseText);
		var channeltitle = rss[0].title;
		var titleHead = document.createElement('h2');
		titleHead.style.padding=0;
		titleHead.style.margin=0;
		titleHead.style.color='white';
		var titleText = document.createTextNode(channeltitle);
		titleHead.appendChild(titleText);
		popupDiv.appendChild(titleHead);
		var rssList = document.createElement('ul');
		rssList.style.paddingTop=0;
		rssList.style.marginTop=0;
		rssList.style.height='60px';
		rssList.style.overflow='auto';
		// let's get the list items
//		for (var i = 1; i < rss.length; i++)
		var rssdata = rss[1];
		for (var i = 0; i < rssdata.length; i++)
		{
			var listItem = document.createElement('li');
			var item = rssdata[i];
			var liTextTitle = document.createTextNode(item.title);
			var liTextDescription = '';
			if (item.description && item.description.length > 0)
				liTextDescription = " - " + item.description;
			var liLinkNode = document.createElement('a');
			liLinkNode.href = item.link;
			liLinkNode.appendChild(liTextTitle);
			liLinkNode.target='_blank';
			liLinkNode.style.color='white';
			listItem.appendChild(liLinkNode);
			if (item.description && item.description.length > 0)
				listItem.appendChild(liTextDescription);
			rssList.appendChild(listItem);
		}
		popupDiv.appendChild(rssList);
	}
	else if (rssXmlHttp.readyState >= 3)
	{
		var popupDiv = document.getElementById('popupDiv');
		var myP = document.createElement('p');
		var someText = document.createTextNode('loading...');
		myP.appendChild(someText);
		// flush anything after the close button
		for (var i = 1; i < popupDiv.childNodes.length; i++)
			popupDiv.removeChild(popupDiv.childNodes[i]);
		// put the loading message
		popupDiv.appendChild(myP);
	}
	return false;
}

function updateBuffer()
{
	// objHidden represents a hidden input element
    var objHidden = document.getElementById('hiddenobject');

	// change the value - this is meant to try to update the JAWS buffer at the end of an AJAX call
	// the idea - a form value update will force JAWS to update it's buffer (as of JAWS 7.1)
	// develoeprs note: patrick says this works w/ IE6 and JAWS 7 but not so well with more recent browser/JAWS combos. Will review later
    if (objHidden)
    {
        if (objHidden.getAttribute('value') == '1')
            objHidden.setAttribute('value', '0');
        else
            objHidden.setAttribute('value', '1');
    }
}

function pushError(error_msg)
{
	flushStatus();
	var newP = document.createElement('p');
	newP.className='error';
	var newText = document.createTextNode(error_msg);
	newP.appendChild(newText);
	document.getElementById("success-label").appendChild(newP);
	document.getElementById("status").focus();
}

function flushStatus(label_id)
{
	// how do I clear out all the stuff underneath status
	var status = document.getElementById(label_id);
	for (var i = 0; i < status.childNodes.length; i++)
		document.getElementById(label_id).removeChild(status.childNodes[i]);
}

function flush(id)
{
	// flush all the items underneath id
	var node = document.getElementById(id);
	for (var i = 0; i < node.childNodes.length; i++)
		node.removeChild(node.childNodes[i]);
	
}

// required for AJAX processing
function GetXmlHttpObject()
{
	var thisXmlHttp;
	try
	{
		// Firefox, Opera 8.0+, Safari
		thisXmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
		thisXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
		thisXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return thisXmlHttp;
}

function emailfriend(url,e,id) {
	if (document.getElementById('popupDiv'))
		return false;
	// get the mouse location
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document

	// we shoudl remove the onclick of this post for now (so they don't open a bazillion popups)
	// anchorId = id; // cuz this has to be kept across a few functions
	// var currentObj = document.getElementById(id);

	// let's make a div
	var popupDiv = document.createElement('div');
	popupDiv.id = 'popupDiv';
	popupDiv.style.backgroundColor='rgb(200,200,200)';
	popupDiv.style.color='black';
	popupDiv.style.opacity='0.9';
	popupDiv.style.filter='alpha(opacity=90)';
	popupDiv.style.position='absolute';
	popupDiv.style.left=posx+'px';
	popupDiv.style.top=posy+'px';
	popupDiv.style.width='400px';
	popupDiv.style.padding='2px';
	popupDiv.style.height='320px';
	popupDiv.style.zIndex=1;

	var form = makeFriendForm(url);
	var closeform = makeCloseForm();
	popupDiv.appendChild(form);
	popupDiv.appendChild(closeform);

	// show the div?
	var mailDiv = document.getElementById('mail-friend');
	mailDiv.appendChild(popupDiv);
	
	return false;
}

function makeFriendForm(page) {
	// let's make our form
	var newForm = document.createElement('form');	
	// what inputs do we need?
	var from = document.createElement('input');
	var fromlabel = document.createElement('label');
	var to = document.createElement('input');
	var tolabel = document.createElement('label');
	var target = document.createElement('input');
	var commentlabel = document.createElement('label');
	var comment = document.createElement('textarea');
	// to and from are email addresses, comment should be a textbox
	// let's define our form values
	newForm.id = 'mail-friend-form';
	newForm.method='POST';
	newForm.action='/ajax-processing/email_friend.php';

	var fieldset = document.createElement('fieldset');
	var legend = document.createElement('legend');
	var newText = document.createTextNode('Email a Friend');
	
	fieldset.style.fontSize='1.2em';

	legend.appendChild(newText);
	fieldset.appendChild(legend);
	newForm.appendChild(fieldset);

	from.type="text";
	from.id='from';
	from.name='from';
	from.value='joebruin@ucla.edu';
	
	fromlabel.htmlFor='from';
	newText = document.createTextNode('From : ');
	fromlabel.appendChild(newText);	

	var newP = document.createElement('p');
	newP.appendChild(fromlabel);
	newP.appendChild(from);
	fieldset.appendChild(newP);
	
	to.type="text";
	to.id='to';
	to.name='to';
	to.value='janebruin@ucla.edu';
	
	tolabel.htmlFor='to';
	newText = document.createTextNode('To : ');
	tolabel.appendChild(newText);	

	newP = document.createElement('p');
	newP.appendChild(tolabel);
	newP.appendChild(to);
	fieldset.appendChild(newP);
	
	target.type="hidden";
	target.id="target";
	target.name="target";
	target.value=page;
	
	fieldset.appendChild(target);
	
	comment.id='comment';
	comment.name='comment';
	comment.rows='5';
	comment.cols='35';
	comment.value='Enter a personal message here';

	commentlabel.htmlFor='comment';
	newText = document.createTextNode('Comment : ');
	commentlabel.appendChild(newText);	
	
	newP = document.createElement('p');
	newP.appendChild(commentlabel);
	newP.appendChild(comment);
	fieldset.appendChild(newP);
	
	// let's insert a status field (for the ajax call return)
	var statuslabel = document.createElement('label');
	statuslabel.htmlFor='status';
	statuslabel.id='friend-success-label';
	fieldset.appendChild(statuslabel);
	
	var status = document.createElement('input');
	status.id='status';
	status.name='status';
	status.type="hidden";
	status.disabled="disabled";
	status.style.display="none";
	fieldset.appendChild(statuslabel);
	
	// where's my submit button?
	var submit = document.createElement('input');
	submit.type='submit';
	submit.id='submit';
	submit.id='submit';
	submit.value='Send';

	newP = document.createElement('p');
	newP.style.textAlign = 'right';
	
	newP.appendChild(submit);
	fieldset.appendChild(newP);
	
	// WAIT -
	// the form needs on onsubmit which calls the email a friend function
	newForm.onsubmit = send_email_wrapper;
	
	return newForm;
}

function makeCloseForm() {

	var newForm = document.createElement('form');	
	// to and from are email addresses, comment should be a textbox
	// let's define our form values
	newForm.id = 'close-popup-form';
	newForm.method='POST';
	newForm.action='';

	// where's my submit button?
	var submit = document.createElement('input');
	submit.type='submit';
	submit.id='submit';
	submit.id='submit';
	submit.value='Close';
	
	var newP = document.createElement('p');
	newP.style.textAlign='right';
	
	newP.appendChild(submit);
	newForm.appendChild(newP);	
	
	// let's add my onsubmit event
	newForm.onsubmit = close_form;
	
	return newForm;
}

function send_email_wrapper() {
	return send_email();
}

function close_form()
{
	if (document.getElementById('popupDiv') && document.getElementById('mail-div') )
		document.getElementById('mail-div').removeChild(document.getElementById('popupDiv'));
	else if (document.getElementById('mail-friend'))
	{
		document.getElementById('mail-friend').removeChild(document.getElementById('popupDiv'));
	}
	return false;
}