jQuery.preloadCssImages();
var lastPathLoaded = window.location.pathname;
jQuery.metadata.setType("attr", "data");

function pageTree(selector) {
	var $nodes = jQuery(selector);
	$nodes.each(function() {
		var $node = jQuery(this);
		var metadata = $node.metadata();
		$node.data('pageTree', {path: metadata.path});
	});
	var rootNodes = [];
	$nodes.each(function() {
		var $node = jQuery(this);
		var ptr = this.parentNode;
		while (ptr != null) {
			var $ptr = jQuery(ptr);
			var parentTree = $ptr.data('pageTree');
			if (parentTree) {
				//alert('found parent:[' + parentTree + ':' + typeof parentTree + ']');
				if (!parentTree.children) {
					parentTree.children = [];
				}
				parentTree.children.push($node);
				return
			}
			ptr = ptr.parentNode;
		}
		rootNodes.push($node);
	});
	$nodes.each(function() {
		var $node = jQuery(this);
		var pageTree = $node.data('pageTree');
		if (pageTree.children) {
			var tree = {};
			for (var i = 0; i < pageTree.children.length; i++) {
				var child = pageTree.children[i];
				var data = pageTree.children[i].data('pageTree');
				tree[child.metadata().name] = child.data('pageTree');
			}
			delete pageTree.children;
			pageTree.tree = tree;
		}
	});
	var result = {};
	jQuery.each(rootNodes, function() {
		result[this.metadata().name] = this.data('pageTree');
	});
	$nodes.each(function() {
		jQuery(this).removeData('pageTree');
	});
	//alert("result=" + webslinger.toJSON(result));
	//throw 'foo';
	return result;
}

function setMenu() {
	jQuery('#setleftform').attr('action','/Edit' + webslinger.getPath());
	jQuery('#setleftform').ajaxSubmit(function() { 
		webslinger.pageReload();
	});
}

function insertToolbar(id) {
	jQuery('.mceToolbarExternal').appendTo(id);
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
function createPathTimeoutHandler(handler, href) {
	return function(type, error) {
		switch (type) {
			case "server":
				if (error.timeout) {
					window.location.replace(href);
				}
				return;
		}
		if (handler) handler(type, error);
	};
}

function _sendAJAX(path, loadParameters, ajaxParameters, callback) {
	//alert('_sendAJAX(' + path + ', ' + webslinger.toJSON(ajaxParameters, false, false) + ')');
	try {
	jQuery.ajax({
		type:		"GET",
		url:		path,
		data:		loadParameters,
		beforeSend:	function(req) {
			req.setRequestHeader('X-Webslinger-AJAX', webslinger.toJSON(ajaxParameters, false, false));
		},
		dataType:	'html',
		error:		function() {
			window.location.replace(path);
		},
		success:	callback
	});
	} catch (e) {
		alert('_sendAJAX caught error: ' + e);
	}
}
function ajaxAutoRefreshUpdate() {
	try {
	jQuery.ajax({
		type:		'GET',
		url:		'/',
		cache:		false,
		beforeSend:	function(req) {
			req.setRequestHeader('X-Webslinger-AJAX', webslinger.toJSON({ajaxAutoRefresh:true}, false, false));
		},
		dataType:	'html',
		error:		function() {
		},
		success:	function(data) {
			jQuery(function() {
				processAjaxResult('/', data, jQuery('<div data="{refreshOnly:true}"></div>'));
			});
		}
	});
	} catch (e) {
		alert('ajaxAutoRefreshUpdate caught error: ' + e);
	}
}
function getContent(path, loadParameters, callback) {
	//alert('getContent(' + path + ', ' + loadParameters + ')');
	var ajaxParameters = {type: 'Load'};
	_sendAJAX(path, loadParameters, ajaxParameters, callback);
}

function preopenMenu(path) {
	var treeItem = jQuery(this).find("li[href$='" + path + "']");
	var nodes = [];
	var ptr = treeItem[0];
	while (ptr && ptr != this) {
		nodes[nodes.length] = ptr;
		ptr = ptr.parentNode;
	}
	for (var i = nodes.length - 1; i >= 0; i--) {
		jQuery(nodes[i]).trigger('Tree:Node:Open');
	}
}

(function() {
	var $busy;
	webslinger.addBusyHandler(function(cmd) {
		$busy = jQuery('#AjaxBusy');
		if (cmd == 'start') {
			var $win = jQuery(window);
			$busy.css({
				top:	($win.height() - $busy.height()) / 2,
				left:	($win.width() - $busy.width()) / 2
			});
			$busy.fadeIn(500);
		} else if (cmd == 'end') {
			$busy.fadeOut(500);
		}
	});
})();
(function($) {
	var wsProgressIdCounter = 0;
	var uploadIds = {};
	var updateStatusTimerId;
	var percentShowing = false;
	function updateStatus() {
		var ids = [];
		for (id in uploadIds) ids.push({name: 'i', value: id});
		if (!ids.length) return;
		$.ajax({
			global: false,
			data: ids,
			url: '/AJAX/UploadStatus',
			success: function(data) {
				var parts = data.split(' ');
				var bytesRead = parseInt(parts[0]);
				var length = parseInt(parts[1]);
				if (length && bytesRead) updatePercent(Math.floor(bytesRead / length * 100));
			}
		});
		updateStatusTimerId = setTimeout(updateStatus, 500);
	}
	function updatePercent(percent) {
		jQuery('#AjaxDebug').text(percent);
		jQuery('#AjaxBusyPercent').text(percent);
		jQuery('#AjaxBusyCompletion').css({width: percent + '%'});
		if (percent > 0 && !percentShowing) {
			percentShowing = true;
			//jQuery('#AjaxBusyCompletionPercent').fadeIn();
		}
		if (percent == 100) {
			//jQuery('#AjaxBusyCompletionPercent').fadeOut();
			percentShowing = false;
		}
	}
	function allocationFormProgressId(options) {
		var wsProgressId = options['WS-Upload-Progress-Id'];
		if (!wsProgressId) wsProgressId = options['WS-Upload-Progress-Id'] = new Date().getTime() + '-' + wsProgressIdCounter++;
		return wsProgressId;
	}
	jQuery(function() {
		jQuery(document).bind('ajaxSend', function(event, req, options) {
			if (!options) return;
			var wsProgressId = options.wsProgressId;
			if (!wsProgressId) return;
			req.setRequestHeader('WS-Upload-Progress-Id', wsProgressId);
			uploadIds[wsProgressId] = 1;
		}).bind('ajaxComplete', function(event, req, options) {
			if (!options) return;
			var wsProgressId = options.wsProgressId;
			if (!wsProgressId) return;
			delete uploadIds[wsProgressId];
		}).bind('ajaxStart', function(event, req, options) {
			if (!options) return;
			var wsProgressId = options.wsProgressId;
			if (!wsProgressId) return;
			updateStatus();
		}).bind('ajaxStop', function(event, req, options) {
			if (!options) return;
			var wsProgressId = options.wsProgressId;
			if (!wsProgressId) return;
			clearTimeout(updateStatusTimerId);
			updatePercent(100);
		}).bind('form:submit:validate', function(event, params, $this, options, veto) {
			if ($this.find('input:file').length == 0) return;
			var wsProgressId = allocationFormProgressId(options);
			options.wsProgressId = wsProgressId;
			// handles GET, or POST without file.  params ends up being sent
			// with normal jquery.ajax
			params.unshift({name: 'X-WS-Upload-Progress-Id', value: wsProgressId});
			//params.push({name: 'X-WS-Upload-Progress-Id', value: wsProgressId});
			var $input = jQuery('<input type="hidden" name="X-WS-Upload-Progress-Id" value="" />');
			$input.val(wsProgressId);
			$this.prepend($input);
			//$this.append($input);
			if (options.url.indexOf('?') == -1) {
				options.url += '?X-WS-Upload-Progress-Id=' + wsProgressId
			} else {
				options.url += '&X-WS-Upload-Progress-Id=' + wsProgressId
			}
			//alert($this.html());
			uploadIds[wsProgressId] = 1;
			return true;
		}).bind('form:submit:notify', function(event, $this, options) {
			$this.find('input[name="X-WS-Upload-Progress-Id"]:first').remove();
		});
	});
})(jQuery);
(function($) {
	jQuery.fx.step.width = jQuery.fx.step.height = function(fx) {
		var ptr = fx.elem;
		while (ptr != null) {
			jQuery(ptr).resize();
			if (ptr.style && ptr.style.position == 'absolute') break;
			ptr = ptr.parentNode;
		}
		return jQuery.fx.step._default(fx);
	};
})(jQuery);
(function($) {
	jQuery.timedEventHandler = function(period, handler) {
		var timerId = null;
		return function() {
			if (!timerId) {
				timerId = setTimeout(function() {
					timerId = null;
					handler();
				}, period);
				handler();
			}

		};
	};
})(jQuery);
(function($) {
	var $win = jQuery(window);
	var modalPanelHtml = '<div class="ModalContainer"><div class="ModalOverlay"></div></div>';
	var modalWindowHtml = '<div class="ModalWindow"><div class="ModalBox"><div class="ModalHeader"><h1 class="ModalTitle PageTitle">&nbsp;</h1><div class="ModalActions"><span class="ModalClose"></span></div></div><div class="ModalContent"></div><div class="ModalFooter"></div></div></div>';
	var $modalPanel, $modalWindow, currentOptions;
	var overlaySetPosition = function() {
		$modalPanel.find('.ModalOverlay').height(jQuery(document).height());
		$modalPanel.find('.ModalOverlay').width(jQuery(document).width());
	};
	var modalSetPosition = function() {
		if (!$modalWindow) return;
		overlaySetPosition();
		var dims = {
			win:	{ width: $win.width(), height: $win.height() },
			modal:	{ width: $modalWindow.width(), height: $modalWindow.height() }
		};
		var modalOptions = $modalWindow.metadata();
		var left, right, top;
		if (modalOptions) {
			left = modalOptions.left;
			right = modalOptions.right;
			top = modalOptions.top;
		}
		if (top && (left || right)) {
			if (!modalOptions.fixed) top += $win.scrollTop();
			$modalWindow.css('top', top + 'px');
			if (right) {
				$modalWindow.css('right', right + $win.scrollLeft() + 'px');
			} else {
				$modalWindow.css('left', left + $win.scrollLeft() + 'px');
			}
		} else if (modalOptions && modalOptions.fixed) {
		} else {
			left = Math.max((dims.win.width - dims.modal.width) / 2, 0) + $win.scrollLeft();
			top = Math.max((dims.win.height - dims.modal.height) / 2, 0) + $win.scrollTop();
			$modalWindow.css({top:top, left:left});
		}
	};
	var onWindowResize = modalSetPosition; //jQuery.timedEventHandler(50, modalSetPosition);
	var setModalContents = function($content, options, $owner) {
		var $animationCtx;
		var onClose = function(e) {
			if (options.noHistoryOnClose) {
				jQuery.setModalContents(null);
			} else {
				fireDummyClick(lastPathLoaded);
			}
			e.preventDefault();
			return false;
		};
		if (!$modalPanel) {
			$animationCtx = $modalPanel = jQuery(modalPanelHtml);
			$modalPanel.find('.ModalOverlay').click(onClose);
			jQuery.disableFlash();
			$modalWindow = jQuery(modalWindowHtml);
			$win.bind('resize', onWindowResize).bind('scroll', onWindowResize);
		} else {
			$animationCtx = $modalWindow = jQuery(modalWindowHtml);
		}
		$animationCtx.css({
			visibility: 'hidden'
		});
		if (!options.withTitle) $modalWindow.find('.ModalTitle').remove();
		if (options.$header) $modalWindow.find('.ModalHeader').replaceWith(options.$header);
		$content.show();
		var data = $owner ? $owner.metadata() : null;
		var modalOptions = data ? data.modalOptions : null;
		if (!modalOptions) modalOptions = {};
		jQuery.extend($modalWindow.metadata(), modalOptions);
		$modalWindow.removeClass().addClass('ModalWindow');
		if (modalOptions.windowClass) $modalWindow.addClass(modalOptions.windowClass);
		$modalWindow.resize(modalSetPosition);
		if ($animationCtx !== $modalWindow) {
			$animationCtx.appendTo(document.body);
		}
		$modalWindow.appendTo($modalPanel);
		$modalWindow.find('.ModalContent').append($content);
		if (!options.skipMutators) $modalWindow.applyMutators();
		$modalWindow.find('.ModalClose').click(onClose);
		modalSetPosition();
		overlaySetPosition();
		$animationCtx.fadeIn(options.animationSpeed).css({
			visibility: 'visible'
		});
		$content.fadeIn(options.animationSpeed);
	};
	var kill = function($ctx, speed, callback) {
		$ctx.fadeOut(speed, function() {
			$ctx.remove();
			if (callback) setTimeout(callback, 0);
		});
		return null;
	};
	jQuery.setModalContents = function($content, options, $owner) {
		var config = {
			withTitle:		true,
			noHistoryOnClose:	false,
			animationSpeed:		0
		};
		if (!(options instanceof Object)) {
			options = {
				withTitle:	arguments[0]
			};
		}
		if (!$content) {
			if ($modalPanel) {
				jQuery.enableFlash();
				isAttached = false;
				$modalPanel = kill($modalPanel, currentOptions.animationSpeed);
				$modalWindow = null;
				$win.unbind('resize', onWindowResize).unbind('scroll', overlaySetPosition);
				currentOptions = null;
			}
		} else {
			currentOptions = options = jQuery.extend(config, options);
			if ($modalPanel) {
				$modalWindow = kill($modalWindow, currentOptions.animationSpeed, function() {
					setModalContents($content, options, $owner);
				});
			} else {
				setModalContents($content, options, $owner);
			}
		}
	};
	jQuery.replaceModalContents = function($content, $owner) {
		jQuery.setModalContents($content, currentOptions, $owner);
	};
	jQuery.isModalActive = function() {
		return $modalWindow != null;
	};
	jQuery.addMutator(function(ctx) {
		jQuery(ctx).find('.InlineModal').each(function() {
			var $this = jQuery(this);
			var $header = $this.find('.ModalHeader');
			var $content = $this.find('.ModalContent');
			jQuery.setModalContents($content, {$header: $header, skipMutators: true});
			$this.remove();
		});
	});
})(jQuery);
(function($) {
	jQuery.fn.applyAjaxContent = function($origContents) {
		return this.each(function() {
			var $contents = $origContents.clone(true).contents();
			var $this = jQuery(this);
			var $subContents = $contents.find('.AJAX_content');
			if ($subContents.length) {
				processAjaxContents($this, $subContents);
				return;
			}
			var meta = $this.metadata();
			var $target;
			var ajaxUpdateStyle = meta.ajaxUpdateStyle;
			var updateSpeed;
			switch (meta.ajaxUpdateStyle) {
				case 'slide-slow':
					updateSpeed = 700;
					ajaxUpdateStyle = 'slide';
					break;
			}
			if (!updateSpeed) updateSpeed = meta.updateSpeed;
			switch (ajaxUpdateStyle) {
				case 'fade':
					ajaxUpdateStyle = function($target, $contents, doneHandler) {
						$target.fadeOut(updateSpeed, function() {
							$target.empty().append($contents).applyMutators().fadeIn(doneHandler);
						});
					};
					break;
				case 'slide':
					ajaxUpdateStyle = function($target, $contents, doneHandler) {
						$target.slideUp(updateSpeed, function() {
							$target.empty().append($contents).applyMutators().slideDown(doneHandler);
						});
					};
					break;
				default:
					ajaxUpdateStyle = function($target, $contents, doneHandler) {
						$target.empty().append($contents).applyMutators();
						doneHandler();
					};
			}
			if (meta.ajaxTargetSelector) {
				$target = $this.find(meta.ajaxTargetSelector);
			} else {
				$target = $this;
			}
			var localMutators = $target.getLocalMutatorsApplier();
			ajaxUpdateStyle($target, $contents.clone(), function() {
				$target.metadata().path = meta.path;
				localMutators();
			});
		});
	};
})(jQuery);
function processAjaxContents($ctx, $requests) {
	$requests.each(function() {
		var $request = jQuery(this);
		var meta = $request.metadata();
		var $target = $ctx.find(meta.selector);
		//alert('meta(' + $target.length + ')=' + webslinger.toJSON(meta));
		if (meta.type == 'attribute') {
			$target.attr(meta.attrName, meta.attrValue);
			return;
		}
		if (meta.path) $target.metadata().path = meta.path;
		$target.applyAjaxContent($request);
	});
	return;
}
function processAjaxResult(path, data, $target, isAjaxPopup, $owner) {
	var $div = jQuery(jQuery('body').prepend(document.createElement('div'))[0].firstChild).hide();
	var $data = $div.html(data).children();
	var redirectTo = $data.find('input[name="redirectTo"]').val();
	var isDirect = $data.find('input[name="isDirect"]').val();
	var isPopup = 'true' == $data.find('input[name="isPopup"]').val() || isAjaxPopup;
	var newHistoryItem = $data.find('input[name="newHistoryItem"]').val();

	var currentPagePath = webslinger.getPath();
	var hash = path.indexOf('#');
	var jumpPoint;
	var href;
	var hasTarget = $target != null;
	if (hash != -1) {
		jumpPoint = path.substring(hash + 1);
		href = path.substring(0, hash);
	} else {
		href = path;
	}
	function applyAJAXContent() {
		var $toReplace = $data.children('.AJAX_content');
		//alert('toReplace.length=' + $toReplace.length);
		processAjaxContents(jQuery(document), $toReplace);
	}
	if (redirectTo) {
		if (isDirect == 'true') {
			window.location.replace(redirectTo);
			return;
		}
		applyAJAXContent();
		if (redirectTo == currentPagePath && jQuery.isModalActive()) {
			jQuery.setModalContents(null);
		} else {
			loadPath(redirectTo, false, jQuery.isModalActive() ? null : $target, isAjaxPopup || jQuery.isModalActive(), $owner);
		}
		return;
	}
	if (isDirect == 'true') {
		window.location.replace(href);
		return;
	}
	if (newHistoryItem) {
		fireDummyClick(newHistoryItem);
		return;
	}
	if (currentPagePath == href && jumpPoint) return;
	if (!isPopup) lastPathLoaded = href;
	if ($target && $target.metadata().refreshOnly) {
		applyAJAXContent();
	} else if (jQuery.isModalActive()) {
		applyAJAXContent();
		jQuery.replaceModalContents($data.find('.AJAX_hasTarget'), $owner);
	} else if (hasTarget) {
		applyAJAXContent();
		$target.applyAjaxContent($data.find('.AJAX_hasTarget'));
	} else {
		if (isPopup) {
			applyAJAXContent();
			jQuery.setModalContents($data.find('.AJAX_hasTarget'), {withTitle: !isAjaxPopup, noHistoryOnClose: isAjaxPopup}, $owner);
		} else {
			jQuery.setModalContents(null);
			applyAJAXContent();
		}
		var $docTitleData = $data.find('div[class="AJAX_doctitle"]');
		if ($docTitleData.length) document.title = $docTitleData.text();
		var $titleData = $data.find('div[class="AJAX_title"]');
		if ($titleData.length) {
			title = $titleData.text();
			jQuery('.PageTitle').text(title).attr('path', href);
		}
	}
	jQuery.removeLocalMutators();
	$div.remove();
}
function fireDummyClick(path) {
	var $historyDummy = jQuery('<div><a>dummy</a></div>');
	$historyDummy.find('a').attr('href', path);
	$historyDummy.applyMutators();
	$historyDummy.find('a').click();
}
function loadPath(path, doHistory, $target, isAjaxPopup, $owner) {
	if (doHistory) {
		fireDummyClick(path);
		return;
	}
	var currentPagePath = webslinger.getPath();
	var hash = path.indexOf('#');
	var jumpPoint;
	var href;
	var hasTarget = $target != null;
	if (hash != -1) {
		jumpPoint = path.substring(hash + 1);
		href = path.substring(0, hash);
	} else {
		href = path;
	}
	function jumpTo(jumpPoint) {
		var $a = jQuery("a[name='" + jumpPoint + "']");
		//alert("jumpPoint(" + jumpPoint + "): $a.length=" + $a.length);
		var offset = $a.offset();
		//alert(webslinger.toJSON(offset));
		var scrollTo = offset.top + offset.scrollTop;
		setTimeout(function() { window.scrollTo(0, scrollTo); }, 0);
	}
	function finish() {
		if (!hasTarget && !isAjaxPopup) webslinger.setPath(href);
    		jQuery('.Preopen').each(function() {
			preopenMenu.apply(this, [path]);
		});

		//alert("href(" + href + ") jumpPoint(" + jumpPoint + ")");
		if (jumpPoint) {
			var jumpPointBusyHandler = function() {
				webslinger.removeBusyHandler(jumpPointBusyHandler);
				jumpTo(jumpPoint);
			};
			webslinger.addBusyHandler(jumpPointBusyHandler);
		}
		webslinger.decrementBusy('load-path-finish');
		//if (jumpPoint) setTimeout(function() { jumpTo(jumpPoint); }, 0);
	}
	if (href.indexOf("mailto:") == 1) {
		window.location = href.substring(1);
		return;
	}
	if (href == '' && jumpPoint) {
		jumpTo(jumpPoint);
		return;
	}
	//alert("currentPagePath(" + currentPagePath + ") href(" + href + ") jumpPoint(" + jumpPoint + ")");
	if (currentPagePath == href) {
		if (jumpPoint) {
			webslinger.incrementBusy('load-path-jump');
			finish();
			return;
		}
		//return;
	}
	webslinger.incrementBusy('load-path');
	jQuery('a[ajax-href-prefix]').each(function() {
		this.setAttribute('href', this.getAttribute('ajax-href-prefix') + path);
	});
	var ajaxParams = {
		type:		'Load',
		pageTree:	pageTree('.ajax-target')
	};
	if (hasTarget || isAjaxPopup) {
		ajaxParams.hasTarget = true;
	}
	_sendAJAX(
		href,
		{},
		ajaxParams,
		webslinger.cleanupFunction(function(data) {
			processAjaxResult(path, data, $target, isAjaxPopup, $owner);
		}, finish),
		createPathTimeoutHandler(null, href)
	);
}
function ajaxCommand(path) {
	_sendAJAX(path, {}, {type: 'Command'}, function(data) { processAjaxResult(path, data, null); });
	
}
//webslinger.setHistoryListener(loadPath);

/*
 * This is the main JQuery documentReady segment. This activates most of the app logic when
 * a page load successfully completes.
 */
jQuery(document).ready(function(){
	jQuery('#quick_resources').transientClick(
		function(e) {
			return jQuery('#drop_down_menu').is(':hidden');
		},
		function(e) {
			jQuery('#drop_down_menu').slideDown();
			return function() {
				jQuery('#drop_down_menu').slideUp();
			};
		}
	);
});
(function($) {
	var busyCount = 0;
	jQuery.extend({
		enableFlash:	function() {
			busyCount--;
			if (busyCount == 0) {
				jQuery('.FlashMovie').flashstatus(true);
			}
		},
		disableFlash:	function() {
			if (busyCount == 0) {
				jQuery('.FlashMovie').flashstatus(false);
			}
			busyCount++;
		},
		isFlashEnabled:	function() {
			return busyCount == 0;
		}
	});
})(jQuery);
(function() {
 var toPrepend = '<img class="TreeActionToggle" src="/Images/Components/spacer" />';
 var installTree = function(tree) {
  var uls = tree.find('ul:not(.DynamicTree):not([_TreeFixed_])').attr('_TreeFixed_', true).hide();
  tree.children('li:not(.DynamicNode)').prepend(toPrepend);
  uls.children('li:not(.DynamicNode)').prepend(toPrepend);
  uls.each(function() {
   var found = [];
   jQuery(this).parents('li:first:not(.DynamicNode)').each(function() {
    if (this.getAttribute('_TreeFixed_')) return;
    this.setAttribute('href', jQuery(this).children('a').attr('href'));
    this.setAttribute('_TreeFixed_', true);
    found.push(this);
   }).find('div.TreeActionImage:first').addClass('TreeActionToggle');
  });
  tree.wstree({
   removeTree: function(tree, item) {
   }
  });
 };
 jQuery.addMutator(function(ctx) {
  var $ctx = jQuery(ctx);
  var $trees = $ctx.find('.Tree');
  installTree($trees);
  var $contained = $ctx.find('.ContainedTree');
  installTree($contained.find('ul:first'));
  var path = webslinger.getPath();
  if (path) {
   $contained.filter('.Preopen').each(function() {
    preopenMenu.apply(this, [path]);
   });
  }
  if ($ctx.is('.ContainedTree')) {
   var $ulFirst = $ctx.find('ul:first');
   installTree($ulFirst);
   if (path && $ctx.is('.Preopen')) {
    preopenMenu.apply($ulFirst[0], [path]);
   }
  }
 });
 jQuery(function() {
  if (webslinger.getPath()) preopenMenu.apply(this, [webslinger.getPath()]);
 });
})();
(function($) {
	var wrapper = '<div class="BoxWrapper"><div class="BoxContent"></div><div class="BoxWest"></div><div class="BoxEast"></div><div class="BoxNorth"></div><div class="BoxNorthWest"></div><div class="BoxNorthEast"></div><div class="BoxSouth"></div><div class="BoxSouthWest"></div><div class="BoxSouthEast"></div></div>';
	var classes = boxWrapperClasses.join(', ');
	jQuery.addMutator(function(ctx) {
		var $found = jQuery(ctx).find(classes);
		$found.wrapInner(wrapper).filter('td').each(function() {
			var thiz = this;
			setTimeout(function() {
				jQuery(thiz.firstChild).height(jQuery(thiz).height());
			}, 0);
		});
	});
})(jQuery);
(function($) {
	jQuery.fn.extend({
		toggleFlipper: function($a, $b, setter) {
			return this.toggle(function() {
				setter($a, $b);
			}, function() {
				setter($b, $a);
			});
		}
	});
})(jQuery);
(function($) {
	var directionsHtml = '<div><form class="AjaxForm"><table border="1"><tbody><tr><td align="right">From:</td><td><input name="from" /></td><td class="switch" rowspan="2" style="cursor: pointer;">switch</td></tr><tr><td align="right">To:</td><td><input name="to" /></td></tr><tr><td>&nbsp;</td><td colspan="2"><input type="submit" /></td></tr></tbody></table></form></div>';
	jQuery.fn.extend({
		directions:	function(action, address) {
			return this.each(function() {
				var $this = jQuery(this);
				if (!address) {
					address = $this.text();
				}
				var $directions = jQuery(directionsHtml);
				$directions.find('form').attr('action', action);
				$directions.applyMutators();

				var $from = $directions.find('input[name="from"]');
				var $to = $directions.find('input[name="to"]');
				$this.empty().append($directions);
				$directions.find('.switch').toggleFlipper($from, $to, function($a, $b) {
					$a.attr('readonly', false).val($b.val());
					$b.val(address).attr('readonly', true);
				}).click();
			});
		}
	});
})(jQuery);
(function($) {
	$.addMutator(function(ctx) {
		jQuery(ctx).find('ul').each(function() {
			jQuery(this).children('li:first').addClass('first').end()
			       .children('li:last').addClass('last').end()
			;
		});
	});
})(jQuery);
jQuery.addMutator(function(ctx) {
	var onblur = function() {
		var $doc = jQuery(document);
		var $foo = $doc.find('.FormLabelOverlay').each(function() {
			var for_ = this.getAttribute('for');
			if (!for_) return;
			var $label = jQuery(this);
			var $input = $doc.find('#' + for_);
			if ($input.length == 0) return;
			if (!$input.val()) {
				$label.show();
			} else {
				$label.hide();
			}
		});
	};
	var foo = jQuery(ctx).find('.FormLabelOverlay').each(function() {
		var for_ = this.getAttribute('for');
		if (!for_) return;
		var $label = jQuery(this);
		jQuery(ctx).find('#' + for_).blur(onblur).focus(function() {
			$label.hide();
		});
		onblur();
	});
});
function wsFlashReceiveSignal(movieId, signalName, args) {
	jQuery.flash.receiveSignal(movieId, signalName, args);
}
(function() {
	var flashRegistry = {};
	var flashRegistryID = 0;
	jQuery.flash = {
		receiveSignal: function(movieId, signalName, args) {
			if (!flashRegistry[movieId]) return;
			//alert('wsFlashReceiveSignal(' + movieId + ', ' + signalName + ', ' + args + ')');
			var $container = jQuery('#' + movieId);
			switch (signalName) {
				case 'flv-start':
					$container.trigger('animation-stop');
					break;
				case 'flv-stop':
					$container.trigger('animation-start');
					break;
			}
		}
	};
 	jQuery.addMutator(function(ctx) {
		jQuery(ctx).find('.FlashMovie.FlashSendAPI').each(function() {
			var metadata = jQuery(this).metadata();
			if (!metadata) return;
			var id = this.getAttribute('id');
			if (!id) {
				id = '_autogen_flashid_' + (flashRegistryID++);
				this.setAttribute('id', id);
			}
			flashRegistry[id] = true;
			if (metadata.FlashVars) metadata.FlashVars.replace(/(^|&)movieId=.*?($|&)/, '');
			if (metadata.FlashVars) {
				metadata.FlashVars += '&movieId=' + id;
			} else {
				metadata.FlashVars = 'movieId=' + id;
			}
		});
		jQuery(ctx).find('.FlashMovie').each(function() {
			var $this = jQuery(this);
			var data = {
				flashEnable:	function() {
					$this.find('object').each(function() {
						var $this = jQuery(this);
						jQuery(this.parentNode).css({
							visibility:	'',
							height:		$this.css('height'),
							width:		$this.css('width')
						});
					});
				},
				flashDisable:	function() {
					$this.find('object').each(function() {
						jQuery(this.parentNode).css({
							visibility:	'hidden',
							height:		'0px',
							width:		'0px'
						});
					});
				},
				setState:	function(state) {
					if ($this.data('flashstate') == state) return;
					$this.data('flashstate', state);
					if (state) {
						data.staticDisable();
						data.flashEnable();
					} else {
						data.staticEnable();
						data.flashDisable();
					}
				}
			};
			if ($this.data('flashstate') == null) $this.data('flashstate', true);
			$this.data('flashstatus', data);
			setTimeout(function() {
				if ($this.data('flashstate')) {
					data.staticDisable();
					data.flashEnable();
				} else {
					data.staticEnable();
					data.flashDisable();
				}
			}, 0);
		}).filter('.FlashStatic').each(function() {
			var $this = jQuery(this), origChildren = [], ptr = this.firstChild;
			while (ptr != null) {
				if (ptr.style) {
					origChildren.push(ptr);
					ptr.style.display = 'none';
				}
				ptr = ptr.nextSibling;
			}
			var data = $this.metadata();
			var flashvars = data.FlashVars;
			delete data.FlashVars;
			$this.flashembed(data, flashvars);
			jQuery.each(origChildren, function() {
				$this.append(this);
			});
			var $origChildren = jQuery(origChildren);
			jQuery.extend($this.data('flashstatus'), {
				staticEnable:	function() {
					$origChildren.show();
				},
				staticDisable:	function() {
					$origChildren.hide();
				}
			});
		}).end().not('.FlashStatic').each(function() {
			var $this = jQuery(this);
			var data = $this.metadata();
			var flashvars = data.FlashVars;
			delete data.FlashVars;
			$this.flashembed(data, flashvars);
			var cleanups = [];
			jQuery.extend($this.data('flashstatus'), {
				staticEnable:	function() {
					var $newElement = jQuery('<div></div>');
					cleanups.push(function() {
						$newElement.remove();
					});
					$newElement.width($this.width());
					$newElement.height($this.height());
					$this.before($newElement);
				},
				staticDisable:	function() {
					jQuery.each(cleanups, function() {
						this();
					});
					cleanups = [];
				}
			});
		});
	});
	jQuery.fn.flashstatus = function(state) {
		return jQuery(this).each(function() {
			var $this = jQuery(this);
			var data = $this.data('flashstatus');
			if (data) {
				data.setState(state);
			} else {
				$this.data('flashstate', state);
			}
		});
	};
})();
if (jQuery) (function($) {
	var sessionRequestor = function() {
		jQuery.ajax({
			async:false,
			cache:false,
			url:'/Login/DoLogin/'
		});
		return true;
	};
	jQuery.addMutator(function(ctx) {
		var $ctx = jQuery(ctx);
		var $needs = $ctx.find('.NeedsActiveSession');
		$needs.filter('form').submit(sessionRequestor);
		$needs.filter('button').click(sessionRequestor);
		$needs.filter('a').click(sessionRequestor);
	});
})(jQuery);
var gformdata;
jQuery.addMutator(function(ctx) {
//jQuery('.tabs > ul').tabs();
	var $ctx = jQuery(ctx);
	$ctx.find('img.ImageRotate[data]').each(function() {
		var timerId;
		jQuery(this).hover(function() {
			var $this = jQuery(this);
			var data = $this.metadata();
			var i = 0;
			$this.attr('src', data.images[i++]);
			timerId = setInterval(function() {
				if (i == data.images.length) i = 0;
				$this.attr('src', data.images[i++]);
			}, data.time);
		}, function() {
			clearInterval(timerId)
			var $this = jQuery(this);
			var data = $this.metadata();
			$this.attr('src', data.images[0]);
		});
	});
	$ctx.find('.Heading_1:first').children("a").addClass('first');
	$ctx.find('#submenu ul li:first').addClass('first');
	$ctx.find('form.AjaxForm').each(function() {
			var $this = jQuery(this);
			var ajaxParameters = {
				pageTree:	pageTree('.ajax-target'),
				type: 		'Load',
				hasTarget:	jQuery.isModalActive()
			};
			var ajaxSentOptions;
			var type = $this.attr('method');
			type = type ? type.toUpperCase() : 'POST';
			type = 'POST';
			$this.ajaxForm({
				type:		type,
				beforeSend:	function(req) {
					req.setRequestHeader('X-Webslinger-AJAX', webslinger.toJSON(ajaxParameters, false, false));
				},
				beforeSubmit: function(formData, $form, options) {
					ajaxSentOptions = options;
					if (!$form.attr('action')) options.url = webslinger.getPath();
					if (options.url != webslinger.url.removeProtocol(options.url)) {
						$form[0].submit();
						return false;
					}
					options.url = webslinger.url.fix(options.url);
					if (options.type.toUpperCase() == 'GET') {
						var action = webslinger.url.fix(options.url);
						loadPath(action + '?' + jQuery.param(formData), true);
						return false;
					}
					var files = jQuery('input:file', this).fieldValue();
					var found = false;
					for (var j=0; j < files.length; j++)
						if (files[j]) found = true;
					formData.unshift({name: 'isJson', value: 'true'});
					return true;
				},
				success: function(data) {
					var ajaxSuccess = $this.attr("ajaxSuccess");
					if (ajaxSuccess == undefined) {
						if (jQuery.isModalActive()) {
							//alert('data=' + data);
							processAjaxResult(ajaxSentOptions.url, data);
							//jQuery.replaceModalContents(jQuery(data));
						} else {
							if ($this.is('.AjaxPopup')) {
								processAjaxResult(ajaxSentOptions.url, data, null, true);
							} else if ($this.is('.AjaxResult')) {
								processAjaxResult(ajaxSentOptions.url, data);
							} else {
								webslinger.pageReload();
							}
						}
					} else {
						gformdata = data;
						jQuery.globalEval(ajaxSuccess);
					}
				}
			});
	});

	$ctx.find('.clearfield').clearField();
	$ctx.find('.scrollable').wsscrollable();
	$ctx.find(".tablesorter").tablesorter(); 
	$ctx.find("a.LinkReloadPage").click(function() {
		jQuery.get(this.getAttribute("href"), null, function() {
			window.location.reload();
		});
		return false;
	});
	$ctx.find(".PopupExpandableDown").each(function() {
		var $this = jQuery(this);
		var $kids = $this.children();
		var $title = $kids.filter('.PopupExpandableTitle');
		var $pane = jQuery($kids[1]);
		$pane.css('position', 'absolute');
		$pane.css('right', '0px');
		$pane.hide();
		$title.toggle(function() {
			$pane.slideDown(50);
		}, function() {
			$pane.slideUp(50);
		});
	});
	$ctx.find('a.AJAXCommand[href]').click(function(e) {
		ajaxCommand(this.getAttribute('href'));
		e.preventDefault();
		return false;
	});
	$ctx.find('a.AjaxPopup').click(function(e) {
		var $this = jQuery(this);
		var data = $this.metadata();
		var href = this.getAttribute('href');
		if (data.popupAltLink) href = data.popupAltLink;
		if (data && data.ajaxLoadingMessage) {
			jQuery.setModalContents(jQuery('<div>' + data.ajaxLoadingMessage + '</div>'), {noHistoryOnClose: true});
			setTimeout(function() {
				loadPath(href, false, null, true, $this);
			}, 200);
		} else {
			loadPath(href, false, null, true, $this);
		}
		e.preventDefault();
		return false;
	});
	$ctx.find(".gallery").each(function() {
		jQuery(this).mbGallery(jQuery(this).metadata());
	});
	$ctx.find('.googlemap').googlemap({
		directionsAction:	'/DrivingDirections'
	});
	$ctx.find('.googlemapdirections').googlemapdirections();
	$ctx.find('.auto-form-focus').focus();
	jQuery.addMutator(function(ctx) {
		var videos = [];
		jQuery(ctx).find('video').each(function() {
			videos.push(this);
		});
		//VideoJS.addVideos(videos, {controlsBelow: true, controlsHiding: false});
	});
});
(function($) {
	var g = {
		markerShadowImage:	"/Images/mapfiles/shadow50.png",
		markerIconSize:		[20, 34],
		markerShadowSize:	[37, 34],
		markerIconAnchor:	[9, 34],
		markerInfoAnchor:	[9, 2],
		markerImageBase:	"/Images/mapfiles/",

		geoBusyDelay:		500,
		geoBusyMaxAttempt:	10
	};
	var geo = function() {
		var geocoder = new GClientGeocoder();
		geo = function() {
			return geocoder;
		};
		return geocoder;
	};
	var createMarker = function(point, imageName, labels) {
		var base = new GIcon(G_DEFAULT_ICON);
		base.shadow = g.markerShadowImage;
		base.iconSize = new GSize(g.markerIconSize[0], g.markerIconSize[1]);
		base.shadowSize = new GSize(g.markerShadowSize[0], g.markerShadowSize[1]);
		base.iconAnchor = new GPoint(g.markerIconAnchor[0], g.markerIconAnchor[1]);
		base.infoWindowAnchor = new GPoint(g.markerInfoAnchor[0], g.markerInfoAnchor[1]);
		var icon = new GIcon(base);
		icon.image = g.markerImageBase + imageName;
		return labels ? new GMarker(point, {icon: icon, bouncy: true}) : new GMarker(point);
	};
	var controlMap;
	var InstallMap = function(o, element, onMapLoaded) {
		var bounds = new GLatLngBounds();
		jQuery(document.body).trigger('ajaxStart');
		var map = new GMap2(element);
		new GKeyboardHandler(map);

		var createPoint = function(i, p) {
			var latch = webslinger.Latch(2, function() {
				//alert('createPoint:latch.point=' + webslinger.toJSON(latch.point));
				var point = new GLatLng(latch.point[1], latch.point[0], true);
				bounds.extend(point);
				var marker = createMarker(point, 'markerA.png', o.labels);
				if (p.description) {
					jQuery(p.description).resize(function() {
						map.updateInfoWindow();
					});
				}
				GEvent.addListener(marker, 'click', function() {
					map.setCenter(marker.getLatLng(), map.getZoom());
					if (p.description) {
						marker.openInfoWindow(p.description);
					}
				});
				map.addOverlay(marker);
				map.setZoom(Math.min(o.maxAutoZoom, map.getBoundsZoomLevel(bounds)));
				map.setCenter(bounds.getCenter());
			});
			jQuery.googlegeo(p.address, function(point) {
				//alert('createPoint:geo.point[' + i + ']=' + webslinger.toJSON(point));
				latch.point = point.coordinates;
				latch();
			});
			return latch;
		};

		var points = [];
		for (var i = 0; i < o.points.length; i++) {
			points[i] = createPoint(i, o.points[i]);
		}
		//alert('points=' + points);

		var setMapData = function() {
			//alert('map loaded, controlMap=' + controlMap);
			try {
			jQuery(document.body).trigger('ajaxStop');
			map.enableContinuousZoom();
			for (var i = 0; i < points.length; i++) {
				points[i]();
			}
			for (var i = 0; i < o.overlays.length; i++) {
				var overlayDef = o.overlays[i];
				var overlayBounds = new GLatLngBounds();
				overlayBounds.extend(new GLatLng(overlayDef.ul[0], overlayDef.ul[1], true));
				overlayBounds.extend(new GLatLng(overlayDef.lr[0], overlayDef.lr[1], true));
				var groundOverlay = new GGroundOverlay(overlayDef.img, overlayBounds);
				map.addOverlay(groundOverlay);
			}
			for (var i = 0; i < o.controls.length; i++) {
				var name = o.controls[i];
				var constructor = controlMap[name];
				if (!constructor) continue;
				map.addControl(new constructor());
			}
			//map.addOverlay(new GTileLayerOverlay(tileLayer));
			} catch (e) {
			alert('map loaded: ' + e);
			}
		};

		var setCenter = function(center) {
			//alert('setCenter:latch.center=' + webslinger.toJSON(center));
			GEvent.addListener(map, 'load', setMapData);
			if (!center) return;
			map.setCenter(new GLatLng(center[1], center[0]), o.defaultZoom);
		};
		if (!o.center) {
			o.center = o.points[0].address;
		}
		switch (typeof o.center) {
			case 'array':
				setCenter(o.center);
				break;
			case 'string':
				jQuery.googlegeo(o.center, function(point) {
					//alert('setCenter:geo.point=' + webslinger.toJSON(point));
					setCenter(point.coordinates);
				});
				break;
			default:
		}
		if (onMapLoaded) onMapLoaded(map);
		return map;
	};
	var parseOverlays = function(o, $this) {
		var overlays = [];
		if (o.overlays) {
			overlays = overlays.concat(o.overlays);
		}
		o.overlays = overlays;
		$this.children('.overlay').each(function() {
			var $this = jQuery(this);
			var position = $this.find('.position').text().replace(/[\r\n\s]/g, '');
			var match = position.match(/^(\d+):\(([-+]?\d+\.\d+),([-+]?\d+\.\d+)\)-\(([-+]?\d+\.\d+),([-+]?\d+\.\d+)\)$/);
			overlays.push({
				zoom:	match[1],
				ul:	[match[2], match[3]],
				lr:	[match[4], match[5]],
				img:	$this.find('img').attr('src')
			});
		}).remove();
	};

	var optionDefaults = {
		controls:	['map-type', 'large-map-3d', 'overview-map'],
		labels:		true,
		defaultZoom:	13,
		maxAutoZoom:	13,
		center:		null,
		overlays:	[],
		points:		null
	};
	var jQueryMethods = {
		base:	{
			googlemapconfig:	function(config) {
				g = jQuery.extend(g, config);
			},
			googlegeo:		function(address, callback) {
				var attemptsLeft = g.geoBusyMaxAttempt;
				if (!callback) callback = function() { };
				var done = function(point) {
					jQuery(document.body).trigger('ajaxStop');
					callback(point);
				};
				var f = function() {
					attemptsLeft--;
					if (attemptsLeft < 0) {
						done(null);
						return;
					}
					geo().getLocations(address, function(response) {
						switch (response.Status.code) {
							case G_GEO_SUCCESS:
								done(response.Placemark[0].Point);
								break;
							case G_GEO_TOO_MANY_QUERIES:
								setTimeout(f, g.geoBusyDelay);
								break;
							default:
						}
					});
				};
				jQuery(document.body).trigger('ajaxStart');
				f();
			}
		},
		fn:	{
			googlemap:		function(o) {
				var $this = this;
				o = jQuery.extend({}, optionDefaults, o);
				if (!o.points) {
					o.points = [];
					$this.find('.mapmarker').each(function() {
						var $this = jQuery(this);
						var point = {
							address:	$this.find('.address').text()
						};
						var $container = jQuery('<div></div>');
						$container.append($this.find('.description'));

						if (o.directionsAction) {
							$container.find('.autodirections').directions(o.directionsAction, point.address);
						}
						$container.applyMutators();
						if ($container.children().length) point.description = $container[0];
						o.points.push(point);
					});
				}
				parseOverlays(o, $this);
				return this.runWhenAttached(function() {
					InstallMap(o, $this[0]);
				});
			},
			googlemapdirections:	function(o) {
				var $this = jQuery(this);
				o = jQuery.extend({}, optionDefaults, o);
				var from = $this.find('input[name="from"]').val();
				var to = $this.find('input[name="to"]').val();
				o.points = [{address: from}, {address: to}];
				var d = $this.find('.directions');
				parseOverlays(o, $this);
				return this.runWhenAttached(function() {
					var map = InstallMap(o, $this.find('.map')[0]);
					var directions = new GDirections(map, d[0]);
					directions.load('from: ' + from + ' to: ' + to);
					GEvent.addListener(directions, 'addoverlay', function() {
						$this.resize();
					});
				});
			}
		}
	};

	if (!(typeof GBrowserIsCompatible === 'function' && jQuery.isFunction(GBrowserIsCompatible) && GBrowserIsCompatible())) {
		var set_doNothing = function() {
			return this;
		}
		var helper_doNothing = function() {
			return;
		}
		for (name in jQueryMethods.base) {
			jQueryMethods.base[name] = helper_doNothing;
		}
		for (name in jQueryMethods.fn) {
			jQueryMethods.fn[name] = set_doNothing;
		}
	} else {
		controlMap = {
			'large-map-3d':		GLargeMapControl3D,
			'large-map':		GLargeMapControl,
			'small-map':		GSmallMapControl,
			'small-zoom-3d':	GSmallZoomControl3D,
			'small-zoom':		GSmallZoomControl,
			'scale':		GScaleControl,
			'map-type':		GMapTypeControl,
			'h-map-type':		GHierarchicalMapTypeControl,
			'overview-map':		GOverviewMapControl,
			'nav-label':		GNavLabelControl
		};
		jQuery(window).unload(GUnload);
	}
	jQuery.fn.extend(jQueryMethods.fn);
	jQuery.extend(jQueryMethods.base);
})(jQuery);
(function($) {
	$(ajaxAutoRefreshUpdate);
})(jQuery);

