var req;
var fieldId;
var fieldAction = false;
var multiValue;
var multiValList;
var calendarZ = 10;

function ajaxSubmitHandler()
{
	if (fieldAction != "add" && fieldAction != "remove")
	{
		return true;
	}
	else
	{
		return false;
	}
}

function setFieldAction(newAction)
{
	fieldAction = newAction;
}

function fieldHandler(inputId, inputFunction, inputValue, inputAction, metaFunction)
{
/*
myAlert("navigator.appName="+navigator.appName);
myAlert("navigator.appVersion="+navigator.appVersion);
myAlert("navigator.appMinorVersion="+navigator.appMinorVersion);
myAlert("navigator.appCodeName="+navigator.appCodeName);
*/
	
	req = null;
	fieldId = inputId;
	fieldAction = inputAction;
	fieldForm = getFormName(fieldId);
	//fieldForm = document.getElementById(fieldId).form.getAttribute("id");
	//url = document.URL;

	//TODO: FIX THIS!!!!	
	//url = "/post.php?action=" + document.URL;
	url = "ajax_post.php"; //REMOVE THIS !!!!!	
	//TODO: FIX ABOVE!!!

	params = 'form_name=' + fieldForm + '&ajax_post=true'
	
	if (fieldAction == 'remove')
	{
		multiValue = getMultiRemoveChecked();
		
		if (multiValue == null)
		{
			handle_response(false,"No boxes are checked");
			return;
		}
		else
		{
			params = params + "&_multi_remove[" + fieldId + "]=true";
			for (i = 0; i < multiValue.length; i++)
				params = params + "&" + multiValue[i] + "=checked";
		}
	}
	else
	{
		if (fieldAction == 'add' && !isArray(inputValue))
		{
			params = params + '&_multi_add[' + fieldId + ']=Add';
			params = params + '&' + fieldId + '=' + escape(inputValue);

			multiValue = inputValue;
			if (multiValue == "" || multiValue == null)
			{
				handle_response(false,"You must enter or select something to add it.");
				return;
			}
		}
		else
		{
			if (isArray(inputValue))
			{
				for(i=0;i<inputValue.length;i++)
					params = params + '&val[]='+ escape(inputValue[i]);
			}
			else
			{
				params = params + '&val=' + escape(inputValue);
			}
		}
		
		if (metaFunction != "" && metaFunction != "undefined" && metaFunction != null)
		{
			params = params + '&meta_func=' + escape(metaFunction);
		}
		
		if (isArray(inputFunction))
		{
			for(i=0;i<inputFunction.length;i++)
			{
				params = params + '&func[]=' + escape(inputFunction[i]);
			}
		}
		else if (inputFunction != "")
		{
			params = params + '&func=' + escape(inputFunction);
		}
	}
//myAlert(url);
	// Create the HTTPRequest
	req = generateRequest();
	
	
	
	//If the request is invalid, give an alert and return
	if (req == null)
	{
		if (fieldAction == "add" || fieldAction == "remove")
		{
			try {
				tempNode = document.getElementById("_multi_" + fieldAction + "[" + fieldId + "]");
				tempNode.id = "_button_multi_" + fieldAction + "[" + fieldId + "]";
				tempNode.name = "_button_multi_" + fieldAction + "[" + fieldId + "]";
				
				tempNode = document.createElement('INPUT');
				tempNode.type = "hidden";
				tempNode.value = "true";
				tempNode.id = "_multi_" + fieldAction + "[" + fieldId + "]";
				tempNode.name = "_multi_" + fieldAction + "[" + fieldId + "]";
				
				inputForm=document.getElementById(fieldForm);
				inputForm.appendChild(tempNode);
				inputForm.submit();
				return;
			} catch (x) {
				myAlert("There was an error bypassing AJAX: " + x.description);
				return;
			}
		}		
		return;
	}
	
//myAlert(url);
//myAlert(params);
	
	req.onreadystatechange = processReqChange;
	req.open("POST", url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection","close");
	req.send(params);
}

function generateRequest()
{
	request = null;
	if (window.XMLHttpRequest)
		request = new XMLHttpRequest();
	else if(window.ActiveXObject)
		request = new ActiveXObject("Microsoft.XMLHTTP");
	
	return request;
}

/**
 * This section handles the responses from the server
 * @param	status		the status response from the AJAX handler
 * @param	response	the response from the AJAX handler
 */
function handle_response(status, response)
{
//myAlert("fieldAction = "+fieldAction);
//myAlert("status="+status);

	// Try and load the error block element, if it doesn't exist, create it and try again
	error   = document.getElementById(fieldId+'_error');
	meta    = document.getElementById(fieldId+'_meta');
	
	if (fieldAction == "add" && status)
	{
		addMultiItem();
	}
	
	if (fieldAction == "remove" && status)
	{
		removeMultiItems();
	}
	
	
	if (!status)
	{
		while (error == null && response != "")
		{
			addFieldError();
			error = document.getElementById(fieldId+'_error');
		}

		if (response != "")
			error.innerHTML = response;
		
		while (meta != null)
		{
			meta.parentNode.removeChild(meta);
			meta = document.getElementById(fieldId+'_meta');
		}
	}
	else
	{
		while (meta == null && response != "")
		{
			addFieldMeta();
			meta = document.getElementById(fieldId+'_meta');
		}

		if (response != "")
			meta.innerHTML = response;
	
		while (error != null)
		{
			error.parentNode.removeChild(error);
			error = document.getElementById(fieldId+'_error');
			removeFormError();
		}
	}
}

/**
 * This is the event handler for the HTTP stream, when the stream updates it gets called
 */
function processReqChange()
{
	// only if req shows "complete"
	if (req.readyState == 4) {
		// only if "OK"
//myAlert("req.status="+req.status);
		if (req.status == 200) {
			// ...processing statements go here...
//myAlert("responseText="+req.responseText);
			XMLresponse  = req.responseXML.documentElement;
			allDetails = XMLresponse.getElementsByTagName('detail');
			funcStatus = XMLresponse.getElementsByTagName('status')[0].firstChild.data;
			detailString = "";

			if (funcStatus == '1')
				funcStatus = true;
			else
				funcStatus = false;
			
			for (i=0;i < allDetails.length;i++)
			{
				if (i >0 )
					detailString = detailString + "<BR>";
				detailString = detailString + allDetails[i].firstChild.data;
				//detailString = detailString + allDetails[i].textContent;
//myAlert(allDetails[i].textContent);
			}
//myAlert("detailString = "+detailString);			
			handle_response(funcStatus, detailString);
		} else {
			//myAlert("There was a problem retrieving the XML data:\n" + req.statusText);
		}
	}
}

/**
 * This is a homemade function to check whether or not a variable is an array
 */
function isArray(a)
{
	if (typeof a == 'object' && a.constructor == Array)
		return true;
	else
		return false;
}

/**
 * Given a form field id, this will traverse up the DOM tree until the parent form is found.
 */
function getFormName(givenId)
{
	temp = document.getElementById(givenId);
	while (temp.tagName.toLowerCase() != 'form')
		temp = temp.parentNode;
	
	return temp.getAttribute('id');
	
}

/**
 * This function checks the parent form of the field that is being validated to see if there are any field errors
 * returns true if a field error is found
 * returns false if there are no field errors found
 */
function fieldErrorsExist()
{
	formObject = document.getElementById(fieldForm);
	
	//Cycle through all form field elements to check for validation errors
	for (i=0;i<formObject.elements.length;i++)
	{
		if (document.getElementById(formObject.elements[i].id+'_error') || document.getElementById(formObject.elements[i].parentNode.id+'_error'))
		{
//myAlert("form errors found");
			return true;
		}
	}
//myAlert("no form errors found");
	return false;
}

/**
 * check to see if the parent form of the validating field has an error box
 * returns true if the error ul exists
 * returns false if the error ul does not exist
 */
function formErrorExists()
{
	testObject = document.getElementById(fieldForm).previousSibling;
	while (testObject.previousSibling != null && testObject.nodeType != 1)
		testObject = testObject.previousSibling;
	
	if (testObject.tagName.toLowerCase() == "ul" && (testObject.getAttribute('className') == "form-errors" || testObject.getAttribute('class') == "form-errors"))
	{
//myAlert("The form error block found");	
		return true;
	}
	else
	{
//myAlert("NO form error block found");
		return false;
	}
}

/**
 * Add the error span for a field
 */
function addFieldError()
{
//myAlert("the span does not exist yet");
	tempNode = document.createElement('SPAN');
	tempNode.setAttribute('className','red');
	tempNode.setAttribute('class','red');
	tempNode.id = fieldId+'_error';
//myAlert(tempNode.id);
	message = document.getElementById(fieldId).parentNode;
	addBefore = document.getElementById(fieldId).nextSibling;
	if (addBefore)
	{
		while(addBefore.nodeType == 1 && (addBefore.tagName.toLowerCase() == 'input' || addBefore.tagName.toLowerCase() == 'br'))
		{
			if (addBefore.nextSibling == null)
				break;

			addBefore = addBefore.nextSibling;
			if (addBefore == null || addBefore.previousSibling.tagName.toLowerCase() == 'br') {
				break;
			}
		}
			
			
		if (addBefore.previousSibling.tagName.toLowerCase() != 'br')
			document.getElementById(fieldId).parentNode.insertBefore(document.createElement('BR'),addBefore);
			
		document.getElementById(fieldId).parentNode.insertBefore(tempNode,addBefore);
	}
	else
	{
		document.getElementById(fieldId).parentNode.appendChild(document.createElement('BR'));
		document.getElementById(fieldId).parentNode.appendChild(tempNode);
	}	
}

/**
 * Add the meta data span for a field
 */
function addFieldMeta()
{
//myAlert("the span does not exist yet");
	tempNode = document.createElement('SPAN');
	tempNode.setAttribute('className','green');
	tempNode.setAttribute('class','green');
	tempNode.id = fieldId+'_meta';
//myAlert(tempNode.id);
	message = document.getElementById(fieldId).parentNode;
	addBefore = document.getElementById(fieldId).nextSibling;
	if (addBefore)
	{
		while(addBefore.nodeType == 1 && (addBefore.tagName.toLowerCase() == 'input' || addBefore.tagName.toLowerCase() == 'br'))
		{
			if (addBefore.nextSibling == null)
				break;

			addBefore = addBefore.nextSibling;
			if (addBefore == null || addBefore.previousSibling.tagName.toLowerCase() == 'br') {
				break;
			}
		}
			
			
		if (addBefore.previousSibling.tagName.toLowerCase() != 'br')
			document.getElementById(fieldId).parentNode.insertBefore(document.createElement('BR'),addBefore);
			
		document.getElementById(fieldId).parentNode.insertBefore(tempNode,addBefore);
	}
	else
	{
		document.getElementById(fieldId).parentNode.appendChild(document.createElement('BR'));
		document.getElementById(fieldId).parentNode.appendChild(tempNode);
	}	
}


/**
 * Add the form error box
 * Not currently necessary, it makes the page move too much
 */
function addFormError()
{
	if (formErrorExists())
		return false;
//myAlert("form error does not exist, adding now");	
	formObject=document.getElementById(fieldForm);
//myAlert("tempNode created for error");	
	tempNode = document.createElement('UL');
	tempNode.setAttribute('className','form-errors');
	tempNode.setAttribute('class','form-errors');
	tempNode.innerHTML = '<li>There are errors with this form</li>';	
//myAlert("adding temp node into form.parent after form");	
	formObject.parentNode.insertBefore(tempNode,formObject);
//myAlert("verify that the error node was added");
	if (formErrorExists())
		return true;
	else
		return false;
}

/**
 * Remove the form error box
 */
function removeFormError()
{
	if (!formErrorExists() || fieldErrorsExist())
		return false;

	testObject = document.getElementById(fieldForm).previousSibling;
	while (testObject.previousSibling && testObject.nodeType != 1)
		testObject = testObject.previousSibling;
	
	if (testObject.tagName.toLowerCase() == "ul" && (testObject.getAttribute('className') == "form-errors" || testObject.getAttribute('class') == "form-errors"))
	{
//myAlert("The form error block found, now removing");
		testObject.parentNode.removeChild(testObject);
		return true;
	}
	else
	{
//myAlert("NO form error block found");
		return false;
	}
}

/**
 * This function adds a multi checkbox
 * requires an add multi container in case one does not exist
 */
function addMultiItem()
{
	if (!addMultiContainer())
		return false;

	brNode = document.createElement('BR');
	
	checkNode = document.createElement('INPUT');
	checkNode.setAttribute('className','check');
	checkNode.setAttribute('class','check');
	checkNode.setAttribute('type','checkbox');
	checkNode.name = fieldId+"_values["+multiValue+"]";
	checkNode.id = fieldId+"_values["+multiValue+"]";

	parentInput = document.getElementById(fieldId);
	if (parentInput.tagName.toLowerCase() == "select")
	{
		tempValue = "";
		for (i = 0; i < parentInput.childNodes.length; i++)
		{
			if (parentInput.childNodes[i].value == multiValue)
			{
				tempValue = parentInput.childNodes[i].firstChild.data;
			}
			else if (parentInput.childNodes[i].nodeType == 1 && parentInput.childNodes[i].tagName.toLowerCase() == "optgroup")
			{
				for (j = 0; j < parentInput.childNodes[i].childNodes.length; j++)
				{
					if (parentInput.childNodes[i].childNodes[j].value == multiValue)
					{
						tempValue = parentInput.childNodes[i].childNodes[j].firstChild.data;
					}
				}
			}
		}
	}
	else if (document.getElementById(fieldId+"[year]") != null && document.getElementById(fieldId+"[month]") != null && document.getElementById(fieldId+"[day]") != null)
	{
		tempValue = formatDate(multiValue);
	}
	else if (document.getElementById(fieldId+"[hour]") != null && document.getElementById(fieldId+"[minute]") != null)
	{
		tempValue = formatTime(multiValue);
	}
	else
	{
		tempValue = multiValue;
	}

	textNode = document.createTextNode(tempValue);
	
	multiDiv = document.getElementById(fieldId+"_multi_div");
	addBefore = document.getElementById("_multi_remove["+fieldId+"]");

	multiDiv.insertBefore(checkNode,addBefore);
	multiDiv.insertBefore(textNode,addBefore);
	multiDiv.insertBefore(brNode,addBefore);

}

function removeMultiItems()
{
	for (i = 0; i < multiValue.length; i++)
	{
		try
		{
			tNode = document.getElementById(multiValue[i]);
			
			while (tNode.nextSibling.nodeType != 1 || tNode.nextSibling.tagName.toLowerCase() != "input")
			{
//myAlert(tNode.nextSibling.innerHTML);
				tNode.parentNode.removeChild(tNode.nextSibling);
			}

			tNode.parentNode.removeChild(tNode);
		}
		catch(x)
		{
			myAlert("Error removing: "+multiValue[i]);
		}
	}
	removeMultiContainer();
}

/**
 * This function adds a multi ocntainer
 * requires a test for multi container
 */
function addMultiContainer()
{
	if (multiContainerExists())
		return true;
	
//myAlert("multiContainer does not exists, adding it now!");
	
	tempObject = document.getElementById(fieldId);
	while (tempObject.nodeType == 3 || tempObject.tagName.toLowerCase() != "td")
		tempObject = tempObject.parentNode;
	
	newNode = document.createElement('DIV');
	newNode.setAttribute('className','form-multi-list');
	newNode.setAttribute('class','form-multi-list');
	newNode.id = fieldId+'_multi_div';
	newNode.innerHTML = '<input type="button" value="Remove checked" name="_multi_remove[' + fieldId + ']" id="_multi_remove[' + fieldId + ']" style="margin-top: 5px;" onClick="fieldHandler(\'' + fieldId + '\',\'\',\'\',\'remove\')"/>';
	
	tempObject.appendChild(newNode);
	
	if (multiContainerExists())
		return true;
	else
		return false;
}

function removeMultiContainer()
{
	if (!multiContainerIsEmpty())
		return false;
	
	try
	{
		tNode = document.getElementById(fieldId+"_multi_div");
		tNode.parentNode.removeChild(tNode);
	}
	catch(x)
	{
		return false;
	}
	
	return true;
}

/**
 * This function searches for the multi container
 */
function multiContainerExists()
{
	if (document.getElementById(fieldId + '_multi_div') == null)
		return false;
	else
		return true;
}

function multiContainerIsEmpty()
{
	if (!multiContainerExists())
		return false;

	multiDiv = document.getElementById(fieldId+"_multi_div");
	
	for (i = 0; i < multiDiv.childNodes.length; i++) 
	{
		tN = multiDiv.childNodes[i];
		
		if (tN.nodeType == 1 && tN.tagName.toLowerCase() == "input" && tN.type.toLowerCase() == "checkbox")
			return false;
	}

	return true;
}

function getMultiRemoveChecked()
{
	if (!multiContainerExists())
		return null;
	
	multiDiv = document.getElementById(fieldId+"_multi_div");
	
	tCNames = new Array();
	cNameCount = 0;
	
	for (i = 0; i < multiDiv.childNodes.length; i++) 
	{
		tN = multiDiv.childNodes[i];
		
		if (tN.nodeType == 1 && tN.tagName.toLowerCase() == "input" && tN.type.toLowerCase() == "checkbox" && tN.checked)
		{
			tCNames[cNameCount] = tN.id;
			cNameCount++;
		}
	}

	if (cNameCount > 0)
		return tCNames;
	
	return null;
}

function myAlert(message)
{
	temp = document.getElementById("ajax_error_output");
	
	if (temp != null) {
		temp.innerHTML = message;
	}
	
	alert(message);
}

function formatDate(dateString)
{
	year = dateString.substring(0,4);
	month = dateString.substring(5,7);
	day = dateString.substring(8,10);
	
	months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	
	newString = day + ' ' + months[Number(month)-1] + ' ' + year;
	
	return newString;
}

function formatTime(timeString)
{
	hour = timeString.substring(0,2);
	minute = timeString.substring(3,5);

	if (hour > 11)
		newString = "pm";
	else
		newString = "am";
	
	if (hour > 12)
		hour = Number(hour)-12;
	
	newString = hour + ":" + minute + newString;

	return newString;
}

/**
 * This will start the process for creating a calendar pop-up
 */
function initiateCalendarPopup(eventId)
{
	fieldId = eventId;
	
	if (calendarPopupExists(eventId) && calendarLocationUpdate(eventId))
	{
		return false;
	}
	
	url  = "https://"+document.domain+"/calendar/view.php?event_id=" + eventId + "&ajax=true";
	
	// Create the HTTPRequest
	req = generateRequest();
	
	//If the request is invalid, give an alert and return
	if (req == null)
	{
		return true;
	}

//alert(url);

	req.onreadystatechange = calendarReqChange;
	req.open("GET", url, true);
	req.send(null);

	return false;
}

/**
 * This is the event handler for the HTTP stream, when the stream updates it gets called
 */
function calendarReqChange()
{
	try {
		if (req.readyState == 4) {
//alert("current req.status="+req.status);
			if (req.status == 200) {
				XMLresponse  = req.responseXML.documentElement;
				fullEvent = XMLresponse.getElementsByTagName('event');
				funcStatus = XMLresponse.getElementsByTagName('status')[0].firstChild.data;
				detailString = "";
	
				if (funcStatus == '1' && calendarResponse(XMLresponse))
				{
					return;
				}
				else
				{
					window.location.replace("/calendar/view.php?event_id="+fieldId);
				}
			} else {
				window.location.replace("/calendar/view.php?event_id="+fieldId);
			}
		}
	} catch (x) {
		window.location.replace("/calendar/view.php?event_id="+fieldId);
	}
	
	
}

function calendarResponse(XMLresponse)
{
//	alert("we have a calendar response!");
	eventId = XMLresponse.getElementsByTagName('event_id')[0].firstChild.data;
	
	if (!calendarPopupAdd(eventId))
	{
//		alert("calendar popup not added!");
		window.location.replace("/calendar/view.php?event_id="+eventId);
	}
	
//	alert("calendar popup should exist");
	
	eventNode = document.getElementById("popup_container_"+eventId);
	eventShadow = document.getElementById("popup_shadow_"+eventId);
	
//	alert("eventNode.id = "+eventNode.id);
//	alert("eventShadow.id = "+eventShadow.id);
	
	html = "";
	
	eventTitle = XMLresponse.getElementsByTagName('title')[0].firstChild;
	calTitle = XMLresponse.getElementsByTagName('cal_title')[0].firstChild;
	eventDate = XMLresponse.getElementsByTagName('good_date')[0].firstChild;
	eventTime = XMLresponse.getElementsByTagName('good_time')[0].firstChild;
	eventDesc = XMLresponse.getElementsByTagName('description')[0].firstChild;
	eventLoca = XMLresponse.getElementsByTagName('location')[0].firstChild;
	eventSpon = XMLresponse.getElementsByTagName('sponsor_name')[0].firstChild;
	eventAdmn = XMLresponse.getElementsByTagName('admin')[0].firstChild;
	eventUrl  = XMLresponse.getElementsByTagName('url')[0].firstChild;
	
	html = html + '<DIV CLASS="popup_background" ID="popup_bg_'+eventId+'">';
	html = html + '<IMG SRC="/themes/default/images/popup/top.png" STYLE="width: 202px; height: 22px;">';
	html = html + '<IMG SRC="/themes/default/images/popup/center.png" STYLE="width: 202px;" ID="popup_bg_rs_' + eventId + '">';
	html = html + '<IMG SRC="/themes/default/images/popup/bottom.png" STYLE="width: 202px; height: 22px;">';
	html = html + '</DIV>';

	html = html + '<div class="popup_close" id="popup_close_'+eventId+'"><a href="javascript:calendarPopupClose(' + eventId + ')"><img src="/themes/default/images/popup/close.png" BORDER=0></a></div>';
	html = html + '<div class="popup_data" id="popup_data_' + eventId + '">';
	html = html + '<div class="popup_title">' + eventTitle.data + '</div>';
	html = html + '<table style="font-size: 8pt;">';
	//html = html + '<tr><td valign="top">Calendar:</td><td>' + calTitle.data + '</td></tr>';
	html = html + '<tr><td valign="top">Date:</td><td>' + eventDate.data + '</td></tr>';
	html = html + '<tr><td valign="top">Time:</td><td>' + eventTime.data + '</td></tr>';
	if (eventLoca != null && eventLoca.data != 0)
		html = html + '<tr><td valign="top">Location:</td><td>' + eventLoca.data + '</td></tr>';
	if (eventDesc != null)
		html = html + '<tr><td valign="top">Description:</td><td>' + eventDesc.data + '</td></tr>';
	if (eventSpon != null)
		html = html + '<tr><td valign="top">Sponsor:</td><td>' + eventSpon.data + '</td></tr>';
	html = html + '</table>';
	
	if (eventUrl != null)
		html = html + '<P CLASS="popup_link"><A HREF="' + eventUrl.data + '" TARGET="_blank">Event Link</A></P>';
	if (eventAdmn != null && eventAdmn.data == 'true')
		html = html + '<P CLASS="popup_link"><A HREF="/calendar/edit_event.php?event_id=' + eventId + '">Edit This Event</A></P>';
	html = html + '</div>';
	
	
	eventNode.innerHTML = html;
	
//	alert("eventNode.innerHTML = "+eventNode.innerHTML);
	
	document.getElementById('popup_bg_rs_'+eventId).style.height = (eventNode.offsetHeight-44) + "px";
	document.getElementById('popup_bg_rs_'+eventId).style.width = "202px";

	update = calendarLocationUpdate(eventId);
	
//	alert(eventNode.offsetHeight + "px");

	if (update)	
		update = calendarShadowUpdate(eventId);

	return update;
}

function calendarPopupExists(eventId)
{
	if (document.getElementById("popup_container_" + eventId) != null && document.getElementById("popup_shadow_" + eventId) != null)
		return true;
	else
		return false;
}

function calendarPopupAdd(eventId)
{
	if (!calendarPopupExists(eventId))
	{
		container = document.createElement('DIV');
		container.style.visibility = "hidden";
		document.body.appendChild(container);
		container.style.position = 'absolute';
		container.id = 'popup_container_'+eventId;
		container.style.width = "202px";
		
		shadow = document.createElement('DIV');
		shadow.style.visibility = "hidden";
		document.body.appendChild(shadow);
		shadow.style.position = 'absolute';
		shadow.id = 'popup_shadow_'+eventId;
		shadow.setAttribute("class","popup_shadow");
		shadow.className = "popup_shadow";
	}
	
	return calendarPopupExists(eventId);
}

function calendarLocationUpdate(eventId)
{
	eventParent = document.getElementById("event_link_"+eventId);
	eventNode = document.getElementById("popup_container_"+eventId);
	eventContainer = document.getElementById("calendar_month_view");
	
	if (eventNode != null && eventParent != null && eventContainer != null)
	{
		eventNode.style.visibility = "hidden";
		eventNode.style.zIndex = calendarZ++;
		
		document.getElementById("popup_close_"+eventId).style.zIndex = calendarZ++;
		
//		alert(document.getElementById("popup_background_"+eventId).style.zIndex);
//		alert(document.getElementById("popup_data_"+eventId).style.zIndex);
//		alert(document.getElementById("popup_close_"+eventId).style.zIndex);
		
		
		pL = eventParent.offsetLeft;
		pW = eventParent.offsetWidth;
		pT = eventParent.offsetTop;
		pH = eventParent.offsetHeight;
	
		while (eventParent.offsetParent != null)
		{
			eventParent = eventParent.offsetParent;
			
			pL = pL + eventParent.offsetLeft;
			pT = pT + eventParent.offsetTop;
		}
	
		eW = eventNode.offsetWidth;
		eH = eventNode.offsetHeight;

		cL = eventContainer.offsetLeft;
		cT = eventContainer.offsetTop;
		cW = eventContainer.offsetWidth;
		cH = eventContainer.offsetHeight;
		
		while (eventContainer.offsetParent != null)
		{
			eventContainer = eventContainer.offsetParent;
			
			cL = cL + eventContainer.offsetLeft;
			cT = cT + eventContainer.offsetTop;
		}

		if ((pL + pW + eW) < (cW + cL) && (pT - eH) > cT)
		{
			// To the right and above
			eventNode.style.left = (pL + pW) + "px";
			eventNode.style.top  = (pT - eH) + "px";
		}
		else if ((pL - eW) > cL && (pT - eH) > cT)
		{
			// To the left and above
			eventNode.style.left = (pL - eW) + "px";
			eventNode.style.top  = (pT - eH) + "px";
		}
		else if ((pL + pW + eW) < (cW + cL) && (pT + pH + eH) < (cT + cH))
		{
			// To the bottom right
			eventNode.style.left = (pL + pW) + "px";
			eventNode.style.top  = (pT + pH) + "px";
		}
		else if ((pL - eW) > cL && (pT + pH + eH) < (cT + cH))
		{
			// To the bottom left
			eventNode.style.left = (pL - eW) + "px";
			eventNode.style.top  = (pT + pH) + "px";
		}
		else
		{
			return false;
		}
		eventNode.style.visibility = "visible";
		return true;
		
	}

	return false;
}

function calendarShadowUpdate(eventId)
{
	
	try {
		eventNode  = document.getElementById("popup_container_"+eventId)
		shadowNode = document.getElementById("popup_shadow_"+eventId)
		
		baseHeight = Math.floor(eventNode.offsetHeight/2);
		baseNum = Math.floor((baseHeight-30)/5);
		
		shadowNode.style.width = ((baseNum * 2) + 210) + 'px';
		shadowNode.style.height = baseHeight + 'px';
		
		shadowNode.style.top = (eventNode.offsetTop + baseHeight + 50) + 'px';
		shadowNode.style.left = (eventNode.offsetLeft + 50) + 'px';
	
		html = "";
		
		html = html + '<IMG SRC="/themes/default/images/popup/3d_top.png" STYLE="position: relative; left: '+(baseNum * 2)+'px; width: 210px; height: 14px;">';
		for (i = 0; i < baseNum; i++)
			html = html + '<IMG SRC="/themes/default/images/popup/3d_center.png" STYLE="position: relative; left: '+((baseNum - i-1) * 2)+'px; width: 209px; height: 5px;">';
		
		html = html + '<IMG SRC="/themes/default/images/popup/3d_bottom.png" STYLE="position: relative; left: 0px; width: 208px; height: 16px;">';
		
		shadowNode.innerHTML = html;
		shadowNode.style.visibility = "visible";
		
	} catch (x) {
		alert("There was an exception while updating the shadow");
		alert(x);
		return false;
	}
	
	return true;
}

function calendarPopupClose(eventId)
{
	eventNode = document.getElementById("popup_container_" + eventId);
	shadowNode = document.getElementById("popup_shadow_" + eventId);
	
	if (eventNode != null)
	{
		eventNode.parentNode.removeChild(eventNode);
	}
	
	if (shadowNode != null)
	{
		shadowNode.parentNode.removeChild(shadowNode);
	}
}
