/**
 * @author bmarvell
 */

// Globals, these could probably all be factored into the imode Object.
var contextloc = "";
var updateURL = true;
var oldURL = "";
var ajaxresptext = "";
var timer;
var modalid = "";
var ismodal = false;
var inmodal = false;
var iscustommodal = false;
var newrl = "";
var hashbit = "";
var leftNav = true;
var triggerfunc;
var menuFix = {};
var menuCont = [];
var previewToggled = "none";
var bodyfade = true;
var showPreview = false;

// Just lets us make some form of console for IE - used in debugging
//var console = (!console) ? {log: function(data){alert(data)}} : console;

//Wicket calls this function upon a successful AJAX call - last functinon in the call
wicketGlobalPostCallHandler = function()
{
	if(!ismodal)
	{
		$.unblockUI();
	}

	if($('.issue_page').length && $('.noitemserror').length)
	{
		imode.showFirstStory(); // Show the first news story when we’ve arrived on a news issue page, either from elsewhere, or from the funding tab
	}
}

// If Wicket has a problem during the request
wicketGlobalFailureHandler = function()
{
	var reload = confirm('Sorry there has been a serious error. Select "OK" to reload the request or "Cancel" to go back home.');
	if (reload)
	{
		window.location.reload();
	}
	else
	{
		window.location = "/";
	}
}

// Highlight function, triggered from wicket.
function RRFlash(id)
{
	$("#"+id +" *").highlightFade({speed:  2000, color: "#FFFF99"});
}

// History updator
function RWTHistory_update(token)
{
	if (window.location.hash.indexOf("maxPreview") != -1)
	{
		token += "maxPreview$t$";
	}
	updateURL = false;
	$.history.load(token);

	//console.log(token);
	if (token.indexOf("query$") != -1)
	{
		token = token.split("query$");
		token = token[0]+ "query" +token[1].substr(token[1].indexOf("$"), token[1].length);
		//console.log(token)
	}
	//console.log("Logging to google page urchin: " + token)
	pageTracker._trackPageview(token);
}

// Show the Modal
function RWTPopupPanel_show(kind)
{
	var styles = {
		'induction-modal': {
			width: '856px',
			marginLeft: '-428px'
		}
	};

	if (!inmodal)
	{
		bodyfade = false;
		setTimeout(function(){$(".wicketBody").trigger("click")}, 0);
		ismodal = true;
		inmodal = true;
		modalid = $(".aj_modal").attr("id");
		imode.modalControls();
		$.extend($.blockUI.defaults.overlayCSS, { opacity: '0.5' });

		$.blockUI($("#modal .aj_modal"));
	}

	if (styles.propertyIsEnumerable(kind))
	{
		$('.blockMsg').css(styles[kind]);
		iscustommodal = true;
	}
	else
	{
		if (iscustommodal)
		{
			$('.blockMsg').css($.blockUI.defaults.pageMessageCSS);
			iscustommodal = false;
		}
	}
}

// Hide the Modal
function RWTPopupPanel_hide()
{
	//unblockui destrosys the element so we have to make it live AGAIN!!!
	$.unblockUI();
	$.extend($.blockUI.defaults.overlayCSS, { opacity: '0.2' });
	$("#modal").html('<div class="aj_modal" id="' + modalid + '">&nbsp;</div>');
	ismodal = false;
	inmodal = false;
}

// Trigger imode when the document is ready...
$(function()
{
	imode.bodyel = $("body");
	if (window.location.href.indexOf("maxPreview") != -1)
	{
		showPreview = true;
	}

	imode.fixEvents();

	if ($("#contextsave").length)
	{
		imode.controlAjaxDisp($("div.wicketBody").html());
	}

	var checkPage = function(newrl)
	{
		if (!updateURL)
		{
			updateURL = true;
			return;
		}

		if (oldURL == newrl)
			return;
		else
		{
			//if(updateURL)
			$("input.RWTHistoryValue").attr("value", newrl);
			$("body form input.RWTHistoryButton").trigger("click");

			oldURL = newrl;
		}
		//updateURL = true;
	}

	$.history.init(checkPage);
	
	// click induction button
	if ($('.inductionButton')) $('.inductionButton').click();
	
}
);

// Object imode contains all methods
var imode = {
	/*
	 * init - does what it says on the tin, just initializes imode
	 */
	init : function()
	{
		// add this so we can fork javascript only css away from non js users.
		this.bodyel.addClass("js_en");

		//Object Vars - set here to speed things up
		this.advert_height = "";
		this.menu_height = $("#menu").outerHeight();
		this.fixEvents();

		//Bring in the context menu for the first time (runs once)
		$("#main-menu .context-menu").fadeIn(1000).find("a").bind("click", function(){return false;});
		$("#main-menu .context-menu li.hascontext").fadeTo(0, 0.2);
		// Disable the buttons as default.
		$("#contextemail a").click(
			function()
			{
				$(".contextemail").trigger("click");
			}
		);

		//Setup interface heights etc and then bind captures to the resize.
		imode.controlIntFace();

		$(window).resize(
			function()
			{
				clearTimeout(timer);
				timer = setTimeout(
					function()
					{
						imode.scrollHeights();
						imode.controlIntFace();
					}, 50
				);
			}
		);
	},

	// Sends "enter key events" to wicket so it knows if you hit enter in a input box. Not sure why wicket doesnt seem to support this out of the box...?
	fixEvents : function()
	{
		$(".gwt-TextBox, .gwt-PasswordTextBox").each(
			function()
			{
				$(this).unbind("keypress");
				$(this).bind("keypress",
					function(e)
					{
						// is the enter key
						if (e.which == 13)
						{
							if (!$("#RWTTargetId").length)
							{
								$("form").prepend('<input id="RWTTargetId" type="hidden" name="RWTTargetId" value="' + $(this).attr("id") + '" />');
							}
							else
							{
								$("#RWTTargetId").attr("value", $(this).attr("id"));
							}
							$("body form input.RWTDefaultButton").trigger("click");
							return false;
						}
					}
				);
			}
		);
		$("#login-box .gwt-TextBox").unbind();
	},

	/*
	 * mainHeight - used to set the main height in iMode
	 */
	mainHeight : function()
	{
		this.body_height = imode.bodyel.outerHeight();
	},

	// Wipes any content from the Preview panel
	clearPreview : function()
	{
		$("#navigation a, .gwt-TabBar span").bind("click",
			function()
			{
				$("#preview > div").html("");
				return false;
			}
		);
	},

	// Set the scoll heights for differing components
	scrollHeights : function()
	{
		// sets the scroll heights for the main sections
		$("#main .panel .scroll, #preview .scroll").each(
			function()
			{
				// so we dont set scrollbars in browse by sponsor or browse by discipline...
				if ($(this).parent().parent().attr("class") == "itemlists")
				{
					return;
				}
				var comHeight = imode.advert_height;

				// Some elements (“subtractions”) need vertical space left for them by the .scroll sections. Because there may be more than one of each kind of element on a page, we search for them within the layout column that the .scroll section is in.
				var layout_columns = ['#main_with_extras', '.extras', '#submain', '#subleft', '.main_main', '#preview'];
				var current_layout_column;

				for (i in layout_columns)
				{
					var selector = layout_columns[i];
					if ($(this).parents(selector).length > 0)
					{
						current_layout_column = $(this).parents(selector);
						break;
					}
				}

				var subtractions = current_layout_column.find('#pagination, .scrollButtons');
				if(subtractions.length > 0)
				{
					var els = subtractions.get();
					for (i in els) {
						comHeight += $(els[i]).outerHeight();
					}
				}

				$(this).height(imode.body_height - $(this).offset().top - comHeight + 1);
			}
		);

		// this sorts out the heights for the navigation stacks
		$(".stack-panel").each(
			function()
			{
				var leftovers = ($(this).attr("id") == "left") ? (imode.body_height - $(this).offset().top) - 136 : (imode.body_height - $(this).offset().top);

				//IE box model heights mean we need to fork here...
				if ($.browser.msie && $(this).attr("id") == "left")
					leftovers -= 18;
				var headers = $(this).find("li div.stackHandle").outerHeight() * $(this).children("li").children("div.stackHandle").length;

				var stackbodyheight = ($(this).attr("id") == "left") ? leftovers - headers : leftovers - headers - 20;
				if ($.browser.msie)
					stackbodyheight += 20;

				$(this).children("li").children("div.stackHandle").next().height(stackbodyheight);
			}
		);

		$(".main_main").each(function()
		{
			$(this).height(imode.body_height - $(this).offset().top);
		}
		);
	},

	/*
	 * controlIntFace - deals with basic interface prerequisites
	 */
	controlIntFace : function()
	{
		this.mainHeight();
		$("#left>li div.stackHandle").removeClass("d_StartView");
		$("#left>li:has(.selectedNav)").children(".stackHandle").addClass("d_StartView");
		$("#preview li.d_StartView").children(".stackHandle").addClass("d_StartView");

		// triggers the accordion for each stack panel... (navigation panels)
		if ($.browser.msie)
		{
			$('.stack-panel').accordion(
			{
				header: 'div.stackHandle',
				animated: "bounceslide",
				active: '.d_StartView',
				selectedClass: 'd_StartView',
				autoHeight: false,
				animated: false
			}
			);
		} else
		{
			$('.stack-panel').accordion(
			{
				header: 'div.stackHandle',
				animated: "bounceslide",
				active: '.d_StartView',
				selectedClass: 'd_StartView',
				autoHeight: false
			}
			);
		}

		this.scrollHeights();
	},

	/*
	 * controlAjaxDisp - Routes and triggers required methods from ajax responces..
	 */
	controlAjaxDisp : function(ajaxtext)
	{
		imode.ajaxtext = ajaxtext;
		var scrollcounter = 0;
		//either run welcome or continue to main interface fork
		if (ajaxtext.indexOf("welcome-page") != -1)
		{
			imode.bodyel.removeClass("js_en");
			$("input[type=submit]").addClass("inputSubmit");
			$.unblockUI();
		}
		// only ever sent when the entire interface is being loaded so trigger init
		else
		{
			if (ajaxtext.indexOf("branding-panel"))
			{
				$("#branding-panel").click(
					function()
					{
						window.location = "/";
					}
				);
			}

			$("input[type=submit]").addClass("inputSubmit");
			if (ajaxtext.indexOf("uppermenu") != -1)
			{
				imode.init();
			}
			//right nav panel
			if (ajaxtext.indexOf("preview") != -1 && ajaxtext.indexOf("noitemserror") != -1)
			{
				removeTogglePreview();
			}

			if(ajaxtext.indexOf("d_Award_preview_stack") != -1)
			{
				removeTogglePreview();
				togglePreview();
				$("#preview .d_Award_preview_stack > div.stackHandle").css("display", "none");
				$("#preview .d_Award_preview > div.stackHandle").css("display", "none")
				$("#preview .d_Award_preview_meta").addClass("preview-meta");
				$(".d_Award_preview_stack > div > ul").addClass("stack-panel");
			}
			else if(ajaxtext.indexOf("d_Article_preview_stack") != -1)
			{

				$("#preview .d_Article_preview_stack > div.stackHandle").css("display", "none");
				$("#preview .d_Article_preview > div.stackHandle").css("display", "none")
				$("#preview .d_Article_preview_meta").addClass("preview-meta");
				$(".d_Article_preview_stack > div > ul").addClass("stack-panel");
			}
			else if(ajaxtext.indexOf("d_Sponsor_preview_stack") != -1)
			{
				removeTogglePreview();
				togglePreview();
				$("#preview .d_Sponsor_preview_stack > div.stackHandle").css("display", "none");
				$("#preview .d_Sponsor_preview > div.stackHandle").css("display", "none")
				$("#preview .d_Sponsor_preview_meta").addClass("preview-meta");
				$(".d_Sponsor_preview_stack > div > ul").addClass("stack-panel");
				setOpenToggle();
			}
			else if(ajaxtext.indexOf("d_Programme_preview_stack") != -1)
			{
				removeTogglePreview();
				togglePreview();
				$("#preview .d_Programme_preview_stack > div.stackHandle").css("display", "none");
				$("#preview .d_Programme_preview > div.stackHandle").css("display", "none")
				$("#preview .d_Programme_preview_meta").addClass("preview-meta");
				$(".d_Programme_preview_stack > div > ul").addClass("stack-panel");
				setOpenToggle();
			}

			if (ajaxtext.indexOf("d_Person_edit") != -1)
			{
				$(".d_Person_edit").click(
					function(e)
					{
						e.stopPropagation();
					}
				);
			}

			//
			if (ajaxtext.indexOf("matches") != -1)
			{
				$(".gwt-CheckBox[disabled]").next().css("color", "gray");
			}

			if (ajaxtext.indexOf("resultsgroup") != -1)
			{
				$("#resultsgroup .border").click(
					function(e)
					{
						e.stopPropagation();
					}
				);
			}

			//left nav panel...
			if (ajaxtext.indexOf("aj_navigation") != -1 || ajaxtext.indexOf("notselectedNav") != -1)
			{
				if (typeof(triggerfunc) == "function")
				{
					triggerfunc();
				}
				if (leftNav)
				{
					//this.navigationPanel($("#navigation .stack-panel"), "left");
				}
				else
				{
					leftNav = true;
				}
			}

			// to fix ropey old wicket
			if (ajaxtext.indexOf("gwt-TextBox"))
			{
				this.fixEvents();
			}


			if(ajaxtext.indexOf("scroll") != -1)
			{
				if (scrollcounter == 0)
				{
					//console.log(scrollcounter);
					this.scrollHeights();
					scrollcounter++;
				}
				if(ajaxtext.indexOf("checkbox") !=-1)
				{
					clickable_row();
				}
			}

			if (ajaxtext.indexOf("context") != -1)
			{
				this.contextMenu();
			}
			/*if (ajaxtext.indexOf("iframe") != -1)
			{
				$.frameReady(
				function()
				{
					window.top.imode.contextMenu(true);
				},
				"iframe"
				);
			}*/
			if(ajaxtext.indexOf("openclose") != -1)
			{
				imode.toggleSlide();
			}
			if(ajaxtext.indexOf("d_edit") != -1)
			{
				//this.mainHeight();
				this.scrollHeights();
			}

			if(ajaxtext.indexOf("class=\"html\"") != -1)
			{

			}

			if(ajaxtext.indexOf("main_main") != -1)
			{
				$("#main").addClass("no_preview");
			}

			if(ajaxtext.indexOf("main_layout1") != -1)
			{
				if ($("#togglePreview").length)
				{
					$("#toggleWrapper").remove();
				}
				/*$(".main_main").css("display", "block");*/
				$("#preview").removeClass("fullWidth");
			}

			if(ajaxtext.indexOf("issue_page") != -1 || ajaxtext.indexOf("main_layout2") != -1)
			{
				$("#main").removeClass("no_preview");
			}

			if(ajaxtext.indexOf("orderBy") != -1)
			{
				$("#groupSort input[type=image]").toggle(
					function(e)
					{
						$(this).attr("src", $(this).attr("src").replace("ascend", "descend"));
					},
					function(e)
					{
						$(this).attr("src", $(this).attr("src").replace("descend", "ascend"));
					}
				);
			}
			if (ajaxtext.indexOf('id="preview"') != -1 && showPreview)
			{
				setOpenToggle();
				showPreview = false;
			}
		}

		//Bind the datepicker, its here incase a datepicker comes back in an ajax call.
		this.datePicker();
		this.controlIntFace();
		this.scrollHeights();
		popUps($("a[rel=external]"));

		// ie blows chunks etc.
		if ($.browser.msie || $.browser.safari)
		{
			ieHashLinks($("a:not(rel=external)"));
		}
	},

	/*
	 * contextMenu - Acts as a router for local context buttons in the interface
	 */
	contextMenu : function(iframe)
	{
		$(".wicketBody").unbind();
		$(".wicketBody").bind("click",
			function(e)
			{
				e.stopPropagation();
				if (!bodyfade)
				{
					//Bring in the context menu for the first time (runs once)
					$("#main-menu .context-menu li").fadeTo(0, 0.2);
					// Disable the buttons as default.
					$("#main-menu .context-menu li.hascontext").fadeTo("slow", 0.2).children("a").unbind().click(function(){return false;});
					contextloc = "";
					$(".contextFocus").removeClass("contextFocus");
					bodyfade = true;
				}
			}
		);

		//Setup binds to context areas
		contextareas = [];
		$(".contextual-buttons").each(
			function()
			{
				if ($(this).find("input.hascontext").length > 0)
				{
					contextareas.push($(this).parent());
				}
			}
		);

		// go through each possible area and setup its associated actions.
		$.each(contextareas,
			function(i, n)
			{
				n.unbind();
				n.bind("click",
					function(e)
					{
						//stop event bubble
						e.stopPropagation();
						//Only one click!
						if (contextloc != $(this).text())
						{
							bodyfade = false;
							$(".contextFocus").removeClass("contextFocus");
							$(this).addClass("contextFocus");
							contextloc = $(this).text();
							var fadeinstring = "";
							$(this).find(".contextual-buttons input.hascontext").each(
								function(i)
								{
									var contextbutt = $(this);
									//var classpart = ($(this).attr("class").split(" ")) ? $(this).attr("class").split(" ")[0] : $(this).attr("class");
									var classpart = $(this).attr("class");
									classpart = classpart.substr(classpart.indexOf("context"), (classpart.indexOf("hascontext") - classpart.indexOf("context")));

									fadeinstring += (fadeinstring.length > 0) ? ", #"+ classpart : "#"+ classpart;

									$("#" + classpart+" a").attr("title", contextbutt.attr("title"));
									$("#" + classpart+" a").text(contextbutt.attr("value"));
									$("#" + classpart+" a").unbind().click(
										function(e)
										{	
											var t=$("#" + classpart+" a").text();
											if (t=="Publish") $("#" + classpart+" a").text("Unpublish");
											if (t=="Unpublish") $("#" + classpart+" a").text("Publish");
											if (t=="Subscribe") $("#" + classpart+" a").text("Unsubscribe");
											if (t=="Unsubscribe") $("#" + classpart+" a").text("Subscribe");
											contextbutt.click();
											e.stopPropagation();
											return false;
										}
									);
								}
							);

							$("#main-menu .context-menu li.hascontext").attr("bringin", "");
							$(fadeinstring).attr("bringin", "true");

							var fadeout = [];
							var highlight = [];
							var fadecount = 0;
							var highcount = 0;
							$("#main-menu .context-menu li.hascontext").each(
								function()
								{
									if ($(this).attr("bringin") != "true")
									{
										fadeout[fadecount] = "#" + $(this).attr("id");
										fadecount++;
									}
									if ($(this).attr("bringin") == "true" && $(this).css("opacity") != 1)
									{
										highlight[highcount] = "#" + $(this).attr("id");
										highcount++;
									}
								}
							);
							var fadeout = String(fadeout);
							var highlight = String(highlight);
							var highlight = String(highlight);

							$(fadeout).fadeTo("slow", 0.2, function(){butclick = 0;}).children("a").unbind().bind("click",
								function()
								{
									return false;
								}
							);

							$(fadeinstring).each(
								function()
								{
									var $this = $(this);
									if ($this.css("opacity") != 1){
										$this.fadeTo("slow", 1,
											function()
											{
												//Highlight new buttons if any
												if (highlight)
												{
													$this.children("a").highlightFade({speed:  500, color: "#FFFF99"});
												}

												$this.attr("bringin", "false");
												//butclick = 0;
											}
										);
									}
								}
							);
						}
					}
				);
			}
		);
	},

	/*
	 * modalControls - overrides some default actions on the modal so they cant send requests back to the server (hijack buttons)
	 */
	modalControls : function()
	{
		// buttons send requests to the server by default lets stop this here!
		$(".aj_modal button, .aj_modal input[type=submit]").click(
			function()
			{
				return false;
			}
		);

		$(".aj_modal input").click(
			function()
			{
				inmodal = true;
			}
		);
	},

	/*
	 * Will slide an element up down
	 */
	toggleSlide : function(element)
	{
		$("#openclose").html('<div title="Minimise this section">Hide</div>');

		$("#openclose").toggle(
			function()
			{
				$("#main .scroll").css("overflow-y", "hidden");
				$("#search-widget").css("display", "none");
				imode.scrollHeights();
				$("#main .scroll").css("overflow-y", "auto");
				return $(this).html('<div title="Reveal this section" class="down">Show</div>');
			},
			function()
			{
				$("#main .scroll").css("overflow-y", "hidden");
				$("#search-widget").css("display", "block");
				imode.scrollHeights();
				$("#main .scroll").css("overflow-y", "auto");
				return $("#openclose").html('<div title="Minimise this section">Hide</div>');
			}
		);
	},

	/*
	 * datePicker - just checkes that a datepicker doenst alredy exist so it cant apply one over itself
	 * then it just calls datepicker (plugin)
	 */
	datePicker : function(element)
	{
		$(".deadline").each(function()
		{
			var $this = $(this);
			if ($this.find(".dp-choose-date").length == 0)
			{
				$this.find("input").datePicker({startDate:'01/01/1997'});
			}

			$this.parent().prev().unbind();
			$this.parent().prev().change(
				function()
				{
					var setDisabled = ($(this).attr("value") == 3) ? true : false;
					$this.find("input").dpSetDisabled(setDisabled);
				}
			);
		}
		);
	},

	/* showFirstStory: finds the first news story (or funding opportunity) listed in search results, and calls its onclick function (thus making it display in the preview pane). Only meant to be called from a news issue page. */
	showFirstStory : function()
	{
		var firstStory = $('.main_main .scroll .calls-results tr:nth-child(2) a');
		firstStory.trigger('click');
	}
};

/* if you add the class clickable to a table this function will add the ability to click its rows
 * possibly link to another function that selects checkboxes behind the scences!!!!
 */
function clickable_row()
{
	var inputs = $(".clickable tr input");
	var pvcache = $("#preview").children();

	var previewCacheFirst = '<div id="' + $("#preview").children().attr("id") + '"><div id="' + $("#preview").children().children().attr("id") + '"><div class="scroll"><div class="noitemserror">'
	var previewCacheLast = '</div></div></div></div>'

	var results = {};
	// shows the amount of checked elements in the preview panel
	function updateSelected()
	{
		var counter = 0;
		for (var x in results)
		{
			if (results[x])
			{
				counter++;
			}
		}
		if (counter >= 1)
		{
			$("#preview").html(previewCacheFirst + '<p>You have selected: '+ counter +' results</p>' + previewCacheLast);
			removeTogglePreview()
		}
		else
		{
			$("#preview").html(previewCacheFirst + '<p>Select an item from the search listings to view it here in the preview panel.</p>' + previewCacheLast);
			removeTogglePreview();
			setTimeout(function(){$(".wicketBody").trigger("click")}, 0);
		}
	}

	$("#togglechecks").unbind();
	$("#togglechecks").click(
		function(e)
		{
			if ($(this).is(":checked"))
			{
				inputs.trigger("checked");
				setTimeout(function(){$("#main div.scroll").trigger("click")}, 0);
				e.stopPropagation();
			}
			else
			{
				inputs.trigger("unchecked");
			}
			updateSelected();
		}
	);

	$(".clickable tr").each(
		function()
		{
			var $this = $(this);
			var link = $this.find("a");

			$this.attr("title", "Click here to select and view the item");

			//sanatise the elements else we're gonna bind lots of click events to them!
			$this.unbind();

			var inputs = $this.find("input");

			inputs.attr("title", "Check this box to select the item");

			inputs.click(
				function(e)
				{
					$("#togglechecks").attr("checked", "");
					if ($(this).is(":checked"))
					{
						$(this).trigger("checked");
					}
					else
					{
						$(this).trigger("unchecked");
					}
					setTimeout(function(){$("#main div.scroll").trigger("click")}, 0);
					updateSelected();
					e.stopPropagation();
				}
			);

			inputs.bind("checked",
				function(e)
				{
					$(this).attr("checked", "checked");
					$this.addClass("getsFocus");
					results[$this.find("input").attr("id")] = true;
				}
			);

			inputs.bind("unchecked",
				function(e)
				{
					$(this).attr("checked", "");
					$this.removeClass("getsFocus");
					results[$this.find("input").attr("id")] = false;
				}
			);

			link.click(
				function(e)
				{
					e.stopPropagation();
					$(this).parent().parent().parent().trigger("clickableRow", [true]);
					$("#togglechecks").attr("checked", "");
					return false;
				}
			);

			// clicking on a row will load a item
			$this.click(
				function(){
					$(this).trigger("clickableRow")
				}
			);
			$this.bind("clickableRow",
				function(e, stuff)
				{
					e.stopPropagation();
					$this.parent().find("input").trigger("unchecked");
					$this.find("input").trigger("checked");
					//$this.parent().parent().addClass("viewingItem");
					//$(".clickable tr").removeClass("getsFocus");
					//wicket assigns an annonymous function to each link, to call this in ie we
					//have to do this dirty hack as ie wont let you trigger an onclick in jquery
					//yes wicket blows
					if (!stuff)
					{
						if ($.browser.msie)
							eval(link.attr("onclick") + "anonymous()");
						else
							link.trigger("click");
						// and breathe
					}
					setTimeout(function(){$("#main div.scroll").trigger("click")}, 0);
					return false;
				}
			);
		}
	);

	// if users changes panel
	inputs.each(
		function()
		{
			if ($(this).is(":checked"))
			{
				$(this).trigger("checked");
				setTimeout(function(){$("#main div.scroll").trigger("click")}, 0);
			}
		}
	);
}

//Any passed in link will be opened in a new window...
function popUps(elements)
{
	elements.addClass("external");
	elements.unbind("click");
	elements.click(
		function()
		{
			window.open($(this).attr("href"));
			return false;
		}
	);
}

// to open and close the preview panel
// they dont belong here and are a bit hacky at present
function togglePreview()
{
	if (!$("#togglePreview").length)
	{
		$('<div id="toggleWrapper" class="gwt-TabBar"><input type="submit" id="togglePreview" class="gwt-Button inputSubmit" value="Maximise"/></div>').insertAfter("#main");
		$("#preview").removeClass("fullWidth");
		$("#togglePreview").click(
			function()
			{
				var winloc = window.location.hash;
				if (!$("#preview.fullWidth").length)
				{
					if (winloc.indexOf("maxPreview") == -1)
					{
						updateURL = false;
						winloc += "maxPreview$t$";
						if (winloc.indexOf("#") != -1)
							winloc = winloc.substr(1, winloc.length);
						$.history.load(winloc);
					}
					setOpenToggle();
				}
				else
				{
					if (winloc.indexOf("maxPreview") != -1)
					{
						updateURL = false;
						winloc = winloc.split("maxPreview$t$")[0];
						if (winloc.indexOf("#") != -1)
							winloc = winloc.substr(1, winloc.length);
						//updateURL = false;
						$.history.load(winloc);
					}
					setClosedToggle();
				}
				imode.controlIntFace();
				imode.scrollHeights();
				return false;
			}
		);
	}
	$(".main_main").css("display", "block");
}

function removeTogglePreview()
{
	if ($("#togglePreview").length)
	{
		$("#toggleWrapper").remove();
	}
	$(".main_main").css("display", "block");
	$("#preview").removeClass("fullWidth");
}

function setOpenToggle()
{
	$("#togglePreview").attr("value", "Minimize");
	$("#preview").addClass("fullWidth");
	$(".main_main").css("display", "none");
	$("#togglePreview").addClass("minimize");
	$("#preview .getsFocus").parent().trigger("click");
}

function setClosedToggle()
{
	$("#togglePreview").attr("value", "Maximize");
	$("#preview").removeClass("fullWidth");
	$(".main_main").css("display", "block");
	$("#togglePreview").removeClass("minimize");
}

// arg links is a jquery object
function ieHashLinks(links)
{
	links.each(
		function()
		{
			if ($(this).attr("href").indexOf("#") != -1 && $(this).attr("iehl") != "t")
			{
				$(this).click(
				 	function()
					{
						var hash = $(this).attr("href").substr($(this).attr("href").indexOf("#")+1, $(this).attr("href").length);
						$.history.load(hash);
						return false;
					}
				);
				$(this).attr("iehl", "t");
			}
		}
	);
}