
// GroundBooth Software, Inc.
// Copyright 2010.  All rights reserved.

// TODO: need to preload all our ajax images and icons..
var weburl = "http://www.groundbooth.com/";

img_male = new Image(200, 200);
img_male.src = weburl + "profiles/default_profile_pic_1.jpg";

img_female = new Image(200, 200);
img_female.src = weburl + "profiles/default_profile_pic_0.jpg";

img_male = new Image(20, 20);
img_male.src = weburl + "profiles/default_profile_thumb_1.jpg";

img_female = new Image(20, 20);
img_female.src = weburl + "profiles/default_profile_thumb_0.jpg";

//img_wait = new Image(48, 48);
//img_wait.src = weburl + "wait_tab.gif";
img_wait3 = new Image(16, 16);
img_wait3.src = weburl + "load_e033.gif";

img_wait = new Image(16, 16);
img_wait.src = weburl + "wait_F5F5F5.gif";

img_wait2 = new Image(16, 16);
img_wait2.src = weburl + "wait_16_ECECEC.gif";

img_add0 = new Image(11, 11);
img_add0.src = weburl + "add_0.gif";

img_add1 = new Image(11, 11);
img_add1.src = weburl + "add_1.gif";

img_add2 = new Image(11, 11);
img_add2.src = weburl + "add_2.gif";

img_shared= new Image(11, 11);
img_shared.src = weburl + "shared.gif";

img_config_0 = new Image(11, 11);
img_config_0.src = weburl + "config_0.gif";

img_config_1 = new Image(11, 11);
img_config_1.src = weburl + "config_1.gif";

img_config_2 = new Image(11, 11);
img_config_2.src = weburl + "config_2.gif";

img_hint_0 = new Image(11, 11);
img_hint_0.src = weburl + "hint_0.gif";

img_hint_1 = new Image(11, 11);
img_hint_1.src = weburl + "hint_1.gif";

img_favorite_0 = new Image(11, 11);
img_favorite_0.src = weburl + "favorite_0.gif";

img_favorite_1 = new Image(11, 11);
img_favorite_1.src = weburl + "favorite_1.gif";

img_favorite_2 = new Image(11, 11);
img_favorite_2.src = weburl + "favorite_2.gif";

img_lock_0 = new Image(23, 20);
img_lock_0.src = weburl + "lock_0.gif";

img_lock_1 = new Image(23, 20);
img_lock_1.src = weburl + "lock_1.gif";

img_bulb_0 = new Image(23, 20);
img_bulb_0.src = weburl + "bulb_0.gif";

img_bulb_1 = new Image(23, 20);
img_bulb_1.src = weburl + "bulb_1.gif";

img_toolbar_favorite_0 = new Image(16, 16);
img_toolbar_favorite_0.src = weburl + "toolbar_favorite_0.png";

img_toolbar_favorite_1 = new Image(16, 16);
img_toolbar_favorite_1.src = weburl + "toolbar_favorite_1.png";

img_toolbar_favorite_2 = new Image(16, 16);
img_toolbar_favorite_2.src = weburl + "toolbar_favorite_2.png";

img_postit_0 = new Image(16, 16);
img_postit_0.src = weburl + "postit_0.png";

img_postit_1 = new Image(16, 16);
img_postit_1.src = weburl + "postit_1.png";

img_postit_2 = new Image(16, 16);
img_postit_2.src = weburl + "postit_2.png";

img_postit_close = new Image(12, 12);
img_postit_close.src = weburl + "postit_close.gif";

docket_busy = new Image(80, 20);
docket_busy.src = weburl + "docket_bar_anim.gif";

docket_filter_busy = new Image(80, 20);
docket_filter_busy.src = weburl + "gray_busy_bar.gif";

notecard_0 = new Image(520, 375);
notecard_0.src = weburl + "notecard_0.jpg";

notecard_1 = new Image(520, 375);
notecard_1.src = weburl + "notecard_1.jpg";

img_tab_0 = new Image(105, 24);
img_tab_0.src = weburl + "tab_0.jpg";

img_tab_1 = new Image(105, 24);
img_tab_1.src = weburl + "tab_1.jpg";

prof_img_tab_0 = new Image(105, 24);
prof_img_tab_0.src = weburl + "prof_tab_0.jpg";

prof_img_tab_1 = new Image(105, 24);
prof_img_tab_1.src = weburl + "prof_tab_1.jpg";

img_chat_icon = new Image(38, 38);
img_chat_icon.src = weburl + "chat_icon.jpg";

img_small_chat_logo = new Image(38, 38);
img_small_chat_logo.src = weburl + "small_chat_logo.gif";

// docket icons

docket_icon_1_0 = new Image(11, 11);
docket_icon_1_0.src = weburl + "icon/docket/1_0.gif";

docket_icon_1_1 = new Image(11, 11);
docket_icon_1_1.src = weburl + "icon/docket/1_1.gif";

docket_icon_2_0 = new Image(11, 11);
docket_icon_2_0.src = weburl + "icon/docket/2_0.gif";

docket_icon_2_1 = new Image(11, 11);
docket_icon_2_1.src = weburl + "icon/docket/2_1.gif";

docket_icon_3_0 = new Image(11, 11);
docket_icon_3_0.src = weburl + "icon/docket/3_0.gif";

docket_icon_3_1 = new Image(11, 11);
docket_icon_3_1.src = weburl + "icon/docket/3_1.gif";

docket_icon_4_0 = new Image(11, 11);
docket_icon_4_0.src = weburl + "icon/docket/4_0.gif";

docket_icon_4_1 = new Image(11, 11);
docket_icon_4_1.src = weburl + "icon/docket/4_1.gif";

docket_icon_6_0 = new Image(11, 11);
docket_icon_6_0.src = weburl + "icon/docket/6_0.gif";

docket_icon_6_1 = new Image(11, 11);
docket_icon_6_1.src = weburl + "icon/docket/6_1.gif";

docket_icon_9_0 = new Image(11, 11);
docket_icon_9_0.src = weburl + "icon/docket/9_0.gif";

docket_icon_9_1 = new Image(11, 11);
docket_icon_9_1.src = weburl + "icon/docket/9_1.gif";



thumbs_up = new Image(11, 11);
thumbs_up.src = weburl + "icon/thumb.gif";

comment = new Image(11, 11);
comment.src = weburl + "icon/comment.gif";

chat_tab_0 = new Image(38, 84);
chat_tab_0.src = weburl + "chat_tab_0.gif";

chat_tab_1 = new Image(38, 84);
chat_tab_1.src = weburl + "chat_tab_1.gif";

gb_button = new Image(144, 23);
gb_button.src = weburl + "docket_button.png";

gb_button_hover = new Image(144, 23);
gb_button_hover.src = weburl + "docket_button_hover.png";

gb_button_click = new Image(144, 23);
gb_button_click.src = weburl + "docket_button_click.png";

gb_button_disabled = new Image(144, 23);
gb_button_disabled.src = weburl + "docket_button_disabled.png";


search_bar_bg = new Image(260, 32);
search_bar_bg.src = weburl + "search_gradient.png";

//////////////////////

i_d1 = new Image(20, 20);
i_d1.src = weburl + "icon/docket/d1.jpg";

i_d2 = new Image(20, 20);
i_d2.src = weburl + "icon/docket/d2.jpg";

i_d3 = new Image(20, 20);
i_d3.src = weburl + "icon/docket/d3.jpg";

i_d4 = new Image(20, 20);
i_d4.src = weburl + "icon/docket/d4.jpg";

i_d6 = new Image(20, 20);
i_d6.src = weburl + "icon/docket/d6.jpg";

i_d9 = new Image(20, 20);
i_d9.src = weburl + "icon/docket/d9.jpg";

cube_0 = new Image(26, 32);
cube_0.src = weburl + "cube_bw.png";

cube_1 = new Image(26, 32);
cube_1.src = weburl + "cube_color.png";


// we should only allow one config/admin/insert at a time
// so as to avoid issues related to subsequent data change
var curElementConfig = -1;
var curSectionConfig = -1;
var curInsertElement = "";
var curSectionConfig = -1;
var curDropping = -1;
var enrolledText = "Enrolled";
var nch = "No chat history.";
var card_pos = 0;
var flashcard_array = new Array();
var meteorChannels = new Array();
var error_log = "";
var show_after_load = "";

	(function($,sr){
	 
	  // debouncing function from John Hann
	  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
	  var debounce = function(func, threshold, execAsap) {
		  var timeout;
	   
		  return function debounced () {
			  var obj = this, args = arguments;
			  function delayed () {
				  if (!execAsap)
					  func.apply(obj, args);
				  timeout = null; 
			  };
	   
			  if (timeout)
				  clearTimeout(timeout);
			  else if (execAsap)
				  func.apply(obj, args);
	   
			  timeout = setTimeout(delayed, threshold || 100); 
		  };
	  };
	  
		// smartresize 
		jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
	 
	})(jQuery,'smartresize');


	function dropCreateStudyGroup()
	{
		if (top.location.href.indexOf(weburl+"dashboard/")!=-1)
		{
			undoDropMenus();
			if (get("addNewStudyGroup").style.display=="")
			{
				alert("You are currently adding a new study group.");
				return;
			}
			
			if (get("editStudyGroup").style.display=="")
			{
				alert("You are currently editing a study group.");
				return;
			}
			
			addNewStudyGroupForm();
			smoothScroll("addNewStudyGroup", -80);
		}
		else
		{
			top.location.href = weburl+"dashboard/?addsg#addsg";
		}
	}

	function gbButtonMouse(t, action)
	{
		if (t.className=="gbButtonDisabled")
		{
			return;
		}
		
		if (action=="up")
		{
			t.className = "gbButton";
			return;
		}
		
		if (action=="down")
		{
			t.className = "gbButtonDown";
			return;
		}
	}

	function gbAlert(msg)
	{
		alert(msg);
	}
	
	function gbConfirm(msg)
	{
		var c = confirm(msg);
		return c;
	}

	function typeAhead(e, type)
	{
		if (trim(type)=="")
		{
			alert("Bad search type.");
			return;
		}
						
		function _typeAhead(r)
		{
			session(r);
			//alert(r);
			get("search_drop_results_" + type).innerHTML = r;
			show("search_drop_results_" + type);
			return;
		}
		
		if (e.keyCode==27)
		{
			get("tb_menu_" + type + "_search").value = "";
		}
		
		var q = get("tb_menu_" + type + "_search").value;
		
		if (trim(q)=="")
		{
			hide("search_drop_results_" + type);
			get("search_drop_results_" + type).innerHTML = "";
			return;
		}
		if (false) //q.length<=2)
		{
			return;
		}
		
		var url = "typeAhead=1&type=" + type + "&q=" + q;
		if (type=="outline")
		{
			url += "&outline_id=" + get("loaded_outline_id").value;
			//alert(url);
		}
		
		//alert(url);		
		//get("search_drop_results").innerHTML = "Loading...";
		
		Aajax(weburl + "drops/search.php", url, _typeAhead);
	}

	function hTip(w, tip)
	{
		return " onmouseout=\"killHoverTip();\" onmouseover=\"hoverTip(this, " + w + ", '" + tip + "');\" ";
	}

	function flagDocketEntry(deid)
	{
		var f = get("docketEntryFlag_" + deid);
		var l = get("flag_link_" + deid);
		if (f.style.display=="")
		{
			hide(f.id);
			if (l!=null)
			{
				l.innerHTML = "Flag";
			}
		}
		else
		{
			show(f.id);
			if (l!=null)
			{
				l.innerHTML = "Unflag";
			}
		}
	}
	
	function deleteDocketEntry(deid, apti, api)
	{
		var cur_html = get("complete_docket_container_" + deid).innerHTML;
		function _deleteDocketEntry(r)
		{

			session(r);
			if (r=="toolong")
			{
				get("complete_docket_container_" + deid).innerHTML = cur_html;
				gbAlert("You can only delete posts that are less than a day old.");
				return;
			}
			
			
			// first handle possible response with panels...
			var resp_type = "";
			resp_type = r.substr(0, 9);
			if (resp_type=="-profile-" || resp_type=="-profess-") // right now only profiles and professor pages require updating of other panels
			{
				r = r.substr(9);
				// next we look for -- for the length of the panel chars
				pos = r.indexOf("--");
				var panel_len = Number(r.substr(0, pos));		
				var len_str_len = Number(String(panel_len).length);
				r = r.substr(len_str_len+2);
				// at this point we've stripped the length of the panel so all that's left is to rip the panel html
				var panel_html = r.substr(0, panel_len);
				r = r.substr(panel_len); // strip the panel html from the r so that we can update the docket as normal			
				get("bioPanel").innerHTML = panel_html;
				
			}
			
			
			pos = r.indexOf("ENDOFDOCKETINPUT");
			var docket_input_html = r.substr(0, pos);
			get("docket_input").innerHTML = docket_input_html;
			r = r.substring(pos+16);
			get("docket").innerHTML = r;
			get("docket_filter").value = "0";	
			get("docket_query").value = "Search Docket...";
			currently_posting = false;
			return;
		}
		var url = "deleteDocketEntry=1&deid=" + deid + "&apti=" + apti + "&api=" + api;
		//alert(url);		
		if (!confirm("Are you sure you want to delete this docket entry?"))
		{
			return;
		}
		get("complete_docket_container_" + deid).innerHTML = "Deleting...";
		Aajax(weburl+"docket.php", url, _deleteDocketEntry);
	}
	
	function actuallyFlagDocketEntry(deid)
	{

		var f = get("docketEntryFlag_" + deid);
		//var l = get("flag_link_" + deid);	
		var lc = get("flag_link_container_" + deid);
		var reason = get("docketEntryFlagReason_" + deid);
		var details = get("docketEntryFlagDetails_" + deid);
		
		function _actuallyFlagDocketEntry(r)
		{			
			session(r);
			//alert(r);
			var ht = hTip(100, "This docket entry has been flagged.");			
			lc.innerHTML = "<span>Flagged</span>";
			show("flagged_row_" + deid);
			flagDocketEntry(deid);
			//get("complete_docket_container_" + deid).className = "docketEntryFlagged";
			return;
		}
		
		if (Number(reason.value)==-1)
		{
			alert("You must select a reason for flagging this.");
			get("docketEntryFlagReason_" + deid).focus();
			return;
		}
		
		var c = confirm("Are you sure you want to flag this?");
		if (!c)
		{
			return;
		}
		reason.disabled = true;
		details.disabled = true;
		
		var url = "flagDocketEntry=1&entry_id=" + deid + "&reason=" + escape(reason.value) + "&details=" + escape(details.value);
		lc.style.color = "#ff0000";
		lc.innerHTML = "Flagging...";
				
		//alert(url);
		Aajax(weburl+"docket.php", url, _actuallyFlagDocketEntry);
	}

/*
	function dropEditStudyGroup(id)
	{
		//alert(top.location.href);
		if (top.location.href==weburl + "dashboard/")
		{
			editStudyGroupForm(id);
		}
	}
*/

	function tbHomeHover(torf)
	{
		var cube = get("home_icon");
		var ico = get("home_button_1");
		var btn = get("home_button_2");
		
		if (torf)
		{
			ico.style.backgroundImage = "url('" + weburl + "tb_highlight.png')";
			ico.style.backgroundRepeat = "repeat-x";
			
			btn.style.backgroundImage = "url('" + weburl + "tb_highlight.png')";
			btn.style.backgroundRepeat = "repeat-x";
			
			cube.src = weburl + "cube_color.png";
		}
		else
		{
			ico.style.backgroundImage = "";
			ico.style.backgroundRepeat = "repeat-x";
			
			btn.style.backgroundImage = "";
			btn.style.backgroundRepeat = "repeat-x";

			cube.src = weburl + "cube_bw.png";			
		}		
	}
	
	function undoDropMenus()
	{
		undoDropMenu("tb_menu_courses");
		undoDropMenu("tb_menu_professors");
		undoDropMenu("tb_menu_study_groups");
		undoDropMenu("tb_menu_sg");
		undoDropMenu("tb_menu_people");
		undoDropMenu("tb_menu_students");
		undoDropMenu("tb_menu_scoreboard");
		undoDropMenu("tb_menu_outline");
		undoDropMenu("tb_menu_outlines");
		undoDropMenu("tb_menu_marketplace");
		undoDropMenu("tb_menu_store");
		undoDropMenu("tb_menu_admin");
	}
	
	function undoDropMenu(id)
	{
		try
		{
			var btn = get(id);
			var drop = get(id + "_drop");
			var arrow = get(id + "_arrow");
					
			drop.style.display = "none";	
			arrow.style.backgroundImage = "";
			btn.style.backgroundImage = "";		
		}
		catch (ep38) {}
	}

	function dropTbMenu(id)
	{
		var btn = get(id);
		//alert(id);
		var drop = get(id + "_drop");
		var arrow = get(id + "_arrow");
				
		drop.style.left = findPosX(btn) + "px";
		
		function _dropTbMenu(r)
		{
			session(r);
			drop.innerHTML = r;
			// maybe we have a search box to focus
			//alert(id);// + " " + get("search_drop_" + id).value);
			
			var s = null;
			//alert(id);
			switch (id)
			{
				case "tb_menu_students":
					s = get("tb_menu_profiles_search");
					break;
				case "tb_menu_study_groups":
					s = get("tb_menu_studygroups_search");
					break;
				case "tb_menu_sg":
					s = get("tb_menu_studygroups_search");
					break;					
				case "tb_menu_professors":
					s = get("tb_menu_professors_search");
					break;
				case "tb_menu_courses":
					s = get("tb_menu_courses_search");
					break;
				case "tb_menu_outline":
					s = get("tb_menu_outline_search");
					break;
				case "tb_menu_outlines":
					s = get("tb_menu_outlines_search");
					break;
				case "tb_menu_people":
					s = get("tb_menu_profiles_search");
					break;					
			}
			
			
			if (s!=null)
			{
				s.focus();
			}
			return;
		}
		
		//alert(id);
		if (drop.style.display=="")
		{
			drop.style.display = "none";
			arrow.style.backgroundImage = "url('" + weburl + "tb_highlight.png')";
			btn.style.backgroundImage = "url('" + weburl + "tb_highlight.png')"
			
		}
		else
		{
			undoDropMenus();
			drop.style.display = "";	
			arrow.style.backgroundImage = "url('" + weburl + "tb_arrow_1.png')";
			btn.style.backgroundImage = "url('" + weburl + "tb_arrow_1.png')";
			drop.innerHTML = "<div style=\"padding:15px\">Loading...</div>";
			var url = "getDropHtml=" + id;
			if (id=="tb_menu_outline")
			{
				// also pass outline_id
				if (get("loaded_element_id")!=null)
				{
					url += "&loaded_outline_id=" + get("loaded_outline_id").value + "&loaded_element_id=" + get("loaded_element_id").value;
				}
				else
				{
					url += "&loaded_outline_id=" + get("loaded_outline_id").value;
				}
				//alert(url);
			}
			
			Aajax(weburl + "drops.php", url, _dropTbMenu);
		}
	}

	function tbhover(t, torf, id)
	{
		var btn = null;
		var arrow = null;
		var drop = null;
		var dropVisible = false;
		
		btn = get(id);
		arrow = get(id + "_arrow");
		drop = get(id + "_drop");
		
		if (drop!=null)
		{		
			dropVisible = drop.style.display=="" ? true : false;
		}
			
		if (torf)
		{
			if (!dropVisible)
			{
				btn.style.backgroundImage = "url('" + weburl + "tb_highlight.png')";
				btn.style.backgroundRepeat = "repeat-x";
			}
			if (arrow!=null && !dropVisible)
			{
				arrow.style.backgroundImage = "url('" + weburl + "tb_highlight.png')";
				arrow.style.backgroundRepeat = "repeat-x";				
			}
		}
		else
		{		
			if (!dropVisible)
			{	
				btn.style.backgroundImage = "";
				btn.style.backgroundRepeat = "repeat-x";
			}
			if (arrow!=null && !dropVisible)
			{
				arrow.style.backgroundImage = "";
				arrow.style.backgroundRepeat = "repeat-x";				
			}			
		}
	}
	
	function shareBoxClick(code, val)
	{
		get("text_" + code).blur();
		get("text_" + code).value=val;
	}
	
	function shareElement(seid)
	{
		function _shareElement(r)
		{
			session(r);
			//alert(r);
			cleanMe();
			if (Number(r)!=0)
			{
				show("shared_icon_" + seid);
			}
			else
			{
				hide("shared_icon_" + seid);
			}
			cloud(false);			
			return;
		}
		
		var sg_count = Number(get("share_sg_count_" + seid).value);
		var fr_count = Number(get("share_fr_count_" + seid).value);
		//alert(seid);
		var pub = get("share_pub_cb_" + seid).checked ? "1" : "0";
		
		var url = "";
		var sg_url = "";
		var fr_url = "";
		var sg_i = 0;
		var fr_i = 0;

		
		// loop sg first
		for (var i=0; i<sg_count; i++)
		{
			if (get("share_sg_cb_" + seid + "_" + i).checked)
			{
				sg_url += "&sg_" + sg_i + "=" + get("share_sg_" + seid + "_" + i).value;
				sg_i++;
			}
		}
	
		// loop fr second
		for (var i=0; i<fr_count; i++)
		{
			//alert(seid);
			if (get("share_fr_cb_" + seid + "_" + i).checked)
			{
				fr_url += "&fr_" + fr_i + "=" + get("share_fr_" + seid + "_" + i).value;
				fr_i++;
			}
		}		
		cloud(true);
		url = "updateShares=1&seid=" + seid + "&sg_count=" + sg_i + "&fr_count=" + fr_i + sg_url + fr_url + "&public=" + pub;
		//alert(url);		
		Aajax(weburl+"outline/ajax.php", url, _shareElement);
	}
	
	function switchCoursesTerms(t)
	{
		var term_id = t.value;
		function _switchCoursesTerms(r)
		{
			session(r);
			get("courseListHtml").innerHTML = r;
			cloud(false);
			return;
		}
		var url = "getCourseListForTerm=1&submitted_term_id=" + term_id;
		cloud(true);
		Aajax(weburl+"courses/index.php", url, _switchCoursesTerms);
	}
	
	function removeProfilePic(user_id, pic, sex)
	{
		var c = confirm("Are you sure you want to remove your profile pic?");
		if (!c)
		{
			return;
		}
		
		function _removeProfilePic(r)
		{
			var mf = pic.substr(20, 1);
			if (mf!=".")
			{
				get("profileThumb_" + user_id).src = weburl + "profiles/default_profile_thumb_" + mf + ".jpg";
				get("profilePic_" + user_id).src = weburl + "profiles/" + pic;
			}
			else
			{
				get("profileThumb_" + user_id).src = weburl + "profiles/default_profile_thumb_1.jpg";
				get("profilePic_" + user_id).src = weburl + "profiles/default_profile_pic_1.jpg";
			}
		
			get("add_pic").innerHTML = "Add Picture?";
			get("add_pic_link").innerHTML = "<a href=\"" + weburl + "profile/upload/\">Upload File</a>";
			return;
		}
		
		//cloud(true);
		get("add_pic").innerHTML = "Removing your pic...";
		var url = "removeProfilePic=1";
		Aajax(weburl+"profile/index.php", url, _removeProfilePic)
	}
	
	function hoverAddSg(torf)
	{
		if (torf)
		{
			get("add_sg_plus").src = weburl + "add_2.gif";			
		}
		else
		{
			get("add_sg_plus").src = weburl + "add_1.gif";
		}
	}

	function setAutoResize(ed)
	{   
		//Function to fix iframe to document height
		fitEditor = function(ed)
		{
			editorID = ed.id;
			var tble, frame, doc, docHeight, frameHeight;
			
			frame = document.getElementById(editorID+"_ifr");
			if ( frame != null )
			{
				//get the document object
				if (frame.contentDocument) doc = frame.contentDocument; 
				else if (frame.contentWindow) doc = frame.contentWindow.document; 
				else if (frame.document) doc = frame.document; 
				
				if ( doc == null )
				return;
				
				//prevent the scrollbar from showing
				doc.body.style.overflow = "hidden";
				
				//Fixes the issue of the table leaving empty space below iframe
				tble = frame.parentNode.parentNode.parentNode.parentNode;
				tble.style.height = 'auto';
				
				frameHeight = parseInt(frame.style.height);
				
				//Firefox
				if ( doc.height ) docHeight = doc.height;
				//MSIE
				else docHeight = parseInt(doc.body.scrollHeight);
				
				//MAKE BIGGER
				if ( docHeight > frameHeight ) frame.style.height = (docHeight + 20) + "px";
				//MAKE SMALLER
				else if ( docHeight < frameHeight ) frame.style.height = Math.max((docHeight + 20), 100) + "px";
			}
		};
		
		//add fitEditor function to tinyMCE events
		ed.onSetContent.add( fitEditor );
		ed.onChange.add( fitEditor );
		ed.onKeyPress.add( fitEditor );
		
	//Remaining bug: (Chrome and Opera) editor grows but doesn't shrink
	}

	
	function changeProfessorListSort()
	{
		var sort_method = get("professorListSortMethod").value;
		
		function _changeProfessorListSort(r)
		{
			session(r);
			get("profListHtml").innerHTML = r;
			//cloud(false);
			return;
		}
		
		//cloud(true);
		var url = "getSortedProfs=1&sort_method=" + sort_method;
		Aajax(weburl+"professors/index.php", url, _changeProfessorListSort);
	}
	
	function windowSize(what) {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	  }
	  
	  // modified from original script to allow return of h or w
	  if (what=="h")
	  {
		  return myHeight;
	  }
	  else
	  {
		  return myWidth;
	  }
	}	

	function resizeChatArea(type, h)
	{
		//alert(get(type + "_chat_text").style.height);
		if (get(type + "_chat_text")!=null)
		{
			get(type + "_chat_text").style.height = h + "px";
		}		
	}
	
	function resizeWindow()
	{
		/*
		// updates size of chat area
		var h = Number(windowSize("h"));
		var w = Number(windowSize("w"));
		var th = h - 268;

		var show_ad = false;
		if (!show_ad)
		{
			th = h - 200;
		}

		th = th < 50 ? 50 : th;		
				
		resizeChatArea("public", th);
		resizeChatArea("courses", th);
		resizeChatArea("studygroups", th);
		resizeChatArea("friends", th);
		
		// resize the list area too
		
		get("unread_chats").style.height = (th+78) + "px";
		
		if (get("idTextEditor_tbl")!=null)
		{
			var eh = h - 95;
			var ew = w - 13;
			ew = ew < 728 ? 728 : ew;
			get("idTextEditor_tbl").style.height = eh + "px";
			get("idTextEditor_ifr").style.height = eh + "px";
	
			get("idTextEditor_tbl").style.width = ew + "px";
			get("idTextEditor_ifr").style.width = ew + "px";
		}
		*/

	}
	

	function dirtyTab(type)
	{
		var type_name = "";
		
		switch(type)
		{
			case "courses":
				type_name = "courses";
				break;
			case "studygroups":
				type_name = "study groups";
				break;				
			case "friends":
				type_name = "friends";
				break;				
		}
		
		var h = Number(windowSize("h"));
		
		// dirties a tab and shows refresh button for that tab
		/*
		get("refresh_tab_name").innerHTML = type_name; // sets name in the html before we grab it
		var refresh_html = get("refreshTab").innerHTML;
		get(type + "_chat_tab").style.height = (h-100) + "px";
		get(type + "_chat_tab").innerHTML = refresh_html;
		*/
	}

	function refreshTabPage()
	{
		var url = cur_page;
		//alert(url);
		top.location.href=url;
	}

	function updateStudyGroupPanels(r)
	{
		//alert(r);
		// always get first char to see if we're to include invitations panel also
		var show_invitations = r.substr(0,1)=="Y" ? true : false;
		r = r.substring(1);
		//alert(show_invitations);
		
		var studyGroupDetails = getNextChunk(r, true);
		get("studyGroupDetails").innerHTML = studyGroupDetails["chunk"];
		r = studyGroupDetails["blob"];

		var studyGroupDetails2 = getNextChunk(r, true);
		try
		{
			get("studyGroupDetails2").innerHTML = studyGroupDetails2["chunk"];
		}
		catch(somee)
		{
		}
		r = studyGroupDetails2["blob"];		
						
		var memberList = getNextChunk(r, true);
		if (get("memberList")!=null)
		{
			get("memberList").innerHTML = memberList["chunk"];
		}
		r = memberList["blob"];		
		
		
		if (show_invitations)
		{
			var inviteList = getNextChunk(r, true);
			get("inviteList").innerHTML = inviteList["chunk"];
			r = inviteList["blob"];					
		}

	}

	function getNextChunk(r, asLen)
	{
		var resp = new Array();
		if (asLen)
		{
			var pos = r.indexOf("--");
			var count = Number(r.substr(0, pos));
			var r = r.substring(pos+2);
						
			var chunk = r.substr(0, count);
			var blob = r.substring(count);
						
			resp["chunk"] = chunk;
			resp["blob"] = blob;		
		}
		else
		{
			var pos = r.indexOf("--");
			var chunk = r.substr(0, pos);
			var blob = r.substring(pos+2);	
						
			resp["chunk"] = chunk;
			resp["blob"] = blob;	
		}
		
		return resp;		
	}


	function inviteToStudyGroup(user_id, sg_id)
	{
		function _inviteToStudyGroup(r)
		{
			session(r);
			updateStudyGroupPanels(r);
			cloud(false);	
			return;
		}
		
		cloud(true);
		var url = "inviteToStudyGroup=1&studygroups_id=" + sg_id + "&user_id=" + user_id;
		Aajax(weburl+"studygroups/index.php", url, _inviteToStudyGroup);
	}


	function removeMemberFromStudyGroup(sg_id, sgu_id)
	{
		
		var c = confirm("Are you sure you want to remove this member?");
		if (!c)
		{
			return;
		}

		function _removeMemberFromStudyGroup(r)
		{
			session(r);
			updateStudyGroupPanels(r);
			cloud(false);			
			return;
		}

		cloud(true);
			
		var url = "removeMemberFromStudyGroup=1&studygroups_id=" + sg_id + "&studygroup_users_id=" + sgu_id;
		Aajax(weburl+"studygroups/index.php", url, _removeMemberFromStudyGroup);
	}

	function cancelAnnouncementClick(course_id)
	{
		var c = confirm("This will dismiss any changes you've currently made to your announcement and revert to what was last saved.  Continue?");
		if (!c)
		{
			return;
		}
		changeProfTab('0', course_id);
	}

	function profSaveCoursePostings(course_id)
	{
		var postings = get("coursePostings_" + course_id).value;
		
		function _profSaveCoursePostings(r)
		{
			session(r);
			cloud(false);
			//alert(r);
			get("notifyStudents_" + course_id).checked = false;
			get("cancelAnnouncement_" + course_id).disabled = true;
			alert("The course posting has been saved.");			
			return;
		}
		cloud(true);
		var notifyStudents = get("notifyStudents_" + course_id).checked ? "1" : "0";
		var url = "updateCoursePostings=1&postings=" + postings + "&course_id=" + course_id + "&notifyStudents=" + notifyStudents;
		Aajax(weburl+"courses/index.php", url, _profSaveCoursePostings);
	}
	
	function joinViaPassword(sg_id)
	{
		var pw = get("join_password_" + sg_id).value;
		if (pw=="")
		{
			gbAlert("You must supply a password to join.");
			return;
		}
		
		//cloud(true);
		var h = harvest(null);
		h.add("joinViaPassword", "1");
		h.add("pw", pw); 
		h.add("studygroups_id", sg_id);
		ajax("sg", h.pJSON(), function(data)
		{			
			var r = pJSON(data);
			if (r.error)
			{
				gbAlert(r.error);
				return;
			}
			else
			{
				$("#studyGroupDetails").html(r.html);
			}
			
		});				
	}
		



	function respondStudyGroupInvite(sgu_id, action)
	{
		function _respondStudyGroupInvite(r)
		{
			session(r);
			
			if (r.substr(0,4)=="full")
			{				
				r = r.substring(4);
				var pos = r.indexOf("--");
				r = r.substring(pos+2);				
				if (r=="0notifications")
				{				
					hide("notificationList_row_1");
					hide("notificationList_row_2");
				}
				else
				{
					get("notificationsList").innerHTML = r;
				}	
				cloud(false);
				alert("You cannot join the group because it is full.");			
				return;
			}
			
			if (action=="accept")
			{
				dirtyTab("studygroups");
			}
			
			var notifications = getNextChunk(r, true);
			r = notifications["blob"];
			//alert(r);
			notifications = notifications["chunk"];
			//alert(notifications);
			
			// next thing streamed is the studygroup list
			var studygrouplist = getNextChunk(r, true);
			studygrouplist = studygrouplist["chunk"];
			//salert(studygrouplist);
			
			
			if (notifications=="0notifications")
			{				
				hide("notificationList_row_1");
				hide("notificationList_row_2");
				get("studygroupsList").innerHTML = studygrouplist;
			}
			else
			{
				get("notificationsList").innerHTML = notifications;
				get("studygroupsList").innerHTML = studygrouplist;
			}
			cloud(false);
			return;
		}
		cloud(true);
		var url = "respondStudyGroupsInvite=1&action=" + action + "&studygroup_users_id=" + sgu_id;
		Aajax(weburl+"dashboard/index.php", url, _respondStudyGroupInvite);
	}

	function respondStudyGroupRequest(sgu_id, action)
	{
		function _respondStudyGroupRequest(r)
		{
			session(r);
			if (r.substr(0,4)=="full")
			{
				r = r.substring(4);
				var pos = r.indexOf("--");
				r = r.substring(pos+2);				
				if (r=="0notifications")
				{				
					hide("notificationList_row_1");
					hide("notificationList_row_2");
				}
				else
				{
					get("notificationsList").innerHTML = r;
				}				
				cloud(false);
				alert("The study group is full.");
				return;
			}
			if (r=="0notifications")
			{
				//alert("Hiding all notifications");
				hide("notificationList_row_1");
				hide("notificationList_row_2");
			}
			else
			{
				get("notificationsList").innerHTML = r;
			}
			cloud(false);
			return;
		}
		cloud(true);
		var url = "respondStudyGroupsRequest=1&action=" + action + "&studygroup_users_id=" + sgu_id;
		Aajax(weburl+"dashboard/index.php", url, _respondStudyGroupRequest);
	}





	function colonLoop(c, fn)
	{
		c = (c.substring(c.length-1)!=":") ? c+":" : c;	// ensures colon at the end
		var i = 0;
		while (c.indexOf(":")>0)
		{
			var pos = c.indexOf(":");
			var x = c.substr(0, pos);
			fn(x);
			c = c.substring(pos+1);
			i++;
		}
	}

	function toggleFieldShow(t, c)
	{
		if (t.checked)
		{
			colonLoop(c, function(x)
							{
								show(x);
							});
		}
		else
		{
			colonLoop(c, function(x)
							{
								hide(x);
							});
		}
	}

	function meteorDisconnect()
	{
		var i = 0;
		while (i < meteorChannels.length)
		{
			Meteor.leaveChannel(meteorChannels[i]);
			i++;
		}
		Meteor.disconnect();
	}

	function meteorConnect()
	{
		var i = 0;
		while (i < meteorChannels.length)
		{
			Meteor.joinChannel(meteorChannels[i] , 0);
			i++;
		}
		try
		{
			Meteor.connect();
		}
		catch(ep38) {}
		//alert(document.domain);
	}
	
	function meteorAddChannel(ch)
	{
		//alert("CH: " + ch);
		var new_index = Number(meteorChannels.length);
		meteorChannels[Number(new_index)] = ch;
	}
	
	


	function cancelAddNewStudyGroup()
	{
		hide("editStudyGroup");
		get("studygroup_name").value = "";
		get("studygroup_about").value = "";
		get("studygroup_public").checked = true;;
		get("studygroup_invite_only").checked = false;		
		hide("addNewStudyGroup");
		show("studyGroupsListHtml");
	}
	
	function addNewStudyGroupForm()
	{
		hide("studyGroupsListHtml");		
		show("addNewStudyGroup");
		get("studygroup_name").focus();
	}
	
	
	function deleteStudyGroupForm(sg_id)
	{
		get("studygroups_row_" + sg_id).style.backgroundColor = "#ffd3d3";
		var c = confirm("Are you sure you want to delete this study group?  You will no longer be able to chat with this study group, and all current members will be removed.  This action cannot be undone.");
		if (!c)
		{
			get("studygroups_row_" + sg_id).style.backgroundColor = "";
			return;
		}
		
		function _deleteStudyGroupForm(r)
		{
			session(r);
			dirtyTab("studygroups");
			r = r.substring(1);
			var pos = r.indexOf("--");
			var count = r.substr(0, pos);
			r = r.substring(pos+2);
			var sg_box = r.substr(0, Number(count));
			r = r.substring(Number(count)+2+count.length);
			get("studygroupsList").innerHTML = r;
			cloud(false);
			return;
		}
		cloud(true);
		var url = "deleteStudyGroup=1&studygroups_id=" + sg_id;
		Aajax(weburl+"dashboard/index.php", url, _deleteStudyGroupForm);
	}
	
	function editStudyGroupForm(sg_id)
	{
		function _editStudyGroupForm(r)
		{
			session(r);
			hide("studyGroupsListHtml");
			get("editStudyGroup").innerHTML = r;
			show("editStudyGroup");
			cloud(false);
			return;
		}
		
		cloud(true);
		var url = "getEditStudyGroup=1&studygroups_id=" + sg_id;
		Aajax(weburl+"dashboard/index.php", url, _editStudyGroupForm);
	}	

//////////////////////////////////////////////////////////////////////////////////////////
/////// METEOR SUPPORT FUNCTIONS TO HANDLE REAL TIME DATA STREAMS FOR CHANNELS
//////////////////////////////////////////////////////////////////////////////////////////

	// fuckall
	function setGlobalUnreadCount(reduced_number)
	{
		var cur_unread_o = get("unread_chat_count_link_number");
		var cur_balloon_unread_o = get("unread_chat_count");		

		if (reduced_number==1)
		{
			get("chat_balloon_image").src = weburl + "chat_tab_1.gif";
			get("unread_chat_link").innerHTML = "<a id=\"actual_unread_chat_count_link\" class=\"unread_chat_count_link_1\" href=\"javascript:viewUnreadChatMessages();\"><span id=\"unread_chat_count_link\"><b><span id=\"unread_chat_count_link_number\">1</span></b> unread chat message</span></a>";
			cur_unread_o.innerHTML = "1";	
			cur_balloon_unread_o.innerHTML = "1";						
		}
		
		if (reduced_number==0)
		{
			get("chat_balloon_image").src = weburl + "chat_tab_0.gif";
			cur_unread_o.innerHTML = "0";	
			cur_balloon_unread_o.innerHTML = "0";						
		}							
		
		if (reduced_number!=1 && reduced_number!=0)
		{
			get("chat_balloon_image").src = weburl + "chat_tab_1.gif";			
			cur_unread_o.innerHTML = String(reduced_number);	
			cur_balloon_unread_o.innerHTML = String(reduced_number);
		}	
		updateChatCalculationsFromMessageContainers();	
	}
	
	function goChat(type, type_id)
	{
		doTab(true);	// opens tab -- no ajax
		var toshow = type + "_chat_tab";
		var cur = "";
		var pinned_chat_tab = -1;
		if (get("tab_message_" + type)!=null)
		{
			get("tab_message_" + type).disabled = true;
		}
		switch(type)
		{
			case "public":
				pinned_chat_tab = 0;
				break;
			case "courses":
				pinned_chat_tab = 1;
				break;
			case "studygroups":
				pinned_chat_tab = 2;
				break;
			case "friends":
				pinned_chat_tab = 3;
				break;
		}
		
		function _goChat(r)
		{
			session(r);
			updateChatCalculationsFromMessageContainers();
			get(type + "_chat_text").innerHTML = r;
			get(type + "_chat_text").scrollTop = get(type + "_chat_text").scrollHeight;
			get("tab_message_" + type).disabled = false;	
			get("tab_message_" + type).focus();
			return;
		}
		
		// we must be able to reduce our counts by whatever we've just navigated to, and before we remove the child later...
		if (get("unread_chats_" + type + "_" + type_id)!=null)
		{			
			// div exists so just update that div's count
			var to_reduce_by = Number(get("unread_chats_" + type + "_" + type_id + "_count").innerHTML);
			if (true) //me_user_id=="37")
			{
				var uc_public = null;
				var uc_courses = null;
				var uc_studygroups = null;
				var uc_friends = null;
				
				uc_public = get("unread_count_public")==null ? null : get("unread_count_public");
				uc_courses = get("unread_count_courses")==null ? null : get("unread_count_courses");
				uc_studygroups = get("unread_count_studygroups")==null ? null : get("unread_count_studygroups");
				uc_friends = get("unread_count_friends")==null ? null : get("unread_count_friends");
				
				var cur_unread_o = get("unread_chat_count_link_number");
				var cur_balloon_unread_o = get("unread_chat_count");

				if (cur_unread_o!=null)
				{
					var cur_unread = Number(cur_unread_o.innerHTML);
					var reduced_number = cur_unread - to_reduce_by;
										
					reduced_number = reduced_number >= 0 ? reduced_number : 0;
					
					// special scenarios
					setGlobalUnreadCount(reduced_number);
					updateChatCalculationsFromMessageContainers();
					
					// no matter what we update the # in the category that this link was reduced by
					var the_obj = null;
					switch(type)
					{
						case "public": the_obj = uc_public; break;
						case "courses": the_obj = uc_courses; break;
						case "studygroups": the_obj = uc_studygroups; break;
						case "friends": the_obj = uc_friends; break;
					}
					
					try
					{
						var category_cur_num = Number(the_obj.innerHTML);
						var category_reduced_num = category_cur_num - to_reduce_by < 0 ? 0 : category_cur_num - to_reduce_by;
						the_obj.innerHTML = category_reduced_num;
					}
					catch (ep38)
					{}
					
				}
				
				cancelViewUnreadChatMessages();
				
			}
			//get("unread_chats_" + ch + "_" + id + "_count").innerHTML = new_count;
		}			
		
		var cur_num = -1;
		if (get("public_chat_tab").style.display=="") { cur = "public_chat_tab"; cur_num=0; }
		if (get("courses_chat_tab").style.display=="") { cur = "courses_chat_tab"; cur_num=1; }
		if (get("studygroups_chat_tab").style.display=="") { cur = "studygroups_chat_tab"; cur_num=2; }
		if (get("friends_chat_tab").style.display=="") { cur = "friends_chat_tab"; cur_num=3; }	
		
		// update the station
		try
		{
			get("station_" + type).value = type_id;
		}
		catch(ep38)
		{
			alert("You must refresh your page to be able to chat.");
			return;
		}
		get(type + "_chat_text").innerHTML = "Loading...";

		get("tab_" + cur_num).style.backgroundImage = "url('" + weburl + "tab_0.jpg')";
		get("tab_" + pinned_chat_tab).style.backgroundImage = "url('" + weburl + "tab_1.jpg')";
		
		hide(cur);		
		show(toshow);	
			
		if (get("tab_message_" + type)==null)
		{
			return;
		}
		
		// eliminate the chat notification, if it exists
		try
		{
			var type_container = get("unread_" + type + "_messages");
			var individual_container = get("unread_chats_" + type + "_" + type_id);
			type_container.removeChild(individual_container);
		}
		catch (ep38)
		{}
		
		// always hide the container showing notifications even if we don't have to
		if (get("unread_chats")!=null)
		{
			hide("unread_chats");
			show("chat_container");
		}
		updateChatCalculationsFromMessageContainers();	
		var url = "goChat=1&pinned_chat_tab=" + pinned_chat_tab + "&type=" + type + "&type_id=" + type_id;
		Aajax(weburl+"chat/ajax.php", url, _goChat);		
	}

	function cleanMessage(r)
	{
		//str.replace(/microsoft/gi, "W3Schools"
		r = r.replace(/\\\\/gi, "\\");		
		r = r.replace(/\\'/gi, "'");	
		r = r.replace(/\\\"/gi, "&quot;");
		r = r.replace(/\\&quot;/gi, "&quot;");
		return r;
	}

	var cur_tab_closed_count = 0;

	function meteorShowerNotifications(ch, id)
	{
		
		// given the channel let's make sure we have the right url folder for that ch link
		var ch_url = "";
		var clean_name = "";
		switch (ch)
		{
			case "public":	// no page for this
				clean_name = "Public";
				break;
			case "friends":
				ch_url = "profiles";
				clean_name = "Friends";
				break;
			case "studygroups":
				ch_url = "studygroups";
				clean_name = "Study Groups";
				break;
			case "courses":
				ch_url = "courses";
				clean_name = "Courses";
				break;
			default:
				ch_url = ch;
				break;
		}
		
		// this means we need to update the 'unread' count
		var cur_unread = Number(get("unread_chat_count").innerHTML);
		var new_unread = cur_unread+1;
		get("unread_chat_count").innerHTML = String(new_unread);
		var msg_name = "message";
		if (new_unread!=1)
		{
			msg_name = "messages";
		}

		get("unread_chat_count_link").innerHTML = "<b><span id=\"unread_chat_count_link_number\">" + String(new_unread) + "</span></b> unread chat " + msg_name;
		//alert("yo" + new_unread);
		
		// update the balloon graphic if we're above 0
		get("chat_balloon_image").src = Number(new_unread)>0 ? weburl + "chat_tab_1.gif" : weburl + "chat_tab_0.gif";
		
		
		//fuckall
		//alert("CH: " + ch + " ID: " + id + " TYPE: " + type);
		var chatName = convertChatNames(ch, id, "name");
		var chatId = convertChatNames(ch, id, "id");

		// each unread chat has a div object containing it, and a span object surrounding missed msgs
		// first check to see if that div exists, and if so just update the span
		// if div does not exist create

		// update messages container count
		var uco = Number(get("unread_count_" + ch).innerHTML);
		var nuco = uco + 1;
		get("unread_count_" + ch).innerHTML = nuco;
		
		if (get("unread_chats_" + ch + "_" + id)!=null)
		{
			// div exists so just update that div's count
			var cur_count = Number(get("unread_chats_" + ch + "_" + id + "_count").innerHTML);
			var new_count = String(cur_count+1);
			get("unread_chats_" + ch + "_" + id + "_count").innerHTML = new_count;
			updateChatCalculationsFromMessageContainers();
		}
		else
		{
			// create a new div for that chat type	
			var new_div = "";
			var ch_link = "";
			if (ch_url!="")
			{
				ch_link = "<a style=\"color:#FFF\" href=\"" + weburl + ch_url + "/?" + chatId + "\">" + chatName + "</a>";
			}
			else
			{
				ch_link = chatName;								
			}
			ch_link = chatName; // for right now don't worry about the link logic, just use name

			new_div = "<div style=\"color:#FFF;\" id=\"unread_chats_" + ch + "_" + id + "\"><a class=\"unread_chat_count_link_1\" href=\"javascript:goChat('" + ch + "', '" + id + "');\">" + ch_link + " - <b><span id=\"unread_chats_" + ch + "_" + id + "_count\">1</span></b> unread message</a></div>";										
			get("unread_" + ch + "_messages").innerHTML = get("unread_" + ch + "_messages").innerHTML + new_div;
			updateChatCalculationsFromMessageContainers();
		}
		updateChatCalculationsFromMessageContainers();
		show("unread_" + ch);
		
	}
	
	
	
	function meteorShower(r)
	{
		
		try
		{
			var test = r.indexOf("--");
		}
		catch (ep38)
		{
			//debug("Error: " + r);
		}
		var ch = r.substr(0, r.indexOf("--"));		// actual channel ex school_23
		
		var id = ch.substring(r.indexOf("_")+1);	// strips id ex 23
		ch = ch.substr(0, r.indexOf("_"));			// useful channel ex school
		var r = r.substring(r.indexOf("--")+2);		
		var pos = r.indexOf("--");
		var type = r.substr(0, pos);
		r = r.substring(pos+2);
		
		if (type=="kill")
		{
			if (r==me_user_id)
			{
				dirtyTab(ch);
			}
			return;
		}		
		
		//alert(ch + " " + id + " " + r);
		
		if ((ch=="public" || ch=="courses" || ch=="studygroups" || ch=="friends") && type!="KILL")
		{			
			try
			{			
				if (get("station_" + ch).value==id)  // only allow a chat to show up if its what we're viewing
				{
					eval("meteor_" + ch + "('" + escape(r) + "', '" + id + "', '" + type + "');"); // must escape to avoid harmful chars like ';'
					// but even if this is the current "visible" chat we still might be on another tab so 
					// have to update the notifications
					if (true) //me_user_id==37)
					{						
						var panel = get(ch + "_chat_tab");
						if (panel.style.display=="none")
						{
							meteorShowerNotifications(ch, id);
						}
						else
						{
							// fuck
							// if we're here it means we're on the tab that the chat message should be coming into
							// only update the notifications for this chat if the entire chat tab is closed though
							if (get("tab").style.display=="none")
							{							
								//alert("we're on the tab, but we still need to display the #");
								meteorShowerNotifications(ch, id);
								cur_tab_closed_count++;
								//alert(cur_tab_closed_count);
							}
						}
					}
				}
				else
				{
					if (true) //me_user_id==37)
					{
						meteorShowerNotifications(ch, id);	
					}
				}
			}
			catch(ep38)
			{}
		}
	}
	
	function meteorEof()
	{
		//alert("M just died." + document.domain);
		meteordead = true;
		//alert("It appears that you have opened another window.  Chat services can only work in one window and will no longer work in this window.");
	}
	
	function meteor_public(r, id, type)
	{
		r = cleanMessage(unescape(r)); // undo our protective escape
		
		if (type=="CHAT")
		{	
			if (get("public_chat_text").innerHTML=="No chat history.")
			{
				get("public_chat_text").innerHTML = r;
			}
			else
			{
				get("public_chat_text").innerHTML = get("public_chat_text").innerHTML + r;
				get("public_chat_text").scrollTop = get("public_chat_text").scrollHeight;
			}
		}		
	}
	
	function meteor_courses(r, id, type)
	{
		r = cleanMessage(unescape(r)); // undo our protective escape
		
		if (type=="CHAT")
		{
			if (get("courses_chat_text").innerHTML=="No chat history.")
			{
				get("courses_chat_text").innerHTML = r;
			}
			else
			{
				get("courses_chat_text").innerHTML = get("courses_chat_text").innerHTML + r;
				get("courses_chat_text").scrollTop = get("courses_chat_text").scrollHeight;
			}
		}	
	}	
	
	function meteor_friends(r, id, type)
	{
		r = cleanMessage(unescape(r)); // undo our protective escape
		
		if (type=="CHAT")
		{
			if (get("friends_chat_text").innerHTML=="No chat history.")
			{
				get("friends_chat_text").innerHTML = r;
			}
			else
			{
				get("friends_chat_text").innerHTML = get("friends_chat_text").innerHTML + r;
				get("friends_chat_text").scrollTop = get("friends_chat_text").scrollHeight;
			}
		}	
		
	}	
	
	function meteor_studygroups(r, id, type)
	{
		r = cleanMessage(unescape(r)); // undo our protective escape
		
		if (type=="CHAT")
		{
			if (get("studygroups_chat_text").innerHTML=="No chat history.")
			{
				get("studygroups_chat_text").innerHTML = r;
			}
			else
			{
				get("studygroups_chat_text").innerHTML = get("studygroups_chat_text").innerHTML + r;
				get("studygroups_chat_text").scrollTop = get("studygroups_chat_text").scrollHeight;
			}
		}		
	}	


//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////	

	function trashNotification(notification_id)
	{
		function _trashNotification(r)
		{
			session(r);
			//alert(r);
			if (r=="0notifications")
			{
				//alert("Hiding all notifications");
				hide("notificationList_row_1");
				hide("notificationList_row_2");
			}
			else
			{
				get("notificationsList").innerHTML = r;
			}
			cloud(false);
			return;
		}
		//cloud(true);
		get("naction_" + notification_id).innerHTML = "Trashing";
		var url = "trashNotification=1&notification_id=" + notification_id + "&norefresh=1";
		Aajax(weburl+"dashboard/index.php", url, _trashNotification);
	}

	function handleProfilePanels(r)
	{
		var pos = r.indexOf("--");
		var friends_text_toolbar = r.substr(0, pos);			
		r = r.substring(pos+2);
		
		pos = r.indexOf("--");
		var count = Number(r.substr(0, pos));
		var bioPanel = r.substr(String(count).length+2, count);			
		r = r.substring(count+String(count).length+2);			
		var bioPanel2 = r;
		
		get("bioPanel").innerHTML = bioPanel;
		get("bioPanel2").innerHTML = bioPanel2;			
		get("friends_text_toolbar").innerHTML = friends_text_toolbar;		
	}


	
	function respondFriendshipRequestFromNotifications(user_id, torf)
	{
		function _respondFriendshipRequestFromNotifications(r)
		{
			session(r);
			
			if (torf)
			{
				dirtyTab("friends");
			}
			
			var pos = r.indexOf("--");
			var friend_bar_text = r.substr(0, pos);
			r = r.substring(pos+2);
			var notificationList = r;
			
			get("friends_text_toolbar").innerHTML = friend_bar_text;
			
			// do notification panel update
			if (notificationList=="")
			{
				hide("notificationList_row_1");
				hide("notificationList_row_2");				
			}
			else
			{
				get("notificationsList").innerHTML = r;
			}
			
			cloud(false);
			return;
		}		
		
			
		var acceptRequest = torf ? "1" : "0";
		cloud(true);		
		var url = "respondFriendshipRequest=1&acceptRequest=" + acceptRequest + "&user_id=" + user_id;
		Aajax(weburl + "dashboard/index.php", url, _respondFriendshipRequestFromNotifications);
	}

	function respondFriendshipRequestFromProfilesPage(user_id, torf)
	{
		function _respondFriendshipRequestFromProfilesPage(r)
		{
			session(r);
			
			if (torf)
			{
				dirtyTab("friends");
			}
			
			handleProfilePanels(r);				
			cloud(false);
			return;
		}		
		
			
		var acceptRequest = torf ? "1" : "0";
		//cloud(true);
		get("friend_text_" + user_id).innerHTML = "Responding...";
		var url = "respondFriendshipRequest=1&acceptRequest=" + acceptRequest + "&user_id=" + user_id;
		Aajax(weburl + "profiles/index.php", url, _respondFriendshipRequestFromProfilesPage);
	}

	function addFriendFromProfilesPage(user_id)
	{
		if (get("addFriendButton").className == "gbButtonDisabled")
		{
			return;
		}
		function _addFriendFromProfilesPage(r)
		{
			session(r);
			if (r=="true")
			{
				get("friend_text_" + user_id).innerHTML = "Request Pending";
			}
			cloud(false);
			return;
		}
		//cloud(true);
		get("addFriendButton").className = "gbButtonDisabled";
		var url = "addFriend=1&user_id=" + user_id;
		Aajax(weburl+"profiles/index.php", url, _addFriendFromProfilesPage);		
	}

	function filterUsersList()
	{
		var filter_type = get("filterUsersType").value;
		
		function _filterUsersList(r)
		{
			session(r);
			get("usersListHtml").innerHTML = r;
			//cloud(false);
			return;
		}
		
		var url = "getUpdatedProfilesList=1&filter_type=" + filter_type;
		//alert(url);
		//cloud(true);
		Aajax(weburl+"profiles/index.php", url, _filterUsersList);
	}


	function likeProfReview(t, prof_review_id, prof_id)
	{
		function _likeProfReview(r)
		{
			session(r);
			if (get("link_like_text_" + prof_review_id).innerHTML=="Unlike")
			{
				get("link_like_text_" + prof_review_id).innerHTML = "Like";	
			}
			else
			{
				get("link_like_text_" + prof_review_id).innerHTML = "Unlike";
			}			
			//alert(r);
			var pos = r.indexOf("--");
			var updatedText = r.substring(pos+2);
			get("prof_like_text_" + prof_review_id).innerHTML = updatedText;
			cloud(false);
			return;
		}
		cloud(true);
		var url = "likeProfReview=1&professor_id=" + prof_id + "&professor_review_id=" + prof_review_id;
		Aajax(weburl+"professors/index.php", url, _likeProfReview);
		
	}

	function highlightCourseRow(t, id, torf, rowname)
	{
		//alert(rowname);
		if (rowname==null)
		{
			rowname = "outline";
		}
		
		//alert(get("outline_row_" + id).style.backgroundColor);
		if (get(rowname + "_row_" + id)!=null && (get(rowname + "_row_" + id).style.backgroundColor=="rgb(255, 211, 211)" || get(rowname + "_row_" + id).style.backgroundColor=="#ffd3d3"))
		{
			return;
		}
		
		if (torf)
		{
			t.style.backgroundColor = "#ebebeb";
		}
		else
		{
			t.style.backgroundColor = "";
		}
	}

	function doActualDropCourseFromDashboard(outline_id)
	{
		var p = get("dropCoursePassword_" + outline_id).value;

		function _doActualDropCourseFromDashboard(r)
		{
			session(r);
			if (r=="BadPassword")
			{
				alert("The password you entered was incorrect.");
				cloud(false);
				return;
			}						

			dirtyTab("courses");
						
			r = r.substring(1);
			var pos = r.indexOf("--");
			var course_id = r.substr(0, pos);
			r = r.substring(pos+2);			
			
			pos = r.indexOf("--");
			var count = r.substr(0, pos);
			r = r.substring(pos+2);
			
			var select_box = r.substr(0, Number(count));
			//alert(select_box);
			r = r.substring(Number(count));
			
			
			//Meteor.leaveChannel("courses_" + course_id);
			//get("courses_selectbox_div").innerHTML = select_box;
			get("courseListHtml").innerHTML = r;
			curDropping = -1;
			cloud(false);
			return;
		}

		cloud(true);
		var url = "dropCourse=1&outline_id=" + outline_id + "&password=" + p;
		Aajax(weburl+"dashboard/", url, _doActualDropCourseFromDashboard);	

	}
	
	function cancelDropCourseFromDashboard(outline_id)
	{
		curDropping = -1;
		get("outline_row_" + outline_id).style.backgroundColor = "";
		hide("deleteRow_" + outline_id);
		get("dropCoursePassword_" + outline_id).value = "";
	}

	function dropCourseFromDashboard(outline_id)
	{
		if (curDropping!=-1)
		{			
			get("outline_row_" + curDropping).style.backgroundColor = "";
			hide("deleteRow_" + curDropping);
		}
		
		curDropping = outline_id;
		get("outline_row_" + outline_id).style.backgroundColor = "#ffd3d3";
		show("deleteRow_" + outline_id);
	}

	function vert(col)
	{
		if (col==null)
		{
			col = "#CCC";
		}
		
		return "&nbsp;<span style=\"color:" + col + "\">|</span>&nbsp;";
	}
	
	function enrollCourse(course_id)
	{
		function _enrollCourse(r)
		{
			session(r);
			if (r!="false")
			{				
				var pos = r.indexOf("--");
				var count = r.substr(0, pos);
				r = r.substring(pos+2);
				dirtyTab("courses");
				if (get("enrolled_link_" + course_id)!=null)
				{					
					// this means we're on the list page and merely update the count
					get("enrolled_link_" + course_id).innerHTML = "Enrolled"; // + vert() + "<a href=\"" + weburl + "outline/?" + r + "\">Outline</a>";				
					get("studentsEnrolledCount_list_" + course_id).innerHTML = count;					
				}
				else
				{
					// here we're on the course page and must update panels
					pos = r.indexOf("--");
					count = Number(r.substr(0, pos));
					
					
					
					var professorPostsHtmlContent = r.substr(2+String(count).length, count);
					var courseStatsHtml = r.substring(2+String(count).length+count);
					
					//professorPostsHtml
					
					// this means we've enrolled on the single page and need to update the 2 panels					
					get("professorPostsHtml").innerHTML = professorPostsHtmlContent;
					get("courseStatsHtml").innerHTML = courseStatsHtml;						

				}
			}
			
			//get("searchBusy").src = weburl + "wait_blank.gif";
			cloud(false);
			return;
		}

		var updatePanels = 0;
		if (get("enrolled_link_" + course_id)==null)
		{
			if (get("course_enroll_button").className=="gbButtonDisabled")
			{
				//alert("cannot click");
				return;
			}
			updatePanels = 1;
			get("course_enroll_button").className = "gbButtonDisabled";			
		}
		else
		{
			get("enrolled_link_" + course_id).innerHTML = "Enrolling...";
		}
	
		//get("searchBusy").src = weburl + "wait_16_333333.gif";
		var url = "enrollCourse=1&course_id=" + course_id + "&updatePanels=" + updatePanels;
		Aajax(weburl+"courses/", url, _enrollCourse);		
	}
	

	function loading (t)
	{
		return "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td width=\"1%\" style=\"height:35px; padding:15px;\" align=\"left\"><img src=\"" + weburl + "wait_F5F5F5.gif\" height=\"16\" width=\"16\" border=\"0\" /></td><td align=\"left\" valign=\"middle\" style=\"padding:15px; padding-left:0px; font-size:10px; color:#333333\"><nobr>" + t + "</nobr></td><td width=\"100%\">&nbsp;</td></tr></table>";		
	}


	function switchTerms(t)
	{
		var term_id = t.value;
		var o = get("courseListHtml");
		
		function _switchTerms(r)
		{
			session(r);
			o.innerHTML = r;
			return;
		}
		
		o.innerHTML = loading("Loading courses..."); //waitAjax();
		
		var url = "getCourseList=1&for_term_id=" + term_id;
		Aajax(weburl+"dashboard/index.php", url, _switchTerms);
		
		return;
	}

	function bugMenuHover(e, t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "bug" + change + ".gif";
		}
		else
		{
			t.src = weburl + "bug" + change + ".gif";
		}		
		
		//t.style.cursor = "pointer";	
	}



	function postitMenuHover(e, t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "postit" + change + ".png";

		}
		else
		{
			t.src = weburl + "postit" + change + ".png";
		}		
		
		//t.style.cursor = "pointer";	
	}




	function favoriteMenuClick(e, t, outline_id)
	{
		var on = false;
		var tick = 2;
		undoDropMenus();
		t = get("toolbar_favorite_icon");
		if (t.src.indexOf("_2")>0)
		{
			tick = 0;
			t.src=weburl+"toolbar_favorite_0.png";
			cancelSearchOutline();
			
		}
		else
		{
			t.src=weburl+"toolbar_favorite_2.png";
			on = true;
		}

		if (on)
		{
			searchOutline(null, outline_id, true);
		}
	}

	function favoriteMenuHover(e, t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "toolbar_favorite" + change + ".png";
		}
		else
		{
			t.src = weburl + "toolbar_favorite" + change + ".png";
		}		
		
		//t.style.cursor = "pointer";	
	}


	function expandSection(section_id)
	{
		get("sectionHolderDiv_" + section_id).style.display = "";
		get("plusminus_section_" + section_id).src = weburl + "minus_0.gif";
		return;
	}
	
	function expandSectionElement(section_element_id)
	{
		// 
		t = get("plusminus_" + section_element_id);
		var o = get("elementDetails_" + section_element_id);
		var thisIndent = findPosX(t);
		o.style.marginLeft = (thisIndent-7) + "px";
		t.src = weburl + "minus_0.gif";
		show(o.id);		
		
	}

	function navigateTo(type, id, expand)
	{
		if (expand==null)
		{
			expand = false;
		}
		
		//alert(expand);
		cloud(true);
		cleanMe();
		cancelSearchOutline();		
		var t = null;
		switch (type)
		{
			case "section":
				t = get("plusminus_section_" + id);
				break;
			case "section_element":
				t = get("plusminus_" + id);
				break;
		}
		
		
		function _navigateTo(r)
		{
			session(r);
			
			if (r=="fail")
			{
				alert("Cannot locate that element.  Perhaps it was removed.");
				cloud(false);
				return;
			}
			
			var js = r;
			var html = "";
			if (type=="section_element")
			{
				// we need to update the html for this element that is about to be expanded
				//alert(r);
				if (expand)
				{
					var pos = r.indexOf("--");
					js = r.substr(0, pos);
					html = r.substring(pos+2);
					get("elementDetails_" + id).innerHTML = html;
				}
				else
				{
					js = r;
				}
			}
			
			
			eval(js);
			jQuery("textarea[class*=expand]").TextAreaExpander();
			smoothScroll(t.id, -67);
			cloud(false);
			return;
		}
			
		var expandThis = expand ? "1" : "0";
		var url = "navigateTo=1&type=" + type + "&id=" + id + "&expand=" + expandThis;
		//alert(url);
		Aajax(weburl+"outline/ajax.php", url, _navigateTo);
	}


	function notifyEnrolled()
	{
		alert("You are currently enrolled in this course.  To drop this course go to the dashboard and click the 'Drop' link associated with this course in the 'My Courses' area ");
	}

	function navigateSearchResult(type, id)
	{
		cancelSearchBasic();
		//alert(type + " " + id);
		switch (type)
		{
			case "courses":
				if (get("singleCourseDetailContainer").style.display=="")
				{
					hide("loading_courses");
					show("courseListHtml");					
					hide("singleCourseDetailContainer");
					show("parentCourseListContainer");
				}
				smoothScroll("course_listing_" + id, -65);
				break;
		}
	}

	function cancelSearchBasic()
	{
		show("tab_container");
		show("footer_container");
		show("page_container");		
		get("body").style.backgroundColor = "#F1F1F1";
		hide("searchResults");	
	}

	function cancelSearchOutline()
	{
		get("toolbar_favorite_icon").src=weburl+"toolbar_favorite_0.png";
		show("tab_container");
		show("footer_container");
		show("outlineDiv");
		show("mainContentTable");
		get("body").style.backgroundColor = "#F1F1F1";
		hide("searchResults");	
		show("toolbar_favorite_icon");
	}

	function searchOutlineDrop(s, outline_id)
	{
		//alert(s + "--" + outline_id);
		function _searchOutlineDrop(r)
		{
			session(r);
			if (debug())
			{
				//alert(r);
			}
			cancelBug();
			get("body").style.backgroundColor = "#666666";
			hide("outlineDiv");
			hide("tab_container");
			hide("footer_container");
			get("searchResults").innerHTML = r;
			//get("searchResults").style.height = sh + "px";
			show("searchResults");
			if (!asFavorite)
			{
				get("toolbar_favorite_icon").src=weburl+"toolbar_favorite_0.png";
			}
			return;
		}
		undoDropMenus();
		var url = "searchOutline=1&q=" + escape(s) + "&outline_id=" + outline_id;
		s.value = "";
		Aajax(weburl+"outline/ajax.php", url, _searchOutlineDrop);

	}

	function searchOutline(e, outline_id, asFavorite)
	{
		var s = get("search");
		
		
		function _searchOutline(r)
		{
			session(r);
			if (debug())
			{
				//alert(r);
			}
			cancelBug();
			get("body").style.backgroundColor = "#666666";
			hide("outlineDiv");
			hide("tab_container");
			hide("footer_container");
			get("searchBusy").src = weburl + "wait_blank.gif";
			get("searchResults").innerHTML = r;
			//get("searchResults").style.height = sh + "px";
			show("searchResults");
			if (!asFavorite)
			{
				get("toolbar_favorite_icon").src=weburl+"toolbar_favorite_0.png";
				s.focus();
			}
			return;
		}
		
		if (asFavorite)
		{			
			get("searchBusy").src = weburl + "wait_16_333333.gif";
			var url = "searchOutline=1&outline_id=" + outline_id + "&asFavorite=1";
			Aajax(weburl+"outline/ajax.php", url, _searchOutline);	
			return;
		}

		// this handles search... (favorites handled below)
		if(e.keyCode==13)
		{			
			if (trim(s.value)=="" || trim(s.value).length<2)
			{
				return;
			}
			
			get("searchBusy").src = weburl + "wait_16_333333.gif";
			var url = "searchOutline=1&q=" + escape(s.value) + "&outline_id=" + outline_id;
			s.value = "";
			Aajax(weburl+"outline/ajax.php", url, _searchOutline);
		}

	}
	
	function searchOutlineFocus(type)
	{
		var s = get("search");
		if (type)	// focus
		{
			if (s.value=="Search outline...")
			{
				s.value = "";
			}
		}
		else
		{
			if (trim(s.value)=="")
			{
				s.value = "Search outline...";
			}
		}
	}
	

	function searchBasicFocus(type)
	{
		var s = get("search");
		if (type)	// focus
		{
			if (s.value==s.getAttribute("default_text"))
			{
				s.value = "";
			}
		}
		else
		{
			if (trim(s.value)=="")
			{
				s.value = s.getAttribute("default_text");
			}
		}
	}
	
	
	function saveProfReview(professor_id)
	{
		var rating = get("rating_" + professor_id).value;
		var title = escape(get("title_" + professor_id).value);
		var review = escape(get("review_" + professor_id).value);
		review = replaceAll("\\+", "%2B", review);
		//fuck
		
		// also need to get the current 'sort' state so that we maintain persistency
		var sort_method = "rating desc";
		if(get("review_sort_" + professor_id)!=null)
		{
			sort_method = get("review_sort_" + professor_id).value;
		}
		function _saveProfReview(r)
		{
			session(r);			
//			alert(r);
	//		get("poop").value = r;
			
			// we get 3 things back -- student review pane, bio pane, and then js for pie chart eval
			
			var pos = r.indexOf("--");
			var count = Number(r.substr(0, pos));
			var studentReviewHtml = r.substr(pos+2, count);
			r = r.substring(pos+2+count);
			
			//alert("SRH: " + studentReviewHtml);
			
			pos = r.indexOf("--");
			count = Number(r.substr(0, pos));
			var bioPanelHtml = r.substr(pos+2, count);
			r = r.substring(pos+2+count);
			
			//alert("BPH: " + bioPanelHtml);
			

			var js = r;
			//alert("JS: " + js);
			
			get("bioPanel").innerHTML = bioPanelHtml;
			get("studentReviewPanel").innerHTML = studentReviewHtml;
			eval(js);
			
			cloud(false);
			return;
		}
		
		cloud(true);
		var url = "updateProfReview=1&professor_id=" + professor_id + "&title=" + title + "&rating=" + rating + "&review=" + review + "&sort_method=" + escape(sort_method);
	//	alert(url);
		Aajax(weburl+"professors/index.php", url, _saveProfReview);
	}
	
	function doBugReport()
	{
		var type = get("bug_type").value;
		var title = escape(get("bug_title").value);
		var issue = escape(get("bug_issue").value);
		var browser_server = get("bug_browser_server").value;
		var browser_client = navigator.userAgent;
		var page = escape(get("bug_page").value);

		function _doBugReport(r)
		{
			session(r);						
			cancelBug();
			alert("Thank you for reporting the bug.  The issue has been marked as Bug Report #" + r + ".");						
			return;
		}
		
		if (get("bug_title").value=="Give your bug report a title that sums up the issue..." || get("bug_issue").value=="Tell us about the bug and steps to reproduce it if possible..." || type=="-1")
		{
			alert("You must supply all fields to report a bug.");
			return;
		}
		
		var url = "doBugReport=1&type=" + type + "&title=" + title + "&issue=" + issue + "&browser_server=" + escape(browser_server) + "&browser_client=" + escape(browser_client) + "&page=" + page;
		Aajax(weburl+"dashboard/index.php", url, _doBugReport);	
	}
	
	function cancelBug()
	{
		show("outlineDiv");
		show("tab_container");
		show("footer_container");
		show("page_container");		
		get("body").style.backgroundColor = "#F1F1F1";
		hide("reportBugDiv");					
		get("bug_icon").src = weburl + "bug_0.gif";
		get("bug_type").value = "-1";
		get("bug_title").value = "Give your bug report a title that sums up the issue...";
		get("bug_issue").value = "Tell us about the bug and steps to reproduce it if possible...";
	}
	
	
	function reportBug(def)
	{
		try
		{
			cancelSearchBasic();
		}
		catch(ep38) {}
		try
		{
			cancelSearchOutline();
		}
		catch(ep38) {}
		
		if (get("bug_icon").src.indexOf("_2")>0)
		{
			cancelBug();
			return;
		}
		get("bug_icon").src = weburl + "bug_2.gif";
		//show("reportBugDiv");
				
		if (def!="[object HTMLImageElement]")
		{
			get("bug_type").value = def;
		}

		get("body").style.backgroundColor = "#666666";
		hide("outlineDiv");
		hide("page_container");
		hide("tab_container");
		hide("footer_container");
		show("reportBugDiv");
		
	}	
	
	function searchBasicDrop(q, type)
	{
		var s = get("search");	
		function _searchBasicDrop(r)
		{
			session(r);
			cancelBug();
			//alert(r);
			get("body").style.backgroundColor = "#666666";
			hide("page_container");
			hide("tab_container");
			hide("footer_container");
			get("searchBusy").src = weburl + "wait_blank.gif";
			get("searchResults").innerHTML = r;
			show("searchResults");
			return;
		}
		undoDropMenus();
		var url = "searchBasic=1&q=" + escape(q) + "&type=" + type;
		Aajax(weburl+"dashboard/index.php", url, _searchBasicDrop);

	}

	function searchBasic(e, type)
	{
		var s = get("search");	
		function _searchBasic(r)
		{
			session(r);
			cancelBug();
			//alert(r);
			get("body").style.backgroundColor = "#666666";
			hide("page_container");
			hide("tab_container");
			hide("footer_container");
			get("searchBusy").src = weburl + "wait_blank.gif";
			get("searchResults").innerHTML = r;
			//get("searchResults").style.height = sh + "px";
			show("searchResults");
			return;
		}
		
		// this handles search... (favorites handled below)
		if(e.keyCode==13)
		{			
			if (trim(s.value)=="" || trim(s.value).length<2)
			{
				return;
			}
			
			get("searchBusy").src = weburl + "wait_16_333333.gif";
			var url = "searchBasic=1&q=" + escape(s.value) + "&type=" + type;
			//alert(url);
			//return;
			s.value = "";
			Aajax(weburl+"dashboard/index.php", url, _searchBasic);
		}

	}


	function cleanMe()
	{
		// this kills any open config/admin/insert divs that exist
		// so that a subsequent action is the only one visible to the user
		try
		{
			cancelConfigSectionOptions(curSectionConfig, true);
		}
		catch(e) {}
		try
		{
			cancelConfigOptions(curElementConfig, true);
		}
		catch(e) {}
		try
		{
			cancelAddNewElement(curInsertElement);
			//get("addFreshButton").className = "gbButton";
		}
		catch(e) {}
		try
		{
			hide("first_element");
		}
		catch (ep38)
		{}		
		
		undoDropMenus();
		show("toolbar_favorite_icon");
	}
	

	function session(r)
	{
		
		try
		{		
			var x = pJSON(r);
			if (x.session=="false")
			{
				cloud(true);
				top.location.href = weburl;
				return false;				
			}
		}
		catch(e)
		{
			if (trim(r)=="nosession#&FHJ#*hfwlihjq234i579f9h@#@@fw@@Fvvedfgfg")
			{
				cloud(true);
				top.location.href = weburl;
				return false;
			}
		}
	}

	function toggleLock(t, field, id, elements_id, section_element_id)
	{
		
		function _toggleLock(r)
		{
			session(r);
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_blank.gif";
			if (tick==0)
			{
				get(id).disabled = false;
			}
			else
			{
				get(id).disabled = true;
			}
			get(id).className="fieldValue";			
			return;
		}
	
		//alert(id);
		var curVal = "";
		get(id).disabled = true;
		curVal = get(id).value;
	
		get("wait_" + field + "_" + section_element_id).src=weburl+"wait_16_ECECEC.gif";
		var tick = 0;
		if (t.src.indexOf("_0")>0)
		{
			if (get(id).type!="select-one")
			{
				get(id).setAttribute("contenteditable", false);
			}
			else
			{
				get(id).disabled = true;
			}
			t.src=weburl+"lock_1.gif";
			tick = 1;
		}
		else
		{
			get(id).disabled = false;
			t.src=weburl+"lock_0.gif";			
		}		
		Aajax(weburl+"outline/ajax.php", "toggleLock=1&elements_id=" + elements_id + "&tick=" + tick + "&field=" + field + "&value=" + curVal, _toggleLock);
	}

	function toggleBulb(t, field, id, elements_id, section_element_id)
	{	
		
		function _toggleBulb(r)
		{
			session(r);
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_blank.gif";			
			get(id).className="fieldValue";
			return;
		}


		get(id).className="fieldValueNonEdit";		
		get("wait_" + field + "_" + section_element_id).src=weburl+"wait_16_ECECEC.gif";
		var tick = 0;
		if (t.src.indexOf("_0")>0)
		{
			t.src=weburl+"bulb_1.gif";
			tick = 1;
		}
		else
		{
			t.src=weburl+"bulb_0.gif";			
		}	
		
		Aajax(weburl+"outline/ajax.php", "toggleBulb=1&section_element_id=" + section_element_id + "&tick=" + tick + "&field=" + field, _toggleBulb);
	}
	
	function isIE()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("msie")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}
	
	function killSectionElement(section_element_id)
	{
		var section_element = get("section_element_container_" + section_element_id);
		var section = get(section_element.parentNode.id);

		cleanMe();
		
		function _killSectionElement(r)
		{
			session(r);
			section.removeChild(section_element);
			var pos = 0;
			pos = r.indexOf("--");
			r = r.substring(pos+2);	
			//alert(r);
			eval(r);
			cloud(false);
		}
		cloud(true);
		var url = "killSectionElement=1&section_element_id=" + section_element_id;
		Aajax(weburl+"outline/ajax.php", url, _killSectionElement);
	}
	
	/*
	function debug(txt)
	{
		get("debug").innerHTML = "&gt; " + txt + "<br>" + get("debug").innerHTML;
	}
	*/

	function stopEvent(e) {
		if(!e) var e = window.event;
		
		//e.cancelBubble is supported by IE - this will kill the bubbling process.
		e.cancelBubble = true;
		e.returnValue = false;
	
		//e.stopPropagation works only in Firefox.
		if (e.stopPropagation) {
			e.stopPropagation();
			e.preventDefault();
		}
		return false;
	}

	function keydownSectionElement(e, t)
	{

		// firefox is starting to become as bullshit as ie is with
		// little nuance bugs... if cur = 0,0 and keyCode=8 then it
		// will del previous appearing char in a ce div... gay.
		// this prevents it.
		if (isFF() && e.keyCode==8)
		{	
			var selection = window.getSelection(),
		    selectedText = selection.toString(),
		    selectedRange = selection.getRangeAt(0);
			var start = selectedRange.startOffset;
			var end = selectedRange.endOffset;
		
			
			
			if (end==start && end==0)
			{		
				e.preventDefault();
				e.cancelBubble = true;
				e.returnValue = false;
				return false;
			}
		}		
	}

	function keypressSectionElement(e, t)
	{
		
		
		if (Number(t.style.height.replace("px", ""))<18)
		{
			//alert(t.style.height);
			t.style.height = "18px";
		}
		if (trim(removeHTMLTags(t.innerHTML))!="" && t.type!="select-one")
		{
			t.style.height = "";
		}
		else
		{
			t.style.height = "18px";
		}
	}

	function replaceAll(needle, w, haystack)
	{
		//fuck
		var r = "";
		eval("r = haystack.replace(/" + needle + "/g, '" + w + "');");
		//alert(r);
		return r;
	}
	
	function removeHTMLTags(s)
	{
		
		var strInputCode = s; 		
		strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
			return (p1 == "lt")? "<" : ">";
		});
		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		return strTagStrippedText;

	}
	
	function blurSectionElementNewTA(t, id, elements_id, section_element_id)
	{
		t.className="fieldValue";
	}

	function blurSectionElementNew(t, id, elements_id, section_element_id)
	{
		t.className="fieldValue";
	}
	
	function killHint(e, t, section_element_id, elements_id)
	{
		get("hint").style.visibility = "hidden";
		t.src = weburl + "hint_0.gif";
	}
	
	function hideHint()
	{
		hide("hint");
	}
	
	function strippx(s)
	{
		//alert(s);
		//s = (String)s;
		return s.replace("px", "");
	}

	function hoverHint(e, t, section_element_id, elements_id)
	{
		var left = findPosX(t);
		var top = findPosY(t);// - (t.height/2);
		var windowWidth = screen.availWidth; //window.innerWidth;
		if (isIE())
		{
			windowWidth = document.body.offsetWidth;
		}
		t.src = weburl + "hint_1.gif";
		
		
		function _hoverHint(r)
		{		
			session(r);
			get("tooltip").innerHTML = r;	
		}

		//alert((left + t.width + 450) + " compare " + windowWidth);
		if (left + t.width + 455 >= windowWidth)		
		{
			// i.e. we need to show on the left
			left-=(450);
			get("hintleft").style.display = "none";
			get("hintright").style.display = "";
		}
		else
		{
			// i.e. we need to show on the right
			left+=t.width;
			get("hintright").style.display = "none";
			get("hintleft").style.display = "";
		}
		
					
		get("hint").style.left = left + "px";
		get("hint").style.top = top + "px";
		get("tooltip").innerHTML = "Loading...";		
		get("hint").style.visibility = "visible";
		var url = "getHint=1&elements_id=" + elements_id + "&section_element_id=" + section_element_id;
		Aajax(weburl+"outline/ajax.php", url, _hoverHint)
	}
	
	function focusSectionElementTA(t)
	{
						
		// add attrib to this of a backup of the value or the innerHTML		
		t.setAttribute("backup", t.value);
		
		if (t.type!="select-one")
		{		
			t.className="fieldValueEdit";		
		}
	}

	function focusSectionElement(t)
	{
		//debug("i've just been focused");
		// since ie is dumb we must do some work to know if this is a real blur
		if (isIE() && t.type!="select-one")
		{
			if (t.getAttribute("contenteditable")==null || t.getAttribute("contenteditable")=="false")
			{
				return;
			}
		}				
		
		// add attrib to this of a backup of the value or the innerHTML		
		if (t.type!="select-one")
		{
			t.setAttribute("backup", t.innerHTML);
		}
		else
		{
			t.setAttribute("backup", t.value);
		}
		
		if (t.type!="select-one")
		{		
			t.className="fieldValueEdit";
			if (false && window.getSelection)
			{

				
				//alert(t.getAttribute("startOffset") + " " + t.getAttribute("endOffset"));
				var cPosStart = t.getAttribute("startOffset");
				var cPosEnd = t.getAttribute("endOffset");
				
				
				//debug("About to update pos: " + cPosStart + " " + cPosEnd);
				try
				{
					var s = window.getSelection();
					if (s.rangeCount > 0) 
					{
						s.removeAllRanges();
					}				
					
					if (cPosStart=="null" || cPosEnd=="null")
					{
						//debug("From null to life.");
						cPosStart = 0;
						cPosEnd = 0;
					}
					var range = document.createRange();
					range.setStart(t.anchorNode, t.getAttribute("startOffset"));
					range.setEnd(t.focusNode, t.getAttribute("endOffset"));
					s.addRange(range);
					
					t.setSelectionRange(cPosStart,cPosEnd);
				}
				catch (e) {}
			}			
		}
	}
	
	function repositionSection(section_id) 	// ie the person actually clicked the 'move' button
	{
		var orig_pos = get("origPos_" + section_id).value;
		var new_pos = get("curSelectedNewPos_" + section_id).value;
		
		//debug("O: " + orig_pos + " N: " + new_pos);
		if (orig_pos==new_pos)
		{
			alert("This is the original position of the element."); 
			return;
		}
		
		
		cloud(true);
		function _repositionSection(r)
		{
			//alert(r);
			session(r);
			var after = r;
			//alert(after);
			cleanMe();
			
			var f = get(after);
			var me = get("section_container_" + section_id);
			insertAfter(f, me);
			
			cloud(false); 
			smoothScroll("plusminus_section_" + section_id, -67);
			return;
		}
		
		var url = "repositionSection=1&section_id=" + section_id + "&nodePos=" + new_pos + "&origPos=" + orig_pos;
		//alert(url);
		Aajax(weburl+"outline/ajax.php", url, _repositionSection);
	}


	function positionSection(t, pos, section_id)
	{
		if (t.className=="repositionCurrentElement")
		{
			return;
		}
		var grabbedPos = t.getAttribute("pos");
		var prevPos = get("curSelectedNewPos_" + section_id).value;
		
		//debug("T: " + t.id + "Grabbed: " + grabbedPos + " POS: " + pos + " SEID " + section_id);
		
		
		get("curSelectedNewPos_" + section_id).value = grabbedPos;
		
		var prev = null;
		if (get("pos_" + prevPos + "_" + section_id)!=null)
		{
			prev = get("pos_" + prevPos + "_" + section_id);
		}

		
		// essentially swap places for the timebeing while user is editing
		t.innerHTML = prev.innerHTML;		
		prev.innerHTML = "";
		
		t.className = "repositionCurrentElement";		
		prev.className = "reposition";
	
	}
	

	function repositionElement(section_element_id) 	// ie the person actually clicked the 'move' button
	{
		var orig_pos = get("origPos_" + section_element_id).value;
		var new_pos = get("curSelectedNewPos_" + section_element_id).value;
		
		//debug("O: " + orig_pos + " N: " + new_pos);
		if (orig_pos==new_pos)
		{
			alert("This is the original position of the element."); 
			return;
		}
		
		
		cloud(true);
		function _repositionElement(r)
		{
			session(r);
			get("debugPosition").innerHTML = r;
			var pos = r.indexOf("--");
			var after = r.substr(0, pos);
			r = r.substring(pos+2);
			
			var js = r;
			cleanMe();
			
			var f = get(after);
			var me = get("section_element_container_" + section_element_id);
			insertAfter(f, me);
			
			eval(js);
			cloud(false);
			smoothScroll("plusminus_" + section_element_id, -67);
			return;
		}
		
		var url = "repositionElement=1&section_element_id=" + section_element_id + "&nodePos=" + new_pos + "&origPos=" + orig_pos;
		Aajax(weburl+"outline/ajax.php", url, _repositionElement);
	}

	function positionElement(t, pos, section_element_id)
	{
		if (t.className=="repositionCurrentElement")
		{
			return;
		}
		var grabbedPos = t.getAttribute("pos");
		var prevPos = get("curSelectedNewPos_" + section_element_id).value;
		
		//debug("T: " + t.id + "Grabbed: " + grabbedPos + " POS: " + pos + " SEID " + section_element_id);
		
		
		get("curSelectedNewPos_" + section_element_id).value = grabbedPos;
		
		var prev = null;
		if (get("pos_" + prevPos + "_" + section_element_id)!=null)
		{
			prev = get("pos_" + prevPos + "_" + section_element_id);
		}

		
		// essentially swap places for the timebeing while user is editing
		t.innerHTML = prev.innerHTML;		
		prev.innerHTML = "";
		
		t.className = "repositionCurrentElement";		
		prev.className = "reposition";
		
		
		
		
		
	}

	function blurSectionElementTA(t, id, elements_id, section_element_id, torf)
	{		
		// since ie is dumb we must do some work to know if this is a real blur
		var prevContent = t.getAttribute("backup");
		var value = "";
		
	
		if (t.getAttribute("required") && trim(removeHTMLTags(t.value))=="")
		{
			t.value = t.getAttribute("backup");	
			t.className="fieldValue";			
			alert("You cannot leave the " + t.getAttribute("fieldName") + " field blank.");
			return;
		}

		value = t.value;
		if (value==prevContent)
		{
			if (torf)
			{
				t.className="fieldValue";
			}
			else
			{
				t.className="fieldValueEdit";
			}
			return;	
		}			
		
		t.disabled = true;
		t.className="fieldValueNonEdit";			

		
		var pos = id.lastIndexOf("_");
		var field = id.substr(0, pos);
		var origPos = null;
		
		value = t.value;
		
		function _blurSectionElementTA(r)
		{
			session(r);
			if (me_user_id==84)
			{
				//alert(r);
			}
			var pos = r.indexOf("--");
			var count = Number(r.substr(0, pos));
			var name = r.substr(pos+2, count);
			r = r.substring(pos+2+count);
			
			r = replaceAll("--S--", "§", r);
			name = replaceAll("--S--", "§", name);
			
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_blank.gif";
			
			if (t.getAttribute("updateName"))
			{
				get("section_element_name_" + section_element_id).innerHTML = name;				
			}
			
			
			if (torf)
			{
				t.className="fieldValue";
			}
			t.disabled = false;
			t.value = r;
			if (!torf)
			{
				// i.e. we're here if we've just hit CTRL+S
				t.className = "fieldValueEdit";
			}
			

			t.setAttribute("backup", r);
			return;
		}

		//debug("Just blurred..." + t.getAttribute("startOffset") + " " + t.getAttribute("endOffset"));

		// before we dial home let's first check if we've even made a change and if we haven't don't
		// dial home because that's a waste of time.
		if (prevContent!=value)
		{				
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_16_ECECEC.gif";
			var element_type = t.getAttribute("element_type");
			var url = "updateElementField=1&field=" + field + "&value=" + escape(value) + "&elements_id=" + elements_id + "&element_type=" + element_type + "&section_element_id=" + section_element_id;
			//alert(escape(value));
			//alert(url);
			url = replaceAll("%A7", "--S--", url);
			if (me_user_id==84)
			{
				
				//alert(url);
			}
			Aajax(weburl+"outline/ajax.php", url , _blurSectionElementTA);
		}
	}

	function blurSectionElement(t, id, elements_id, section_element_id, torf)
	{		
		// since ie is dumb we must do some work to know if this is a real blur
		if (isIE() && t.type!="select-one")
		{
			if (t.getAttribute("contenteditable")==null || t.getAttribute("contenteditable")=="false")
			{
				return;
			}
		}
		
		var prevContent = t.getAttribute("backup");
		var value = "";
		
		if (trim(removeHTMLTags(t.innerHTML))=="" && t.type!="select-one")
		{
			t.style.height = "18px";
		}
	
		if (t.getAttribute("required") && trim(removeHTMLTags(t.innerHTML))=="")
		{
			if (t.type!="select-one")
			{
				t.innerHTML = t.getAttribute("backup");
			}
			else
			{
				t.value = t.getAttribute("backup");
			}
			t.className="fieldValue";			
			alert("You cannot leave the " + t.getAttribute("fieldName") + " field blank.");
			return;
		}

		if (t.type!="select-one")
		{
			value = t.innerHTML;
			if (value==prevContent)
			{
				if (torf)
				{
					t.className="fieldValue";
				}
				else
				{
					t.className="fieldValueEdit";
				}
				return;	
			}			
			t.setAttribute("contenteditable", false);
			t.className="fieldValueNonEdit";			
		}
		else
		{
			value = t.value;
			if (value==prevContent)
			{
				t.className="fieldValue";
				return;	
			}
			t.disabled = true;
		}
		
		var pos = id.lastIndexOf("_");
		var field = id.substr(0, pos);
		var origPos = null;
		
		if (t.type!="select-one")
		{
			value = t.innerHTML;
		}
		else
		{
			value = t.value;
		}
		
		function _blurSectionElement(r)
		{
			session(r);
			//alert(r);
			var pos = r.indexOf("--");
			var count = Number(r.substr(0, pos));
			var name = r.substr(pos+2, count);
			r = r.substring(pos+2+count);
			
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_blank.gif";
			
			if (t.getAttribute("updateName"))
			{
				get("section_element_name_" + section_element_id).innerHTML = name;				
			}
			
			if (t.type!="select-one")
			{
				if (torf)
				{
					t.className="fieldValue";
				}
				t.setAttribute("contenteditable", true);
				t.innerHTML = r;
				if (!torf)
				{
					// i.e. we're here if we've just hit CTRL+S
					t.className = "fieldValueEdit";
					//debug("ctrl + S caught in blur");
					var cPosStart = t.getAttribute("startOffset");
					var cPosEnd = t.getAttribute("endOffset");
					//debug("About to update pos after ctrl + s: " + cPosStart + " " + cPosEnd);
					try
					{
						// at least chrome can put the cursor back in the
						// right position after a save.
						var s = window.getSelection();
						if (s.rangeCount > 0) 
						{
							s.removeAllRanges();
						}					
						var range = document.createRange();
						range.setStart(t.anchorNode, t.getAttribute("startOffset"));
						range.setEnd(t.focusNode, t.getAttribute("endOffset"));
						s.addRange(range);
					}		
					catch (e)
					{
					}
					
				}
			}
			else
			{
				t.disabled = false;
			}
			t.setAttribute("backup", r);
			return;
		}

		//debug("Just blurred..." + t.getAttribute("startOffset") + " " + t.getAttribute("endOffset"));

		// before we dial home let's first check if we've even made a change and if we haven't don't
		// dial home because that's a waste of time.
		if (prevContent!=value)
		{				
			get("wait_" + field + "_" + section_element_id).src=weburl+"wait_16_ECECEC.gif";
			var element_type = t.getAttribute("element_type");
			var url = "updateElementField=1&field=" + field + "&value=" + escape(value) + "&elements_id=" + elements_id + "&element_type=" + element_type + "&section_element_id=" + section_element_id;
			//alert(url);
			Aajax(weburl+"outline/ajax.php", url , _blurSectionElement);
		}
	}
	
	function loopColon(text, fn)
	{
		var cText = text;
		var pos = 0;
		var value = "";
		var count = 0;
		while (cText!="")
		{
			pos = cText.indexOf(":");
			value = cText.substr(0, pos);
			cText = cText.substr(pos+1, cText.length);
			fn(value);
			count++;
		}		
		return count;
	}


	function cancelAddNewSection(section_id)
	{
		var o = get("configSection_" + section_id)
		o.style.display = "none";
			
	}
	
	function saveSectionDetails(section_id)
	{
		function _saveSectionDetails(r)
		{
			session(r);
			//alert(r);
			cancelAddNewSection(section_id);
			
			get("section_" + section_id + "_name").innerHTML = r;
			cloud(false);
			return;
		}

		var name = get("editSectionName_" + section_id).value;

		if (trim(removeHTMLTags(name))=="")
		{
			alert("You must supply a name for the section.");
			cloud(false);
			return;
		}
		cleanMe();
		//cloud(true);
		
		var url = "editSectionName=1&name=" + escape(name) + "&section_id=" + section_id;
		Aajax(weburl + "outline/ajax.php", url, _saveSectionDetails);		
	}
	
	function removeSection(section_id)
	{
		var section = get("section_container_" + section_id);
		var section_parent = get(section.parentNode.id);		

		var c = (get("confirmRemoveSection_" + section_id).checked);
		if (!c)
		{
			alert("You must confirm that you want to remove this section from your outline.");
			return;
		}

		function _removeSection(r)
		{
			session(r);
			//alert(r);
			eval(r);
			section_parent.removeChild(section);			
			cloud(false);
			return;
		}
		
		cloud(true);
		var url = "removeSection=1&section_id=" + section_id;
		Aajax(weburl+"outline/ajax.php", url, _removeSection);
	}
	
	function handleChildCount(section_id, count)
	{
		//alert("handline child count: " + section_id + " " + count);
		if (count>0)
		{
			get("section_" + section_id + "_count").innerHTML = "(" + count + ")";
		}
		else
		{
			// check if this is a base node
			var bn = get("section_container_" + section_id).getAttribute("isBaseNode")=="1" ? true : false;
			get("section_" + section_id + "_count").innerHTML = "";
			if (!bn)
			{				
			}
		}
	}

	function saveAddNewSection(section_id)
	{
		function _saveAddNewSection(r)
		{
			session(r);
			//alert(r);
			cancelAddNewSection(section_id);
			
			var pos = r.indexOf("--");
			var count = r.substr(0, pos);
			handleChildCount(section_id, count);
			
			cloud(false);
			return;
		}
		//cloud(true);
		var name = get("addSectionName_" + section_id).innerHTML;
		
		if (trim(removeHTMLTags(name))=="")
		{
			alert("You must supply a name for the new section.");
			cloud(false);
			return;
		}
		
		var url = "addNewSection=1&name=" + name + "&section_id=" + section_id;
		//alert(url);
		Aajax(weburl + "outline/ajax.php", url, _saveAddNewSection);
	}

	function removeElement(section_element_id)
	{
		var c = (get("confirmRemove_" + section_element_id).checked);
		if (!c)
		{
			alert("You must confirm that you want to remove this note from your outline.");
			return;
		}
		cloud(true);
		killSectionElement(section_element_id);
		
	}




	function configChosenOption(section_element_id, chosen)
	{
		//alert(section_element_id + " " + chosen);
		//debugger;
		hide("configLinkOptions_" + section_element_id);
		curElementConfig = section_element_id;
		
		if (chosen=="move")
		{
			get("configHeader_text_" + section_element_id).innerHTML = "Move Sections";
			get("configCaption_text_" + section_element_id).innerHTML = "Select where you would like to move this note.";			
		}
		else if (chosen=="pos")
		{
			get("configHeader_text_" + section_element_id).innerHTML = "Position";
			get("configCaption_text_" + section_element_id).innerHTML = "Select where you would like to position this note.";			
		}
		else if (chosen=="share")
		{
			get("configHeader_text_" + section_element_id).innerHTML = "Share";
			get("configCaption_text_" + section_element_id).innerHTML = "Select who you would like to share this note with.";			
		}		
		else
		{
			get("configHeader_text_" + section_element_id).innerHTML = "Remove";
			get("configCaption_text_" + section_element_id).innerHTML = "Remove this note from your outline.";
		}
		
		if (get("configOptionHeader_" + chosen + "_" + section_element_id)!=null)
		{
			show("configOptionHeader_" + chosen + "_" + section_element_id);
		}

		show("configOptionContent_" + chosen + "_" + section_element_id);
		
		show("configActionButton_" + chosen + "_" + section_element_id);		
		show("configActionButtons_" + section_element_id);
		
		smoothScroll("plusminus_" + section_element_id, -67); 	
		
	}
	


	function configChosenSectionOption(section_id, chosen)
	{		
		hide("configSectionLinkOptions_" + section_id);
		curSectionConfig = section_id;

		if (chosen=="add")
		{
			get("configHeader_text_section_" + section_id).innerHTML = "Add Section";
			get("configCaption_text_section_" + section_id).innerHTML = "Add a new section to your outline.";	
			show(section_id + "_addSectionName_field");
			show(section_id + "_addSectionName_value");
			get("addSectionName_" + section_id).focus();
		}

		if (chosen=="edit")
		{
			get("configHeader_text_section_" + section_id).innerHTML = "Rename";
			get("configCaption_text_section_" + section_id).innerHTML = "Rename this section to something else.";	
			show(section_id + "_editSectionName_field");
			show(section_id + "_editSectionName_value");			
		}
				
		if (chosen=="move")
		{
			get("configHeader_text_section_" + section_id).innerHTML = "Move Sections";
			get("configCaption_text_section_" + section_id).innerHTML = "Select where you would like to move this section.";	
			show("configOptionContent_section_" + chosen + "_" + section_id);
		}
		
		if (chosen=="pos")
		{
			get("configHeader_text_section_" + section_id).innerHTML = "Position";
			get("configCaption_text_section_" + section_id).innerHTML = "Select where you would like to position this section.";
			show("configOptionContent_section_" + chosen + "_" + section_id);
		}
		
		if (chosen=="remove")
		{
			get("configHeader_text_section_" + section_id).innerHTML = "Remove";
			get("configCaption_text_section_" + section_id).innerHTML = "Remove this section from your outline.";
			show("configOptionContent_section_" + chosen + "_" + section_id);
		}
		
				
		show("configActionButton_section_" + chosen + "_" + section_id);		
		show("configActionButtons_section_" + section_id);
		
		smoothScroll("plusminus_section_" + section_id, -67); 	
		
	}

	function addSection(section_id)
	{
		function _addSection(r)
		{
			session(r);
			//alert(r);
			// r returns in this order: js, after, html	
			var pos = r.indexOf("--");
			var new_section_id = r.substr(0, pos);
			r = r.substring(pos+2);
			pos = r.indexOf("--");
			var js = r.substr(0, pos);
			r = r.substring(pos+2);
			pos = r.indexOf("--");
			var after = r.substr(0, pos);
			var html = r.substring(pos+2);
			
			/*
			alert(new_section_id);
			alert(js);
			alert(after);
			alert(html);
			*/
			
			cleanMe();
			
			//<div id="sectionHolderDiv_<?PHP echo $section_id; ?>" style="<?PHP echo $borders; ?>; display:<?PHP echo $pinDisplay; ?>">
			
			eval(js);
			
			//alert(html);
			var newEntry = document.createElement("div");
			newEntry.id = "section_container_" + new_section_id;
			newEntry.setAttribute("isBaseNode", "0");
			newEntry.style.display = "";
			newEntry.innerHTML = html;
			
			//alert(after);
			
			// we need the section_element_id of THIS current element we're inserting below
			f = get(after);
			insertAfter(f, newEntry);
			
			get("plusminus_section_" + section_id).src = weburl + "minus_0.gif";
			show("sectionHolderDiv_" + section_id);
			//smoothScroll("plusminus_section_" + new_section_id, -67);
			navigateTo("section", new_section_id);
			//cloud(false);
			return;
		}
		var name = get("addSectionName_" + section_id).value;
		if (trim(name)=="")
		{
			gbAlert("You must supply a name for the new section");
			return;
		}
		var url = "addNewSection=1&section_id=" + section_id + "&name=" + escape(name);
		//cloud(true);		
		Aajax(weburl+"outline/ajax.php", url, _addSection);
	}
	
	
	function cancelConfigSectionOptions(section_id, forClean)
	{//
		
		if (section_id==-1)
		{
			return;
		}
		
		if (forClean)
		{
			curSectionConfig = -1;
			hide("configSection_" + section_id);
			get("config_section_icon_" + section_id).src=weburl+"config_0.gif";		
			return;
		}
		
		if (get("configSectionLinkOptions_" + section_id).style.display=="none" && !forClean)
		{
			//
			hide(section_id + "_addSectionName_field");
			hide(section_id + "_addSectionName_value");
			hide(section_id + "_editSectionName_field");			
			hide(section_id + "_editSectionName_value");				
			hide("configOptionContent_section_move_" + section_id);		
			hide("configOptionContent_section_pos_" + section_id);
			hide("configOptionContent_section_remove_" + section_id);
			
			hide("configActionButton_section_add_" + section_id);
			hide("configActionButton_section_edit_" + section_id);
			hide("configActionButton_section_move_" + section_id);		
			hide("configActionButton_section_pos_" + section_id);
			hide("configActionButton_section_remove_" + section_id);
			hide("configActionButtons_section_" + section_id);
			
			get("configHeader_text_section_" + section_id).innerHTML = "Configure Section";
			get("configCaption_text_section_" + section_id).innerHTML = "What would you like to do?";			
			show("configSectionLinkOptions_" + section_id);
			curSectionConfig = section_id;
			return;
		}
		
		//alert("configElement_" + section_element_id);
		hide("configSection_" + section_id);
		get("config_section_icon_" + section_id).src=weburl+"config_0.gif";
	}



	function cancelConfigOptions(section_element_id, forClean)
	{
		// 
		if (section_element_id==-1)
		{
			//alert("isneg");
			return;
		}
		
		if (forClean)
		{
			curElementConfig = -1;
			hide("configElement_" + section_element_id);
			get("config_icon_" + section_element_id).src=weburl+"config_0.gif";		
			return;
		}
		
		if (get("configLinkOptions_" + section_element_id).style.display=="none" && !forClean)
		{
		//	/debug("caught");
			//debug("cancelConfigOptions Click " + section_element_id + " " + forClean);
			hide("configActionButton_move_" + section_element_id);		
			hide("configActionButton_pos_" + section_element_id);
			hide("configActionButton_remove_" + section_element_id);
			hide("configActionButton_share_" + section_element_id);	
			hide("configOptionContent_move_" + section_element_id);		
			hide("configOptionContent_pos_" + section_element_id);
			hide("configOptionContent_share_" + section_element_id);
			hide("configOptionContent_remove_" + section_element_id);	
			hide("configActionButtons_" + section_element_id);
			get("configHeader_text_" + section_element_id).innerHTML = "Configure Note";
			get("configCaption_text_" + section_element_id).innerHTML = "What would you like to do?";			
			show("configLinkOptions_" + section_element_id);
			curSectionConfig = section_element_id;
			//debug("CSC: " + curSectionConfig);
			return;
		}//
		
		//alert("configElement_" + section_element_id);
		hide("configElement_" + section_element_id);
		get("config_icon_" + section_element_id).src=weburl+"config_0.gif";
	}
	

	function configSection(section_id, action)
	{		

		
	
		var o = get("configSection_" + section_id);
	
		function _editSection(r)
		{
			session(r);
			//alert(r);
			o.innerHTML = r;
			return;
		}
	
		o.innerHTML = waitAjax();
		show(o.id);
		var url = "configSection=1&section_id=" + section_id + "&action=" + action;
		Aajax(weburl+"outline/ajax.php", url, _editSection);
	}
	
	function getIndent(n)
	{
		n = Number(n);
		var i = 0;
		var s = "";
		while (i < n)
		{
			s = s + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			i++;
		}
		return String(s);
	}

	function insertAfter(referenceNode, newNode)
	{
		referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
	}

	function getNodePos(t)
	{
		return t.getAttribute("nodePos");	
	}
	
	function showTextEditor(section_element_id, elements_id, torf)
	{				
		if (!can_click_editor)
		{
			return;
		}
		clearInterval(autosave);
		cloud(true);		
		get("curTextEditorSectionElementId").value = section_element_id;
		get("curTextEditorElementsId").value = elements_id;
		hide("outlineDiv");
		hide("mainContentTable");
		
		function _showTextEditor(r)
		{
			session(r);

			if (me_user_id=="1")
			{
				//alert(r);				
			}

			var notesTitle = "";
			notesTitle = get("section_element_name_" + section_element_id).innerHTML;	
			if (me_user_id=="1")
			{
				//idTextEditor_ifr elm1_ifr
				var editor = document.getElementById('idTextEditor_ifr');
				editor.contentDocument.getElementById('tinymce').innerHTML=r;
				//alert(r);
			}
			else
			{
				tinyMCE.get("idTextEditor").setContent(r);
			}			
			var newPushDown = (64 + editorHeight) + "px";			
			get("mainContentTable").style.paddingTop = newPushDown; 			
			get("centerAnnounce").innerHTML = "Currently Editing <b>" + notesTitle + "</b>";
			hide("normalOutlineToolbar");
			show("editOutlineToolbar");			
			show("textEditorDiv");		
			tinyMCE.execCommand('mceFocus',true,'idTextEditor');
			cloud(false);
			autosave = setInterval("saveTextEditor();", autosaveSeconds*1000);
			return;
		}		

		closePostit();
		if (torf)
		{
			_showTextEditor("");
			return;
		}
		else
		{		
			var url = "getTextEditorContent=1&section_element_id=" + section_element_id + "&elements_id=" + elements_id;
			Aajax(weburl+"outline/ajax.php", url, _showTextEditor);
		}
	}
	
	function saveAndCloseTextEditor()
	{
		//alert("hi");
		clearInterval(autosave);
		cloud(true);
		
		var isFullscreen = false;
		try
		{
			var foo = document.getElementById("mce_fullscreen_container").style.display;
			isFullscreen = true;
		}
		catch(e)
		{}

		if (isFullscreen)
		{
			//mce_fullscreen
			//idTextEditor	
			tinyMCE.get("mce_fullscreen").execCommand("mceFullScreen");
			//tinyMCE.activeEditor.execCommand("mceFullScreen");
		}
		
		get("last_saved_text_editor").innerHTML = "";		
		hide("textEditorDiv");
		function _saveAndCloseTextEditor(r)
		{
			session(r);
			//alert(r);
			get("curTextEditorSectionElementId").value = -1;
			get("curTextEditorElementsId").value = -1;
			tinyMCE.get("idTextEditor").setContent("");		
			get("mainContentTable").style.paddingTop = "64px"; 			
			
			hide("editOutlineToolbar");
			show("normalOutlineToolbar");
			
			hide("textEditorDiv");
			show("outlineDiv");
			show("mainContentTable");
						
			cloud(false);
			return;
		}
		
		// dial home to save this value
		var elements_id = get("curTextEditorElementsId").value;		

		var content = "";
		var curMCE = tinyMCE.activeEditor.id;		
		
		//mce_fullscreen
		if (isFullscreen && curMCE=="idTextEditor")
		{
			content = (tinyMCE.get("mce_fullscreen").getContent());
			//alert("fs " + content);
		}
		else
		{
			content = (tinyMCE.activeEditor.getContent());
			//alert("not " + content);
		}
		
		// be sure to update our outline w/ the updated content before we escape it
		try
		{
			get("justDisplayNotes_" + get("curTextEditorSectionElementId").value).innerHTML = content;
			if (trim(content)=="")
			{
				get("justDisplayNotes_" + get("curTextEditorSectionElementId").value).style.height = "18px"; 
			}
		}
		catch(e)
		{
		}

		content = escape(content);

		var url = "updateClassNotes=1&content=" + content + "&elements_id=" + elements_id;
		//alert(url);
		Aajax(weburl+"outline/ajax.php", url, _saveAndCloseTextEditor);		
	}
	
	function saveTextEditor()
	{
		clearInterval(autosave);
		var isFullscreen = false;
		try
		{
			var foo = document.getElementById("mce_fullscreen_container").style.display;
			isFullscreen = true;
		}
		catch(e)
		{}

		//alert(get("idTextEditor").value);
		hide("last_saved_text_editor");
		show("savingTextEditor");
		
		function _saveTextEditor(r)
		{
			session(r);
			//alert(r);
			get("last_saved_text_editor").innerHTML = "Last saved: " + r;
			hide("savingTextEditor");
			show("last_saved_text_editor");
			if (isFullscreen)
			{
				tinyMCE.get("mce_fullscreen").focus();
			}
			autosave = setInterval("saveTextEditor();", autosaveSeconds*1000);
			return;
		}
		
		// dial home to save this value
		var elements_id = get("curTextEditorElementsId").value;
		//alert(tinyMCE.activeEditor.id);
		
		var content = "";
		var curMCE = tinyMCE.activeEditor.id;
		
		if (isFullscreen && curMCE=="idTextEditor")
		{
			content = (tinyMCE.get("mce_fullscreen").getContent());
			//alert("fs " + content);
		}
		else
		{
			content = (tinyMCE.activeEditor.getContent());
			//alert("not " + content);
		}

		// be sure to update our outline w/ the updated content before we escape it
		try
		{
			get("justDisplayNotes_" + get("curTextEditorSectionElementId").value).innerHTML = content;
		}
		catch(e)
		{
		}
		
		content = escape(content);
		

		var url = "updateClassNotes=1&content=" + content + "&elements_id=" + elements_id;
		//alert(url);
		Aajax(weburl+"outline/ajax.php", url, _saveTextEditor);
		return false;
	}
	

	function saveAddNewElement(type, guid, parent)
	{		
		//alert(type + " " + guid + " " + parent);
		cloud(true);			
		type = Number(type);
		function _saveAddNewElement(r)
		{
			
			session(r);
			
			if (type==9)
			{
				if (r=="notpublic"  || r=="notvalid")
				{
					cloud(false);
					gbAlert("You do not have permission to add those notes.");
					return;
				}
				
				if (r=="notschool")
				{
					cloud(false);
					alert("That type of note is not supported by this school.");
					return;
				}
			}
			
			// first part is # of chars of js to execute
			var pos = null;
			var count = 0;
			var elements_id = 0;
			var section_element_id = 0;
			var content = "";
			if (type==8)
			{
				//alert(r);
				// for a notes inserted we have to tet the elements_id and section_elements_id
				// elements_id first, then section_elements_id
				pos = r.indexOf("--");
				elements_id = Number(r.substr(0, pos));		
				
				r = r.substring(pos+2);
				pos = r.indexOf("--");
				section_element_id = Number(r.substr(0, pos));	
				r = r.substring(pos+2);
				//alert(r);
			}
			else
			{			
				// first thing returned is our section_element_id
				pos = r.indexOf("--");
				section_element_id = r.substr(0, pos);
				r = r.substring(pos+2);
			}
			
			//alert(r);
			pos = r.indexOf("--");
			count = Number(r.substr(0, pos));
			//alert(count);
			var js = r.substr(pos+2, count); 
			// do NOT eval this until we add our new element to the DOM
			
			// we have our js now truncate r to just be the html			
			r = r.substring(pos+2+count);
			//alert(r);
			// make a siblign div and set the id to the container of the new element
			cancelAddNewElement(guid);						
			var newEntry = document.createElement("div");
			newEntry.id = "section_element_container_" + section_element_id;
			newEntry.innerHTML = r;
			//alert(r);
			
			// we need the section_element_id of THIS current element we're inserting below
			pos = guid.indexOf("_");
			var seid = guid.substring(pos+1);
			var f = null; 			
			if (guid.indexOf("sectionguid")>-1)
			{
				//alert(guid);
				f = get("insertDivDetails_" + guid);
				insertAfter(f, newEntry);
			}
			else
			{
				f = get("section_element_container_" + seid);
				insertAfter(f, newEntry);	
			}
			
			//alert(js);
					
			eval(js);
			
			// if we are notes then we ought to show text editor
			if (type==8)
			{
				cloud(false);
				//alert("about to show editor:" + elements_id + " " + section_element_id);
				//showTextEditor(section_element_id, elements_id, true);
				window.open(weburl + "editor/?" + section_element_id);
				return;
			}
			navigateTo("section_element", section_element_id);
			
			//cloud(false);
			//smoothScroll(newEntry.id, -60);
			return;
		}
				
		// depending on what type of data we're attempting to save, go validate		
		var url = "";
		switch (type)
		{
			case 1:		// case
				url=validateCase(guid);
				break;
			case 2:		// blackletter
				url=validateBlackletter(guid);
				break;
			case 3:		// statute
				url=validateStatute(guid);
				break;
			case 4:		// word
				url=validateUpload(guid, 4);
				break;
			case 5:		// excel
				url=validateUpload(guid, 5);
				break;
			case 6:		// pdf
				url=validateUpload(guid, 6);
				break;
			case 7:		// image
				url=validateUpload(guid, 7);
				break;
			case 9:
				url = validateShare(guid);
				break;
			case 10:	// ppt
				url=validateUpload(guid, 10);
				break;				
			case 8:		// notes
				url=validateNotes(guid);
				break;
			case 11:		// article				
				url=validateArticle(guid);
				break;	
			case 12:		// audio
				url=validateUpload(guid, 12);
				break;
		}
		
		if (url!="")
		{
			// dial home with our data to save the case to the system	
			var nodePos = getNodePos(get("insertDivDummy_" + guid));
			//alert(nodePos);
			var indent = get("uniqueSectionId_" + parent).getAttribute("depth_charge");
			url = url + "&actuallyAdd=1&type=" + type + "&guid=" + guid + "&parent=" + parent + "&indent=" + indent + "&nodePos=" + nodePos;
			
			// if we are uploading we actually do things a little differently
			// in fact we take care of everything on the upload form and just handle response accordingly
			// in the stopUpload function... so go there for more stuff to do...
			if (type==4 || type==5 || type==6 || type==7 || type==10 || type==12)
			{
			
				get("name_form_" + guid + "_new").value = get("name_" + guid + "_new").innerHTML;
				get("notes_form_" + guid + "_new").value = get("notes_" + guid + "_new").innerHTML;
				get("nodePos_form_" + guid + "_new").value = nodePos;
				get("indent_form_" + guid + "_new").value = indent;
				get("name_" + guid + "_new").blur();
				get("notes_" + guid + "_new").blur();
				//alert(guid);
				//document.domain="www.groundbooth.com"; //
				eval("document.form_" + guid + "_new.submit();");
				return;
			}
			
			//alert(url);
			// and upload type will never ajax home
			Aajax(weburl + "outline/ajax.php", url, _saveAddNewElement);
		}
		else
		{
			cloud(false);
			return;
		}		
	}



///////////////////////////////////////////////////
// VALIDATION FUNCTIONS - 8 in total
///////////////////////////////////////////////////

	function prepareUrl(s)
	{
		return escape(s);
	}

	function validateNotes(guid)
	{
		if (trim(removeHTMLTags(get("name_" + guid + "_new").value))=="")
		{
			alert("You must supply at least the Title field.");
			return "";
		}
		
		var name = prepareUrl(get("name_" + guid + "_new").value);		
		var brief = prepareUrl(get("brief_" + guid + "_new").value);
		
		var url = 	"name=" + name +
					"&brief=" + brief;
		return url;
	}

	function validateCase(guid)
	{
		if (trim(removeHTMLTags(get("name_" + guid + "_new").value))=="")
		{
			alert("You must supply at least the case name.");
			return "";
		}
		
		var name = prepareUrl(get("name_" + guid + "_new").value);		
		var cite = prepareUrl(get("cite_" + guid + "_new").value);
		var brief = prepareUrl(get("brief_" + guid + "_new").value);
		var posture = prepareUrl(get("posture_" + guid + "_new").value);
		var facts = prepareUrl(get("facts_" + guid + "_new").value);
		var issue = prepareUrl(get("issue_" + guid + "_new").value);
		var rule = prepareUrl(get("rule_" + guid + "_new").value);
		var hold = prepareUrl(get("hold_" + guid + "_new").value);
		var dissent = prepareUrl(get("dissent_" + guid + "_new").value);
		var notes = prepareUrl(get("notes_" + guid + "_new").value);
		var page = prepareUrl(get("page_" + guid + "_new").value);
		var judge = prepareUrl(get("judge_" + guid + "_new").value);
		var case_date = prepareUrl(get("case_date_" + guid + "_new").value);
		
		var url = 	"name=" + name +
					"&cite=" + cite +
					"&brief=" + brief +
					"&posture=" + posture +
					"&facts=" + facts +
					"&issue=" + issue +
					"&rule=" + rule +
					"&hold=" + hold +
					"&dissent=" + dissent +
					"&notes=" + notes +
					"&page=" + page +
					"&judge=" + judge +
					"&case_date=" + case_date;
		return url;
	}
	

	function validateArticle(guid)
	{
		if (trim(removeHTMLTags(get("name_" + guid + "_new").innerHTML))=="")
		{
			alert("You must supply at least the article title.");
			return "";
		}
		
		var name = prepareUrl(get("name_" + guid + "_new").value);	
		var publication = prepareUrl(get("publication_" + guid + "_new").value);
		var publication_date = prepareUrl(get("publication_date_" + guid + "_new").value);
		var author = prepareUrl(get("author_" + guid + "_new").value);
		var brief = prepareUrl(get("brief_" + guid + "_new").value);
		var notes = prepareUrl(get("notes_" + guid + "_new").value);
		var page = prepareUrl(get("page_" + guid + "_new").value);
		
		
		var url = 	"name=" + name +
					"&publication=" + publication +
					"&publication_date=" + publication_date +
					"&author=" + author +
					"&brief=" + brief +
					"&notes=" + notes +
					"&page=" + page;
		return url;
	}

	
	function toggleField(section_element_id, field, disp)
	{
		get(section_element_id + "_" + field + "_field").style.display = disp;
		get(section_element_id + "_" + field + "_value").style.display = disp;

	}
	
	
	function showAllCaseFields(section_element_id)
	{
		// need to get all hidden fields for this case and show them
		var id = "toggleLink_" + section_element_id;
		var linkText = "";
		var newDisp = get(section_element_id + "_cite_field").style.display=="" ? "none" : "";
		
		if (newDisp=="")
		{
			get(id).innerHTML = "Hide Less Important Fields";
		}
		else
		{
			get(id).innerHTML = "Show All Fields";
		}
		//get(o).innerHTML = linkText;
		toggleField(section_element_id, "cite", newDisp);
		toggleField(section_element_id, "posture", newDisp);
		toggleField(section_element_id, "hold", newDisp);
		toggleField(section_element_id, "dissent", newDisp);
		toggleField(section_element_id, "page", newDisp);
		toggleField(section_element_id, "judge", newDisp);
		toggleField(section_element_id, "case_date", newDisp);
	}

	function validateBlackletter(guid)
	{					
		if (trim(removeHTMLTags(get("name_" + guid + "_new").value))=="")
		{
			alert("You must supply the name of the blackletter law.");
			return "";
		}
		
		var name = prepareUrl(get("name_" + guid + "_new").value);		
		var rule = prepareUrl(get("rule_" + guid + "_new").value);
		var notes = prepareUrl(get("notes_" + guid + "_new").value);
		var page = prepareUrl(get("page_" + guid + "_new").value);
		
		var url = 	"name=" + name +
					"&rule=" + rule +
					"&notes=" + notes +
					"&page=" + page;		
		return url;
	}

	function validateStatute(guid)
	{					


		if (trim(removeHTMLTags(get("name_" + guid + "_new").value))=="")
		{
			alert("You must supply the name of the statute.");
			return "";
		}
		
		var statute_type = get("statute_type_" + guid + "_new").value;
		var name = prepareUrl(get("name_" + guid + "_new").value);		
		var rule = prepareUrl(get("rule_" + guid + "_new").value);
		var notes = prepareUrl(get("notes_" + guid + "_new").value);
		var page = prepareUrl(get("page_" + guid + "_new").value);
		
		var url = 	"name=" + name +
					"&rule=" + rule +
					"&notes=" + notes +
					"&page=" + page;
		return url;
	}
	
	function validateUpload(guid, type)
	{					

		if (trim(removeHTMLTags(get("name_" + guid + "_new").innerHTML))=="")
		{
			alert("You must supply a name for the file you are uploading.");
			return "";
		}
		
		var name = prepareUrl(get("name_" + guid + "_new").value);		
		var notes = prepareUrl(get("notes_" + guid + "_new").value);
		
		var url = 	"name=" + name +
					"&notes=" + notes;
		return url;
	}

	function startUpload(id)
	{
		//alert("uploading");
		return true;
	}
	
	function stopUpload(error, guid)
	{
		if (error!="")
		{
			alert(error);
			cloud(false);
			return;
		}

		var pos = guid.lastIndexOf("_");
		trueGuid = guid.substr(0, pos);
		var js = "";
		var r = "";
		var section_element_id = 0;
		eval("js = top.upload_target_frame_" + guid + ".document.getElementById('eval_" + guid + "').innerHTML;");
		eval("r = top.upload_target_frame_" + guid + ".document.getElementById('html_" + guid + "').innerHTML;");
		eval("section_element_id = top.upload_target_frame_" + guid + ".document.getElementById('section_element_id_" + guid + "').innerHTML;");
		

			pos = js.indexOf("--");
			js = js.substring(pos+2); 
			// do NOT eval this until we add our new element to the DOM

			//alert(js);
			//alert(r);
			//alert(section_element_id);
			pos = guid.indexOf("_");
			var seid = guid.substring(pos+1);
			pos = seid.indexOf("_");
			seid = seid.substr(0, pos);

			cancelAddNewElement(trueGuid);			
			var newEntry = document.createElement("div");
			newEntry.id = "section_element_container_" + section_element_id;
			newEntry.innerHTML = r;
			
		//	alert(guid);
			
			var f = null; 			
			if (guid.indexOf("sectionguid")>-1)
			{
				//alert("1: " + guid);
				f = get("insertDivDetails_" + trueGuid);
				insertAfter(f, newEntry);
			}
			else
			{
				//alert("2: " + seid);
				f = get("section_element_container_" + seid);
				insertAfter(f, newEntry);	
			}

			// now eval our js
			eval(js);
			
			//
			navigateTo("section_element", section_element_id, false);
			
			//cloud(false);
			
		return true;   
	}
	
	function toggleFileAttach(guid, torf)
	{
		
		var attachCount = get("attachCount_" + guid).value;
		var nonAttachCount = get("nonAttachCount_" + guid).value;
		
		//alert(attachCount + " " + nonAttachCount);
		
		if (torf)
		{
			// hide insert element and show attach
			for (var i=0; i<nonAttachCount; i++)
			{
				hide("basic_element_" + guid + "_" + i);
			}
			for (var i=0; i<attachCount; i++)
			{
				show("file_upload_" + guid + "_" + i);
			}	
			get("cancel_button_" + guid).value = "Back";
		}
		else
		{
			// hide attach and show insert
			for (var i=0; i<attachCount; i++)
			{
				hide("file_upload_" + guid + "_" + i);
			}	
			for (var i=0; i<nonAttachCount; i++)
			{
				show("basic_element_" + guid + "_" + i);
			}	
			get("cancel_button_" + guid).value = "Cancel";
		}
	}


	

	
	function addElementType(type, guid, parent, nodePos)
	{
		// before anything we need to see if we're type=13 which means we've just selected to attach an element
		// instead of inserting an element
		if (type==13)
		{
			toggleFileAttach(guid, true); 
			return;
		}
		
		
		// someone has clicked what type of element they want to add to their outline
		// now we have to dial home, get the html that corresponds to that type of entry
		// and display it to them.
		var f = get("insertDivDetails_" + guid);
		f.innerHTML = waitAjax();
		
		function _addElementType(r)
		{
			session(r);
			get("insertDivDetails_" + guid).innerHTML=r;
			//alert(guid);
			smoothScroll("insertDivDetails_" + guid, -67);
			
			// let's set focus on the first field for whatever type form we show
			var focusField = "";			
			switch (Number(type))
			{
				case 1:	// case
					focusField = "name";
					break;
				case 8:	// notes
					focusField = "name";
					break;
				case 20:	// blackletter
					focusField = "name";
					break;
				case 21:	// statute
					focusField = "name";					
					break;		
				case 11: // article	
					focusField = "name";
					break;	
				case 18: // hypo
					focusField = "name";
					break;
					
				case 4:
				case 5:
				case 10:
				case 6:
				case 7:
				case 12:
					focusField = "name";
					break;	
												
			}
			if (focusField!="")
			{
				focusField = focusField + "_" + guid + "_new";
				//alert(focusField + " " + type);
				get(focusField).focus();
			}
			jQuery("textarea[class*=expand]").TextAreaExpander();
		}
			undoDropMenus();	
		Aajax(weburl + "outline/ajax.php", "addElementForm_step_2=1&type=" + type + "&guid=" + guid + "&parent=" + parent + "&nodePos=" + nodePos, _addElementType);		
	}

	function cancelAddNewElement(guid)
	{
		
		if (get("cancel_button_" + guid)!=null)
		{	
			if (get("cancel_button_" + guid).value=="Back")
			{
				toggleFileAttach(guid, false);
				return;
			}
		}
		
		if (guid=="")
		{
			//debug("Blank guid in cancel add new element");
			return;
		}
		// we're not adding an element anymore
		curInsertElement = "";
		var f = get("insertDivDetails_" + guid);
		hide(f.id);
		f.innerHTML = "";
		show("insertDivDummy_" + guid);
		get("addFreshButton").className = "gbButton";
	}

	function insertDivClick(t, parent, guid, section_name, section_element_id)
	{
		//alert(parent + " its the problem when we're moving that's an issue");
		
		cleanMe();
		try
		{
			//insertDivDummy_sectionguid_357
			get("insertDivDummy_" + guid).className = "insertDiv";
		}
		catch(e){}
		
		get("addFreshButton").className = "gbButtonDisabled";
		curInsertElement = guid;
		
		var nodePos = 0;	
		
		nodePos = getNodePos(t);
		hide(t.id);
		var f = get("insertDivDetails_" + guid);	
		
		function _insertDivClick(r)
		{
			session(r);
			// gets server response of html for the form we will use to add and element (or section)			
			f.innerHTML = r;
			smoothScroll("insertDivDetails_" + guid, -67);						
			return;
		}
		 
		// show wait until ajax response
		f.innerHTML = waitAjax();		
		show(f.id);
		
		// update the dirty list on the edit link for the section
		// in case user doesnt finish here
		/*
		var curDirty = get("editSectionLink_sectionguid_" + parent).getAttribute("dirtyDivs");
		var newDirty = curDirty + guid + ":";
		get("editSectionLink_sectionguid_" + parent).setAttribute("dirtyDivs", newDirty);
		*/
		
		Aajax(weburl + "outline/ajax.php", "addElementForm_step_1=1&parent=" + parent + "&guid=" + guid + "&section_name=" + section_name + "&nodePos=" + nodePos, _insertDivClick);	
	}
	
	function waitAjax()
	{
		return "<table width=\"100%\" border=\"0\"><tr><td width=\"1%\" style=\"height:35px; padding:15px;\"><img src=\"" + weburl + "wait_16_ECECEC.gif\" height=\"16\" width=\"16\" border=\"0\" /></td><td valign=\"middle\" style=\"padding:15px; font-size:10px; color:#333333\">&nbsp;&nbsp;Loading content...</td></tr></table>";
	}
	
	


  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
	

	function clickPlusMinusElement(t, section_element_id, elements_id, type, e) 		// this is for a clicked element // 
	{
		
		// always ensure we hide a config box
		hideConfig(section_element_id);
		
		// we've overriden the passed t for good reasons 
		t = get("plusminus_" + section_element_id);
		
		var thisIndent = findPosX(t);
		
		//alert(thisIndent);
		var tick = 0;
		var o = get("elementDetails_" + section_element_id);			
		function _clickPlusMinusElement(r)
		{
			session(r);
			if (tick==1)
			{
				o.innerHTML = r;
				if (o.style.display=="")
				{
					//alert(o.id);
					if (false) //e.ctrlKey)
					{
						smoothScroll(t.id, -67);
					}
					show(o.id);
				}
				t.src = weburl + "minus_0.gif";
			}
			if (tick==0)
			{
				//alert(r);
				t.src = weburl + "plus_0.gif";
				get("wait_sectionelement_" + section_element_id).src = weburl + "wait_blank.gif";
			}	
			jQuery("textarea[class*=expand]").TextAreaExpander();			
			return;
		}
		
		if (o.style.display=="")
		{
			get("wait_sectionelement_" + section_element_id).src = weburl + "plus_loader.gif";
			// here we simply hide the div
			o.style.display = "none";
			t.src = weburl + "plus_0.gif";
			tick = 0;
		}
		else
		{
			// here we have some work to do since we have to dial home
			//alert((thisIndent-7));
			o.style.marginLeft = (thisIndent-7) + "px";
			o.innerHTML = waitAjax();
			t.src = weburl + "minus_0.gif";
			show(o.id);
			tick = 1;
		}		
		Aajax(weburl + "outline/ajax.php", "getElementDetails=1&section_element_id=" + section_element_id + "&tick=" + tick + "&elements_id=" + elements_id + "&type=" + type, _clickPlusMinusElement);		
	}


	
	function favoriteClick(t, section_element_id)
	{
		
		var tick = 2;
		if (t.src.indexOf("_2")>0)
		{
			tick = 0;
			t.src=weburl+"favorite_0.gif";
		}
		else
		{
			t.src=weburl+"favorite_2.gif";
		}
		
		
		function _favoriteClick(r)
		{
			session(r);	
			get("wait_sectionelement_" + section_element_id).src = weburl+"wait_blank.gif";
		}

		get("wait_sectionelement_" + section_element_id).src=weburl+"plus_loader.gif";
		var url = "toggleFavorite=1&section_element_id=" + section_element_id + "&tick=" + tick;
		Aajax(weburl+"outline/ajax.php", url, _favoriteClick);
	}

	function hoverFavorite(t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "favorite" + change + ".gif";
		}
		else
		{
			t.src = weburl + "favorite" + change + ".gif";
		}		
		
		//t.style.cursor = "pointer";	
	}
	
	function hideConfig(section_element_id)
	{
		hide("configElement_" + section_element_id);
		get("config_icon_" + section_element_id).src=weburl+"config_0.gif";
		
	}	

	function hideSectionConfig(section_id)
	{
		hide("configSection_" + section_id);
		get("config_section_icon_" + section_id).src=weburl+"config_0.gif";
		
	}	


	function moveSection(section_id, parent_id)
	{
		var o = get("moveSectionSelection_" + section_id);
		var new_section = o.value;		
		
		//alert(parent_id + " " + new_section);
		
		if (parent_id==new_section)
		{
			alert("This is the original section this section is in.");
			//cancelConfigOptions(section_element_id, false);
			return;
		}
		cleanMe();
		var depth = get("uniqueSectionId_" + new_section).getAttribute("depth_charge");
		cloud(true);
		
		function _moveSection(r)
		{
			session(r);			
			var pos = r.indexOf("--");
			var after = r.substr(0, pos);
			//alert(after);			
			r = r.substring(pos+2);
			pos = r.indexOf("--");
			var js = r.substr(0, pos);		
			//alert(js);
			var html = r.substring(pos+2);
			pos = html.indexOf("\n");
			//alert(pos);
			html = html.substring(pos);
			//alert(html);//


			// must remove the old instance		
			var section = get("section_container_" + section_id);
			var section_parent = get(section.parentNode.id);							
			//alert(section.id + " -- " + section_parent.id);
			section_parent.removeChild(section);			

			var newEntry = document.createElement("div");
			newEntry.id = "section_container_" + section_id;
			newEntry.setAttribute("isBaseNode", "0");
			newEntry.style.display = "";
			newEntry.innerHTML = html;
			
			//alert(after);
			
			// we need the section_element_id of THIS current element we're inserting below
			var f = get(after);
			insertAfter(f, newEntry);			
			//smoothScroll("plusminus_section_" + new_section, -67);


						
			cleanMe();
			eval(js);			
			navigateTo("section", section_id);			
			
			//cloud(false);
			//smoothScroll("plusminus_section_" + section_id, -67);
			return;
		}		

		var url = "moveSection=1&section_id=" + section_id + "&new_section=" + new_section + "&depth=" + depth + "&old_section=" + parent_id;
		//alert(url);
		Aajax(weburl+"outline/ajax.php", url, _moveSection);
	}

	
	function moveElement(section_element_id, section_id)
	{

		var o = get("moveElementSelection_" + section_element_id);
		var new_section = o.value;		
		
		if (section_id==new_section)
		{
			alert("This is the original section the element is in.");
			//cancelConfigOptions(section_element_id, false);
			return;
		}
		cleanMe();
		var depth = get("uniqueSectionId_" + new_section).getAttribute("depth_charge");
		cloud(true);
		
		function _moveElement(r)
		{
			session(r);
			//alert(r);
			var pos = r.indexOf("--");
			var after = r.substr(0, pos);
			//alert(after);
			r = r.substring(pos+2);		
			pos = r.indexOf("--");
			var count = r.substr(0, pos);
			//alert(count);
			var js = r.substr(pos+2, count);
			//alert(js);
			r = r.substring(pos+2+Number(count));
			//alert(r);
			// need to remove the previous location of the element we're moving
			var section_element = get("section_element_container_" + section_element_id);
			var section = get(section_element.parentNode.id);	
			section.removeChild(section_element);
			
			// need to insert after the last element in the section we've moved to
			var newEntry = document.createElement("div");
			newEntry.id = "section_element_container_" + section_element_id;
			newEntry.innerHTML = r;		
			
			//alert(after);
			
			var f = get(after);
			insertAfter(f, newEntry);	

			// finally need to update nodePos and (#) for both of the effected sections			
			eval(js);			
			navigateTo("section_element", section_element_id);
			//cloud(false);
			//smoothScroll("plusminus_" + section_element_id, -67);
			return;
		}		

		var url = "moveElement=1&section_element_id=" + section_element_id + "&new_section=" + new_section + "&depth=" + depth;
		Aajax(weburl+"outline/ajax.php", url, _moveElement);
	}

	function configClick(t, section_element_id)	// config for an element
	{
		var wasOrange = false;
		if (t.src.indexOf("_2")>0)
		{
			wasOrange = true;
		}
		// if another config area is open for another elemetn close it before we allow this
		// config.  this will prevent issues if someone cconfigs this and it were to alter.
		cleanMe();
		curElementConfig = section_element_id;
		if (wasOrange)
		{
			t.src=weburl+"config_2.gif";
		}
		var o = get("configElement_" + section_element_id);
		var o2 = get("configElementInner_" + section_element_id);
		
		// always hide details in case they were being viewed
		hide("elementDetails_" + section_element_id);
		get("plusminus_" + section_element_id).src = weburl+"plus_0.gif";
		
		var tick = 2;
		//alert(t.src);
		if (t.src.indexOf("_2")>0)
		{
			//alert("here");
			tick = 0;
			t.src=weburl+"config_0.gif";
			cancelConfigOptions(section_element_id, false);
			return;
		}
		else
		{
			t.src=weburl+"config_2.gif";
		}
		

		
		function _configClick(r)
		{
			session(r);				
			o2.innerHTML = r;
			//smoothScroll("plusminus_" + section_element_id, -67);
			return;
		}
		
		// let's update the config arrow
		o2.innerHTML = waitAjax();
		var arrow = get("config_arrow_" + section_element_id);
		arrow.style.left = (findPosX(t)-24) + "px";
		show(arrow.id);
		show(o.id);
		var url = "getElementConfig=1&section_element_id=" + section_element_id;
		Aajax(weburl+"outline/ajax.php", url, _configClick);
	}


	function configSectionClick(t, section_id)	// config for an element
	{
		var wasOrange = false;
		if (t.src.indexOf("_2")>0)
		{
			wasOrange = true;
		}
		// if another config area is open for another elemetn close it before we allow this
		// config.  this will prevent issues if someone cconfigs this and it were to alter.
		cleanMe();
		curSectionConfig = section_id; //
		if (wasOrange)
		{
			t.src=weburl+"config_2.gif";
		}
		var o = get("configSection_" + section_id);
		var o2 = get("configSectionInner_" + section_id);
		
		// always hide details in case they were being viewed
		if (get("plusminus_section_" + section_id).src.indexOf("minus")>0)
		{
			//clickPlusMinus(get("plusminus_section_" + section_id), section_id);
			
			get("plusminus_section_" + section_id).src = weburl + "plus_0.gif";
			get("sectionHolderDiv_" + section_id).style.display="none";
			// 
		}
		
		var tick = 2;
		if (t.src.indexOf("_2")>0)
		{
			tick = 0;
			t.src=weburl+"config_0.gif";
			cancelConfigSectionOptions(curSectionConfig, false);
			return;
		}
		else
		{
			t.src=weburl+"config_2.gif";
		}
		

		
		function _configSectionClick(r)
		{
			session(r);				
			o2.innerHTML = r;
			//smoothScroll("plusminus_section_" + section_id, -67);
			return;
		}
		
		// let's update the config arrow
		o2.innerHTML = waitAjax();
		var arrow = get("config_section_arrow_" + section_id);
		arrow.style.left = (findPosX(t)-24) + "px";
		show(arrow.id);
		show(o.id);
		var url = "getSectionConfig=1&section_id=" + section_id;
		Aajax(weburl+"outline/ajax.php", url, _configSectionClick);
	}

	// 
	function hoverConfigSection(t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "config" + change + ".gif";
		}
		else
		{
			t.src = weburl + "config" + change + ".gif";
		}		
		
		//t.style.cursor = "pointer";	
	}
	



	function hoverConfig(t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "config" + change + ".gif";
		}
		else
		{
			t.src = weburl + "config" + change + ".gif";
		}		
		
		//t.style.cursor = "pointer";	
	}
	

	
	function hoverRemove(t, torf)
	{	
		if (t.src.indexOf("_2")>0)
		{
			// don't highlight if this is ticked 2
			return;
		}
		
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("_1")>0)
		{
			t.src = weburl + "remove" + change + ".gif";
		}
		else
		{
			t.src = weburl + "remove" + change + ".gif";
		}		
		
		//t.style.cursor = "pointer";	
	}	


	function hoverPlusMinus(t, torf)
	{	
		var change = "_0";
		if (torf)
		{
			change = "_1";
		}
		if (t.src.indexOf("plus")>0)
		{
			t.src = weburl + "plus" + change + ".gif";
		}
		else
		{
			t.src = weburl + "minus" + change + ".gif";
		}		
		
		t.style.cursor = "pointer";	
	}

	function cloud(torf)
	{
		if (torf)
		{
			get("darkBackgroundLayer").style.display = "";
		}
		else
		{
			get("darkBackgroundLayer").style.display = "none";
		}
	}

	function rand(low, high)
	{
		return (Math.round((Math.random()*high)+low));
	}
		
	function opacity(o, op)
	{
		if (op>100)
		{
			op = 100;
		}
		if (op<0)
		{
			op = 0;
		}
		
		if (isMoz())
		{	
			op *= .01;
			o.style.MozOpacity = op;
		}
		
		if (isChrome() || isSafari())
		{			
			op *= .01;
			//o.style.opacity = op;			
			o.style.opacity=op;
		}
		
		if (isIE())
		{
			//o.filters.alpha.opacity=op;
			//o.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity:" + op + ")";	
			//o.style.filter="alpha(opacity=" + op + ")";
			o.filters.alpha.opacity=op;
		}		
	}

	function getCursorPos(id) 
	{
	
		var o = get(id);	
		
		if (document.selection) 
		{	
		//	alert("1");
			// ie
			var r = document.selection.createRange();	
			
			// only insert tab if we are a single blinking cursor (i.e. no range)	
			if (r.text.length==0)
			{
				o.focus ();
				var r = document.selection.createRange();
				r.moveStart ('character', -o.value.length);
				var pos = r.text.length;		
				return pos;
				o.value = o.value.substring(0, pos) + char + o.value.substr(pos);
				
				
				r = o.createTextRange();
				r.collapse(true);
				r.moveEnd('character', pos+1);
				r.moveStart('character', pos+1);
				r.select();
			}		
		}
		else if (o.selectionStart || o.selectionStart=='0') 
		{	
		//	alert("2");
			// ff, saf, chrome
			var text = o.value;		
			var s = o.selectionStart;
			var e = o.selectionEnd
			
			// only insert tab if we are a single blinking cursor (i.e. no range)
			if (s==e)
			{					
				return s;
				o.value = text.substring(0, s) + char + text.substr(s);
				o.selectionStart = s+1;
				o.selectionEnd = s+1;
				s.focus();
			}
			return;
		}
	}

	function insertAtIbeam(id, char) 
	{
	
		var o = get(id);	
		
		if (document.selection) 
		{	
			alert("1");
			// ie
			var r = document.selection.createRange();	
			
			// only insert tab if we are a single blinking cursor (i.e. no range)	
			if (r.text.length==0)
			{
				o.focus ();
				var r = document.selection.createRange();
				r.moveStart ('character', -o.value.length);
				var pos = r.text.length;					
				o.value = o.value.substring(0, pos) + char + o.value.substr(pos);
				
				
				r = o.createTextRange();
				r.collapse(true);
				r.moveEnd('character', pos+1);
				r.moveStart('character', pos+1);
				r.select();
			}		
		}
		else if (o.selectionStart || o.selectionStart=='0') 
		{	
			alert("2");
			// ff, saf, chrome
			var text = o.value;		
			var s = o.selectionStart;
			var e = o.selectionEnd
			
			// only insert tab if we are a single blinking cursor (i.e. no range)
			if (s==e)
			{					
				o.value = text.substring(0, s) + char + text.substr(s);
				o.selectionStart = s+1;
				o.selectionEnd = s+1;
				s.focus();
			}
			return;
		}
	}
	

	function ibeam(o, s, e)
	{
		if (isMoz())
		{
			o.setSelectionRange(s,e);
		}
		else
		{
			var r = o.createTextRange();		
			r.collapse(true);		
			r.moveEnd('character', e);		
			r.moveStart('character', s);		
			r.select();		
		}		
	}
		
	function getOpacity(o)
	{

		if (isMoz())
		{		
			if (o.style.MozOpacity=="")
			{
				o.style.MozOpacity = 1;
			}
			return (o.style.MozOpacity) * 100;
		}
		else
		{
			try
			{
				return o.filters.item("DXImageTransform.Microsoft.Alpha").Opacity;
			}
			catch (e)
			{
				o.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity:100)";
				return 100;
			}
		}		
	}

	
	function getEventObject(e)
	{
		if (isMoz())
		{
			return e.target;
		}
		else
		{
			return e.srcElement;
		}
	}
	
	function niceDate(date)
	{
		// assume date = yyyy-mm-dd
		return String(date.substr(5,2)) + "/" + String(date.substr(8, 2)) + "/" + String(date.substr(0,4));
	}
	
	function mysqlDate(date)	
	{
		// assume date = mm/dd/yyyy
		return String(date.substr(6,4)) + "-" + String(date.substr(0,2)) + "-" + String(date.substr(3,2));
	}

	function getTotalOffset(o, what)
	{
		var totalLeft = 0;
		var totalTop = 0;
		while (o!=null)
		{
			totalLeft += o.offsetLeft;
			totalTop += o.offsetTop;
			o = o.offsetParent;
		}			
				
		if (what.toUpperCase()=="LEFT")
		{
			return totalLeft;
		}
		
		if (what.toUpperCase()=="TOP")
		{
			return totalTop;
		}
	}	
	
	function validatePasswords(p1, p2)
	{
				
		p1 = unescape(p1);
		p2 = unescape(p2);
		
		
		
		if (trim(p1)=="" || trim(p2)=="")
		{
			alert("You must supply a password and a confirmed password.");
			return false;
		}
		
		if (p1!=p2)
		{
			alert("The passwords do not match.  Please try again.");
			return false;
		}
		
		return true;
		
	}
	
	function validateZip(zip)
	{	
		if (isNaN(Number(zip)))
		{
			return false;
		}
		
		if (String(zip).length!=5)
		{
			return false;
		}
		
		return true;
	}


	
	function get(id)
	{
		if (document.getElementById(id)==null)
		{			
			//alert("cannot get element with id: " + id);
			return null;
		}
		return document.getElementById(id);
	}
	
	function hide(id)
	{
		if (document.getElementById(id)==null)
		{
			return;
		}
		document.getElementById(id).style.display = "none";
	}

	
	function show(id)
	{
		if (document.getElementById(id)==null)
		{
			//alert("Cannot show id: " + id);
			return;
		}
		document.getElementById(id).style.display = "";
	}

	function inline(id)
	{
		document.getElementById(id).style.display = "inline";
	}

	function disable(id)
	{
		document.getElementById(id).disabled = true;
	}
	
	function enable(id)
	{
		document.getElementById(id).disabled = false;		
	}
	
	function clear(id)
	{
		document.getElementById(id).value = "";
	}

	function setFocus(id)
	{
		document.getElementById(id).focus();
	}	

function Aajax (page, query, fn)
{
	
	// weird IE bug related to HTTPS ajax calls, sometimes fails
	var x = null;	
	if (window.XMLHttpRequest)  
	{
		// FF
		x = new XMLHttpRequest(); 
	}
	else if (window.ActiveXObject)
	{	
		try
		{
			x = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e2)
		{
			try
			{
				// IE
				x = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e2) 
			{
				fn("Failure in core.js.");
				  return;
			}
		}
	}

	function stateChange()
	{		
		if (x.readyState==4)		
		{
			fn(x.responseText);
		}
	}

	var postPage =  page;
	x.open("POST", postPage, true);
	x.onreadystatechange = stateChange;
	x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");			
//	x.setRequestHeader("Connection", "close");
	x.send(query);
	success = true;
			

	//return x.responseText;
}


	function isSafari()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("safari")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}

	function isChrome()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("chrome")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}

	function isFF()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("firefox")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}


	function isMoz()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("firefox")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}

	function isMoz()
	{
		var browser = navigator.userAgent.toLowerCase();	
		if (browser.indexOf("firefox")!=-1)
		{
			return true;
		}
		else
		{
			return false;
		}		
	}
	

	function getScreenWidth()
	{
		return document.documentElement.clientHeight;
	}
	

	function validatePositiveInteger (val)
	{
		if (isNaN(val))
		{
			return false;
		}
		if (val.indexOf(".")!=-1)
		{
			return false;
		}
		if (val.indexOf("-")!=-1)
		{
			return false;
		}
		return true;
	}
	
	function validateCurrency (val)
	{
		if (isNaN(val))
		{
			return false;
		}
		
		// how many "." places are there?
		if (val.indexOf(".")!=-1)
		{
			var pos = -1;
			var cVal = val;
			pos = cVal.indexOf(".");
			cVal = cVal.substr(pos+1, cVal.length);
			if (cVal.length>2)
			{
				return false;
			}
		}	
		
		if (val.indexOf("-")!=-1)
		{
			return false;
		}
		
		return true;
	}	
	
	function trim(val)
	{
		val = val.replace(/^\s+|\s+$/, "");
		val = val.replace(/&nbsp;/g, "");
		return val;
	}
	
	function validateEmail(email)
	{

		var atPos = email.indexOf("@");

		// no @ sign please
		if (atPos==-1)
		{
			return false;
		}
		
		var first = email.substring(0, atPos);
		var second = email.substr(atPos+1, email.length);
		
		// confirm valid a-z 0-9 and . _ - chars only!!!
		if (!first.match("^[-\._A-Za-z0-9]+$") || !second.match("^[-\._A-Za-z0-9]+$"))
		{
			return false;
		}
		
		
		// @ can't be in the second part if we've already split on it
		atPos = second.indexOf("@");
		if (atPos!=-1)
		{
			return false;
		}

		var tld = second.substr(second.length-5, second.length);
		tld = tld.toLowerCase();
		var cTld = tld;
		// only .com, .net, .org, .biz, .us, .gov, .info .edu addresses are allowed
		var periodPos = 0;
		var i = 0;
		while (i < cTld.length+1)
		{
			var foo = cTld.substr(cTld.length-i, cTld.length);
			if (foo.substring(0,1)==".")
			{
				periodPos = i;
			}
			
			i++;
		}

		var trueTld = tld.substr(tld.length-periodPos, tld.length);
		if (trueTld=="")
		{
			return false;
		}

		if (periodPos==5)
		{
			if (trueTld!=".info")
			{
				return false;
			}
		}				
		if (periodPos==4)
		{
			if (trueTld!=".com" && trueTld!=".net" && trueTld!=".org" && trueTld!=".biz" && trueTld!=".gov" && trueTld!=".edu")
			{
				return false;
			}
		}
		if (periodPos==3)
		{
			if (trueTld!=".us")
			{
				return false;
			}
		}	
		if (periodPos!=3 && periodPos!=4 && periodPos!=5)
		{
			return false;
		}
		
		return true;
	}
	




  function handleElementHover(section_element_id)
  {
	  if (dragObject!=null)
	  {
		  get("debug").innerHTML = section_element_id;
	  }
  }
  
  
function mouseMove(ev){
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);

	

	if(dragObject){
	//	dragObject.style.position = 'absolute';
		//dragObject.style.width = "80%";
		dragObject.style.top      = (mousePos.y - mouseOffset.y) + "px";
		dragObject.style.left     = (mousePos.x - mouseOffset.x) + "px";
		
		// as we move this object we must always be aware of what elements 
		// we are inbetween and render the drop div accordingly
		
		return false;
	}
}

function showPostit()
{
	var o = get("postit");
	if (o.style.display=="none")
	{
		show("postit");
		get("postit_icon").src = weburl+"postit_2.png";
	}
	else
	{
		hide("postit");
		get("postit_icon").src = weburl+"postit_0.png";
	}
	savePostit();
}

function saveEditRefs(section_element_id, count)
{
	count = Number(count);
	//alert(count);
	var actualCount = 0;
	
//	alert(section_element_id + " " + count);
	function _saveEditRefs(r)
	{
		session(r);
		//alert(r);
		get("refsContainer_" + section_element_id).innerHTML = r;
		cancelEditRefs(section_element_id);
		return;		
	}
	
	var error = false;
	var i = 0;
	var colon = "";
	while (i < count)
	{
		try
		{
			var seid = get("refs_" + section_element_id + "_" + i).value;
			var cb = get("refs_cb_" + section_element_id + "_" + i);
			
			if (cb.checked)
			{
				//alert(seid);
				colon = colon + seid + ":";
				actualCount++;
			}
		}
		catch(e)
		{
			alert("Failed to capture all references.");
			error = true;
		}
		i++;
	}
	
	if (!error)
	{
		get("editRefsContainer_" + section_element_id).innerHTML = "Saving...";
		var url = "saveRefs=1&colon=" + colon + "&count=" + actualCount + "&section_element_id=" + section_element_id;
	//	alert(url);
		Aajax(weburl+"outline/ajax.php", url, _saveEditRefs);
	}
}

function cancelEditRefs(section_element_id)
{
	hide("editRefsContainer_" + section_element_id);	
	show("refsContainer_" + section_element_id);	
	get("editRefsContainer_" + section_element_id).innerHTML = "Loading...";
}

function editRefs(section_element_id)
{
	function _editRefs(r)
	{
		session(r);		
		//alert(r);
		get("editRefsContainer_" + section_element_id).innerHTML = r;
		smoothScroll(section_element_id + "_refs", -63);
		return;
	}
	hide("refsContainer_" + section_element_id);
	show("editRefsContainer_" + section_element_id);	
	var url = "getRefsHtml=1&section_element_id=" + section_element_id;
	Aajax(weburl+"outline/ajax.php", url, _editRefs);
}

function showEditRefsLink(section_element_id, torf)
{
	if (torf)
	{
		show("editRefsLink_" + section_element_id);
	}
	else
	{
		hide("editRefsLink_" + section_element_id);
	}
}

function closePostit()
{
	hide("postit");
	get("postit_icon").src = weburl+"postit_0.png";
	savePostit();
}

function savePostit()
{
	function _savePostit(r)
	{		
		session(r);
		return;
	}
	
	var postit = get("postit");
	var yellow_show = postit.style.display=="" ? "1" : "0";
	var yellow_x = Number(strippx(postit.style.left));
	var yellow_y = Number(strippx(postit.style.top));
	
	note_w = Number(strippx(postit.style.width));
	note_h = Number(strippx(postit.style.height));	
	
	postit.style.left = yellow_x + "px";
	postit.style.top = yellow_y + "px";

	//opacity(get("postit"), 50);

	var yellow_text = escape(get("postit_value").value);	
	var url = "updatePostitPos=1&yellow_x=" + yellow_x + "&yellow_y=" + yellow_y + "&yellow_text=" + yellow_text + "&yellow_show=" + yellow_show;
	Aajax(weburl+"outline/ajax.php", url, _savePostit);
}

function mouseUp(){
	//get("debug").innerHTML = dragObject.getAttribute("isCollapsed") + " " + dragObject.getAttribute("collapsedId");
	if (dragObject!=null)
	{
//		dragObject.style.position = "";
		
	}
	
	function _mouseUp(r)
	{
		session(r);
		//alert(r);
		return;
	}
	
	
	
	//alert(dragObject.style.top + " " + );
	if (dragObject!=null)
	{
		//opacity(dragObject, 60);
		dragObject = null;
		savePostit();
	}
}


function goDrag(t, e, section_element_id)
{
	dragObject=t;// get("section_element_container_" + section_element_id);	
	mouseOffset = getMouseOffset(t, e);
	//opacity(get("postit"), 100);
	return false;
}

function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function makeClickable(object){
	object.onmousedown = function(){
		dragObject = this;
	}	
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}



function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {

		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}



function makeDraggable(item){
	if(!item) return;
	item.onmousedown = function(ev){
		dragObject  = get("postit"); //this;
		mouseOffset = getMouseOffset(get("postit"), ev);
		return false;
	}
	//alert(dragObject.id);
}

function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}


function elmXPosition(eID, offset) {
    var elm = document.getElementById(eID);
    var x = elm.offsetLeft;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        x += node.offsetLeft;
    } return (x+offset);
}

function elmYPosition(eID, offset) {
	if (get(eID)==null)
	{
		return;
	}
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return (y+offset);
}

function smoothScroll(eID, offset) {
	if (offset==null)
	{
		offset = 0;
	}
	else
	{
		offset = Number(offset);
	}
	var startY = currentYPosition();
    var stopY = elmYPosition(eID, offset);
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        scrollTo(0, stopY); return;
    }
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
        for ( var i=startY; i<stopY; i+=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        } return;
    }
    for ( var i=startY; i>stopY; i-=step ) {
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
        leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
    }
}
