function elementPosition(which)
{
	var left = 0;
	var top = 0;
	var par = which;

	while( par.parentNode )
	{
		left += par.offsetLeft ? par.offsetLeft : 0;
		top += par.offsetTop ? par.offsetTop : 0;
		par = par.parentNode;
	}

	var pos = [left, top];
	return pos;
}

function openDocumentationWindow(url)
{
	var attributes = "left=20,top=20,width=300,height=250,toolbar=0";
	window.open(url, 'documentation', attributes);
}

function checkCalendarOnly()
{
	document.getElementById('calendar_only').checked='true';
}

function uncheckCalendarOnly()
{
	document.getElementById('calendar_only').checked='false';
}

function hideMeetingFields()
{
	document.getElementById('meetingtopictext').innerHTML='Event Name';
	document.getElementById('eventoptionaltext').innerHTML='Below fields are optional';
	document.getElementById('calendar_only').style.display='none';
	document.getElementById('calendar_only_text').style.display='none';
	document.getElementById('meetingagenda').style.display='none';
	document.getElementById('agenda').value='Plain Event';
	document.getElementById('meetingcomments').style.display='';
	document.getElementById('commentstext').innerHTML='Event Description';
	document.getElementById('comments').value='';
}

function showMeetingFields()
{
	document.getElementById('calendar_only').checked='';
	document.getElementById('meetingtopictext').innerHTML='Meeting Topic';
	document.getElementById('eventoptionaltext').innerHTML='';
	document.getElementById('calendar_only').style.display='none';
	document.getElementById('calendar_only_text').style.display='none';
	document.getElementById('meetingagenda').style.display='';
	document.getElementById('agenda').value='';
	document.getElementById('meetingcomments').style.display='';
	document.getElementById('commentstext').innerHTML='Comments';
	document.getElementById('comments').value='';
}

function showHand(obj)
{
	obj.style.cursor='pointer';
}

function hideHand(obj)
{
	obj.style.cursor='';
}

function hideObject(obj)
{
	obj.style.display='none';
}

function showObject(obj, style)
{
	if ( isset(style)) obj.style.display='';
	else obj.style.display=style;
}

function showHideObject(obj, style)
{
	if (obj.style.display=='none')
	{
		showObject(obj, style);
	}
	
	else
	{
		hideObject(obj);
	}
}

function isset(varname){
  return(typeof(window[varname])!='undefined');
}

function swapPlusMinus(obj)
{
	if (obj.src=="http://thekiva.org/sandbox/images2/minus.gif")
	{
		obj.src="http://thekiva.org/sandbox/images2/plus.gif";
	}
	
	else
	{
		obj.src="http://thekiva.org/sandbox/images2/minus.gif";
	}
}

function navigateTo(place)
{
	window.location=place;
}

function Quote(e, element, poster, text)
{
	
	var quote = "<>" + poster + " said:\n";
	var re1 = new RegExp('\r&gt;&gt;', 'gi');
	var re2 = new RegExp('\n&gt;&gt;', 'gi');
	
	//to get rid of images in quoting and thwart broken image tag in ie
	while((text.indexOf("<<<") != -1) && (text.indexOf(">>>",(text.indexOf("<<<") != -1))))
	{

		var left = text.indexOf("<<<");

		var right = text.indexOf(">>>",(text.indexOf("<<<")));
		
		var combo = text.substring(left+3,right);

		var inline = text.substring(left,right+3);
		
		var name = text.substring(text.indexOf(":",left)+1,right);

		text = text.replace(inline,"Image: " + name);
	}
	
	text = text.replace(re1, ">>");
	text = text.replace(re2, ">>");
	
	re1 = new RegExp('\r', 'gi');
	re2 = new RegExp('\n', 'gi');
//	text = text.replace(re1, "\r>>");
	text = text.replace(re2, "\n>>");


	quote += ">>" + text + "\n\n";

	if( element.value.length > 0 )
		quote  = "\n\n" + quote;	

	resize_textarea(element, e);

	element.value += quote;
	element.focus();
}

function Inline(element, text)
{

	element.value += "<<<" + text + ">>>";;
	element.focus();
}


function Highlight(element)
{
	if( element.className != "select_on" )
		element.className = "highlight_on";
}

function UnHighlight(element)
{
	if( element.className != "select_on" )
		element.className = "select_off";
}

function Select(item, displayelement, formelement)
{
	if( displayelement.className != "select_on" )
	{
		displayelement.className = "select_on";
		var re = new RegExp(',' + item + ',', 'gi');
		formelement.value = formelement.value.replace(re, ",");

		if( formelement.value.substr(0, (item+',').length) == (item + ',') )
			formelement.value = formelement.value.substr((item+',').length, formelement.value.length);

		formelement.value = formelement.value + item + ",";
	}
	else
	{	
		displayelement.className = "highlight_on";
		var re = new RegExp(',' + item + ',', 'gi');
		formelement.value = formelement.value.replace(re, ",");

		if( formelement.value.substr(0, (item+',').length) == (item + ',') )
			formelement.value = formelement.value.substr((item+',').length, formelement.value.length);
	}
}

function togglePublic()
{
	/*
	if( document.getElementById("private").className == "select_on" )
	{ 
		var element = document.getElementById("private");
		element.className = "select_off";
		Check(element);
	}
	*/
	document.getElementById("people").style.display = "none";
	
	if( document.getElementById("public").className == "select_on" )
		document.getElementById("groups").style.display = "none";
	else
		document.getElementById("groups").style.display = "inline";


	document.getElementById("closepopup").style.display = "none";
	document.getElementById("closepopup").style.display = "";
}
/*
function togglePrivate()
{
	if( document.getElementById("public").className == "select_on" )
	{ 
		var element = document.getElementById("public");
		element.className = "select_off";
		Check(element);
	}

	document.getElementById("groups").style.display = "none";

	if( document.getElementById("private").className == "select_on" )
		document.getElementById("people").style.display = "none";
	else
		document.getElementById("people").style.display = "inline";

	document.getElementById("closepopup").style.display = "none";
	document.getElementById("closepopup").style.display = "";

}
*/
function turnOff(element)
{

	if( element.className == "select_on" )
	{
		element.className = "select_off";
		Check(element);
	}

}

function lightUp(element)
{

	if( element.className == "select_on" )
	{
		element.className = "select_off";
	} 
	else 
	{
		element.className = "select_on";
	}

}

function changeSelectRecipients(recipient)
{
	var recipients = document.quickposter.isprivate.value == "1," ? document.quickposter.recipients_user_names.value : document.quickposter.recipients_group_names.value;

	if( recipient != "" )
	{
		var re = new RegExp(recipient + '', 'gi');

		if( recipients.match(re) )
		{
			recipients = recipients.replace(re, "");
			re = new RegExp(', ,', 'gi');
			recipients = recipients.replace(re, "");
		}
		else if( recipients.length > 0 )
		{
			recipients = recipients + ", " + recipient;
		}
		else 
		{
			recipients = recipient;
		}

		if( recipients.substr(0, 2) == ", " )
			recipients = recipients.substr(2);
		if( recipients.substr(-2) == ", " )
			recipients = recipients.substr(0, recipients.length - 2);
	}

	if( recipients != "" && ((document.quickposter.isprivate.value == '1,' && document.quickposter.userids != '') || (document.quickposter.isprivate.value == '0,' && document.quickposter.groupids != '')) )
	{
		document.getElementById("select_recipients_text").innerHTML = recipients.substr(0, (Math.min(recipients.length, 50))) + "...";
	}
	else
	{
		document.getElementById("select_recipients_text").innerHTML = "Select recipients...";
	}
			

	document.quickposter.recipients_user_names.value = document.quickposter.isprivate.value == "1," ? recipients : document.quickposter.recipients_user_names.value;
	document.quickposter.recipients_group_names.value = document.quickposter.isprivate.value == "0," ? recipients : document.quickposter.recipients_group_names.value;
}

function changeSelectForms(type, form)
{
	var types = form.type_names.value;

	if( type != "" )
	{
		var re = new RegExp(type + '', 'gi');

		if( types.match(re) )
		{
			types = types.replace(re, "");
			re = new RegExp(', ,', 'gi');
			types = types.replace(re, "");
		}
		else if( types.length > 0 )
		{
			types = types + ", " + type;
		}
		else 
		{
			types = type;
		}

		if( types.substr(0, 2) == ", " )
			types = types.substr(2);
		if( types.substr(-2) == ", " )
			types = types.substr(0, types.length - 2);
	
	}

	if( types != '' && form.typeids.value != '')
	{
		document.getElementById("select_types_text").innerHTML = types.substr(0, (Math.min(types.length, 50))) + "...";
	}
	else
	{
		document.getElementById("select_types_text").innerHTML = "All forms...";
	}
	
	form.type_names.value = types;
}


function changeSelectGroups(group, form)
{
	var groups = form.group_names.value;

	if( group != "" )
	{
		var re = new RegExp(group + '', 'gi');

		if( groups.match(re) )
		{
			groups = groups.replace(re, "");
			re = new RegExp(', ,', 'gi');
			groups = groups.replace(re, "");
		}
		else if( groups.length > 0 )
		{
			groups = groups + ", " + group;
		}
		else 
		{
			groups = group;
		}

		if( groups.substr(0, 2) == ", " )
			groups = groups.substr(2);
		if( groups.substr(-2) == ", " )
			groups = groups.substr(0, groups.length - 2);
	
	}
		
	if( groups != '' && form.groupids.value != '' )
	{
		document.getElementById("select_groups_text").innerHTML = groups.substr(0, (Math.min(groups.length, 50))) + "...";
	}
	else
	{
		document.getElementById("select_groups_text").innerHTML = "All groups...";
	}
	
	form.group_names.value = groups;
}


function changeSelectPosters(poster, form)
{
	var posters = form.poster_names.value;

	if( poster != "" )
	{
		var re = new RegExp(poster + '', 'gi');

		if( posters.match(re) )
		{
			posters = posters.replace(re, "");
			re = new RegExp(', ,', 'gi');
			posters = posters.replace(re, "");
		}
		else if( posters.length > 0 )
		{
			posters = posters + ", " + poster;
		}
		else 
		{
			posters = poster;
		}

		if( posters.substr(0, 2) == ", " )
			posters = posters.substr(2);
		if( posters.substr(-2) == ", " )
			posters = posters.substr(0, posters.length - 2);
	
	}
		
	if( posters != '' && form.posterids.value != '' )
	{
		document.getElementById("select_posters_text").innerHTML = posters.substr(0, (Math.min(posters.length, 50))) + "...";
	}
	else
	{
		document.getElementById("select_posters_text").innerHTML = "Anyone...";
	}
	
	form.poster_names.value = posters;
}

function Check(element)
{
	if( element.innerHTML != "&nbsp;&nbsp;" )
	{
		element.innerHTML = "&nbsp;&nbsp;";
	}
	else
	{
		element.innerHTML = "X";	
	}
}

function toggleForm(newtype)
{
	form = document.quickposter;

	lasttype = document.getElementById("lasttype").value;

	HidePostForms();

	form.type_id.value = newtype;

	document.getElementById("public").style.display = "inline";
//	document.getElementById("groups").style.display = "inline";
	document.getElementById("public_label").style.display = "inline";
	//document.getElementById("private").style.display = "inline";
	//document.getElementById("private_label").style.display = "inline";

//	document.getElementById("select_recipients_arrow").style.display = "inline";
	document.getElementById("recipients").style.display = "block";
	document.getElementById("worklog_recipients").style.display = "none";

/*
	document.getElementById("barnformtabcornerwhite_1").style.display = "none";
	document.getElementById("barnformtabcornerwhite_2").style.display = "none";	
	document.getElementById("barnformtabcornerwhite_3").style.display = "none";	
	document.getElementById("barnformtabcornerwhite_4").style.display = "none";
	document.getElementById("barnformtabcornerblue_1").style.display = "none";
	document.getElementById("barnformtabcornerblue_2").style.display = "none";	
	document.getElementById("barnformtabcornerblue_3").style.display = "none";	
	document.getElementById("barnformtabcornerblue_4").style.display = "none";	
*/	

/*	if( newtype == 1 || newtype == 2 )
		document.getElementById("previewpost").style.display = "inline";
	else
		document.getElementById("previewpost").style.display = "none";
*/	

	if( newtype == 1 ) // discussion

	{
		document.getElementById("formtab_1").className = "tab_selected";
		document.getElementById("formtab_2").className = "tab";
		document.getElementById("formtab_3").className = "tab";

		document.getElementById("discussion_form").style.display = 'inline';
		if( lasttype == 2 && form.discussion.value != '' )
		{
			form.discussion.value = form.comments.value;
		}
	}
	else if( newtype == 2 ) // meeting
	{
		document.getElementById("formtab_1").className = "tab";
		document.getElementById("formtab_2").className = "tab_selected";
		document.getElementById("formtab_3").className = "tab";

		UpdateDayOfWeek(document.quickposter);

		document.getElementById("meeting_form").style.display = 'inline';	
		if( lasttype == 1 && form.comments.value != '' )
		{
			form.comments.value = form.discussion.value;
		}
		showMeetingFields();
	}
	else if( newtype == 3 ) // event
	{
		document.getElementById("formtab_1").className = "tab";
		document.getElementById("formtab_2").className = "tab";
		document.getElementById("formtab_3").className = "tab_selected";

		document.getElementById("meeting_form").style.display = 'inline';	
		hideMeetingFields();

//  <span onclick=\"toggleForm(2);checkCalendarOnly();hideMeetingFields();\" style=\"font-size: 10pt; text-decoration: underline;\" onmouseover=\"this.style.cursor='pointer'; this.style.textDecoration='none';\" onmouseout=\"this.style.cursor=''; this.style.textDecoration='underline';\">Create Event</span

		UpdateDayOfWeekW(document.quickposter);
	}
	document.getElementById("lasttype").value = newtype;
}

function HidePostForms()
{
	document.getElementById("discussion_form").style.display = 'none';
	document.getElementById("meeting_form").style.display = 'none';
	document.getElementById("worklog_form").style.display = 'none';
//	document.getElementById("action_form").style.display = 'none';
}

function updateDay(tag, form)
{
	
	//alert(tag);
	//alert(form);
	var weekdays=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); 
	var d = new Date(document.getElementById(tag+"year").options[document.getElementById(tag+"year").selectedIndex].value, document.getElementById(tag+"month").options[document.getElementById(tag+"month").selectedIndex].value-1, document.getElementById(tag+"day").options[document.getElementById(tag+"day").selectedIndex].value); 
	var dayname = d.getDay(); 
	document.getElementById(tag+"dayofweek").innerHTML = weekdays[dayname] + ", ";
}


function UpdateDayOfWeek(form) 
{ 
	var weekdays=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); 
	var d = new Date(form.year.options[form.year.selectedIndex].value, form.month.options[form.month.selectedIndex].value-1, form.day.options[form.day.selectedIndex].value); 
	var day = d.getDay(); 
	document.getElementById('dayofweek').innerHTML = weekdays[day] + ", "; 
}

function UpdateDayOfWeekW(form) 
{ 
	var weekdays=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); 
	var d = new Date(form.wyear.options[form.wyear.selectedIndex].value, form.wmonth.options[form.wmonth.selectedIndex].value-1, form.wday.options[form.wday.selectedIndex].value); 
	var day = d.getDay(); 
	document.getElementById('wdayofweek').innerHTML = weekdays[day] + ", "; 
}

function UpdateDayOfWeekA(form) 
{ 
	var weekdays=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); 
	var d = new Date(form.ayear.options[form.ayear.selectedIndex].value, form.amonth.options[form.amonth.selectedIndex].value-1, form.aday.options[form.aday.selectedIndex].value); 
	var day = d.getDay(); 
	document.getElementById('adayofweek').innerHTML = weekdays[day] + ", "; 
}

function getFileNameFromPath(path)
{
	var i = path.lastIndexOf("\\");
	if( i >= 0 )
		path = path.substring(i+1, path.length);

	i = path.lastIndexOf("/");
	if( i >= 0 )
		path = path.substring(i+1, path.length);
	
	return path;
}


function AddFileChooser(container, counter)
{
	var count = eval(counter.value) + 1;
	counter.value = count;

	var widget = "<br /><table><tr><td valign='top'><input type='file' name='file_" + count + "' class='file' onchange='var name = getFileNameFromPath(this.value); document.getElementById(\"file_confirm_" + count + "\").innerHTML = name + \" will be uploaded.\"; document.getElementById(\"file_name_" + count + "\").value = name;'/></td><td valign='top'><span id='file_confirm_" + count + "' class='exciting'></span><input type='hidden' id='file_name_"+count+"' name='file_name_"+ count + "'/></td></tr></table>";

	var nextSpan = "<br /><span id='filecontainer_" + (eval(counter.value)+1) + "'></span>";

	container.innerHTML = container.innerHTML + widget + nextSpan;
}


function AddLinkMaker(container, counter)
{
	var count = eval(counter.value) + 1;
	counter.value = count;

	var widget = "<br /><input type='text' name='link_url_" + count + "' value='URL' onclick='this.value=\"\";' />";
	widget += "<input type='text' name='link_title_" + count + "' value='Link Title' onclick='this.value=\"\";' />";
	widget += "";	

	var nextSpan = "<br /><span id='linkcontainer_" + (eval(counter.value)+1) + "'></span>";

	container.innerHTML = container.innerHTML + widget + nextSpan;
}

//function that allows a user to select a picture, which is then uploaded 
// and inserted inline into the post for display upon viewing
function AddPicPoster(container, counter)
{
	var count = eval(counter.value) + 1;
	counter.value = count;
	
	var widget = "<br /><table><tr><td valign='top'><input type='file' name='file_" + count + "' class='file' onchange='if(isImage(this.value)) {var name = getFileNameFromPath(this.value); document.getElementById(\"file_confirm_" + count + "\").innerHTML = name + \" will be uploaded and posted.\"; document.getElementById(\"file_name_" + count + "\").value = name; Inline(document.quickposter.discussion, getFileNameFromPath(this.value)); document.quickposter.images.value += (this.value+\";\");}' /></td><td valign='top'><span id='file_confirm_" + count + "' class='exciting'></span><input type='hidden' id='file_name_"+count+"' name='file_name_"+ count + "'/></td></tr></table>";
	
	var nextSpan = "<br /><span id='filecontainer_" + (eval(counter.value)+1) + "'></span>";
	container.innerHTML = container.innerHTML + widget + nextSpan;
	
}

//checks if the file has the extension of a common image file
//can firefox etc display tiffs?  Hmmm, might have to take that one out
function isImage(location) {
	
	var name = getFileNameFromPath(location);

	var extension = (name.substring(name.lastIndexOf("."),name.length)).toLowerCase();
												
	if(extension == ".jpg" || extension == ".png" || extension == ".gif" || extension == ".jpeg" || extension == ".bmp")
		return true;
	else 
		return confirm("The file you selected does not appear to be an image that can be displayed in a web browser.\nDo you still want to try to display it inline?");
}

function ToggleVisibleDiv(divid)
{
	var element = document.getElementById(divid);

	if( element.style.display == 'inline' )
		element.style.display = 'none';
	else
		element.style.display = 'inline';
}

function toggleVisibility(element)
{
      if( element.style.display == 'none' )
              element.style.display = 'inline';
      else
              element.style.display = 'none';
}

// ********************************
// application-specific functions *
// ********************************


// Usage:
// Add in the top of the body:
//
// <div onclick="event.cancelBubble = true;" class="infobox" id="nameOfPopup">
// Example popup.
// </div>
// 
// To request the popup:
//
// <a href="#" onMouseOut="hideCurrentPopup();"
// onMouseOver="showPopup('nameOfPopup', event);">Popup</a>

// store variables to control where the popup will appear relative to the cursor position
// positive numbers are below and to the right of the cursor, negative numbers are above and to the left
var xOffset = 5;
var yOffset = 5;

function showPopup (targetObjectId, eventObj) {
    if(eventObj) {
	// hide any currently-visible popups
	hideCurrentPopup();
	// stop event from bubbling up any farther
	eventObj.cancelBubble = true;
	// move popup div to current cursor position 
	// (add scrollTop to account for scrolling for IE)
	//changes by jaz
	var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
	var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);
	//var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
	//var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);

	
	moveObject(targetObjectId, newXCoordinate, newYCoordinate);
	// and make it visible
	if( changeObjectVisibility(targetObjectId, 'visible') ) {
	    // if we successfully showed the popup
	    // store its Id on a globally-accessible object
	    window.currentlyVisiblePopup = targetObjectId;
	    return true;
	} else {
	    // we couldn't show the popup, boo hoo!
	    return false;
	}
    } else {
	// there was no event object, so we won't be able to position anything, so give up
	return false;
    }
} // showPopup

function hideCurrentPopup() {
    // note: we've stored the currently-visible popup on the global object window.currentlyVisiblePopup
    if(window.currentlyVisiblePopup) {
	changeObjectVisibility(window.currentlyVisiblePopup, 'hidden');
	window.currentlyVisiblePopup = false;
    }
} // hideCurrentPopup


// ************************
// layer utility routines *
// ************************

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
        // W3C DOM
        return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
        // MSIE 4 DOM
        return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
        // NN 4 DOM.. note: this won't find nested layers
        return document.layers[objectId];
    } else {
        return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	    if(newVisibility == 'visible')
			newDisplay = "block";
		else
			newDisplay = "none";

		styleObject.display = newDisplay;
        styleObject.visibility = newVisibility;
        return true;
    } else {
        // we couldn't find the object, so we can't change its visibility
        return false;
    }
} // changeObjectVisibility

function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
        styleObject.left = newXCoordinate;
        styleObject.top = newYCoordinate;
        return true;
    } else {
        // we couldn't find the object, so we can't very well move it
        return false;
    }
} // moveObject

function toggleSelectBoxVisibility(elementid, eventObj)
{
      var element = document.getElementById(elementid);
      if( element.style.visibility == '' || element.style.visibility == 'hidden' )
              showPopup(elementid, eventObj);
      else
             hideCurrentPopup();
}


function validateWorklogEntry()
{
	if( document.worklog.hours.value == "0" && document.worklog.mins.value == "00" )
	{
		alert("You must enter a real time increment.");
		return false;
	}
	if( document.worklog.category_id.value == "" )
	{
		alert("You must select a category for this entry.");
		return false;
	}
	if( document.worklog.details.value == "" )
	{
		alert("You must enter the details of how you spent your time.");
		return false;
	}
	return true;
}


function validateReplyPrivate()
{
	if( document.quickposter.isprivate.value == "" )
	{
		alert("You must select recipients before you post.");
		return false;
	}
	else if( document.quickposter.userids.value == "" )
	{
		alert("You must select recipients before you post.");
		return false;
	}

	if( document.quickposter.discussion.value == "" )
	{
		alert("You must enter a body to your message.");
		return false;
	}

	if( document.quickposter.subject.value == "" )
	{
		alert("You must enter a subject for your message.");
		return false;
	}

	return true;
}

function validateReply()
{
	if( document.quickposter.discussion.value == "" )
	{
		alert("You must enter a body to your reply.");
		return false;
	}

	return true;
}



function validateQuickPost()
{
	//WE NO LONGER HAVE PRIVATE POSTS. THE FOLLOWING IS TOTALLY BUNK.
	
	/*
	if( document.quickposter.type_id.value == 2 && document.quickposter.isprivate.value == "1," )
	{
		alert("Meetings must be posted to groups, not individuals.");
		return false;
	}
	*/

	if( document.quickposter.type_id.value == 1 )
		return validateDiscussionTopic();
	else if( document.quickposter.type_id.value == 2 )
		return validateMeetingTopic(true);
	else if( document.quickposter.type_id.value == 3 )
		return validateMeetingTopic(false);
}


function validateDiscussionTopic()
{
	var form = document.quickposter;

	if( form.isprivate.value == "" || (form.isprivate.value == "1," && form.userids.value == "" ) || (form.isprivate.value == "0," && form.groupids.value == "") )
	{
		alert("You must select recipients before you post.");
		return false;
	}

	if( form.subjectDiscussion.value == "" )
	{
		alert("You must enter a topic.");
		return false;
	}

	if( form.discussion.value == "" )
	{
		alert("You must enter post contents.");
		return false;
	}
	return true;
}

function validateMeetingTopic(isMeeting)
{
	
	var meeting = isMeeting ? "meeting" : "event";
	var good_date = true;
	var year = document.quickposter.year.value;
	var month = document.quickposter.month.value;
	var day = document.quickposter.day.value;
	
	if( month == 2 )
	{
		if( year % 4 == 0 && day > 29 )
			good_date = false;
		else if( day > 28 )
			good_date = false;
	}
	else if( (month == 4 || month == 6 || month == 9 || month == 11) && day > 30 )
		good_date = false;
	
	if( !good_date )
	{
		alert("The date you entered is not valid.  Please enter a valid date.");
		return false;
	}
		
	
	var start_time_military;
	var end_time_military;
	//calculate start time in military time.
	//alert(parseInt(document.getElementById('start_hour').value));
	
	var startHour = parseInt(document.getElementById('start_hour').value);
	if(startHour == 12 && (document.quickposter.start_ampm.value == "am"))
	{
		startHour = 0000;
	}
	
	start_time_military = startHour * 100;
	start_time_military += parseInt(document.quickposter.start_mins.value);
	if (document.quickposter.start_ampm.value == "pm"  && start_time_military < 1200){
		//alert("starts in pm");
		start_time_military += 1200;
	}
	
	//calculate end time in military time.
	//alert(parseInt(document.getElementById('end_hour').value));
	
	var endHour = parseInt(document.getElementById('end_hour').value);
	if(endHour == 12 && (document.quickposter.end_ampm.value == "am"))
	{
		endHour = 0000;
	}
	
	end_time_military = endHour * 100;
	end_time_military += parseInt(document.quickposter.end_mins.value);
	if (document.quickposter.end_ampm.value == "pm" && end_time_military < 1200){
		//alert("ends in pm");
		end_time_military += 1200;
	}

	if( isMeeting )
	{
		if(start_time_military >= end_time_military){
			alert("This " + meeting + " does not start and end at valid times. \nPlease check your start and end times and try again.");
			return false;
		}
	}
	
	var form = document.quickposter;

	if( form.isprivate.value == "" || (form.isprivate.value == "1," && form.userids.value == "" ) || (form.isprivate.value == "0," && form.groupids.value == "") )
	{
		alert("You must select recipients before you post.");
		return false;
	}

	if( form.subjectMeeting.value == "" )
	{
		if( isMeeting )
			alert("You must enter a topic for this meeting.");
		else
			alert("You must enter a name for this event.");
		return false;
	}

	if( isMeeting && form.start_ampm.value == form.end_ampm.value && form.start_hour.value == form.end_hour.value && form.start_mins.value == form.end_mins.value )
	{
		alert("You must enter valid start and end times for the " + meeting + ".");
		return false;
	}

	if( isMeeting && form.location.value == "" )
	{
		alert("You must enter a location.");
		return false;
	}

	if( form.agenda.value == "" && isMeeting )
	{
		alert("You must enter an agenda.");
		return false;
	}
	return true;
}

function validateWorklogLineItem()
{
	if( document.quickposter.hours.value == "0" && document.quickposter.mins.value == "00" )
	{
		alert("You must enter a real time increment.");
		return false;
	}
	if( document.quickposter.category_id.value == "" )
	{
		alert("You must select a category for this entry.");
		return false;
	}
	if( document.quickposter.details.value == "" )
	{
		alert("You must enter the details of how you spent your time.");
		return false;
	}
	return true;
}

function validateActionPost()
{
	var form = document.quickposter;

	if( form.isprivate.value == "" || (form.isprivate.value == "1," && form.userids.value == "" ) )
	{
		alert("You must select recipients before you post.");
		return false;
	}

	if( form.todo.value == "" )
	{
		alert("You must enter a todo item.");
		return false;
	}

	if( form.priority_id.value == "" )
	{
		alert("You must enter a priority.");
		return false;
	}

	return true;
}


function resize_textarea(t, e)
{
	//pull some crazy BS to get a usable key event from IE and FF
	var	evt = (e) ? e : ((event) ? event : null);	
	
	//calculate the amount of text in the textarea
	var charCount = t.value.length+(t.cols*(t.value.split(/\n|\f/).length));

	//figure out how much room there actually is
	var maxChars = t.rows*t.cols;


	//if we hit enter, just extend the textarea by one row
	if(evt && evt.keyCode == 13)
	{
		t.rows+=1;
	}
	//if there is more text in the box than it can hold, expand it
	else if(charCount > maxChars)
	{
		//figure out how much overflow there is, and add enough rows to compensate
		//plus a couple of buffer rows
		t.rows += Math.ceil((charCount-maxChars)/t.cols)+2;
	}
	else if(charCount < maxChars)
	{
		//if the textarea has more rows than it needs
		//figure out how many we can take away, still leaving a buffer
		var fewer = Math.ceil(charCount/t.cols)+1;
		
		//don't make the box too small (ie. smaller than it typically will be)
		t.rows = (fewer < 7) ? 7 : fewer;
	}
}
/*
function resize_textarea(t)
{
     	agt=navigator.userAgent.toLowerCase(); 
	
      	a = t.value.split('\n');
      	b = 1;	
      	for( x = 0; x < a.length; x++ )
      	{
      		if( a[x].length >= t.cols) { b += Math.ceil(a[x].length/t.cols); }
      	}
      	b += a.length;

//	if (b > t.rows && agt.indexOf('opera') == -1) t.rows = b;

	if( agt.indexOf('opera') == -1 )
	{
		if( b > 7 ) 
			t.rows = b;
		else
			t.rows = 7;
	}
//	t.rows = b;
}
*/

function displayReplyView(post_id)
{
	var l = document.getElementById("replyleft" + post_id);
	var c = document.getElementById("replycenter" + post_id);
	var r = document.getElementById("replyright" + post_id);
	var plus = document.getElementById("replyViewTogglerPlus" + post_id);
	var minus = document.getElementById("replyViewTogglerMinus" + post_id);
	var text = document.getElementById("line" + post_id);
	
	
//	$("#replyleft" + post_id).toggle();
//	$("#replyright" + post_id).toggle();
//	$("#replycenter" + post_id).toggle();
 	
	l.style.display = "";
	c.style.display = "";
	r.style.display = "";

	minus.style.display = "inline";
	plus.style.display = "none";

	text.style.display = "none";

/*	var pos = elementPosition(l);
	window.scrollTo(0, pos[1] - 85);
	//alert(pos[1]);  */
}

function hideReplyView(post_id)
{
	var l = document.getElementById("replyleft" + post_id);
	var c = document.getElementById("replycenter" + post_id);
	var r = document.getElementById("replyright" + post_id);
	var plus = document.getElementById("replyViewTogglerPlus" + post_id);
	var minus = document.getElementById("replyViewTogglerMinus" + post_id);
	var text = document.getElementById("line" + post_id);
	//$("#replyleft" + post_id).toggle();
	//$("#replyright" + post_id).toggle();
	//$("#replycenter" + post_id).toggle();
	
		l.style.display = "none";
		c.style.display = "none";
		r.style.display = "none";

		minus.style.display = "none";
		plus.style.display = "inline";

		text.style.display = "inline";
}

function toggleReplyView(post_id)
{
	var l = document.getElementById("replyleft" + post_id);

	if( l.style.display == "none" )
	{
		displayReplyView(post_id);
	}
	else
	{
		hideReplyView(post_id);
	}
}


function spawnReplyPreview(url)
{
	var f = document.quickposter;
	
	var discussion = encodeURI(f.discussion.value);
	var filecounter = encodeURI(f.filecounter.value);
	var linkcounter = encodeURI(f.linkcounter.value);

	var query_string = "discussion=" + discussion + "&filecounter=" + filecounter + "&linkcounter=" + linkcounter;

	var dirs = (f.images.value).split(";")
	
	for( var i = 1; i <= filecounter; i++ )
	{
		for(var x=0;x < dirs.length; x++)
		{
			var filename = eval("f.file_" + i + ".value");
			if( filename != "" )
				if(getFileNameFromPath(filename) == getFileNameFromPath(dirs[x]))
					query_string += "&directory_" + i + "=" + dirs[x];
		}	
	}
	
	// cycle through files and links and append them to the query string
	for( var i = 1; i <= filecounter; i++ )
	{
		var filename = eval("f.file_" + i + ".value");
		if( filename != "" )
			query_string += "&file_" + i + "=" + encodeURI(getFileNameFromPath(filename));
	}
	for( var i = 1; i <= linkcounter; i++ )
	{
		var linktitle = eval("f.link_title_" + i + ".value");
		var linkurl = eval("f.link_url_" + i + ".value");
		if( !(linktitle == "Link Title" && linkurl == "URL") && linktitle != "" && linkurl != "" )
		{
			query_string += "&link_url_" + i + "=" + encodeURI(linkurl);
			query_string += "&link_title_" + i + "=" + encodeURI(linktitle);
		}
	}

	url = url + "?" + query_string;

	var features = "location=no,menubar=no,height=300,resizable=yes,scrollbars=yes";

	var win = window.open(url, "preview_reply", features);
	win.focus();
}



function spawnPostPreview(url)
{
	var f = document.quickposter;
	
	var type_id = f.type_id.value;
	var filecounter = encodeURI(f.filecounter.value);
	var linkcounter = encodeURI(f.linkcounter.value);

	var recipients = f.recipients_group_names.value;

	var query_string = "type_id=" + type_id + "&recipients=" + recipients + "&";
	
	
	if( type_id == 1 ) // discussion
	{
		var subjectDiscussion = encodeURI(f.subjectDiscussion.value);
		var discussion = encodeURI(f.discussion.value);
	
		query_string += "discussion=" + discussion + "&subjectDiscussion=" + subjectDiscussion + "&";
	}
	else if( type_id == 2 || type_id == 3 ) // meeting
	{
		var start_hour = f.start_hour.value;
		var start_mins = f.start_mins.value;
		var start_ampm = f.start_ampm.value;
		var end_hour = f.end_hour.value;
		var end_mins = f.end_mins.value;
		var end_ampm = f.end_ampm.value;
		var year = f.year.value;
		var month = f.month.value;
		var day = f.day.value;
		var subjectMeeting = encodeURI(f.subjectMeeting.value);
		var location = encodeURI(f.location.value);
		var agenda = encodeURI(f.agenda.value);
		var comments = encodeURI(f.comments.value);
		var calendar_only = f.calendar_only.checked ? 1 : 0;
		
		query_string += "start_hour=" + start_hour + "&start_mins=" + start_mins + "&start_ampm=" 
						+ start_ampm + "&end_hour=" + end_hour + "&end_mins=" + end_mins
						+ "&end_ampm=" + end_ampm + "&day=" + day + "&month=" + month 
						+ "&year=" + year + "&subjectMeeting=" + subjectMeeting 
						+ "&location=" + location + "&agenda=" + agenda + "&comments=" + comments 
						+ "&calendar_only=" + calendar_only + "&";
	}
	else // anything else--don't preview
	{
		return;
	}

	// cycle through files and links and append them to the query string
	query_string += "filecounter=" + filecounter + "&linkcounter=" + linkcounter;	
	for( var i = 1; i <= filecounter; i++ )
	{
		var filename = eval("f.file_" + i + ".value");
		if( filename != "" )
			query_string += "&file_" + i + "=" + encodeURI(getFileNameFromPath(filename));
	}
	for( var i = 1; i <= linkcounter; i++ )
	{
		var linktitle = eval("f.link_title_" + i + ".value");
		var linkurl = eval("f.link_url_" + i + ".value");
		if( !(linktitle == "Link Title" && linkurl == "URL") && linktitle != "" && linkurl != "" )
		{
			query_string += "&link_url_" + i + "=" + encodeURI(linkurl);
			query_string += "&link_title_" + i + "=" + encodeURI(linktitle);
		}
	}

	url = url + "?" + query_string;

	var features = "location=no,menubar=no,height=300,resizable=yes,scrollbars=yes";

	var win = window.open(url, "preview_post", features);
	win.focus();	
}



// Below are functions for determining the default content of the forms of a page
// as a means of determining if the user has made changes which would then be
// inadvertantly lost.  
var global, allClear, name;

//list of names of pages on which the script should not run.
//name = new Array("views","calendar","topic");
name = new Array("views","calendar","viewsMod","clusters","forgotpassword","emailContact");


//loops through forms on a page and saves the default values
function getDefaults() 
{
	var currForm, currEl;
	pageName = location.pathname;
	pageName = pageName.split("/").pop().split(".")[0];
	
	//if the page is one of the ones blacklisted, set clear to true and forget the rest of the function
	for (var x=0; x <name.length;x++) 
	{
		if (name[x] == pageName) 
		{
			allClear = true;
			return;
		}		
	}


	global = new Array();
	for (var x=0; x<document.forms.length; x++) 
	{
		currForm = document.forms[x];
		for (var y=0; y<currForm.elements.length; y++) 
		{
			currEl = currForm.elements[y];
			if((currEl.type == "text") || (currEl.type == "textarea"))
			{
				//alert(currEl.name + " and value is "+currEl.value);
				global[currEl.name]=currEl.value;
			}
		}
	}
	
	allClear = false;
}

//compares the current contents of the form to see if it is dirty, but only after confirming that the method by which the user is leaving the page would not preserve/submit the data.
function checkExit()
{
	var currForm, currEl, counter;
	counter = 0;
  	
	if(!allClear) 
	{

		for (var x=0; x<document.forms.length; x++) 
		{
			currForm = document.forms[x];
			for (var y=0; y<currForm.elements.length; y++) 
			{
				currEl = currForm.elements[y];
				if(((currEl.type == "text") || (currEl.type == "textarea")) && currEl.value != global[currEl.name])
				{
					return "You have entered information which will not be saved.";
				}
				counter++;
			}
		}
	}
	
	allClear = false;
}

//function called on legit submission of information to keep the error from firing on leaving a page
function confirmExit()
{
	allClear = true;
}

//function to format and make more readable the info 
//contained in ID tags dropped into the cluster create area
function cluster_info(tag)
{
	//alert(tag);
	
	if(tag.charAt(0) == "p")
		return "Post: " + tag.substring(tag.indexOf("*")+1,tag.length) + " Added to the cluster.";
	
	if(tag.charAt(0) == "f")
	{
		return "The File '" + tag.substring(tag.lastIndexOf("*")+1,tag.length) + "' Added to the cluster.";	
	}
	
	if(tag.charAt(0) == "l")
	{		
		return "The url '" + tag.substring(tag.lastIndexOf("*")+1,tag.length) + "' Added to the cluster.";	
		
	}
	
}



//TEMPORARY ADDITION BY JAZ FOR CALENDAR
function showInline (targetObjectId, eventObj) {
    if(eventObj) {
	// hide any currently-visible popups
	
	//hideCurrentPopup();
	
	// stop event from bubbling up any farther
	eventObj.cancelBubble = true;
	// move popup div to current cursor position 
	// (add scrollTop to account for scrolling for IE)
	//changes by jaz
	//var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
	//var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);
	//var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
	//var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);

	document.getElementById("dayInfo").style.display = '';
	//document.getElementById("dayInfo").style.display = targetObjectId;
	//document.getElementById(targetObjectId).style.display = '';
	
	//moveObject(targetObjectId, newXCoordinate, newYCoordinate);
	// and make it visible
	if( changeObjectVisibility(targetObjectId, 'visible') ) {
	    // if we successfully showed the popup
	    // store its Id on a globally-accessible object
	    window.currentlyVisiblePopup = targetObjectId;
	    return true;
	} else {
	    // we couldn't show the popup, boo hoo!
	    return false;
	}
    } else {
	// there was no event object, so we won't be able to position anything, so give up
	return false;
    }
} // showPopup



function showRow () {
    //if(eventObj) {
	// hide any currently-visible popups
	
	hideRow();
	
	document.getElementById("dayInfo").style.display = '';

} // showPopup



function hideRow (item) 
{
 	document.getElementById(item).style.display = 'none';
	
} 

var first_time = 0;

function displayInfo(week, day)
{
	if( navigator.appVersion.indexOf("MSIE") != -1 )
	{
		setTimeout("void();", 1000);  // IE sometimes hides the views on the right when clicking rapid-fire on the calendar
	}
	
	//alert (week + "\n" + day);
	if(day != null && day != "" && document.getElementById(day))
	{
		//alert("the thing id'd the day is there");
		
		if(document.getElementById(week).style.display == 'inline' && document.getElementById(day).style.display == 'inline')
		{
			
			document.getElementById(week).style.display = 'none';
			document.getElementById(day).style.display = 'none';
			first_time = 0;
			document.dirty_hack.dirty_hack_storage.value = "";
			return;
		}else if(first_time !=0){
			var temp_day = document.dirty_hack.dirty_hack_storage.value;
			document.getElementById(temp_day).style.display = 'none';
		}	
		document.getElementById(week).style.display = 'inline';
		document.getElementById(day).style.display = 'inline';
		document.dirty_hack.dirty_hack_storage.value = day;
		first_time++;
		confirmExit();
	}else{
		//alert ("the day id isn't there?");
		document.getElementById(week).style.display = 'inline';
	}
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
{
	for(var i=0; i<document.images.length; i++)
	{
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		{
			var imgID = (img.id) ? "id='" + img.id + "' " : "";
			var imgClass = (img.className) ? "class='" + img.className + "' " : "";
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";

			
			var imgStyle = "display:inline-block;" + img.style.cssText;
			if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
			var strNewHTML = "<div " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='crop'); \"></div>" 
			img.outerHTML = strNewHTML
		
			i = i-1
		}
	}
	window.attachEvent("onload", correctPNG);
}

function clientSideInclude(id, url) {
  var req = false;
//  alert(id + " " + url);
  // For Safari, Firefox, and other non-MS browsers
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch (e) {
      req = false;
    }
  } else if (window.ActiveXObject) {
    // For Internet Explorer on Windows
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        req = false;
      }
    }
  }
 var element = document.getElementById(id);
 if (!element) {
  alert("Bad id " + id +
   "passed to clientSideInclude." +
   "You need a div or span element " +
   "with this id in your page.");
  return;
 }
  if (req) {
    // Synchronous request, wait till we have it all
    req.open('GET', url, false);
    req.send(null);
    element.innerHTML = req.responseText;
  } else {
    element.innerHTML =
   "Sorry, your browser does not support " +
      "XMLHTTPRequest objects. This page requires " +
      "Internet Explorer 5 or better for Windows, " +
      "or Firefox for any system, or Safari. Other " +
      "compatible browsers may also exist.";
  }
}

function escapeQuote(str)
{
	while(str.indexOf("\"") != -1)
		str = str.replace("\"","\\\"");	
	
	return str;
}

function worklogPages(str){
	document.getElementById('changeStudentStatus').style.display = 'none'; 
	document.getElementById('uploadSyllabus').style.display = 'none';
	document.getElementById('uploadRoster').style.display = 'none';
	document.getElementById('createUser').style.display = 'none'; 
	document.getElementById('editWorklogCat').style.display = 'none';
	document.getElementById('editWorklogWeeks').style.display = 'none';
	document.getElementById(str).style.display = 'inline';
}

function worklogOnMouseOver(str)
{
	if (!document.styleSheets) return;
	var ss = document.styleSheets;
	if(ss[1].rules){
		var i = ss[1].rules.length;
		var clss = "#left_col .week_selector .worklogPeriod" + str;
		var rule ="background:#fff; cursor:pointer;";
		ss[1].removeRule(i-1);
		ss[1].addRule(clss, rule);
		return;
	}
	else{
		var i = ss[1].cssRules.length;
		var style = "#left_col .week_selector .worklogPeriod" + str + "{background:#fff; cursor:pointer; }";
		ss[1].insertRule(style, i);
	}
}

function worklogOnMouseOut(str)
{
	if (!document.styleSheets) return;
	var ss = document.styleSheets;
	//INTERNET EXPLORERERERE.R.
	if(ss[1].rules){
		var i = ss[1].rules.length;
		var clss = "#left_col .week_selector .worklogPeriod" + str;
		var rule ="background:#ccc;";
		ss[1].removeRule(i-1);
		ss[1].addRule(clss, rule);
		return;
	}
	else{
		var i = ss[1].cssRules.length;
		var style = "#left_col .week_selector .worklogPeriod" + str + "{background:#ccc; }";
		ss[1].insertRule(style, i);
	}
}
function facultyWorklogWeek(weekid){
	//wmonth$id, wyear$id, wday$id end start
	var begindate;
	var enddate;
	var start = "start";
	var enddateid = "end_date_" + weekid;
	var startdateid = "start_date_" + weekid;
	var enddayid = "wday" + weekid + "end";
	var startdayid = "wday" + weekid + "start";
	var endmonthid = "wmonth" + weekid + "end";
	var startmonthid = "wmonth" + weekid + "start";
	var endyearid = "wyear" + weekid + "end";
	var startyearid = "wyear" + weekid + "start";
	var sy = document.worklog_weeks.startyearid.options[document.worklog_weeks.startyearid.selectedIndex].value;
	var sm = form.worklog_weeks.startmonthid.selectedIndex;
	var sd = document.worklog_weeks.startdayid.selectedIndex;
	var ey = document.worklog_weeks.endyearid.selectedIndex;
	var em = document.worklog_weeks.endmonthid.selectedIndex;
	var ed = document.worklog_weeks.enddayid.selectedIndex;
	begindate =  sy + sm.value + sd.value;
	document.worklog_weeks.startdateid.value = begindate;
}



function getHTTPObject()
{
	var requester;
	try
	{
		 requester = new XMLHttpRequest();
	}
	catch (error)
	{
		try
		{
			requester = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (error)
		{

			try
			{
				requester = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (error)
			{
				
			   requester = false;
			}

		}
		

	}
	return requester;
}


var http;// = getHTTPObject();	
var action = "";
var redirect = "";
var dest = "";

function handleHttpResponse() {
	//alert(http.readyState);
	//alert(http.responseText);
	if (http.readyState == "4") {
		if(http.responseText != "")
		{
			var response = "<div>"+http.responseText+"</div>";
		}
		else
		{
			var response = "";
		}
		

		//alert("response \n"+response);
		//alert("destination \n"+dest);
		//alert("redirect \n"+redirect);
		if(response.indexOf("|") != -1)
		{
			//error message of some sort, no action taken
			//so we don't need to refresh the page in order to show the results
			//because nothing happened.
		 	redirect = "";
			//alert("in here");
			var temp = response.split("|");
			var msg = "";
			msg = msg.concat(temp[0],temp[1]);
			response = msg;
			displayResults(response);
		}

		if (redirect != "")
		{
			displayResults(response);
			if(redirect.indexOf(";") != -1)
			{
				
				var temp = redirect.split(";");
				redirect = "";			
				
				for(x = 0; x < temp.length; x++)
				{
					//alert(temp[x]);
					setTimeout(eval(temp[x]), 2000);
				}
				

			}
			else
			{
				var temp = redirect;
				redirect = "";
				//alert(temp);
				//showCV();
				eval(temp);				
			}
			//document.location = temp;
		}
		else
		{
			displayResults(response);
		}
  	}
}

function displayResults(response)
{
	if(dest != "")
	{
		var oldHTML = document.getElementById(dest).innerHTML;
		var newHTML = "";
		
		if(action == "append")
			newHTML = oldHTML + response;
		else if(action == "prepend")
			newHTML = response + oldHTML;
		else if(action == "replace")
			newHTML = response;
		
		document.getElementById(dest).innerHTML = newHTML;
	}
	
	var the_match = new RegExp('(?:<script.*?>)((\n|.)*?)(?:<\/script>)', 'img');
	var scripts = response.match(the_match);
	if(scripts != null)
	{
		var new_match = new RegExp('(?:<script.*?>)((\n|.)*?)(?:<\/script>)', 'im');
		
		for (var i = 0; i < scripts.length; i++)
		{
			var tmp = scripts[i].match(new_match)[1];
			eval(tmp);
		}
	}
}

function addToCluster(cluster_id, item_id, url)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=add&cid="+cluster_id+"&iid="+item_id, true);
	http.onreadystatechange = handleHttpResponse;
	//alert(http.onreadystatechange);
	if(item_id.indexOf("*") == -1)
	{
		redirect = "organizeClusters(true)";
	}	
	dest = "msg_space";
	action = "append";
	http.send(null);

}

function removeFromCluster(cluster_id, item_id, url)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=remove&cid="+cluster_id+"&iid="+item_id, true);
	http.onreadystatechange = handleHttpResponse;
	//alert(http.onreadystatechange);
	dest = "msg_space";

	if(item_id.indexOf("*") != -1)
	{
		redirect = "displayContents("+cluster_id+",true)";		
	}
	else
	{
		redirect = "displayContents("+cluster_id+",false)";		
	}
	http.send(null);


}

function renameCluster(cluster_id, name, url)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=rename&cid="+cluster_id+"&name="+name, true);
	http.onreadystatechange = handleHttpResponse;
	dest = "msg_space";
	redirect = "displayContents("+cluster_id+",true)";
	http.send(null);

}


function SpawnRename(cid, url)
{
	if(!document.getElementById("new_name"))
	{
		document.getElementById("rename_box").innerHTML = " <input type='text' class='text' id='new_name' size='15' /> ";
		document.getElementById("rename").value = "Rename";
		
	}
	document.getElementById("rename").onClick = changeName(cid, url);
}

function changeName(cid, url)
{
	//alert("change name");
	if(document.getElementById("new_name").value != "")
	{
		var txt = document.getElementById("new_name").value;
		renameCluster(cid, txt, url);
	}
	confirmExit();
}

function topLevel(cid, newtop, url)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=top&cid="+cid+"&top="+newtop, true);
	http.onreadystatechange = handleHttpResponse;
	//alert(http.onreadystatechange);
	redirect = "displayContents("+cid+",true)";
	http.send(null);

}

function deleteCluster(cid, url, name)
{

	if(confirm("Deleting this cluster will remove this cluster from your cluster list permanantly.  You will also delete all subclusters contained within this cluster that are not found in any others. \n\n Are you sure you want to delete the cluster '" + name + "'?"))
	{
		http = getHTTPObject();	
		http.open("GET", "clusters2.php?action=delete&cid="+cid, true);
		http.onreadystatechange = handleHttpResponse;
		redirect = "showCV()";
		dest = "msg_space";
		//var id = document.getElementById("identification").value;
		http.send(null);
		document.getElementById("right_col").innerHTML = "";

	}
	else
	{
		return;
	}
}

function newCluster(url)
{
	if(!document.getElementById("name"))
	{
		document.getElementById("new_cluster").innerHTML = " <input type='text' class='text' id='name' size='15' /> ";
		document.getElementById("new_button").value = "Create";
		
	}
	document.getElementById("new_button").onClick = newName(url);
	confirmExit();
}

function newName(url)
{
	if(document.getElementById("name").value != "")
	{
		var txt = document.getElementById("name").value;
		dest = "msg_space";
		action = "replace";
		makeCluster(txt, url);

	}
	confirmExit();
}

function makeCluster(name, url)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=new&name="+name, true);
	http.onreadystatechange = handleHttpResponse;
	redirect = "showCV()";
	confirmExit();
	http.send(null);
	

}

function clusterizePost(post_id)
{
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=clusterize&pid="+post_id, true);
	http.onreadystatechange = handleHttpResponse;
	//alert(http.onreadystatechange);
	dest = "results_"+post_id;
	action = "replace";
	http.send(null);

}

function doStuff(form_name, post_id)
{
		dest = "results_"+post_id;
		var str = "";
		currForm = document.forms[form_name];
		for (var y=0; y<currForm.elements.length-1; y++) 
		{
			currEl = currForm.elements[y];
			if(currEl.checked == true)
			{
				if(str == "")
					str += currEl.name;
				else
					str += ";"+currEl.name;
			}
		}
		if(str == "")
		{
			alert("you did not select any items");
			//document.getElementById(post_id).innerHTML = "";
			return;
		}
		http = getHTTPObject();	
		http.open("GET", "clusters2.php?action=clusterize2&pid="+post_id+"&content="+str+"&form="+form_name, true);
		http.onreadystatechange = handleHttpResponse;
		//alert(http.onreadystatechange);
		action = "replace";
		http.send(null);
	
	
}

function finalize(post_id, form_name)
{
	var id = "hidden_"+post_id;
	//alert(post_id);
	//alert(id);
	
	var stuff = document.getElementById(id).value;
	
	//alert (stuff);
	dest = "results_"+post_id;
	var str = "";
	currForm = document.forms[form_name];
	for (var y=0; y<currForm.elements.length-1; y++) 
	{
		currEl = currForm.elements[y];
		if(currEl.checked == true)
		{
			if(str == "")
				str += currEl.name;
			else
				str += ";"+currEl.name;
		}
			
	}
	if(str == "")
	{
		alert("you did not select any items");
		//document.getElementById(post_id).innerHTML = "";
		return;
	}
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=finalize&cids="+str+"&content="+stuff, true);
	http.onreadystatechange = handleHttpResponse;
	//alert(http.onreadystatechange);
	action = "replace";
	http.send(null);

	
}	


function displayContents(id, redir)
{
	

	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=contents&cid="+id, true);
	http.onreadystatechange = handleHttpResponse;
	//alert("display contents of cluster "+ id + " redirecting "+redir);
	dest = "right_col";
	action = "replace";
	
	if(redir)
	{
		//alert("need to refresh CV");
		redirect = "showCV()";
	}
	//alert("calling display contents");
	confirmExit();
	http.send(null);

}


function contents(id)
{
	dest = "content_"+id;
	cluster_id = id.split("-").pop();
	http = getHTTPObject();	
	http.open("GET", "clusters2.php?action=synopsis&cid="+cluster_id, true);
	http.onreadystatechange = handleHttpResponse;
	redirect = "";
	action = "replace";
	http.send(null);
	
}

function organizeClusters(redir, second_interface)
{
	dest = "right_col";
	action = "replace";
	
	if(redir)
		redirect = "showCV();";

	http = getHTTPObject();	
	
	//second interface hacking
	if(!second_interface)
		http.open("GET", "clusters2.php?action=organize", true);
	else
		http.open("GET", "clusters2.php?action=organize2", true);
	
	http.onreadystatechange = handleHttpResponse;
	http.send(null);

}

function showCV()
{
	dest = "cv";
	action = "replace";
	//alert("showing clusterviewer");
	if(document.getElementById("identification_right") && document.getElementById("identification_right").value == "cluster_viewer")
	{
		redirect = "organizeClusters(false)";
	}
	
	http = getHTTPObject();		
	http.open("GET", "clusters2.php?action=cv", true);
	http.onreadystatechange = handleHttpResponse;	
	http.send(null);
}

function AddAudioFileBox()
{
	var div = document.getElementById("files");
	var sel = document.getElementById("kivaMemberSelect");
	
	var html = "<table><tr><td><div><input type='file' name='audio[]' size='40'/>";
	html += "</td><td></td>"+ sel.innerHTML +"</tr>";	
	html += "</table><div id='files'></div>";

	div.id = "";
	div.innerHTML = div.innerHTML + html;
	
}