var PbLib = {};
document.html	= document.getElementsByTagName('html').item(0);
document.head	= document.getElementsByTagName('head').item(0);

PbLib.exceptions = [];
PbLib.logException = function (e, element, eventName)
{
	for (var i = 0, length = PbLib.exceptions.length; i < length; ++i) {
		if (PbLib.exceptions[i].message === e.message) {
			return;
		}
	}

	var elementPath = [];
	do {
		elementPath.unshift(element.tagName + element.id ? '#' + element.id : element.className ? '.' + element.className : '');
		element = element.parentNode;
	} while (element);

	var log = {
		message: e.message,
		page: window.location.href,
		file: e.fileName || e.sourceURL || null,
		line: e.lineNumber || e.line || null,
		trace: e.stack || null,
		element: elementPath.join('').toLowerCase(),
		eventName: eventName
	}

	PbLib.exceptions.push(log);
	new Ajax.Request(PbLib.getNewURI('c/jsError') + '?' + Object.toQueryString(log));
}

PbLib.isDebug = function()
{
	var scripts = document.getElementsByTagName('script');

	for (var i = 0, length = scripts.length; i < length; ++i) {

		if (scripts[i].src.match(/ui\/uibase\/script\/pblib\/pblib.js\?.+?isdebug=(\d+)/i)) {
			return true;
		}
	}

	return false;
}

PbLib.getNewURI = (function ()
		{
			var scripts = document.getElementsByTagName('script');
			var match;

			var uriBase = '/';
			var langInfix = '';
			var workspaceInfix = '';

			PbLib.self = {
				pathName: 'ui/uibase/script/pblib',
				fileName: 'pblib.js'
			};
			var re = new RegExp("^(.*)" + PbLib.self.pathName + "/" + PbLib.self.fileName + "(\\?.*)?$");
			for (var i = 0; i < scripts.length; i++) {
				match = scripts[i].src.match(re);
				if (match) {
					uriBase = match[1] == '' ? '/' : match[1];

					/*
						Search for elements:
						* can have l/k/c
						* can have language infix
						* can have workspace infix
					*/
					var url = location.href;
					var re = new RegExp('^(https?:\/\/[^/]*)?' + uriBase + '([a-z]/)?(.*)$');//([a-z]/)?(([a-z]{2})/)?([0-9]*)?(/.*)?$');
					match = url.match(re);
					if (!match) {
						break;
					}
					url = match[3];

					var urlParts = url.split('/');
					if (!Object.isUndefined(urlParts[0]) && urlParts[0].match(/^[a-z]{2}$/)) {
						langInfix = urlParts.shift() + '/';
					}
					if (!Object.isUndefined(urlParts[0]) && urlParts[0].match(/^[0-9]+$/)) {
						workspaceInfix = urlParts.shift() + '/';
					}
					break;
				}
			}

			return function(path)
				{
					if (path) {
						if (path.charAt(0) === '/') {
							path = path.substring(1);
						}
					} else {
						path = '';
					}

					var ret = uriBase;
					if (!path.match(/^(files|ui)\//)) {
						var match = path.match(/^([a-z]\/)/);
						if (match) {
							ret += match[1];
							path = path.substring(2);
						}
						ret += langInfix;
						ret += workspaceInfix;
					}
					return ret + path;
				};
		})();

// single page notice bar
// noticeType: 'failure', 'success', 'info', 'warning', 'question'
PbLib.notice = function (noticeClass, noticeText, showAsHtml)
{
	var topDocument = window.top.document;
	var contentElement = topDocument.getElementById('content');
	if (!contentElement || !contentElement.parentNode) {
		return false;
	}

	// Check for existing spiNotices element and remove it
	var spiNotices = topDocument.getElementById('spiNotices');
	if (spiNotices) {
		spiNotices.parentNode.removeChild(spiNotices);
	}

	var notice = topDocument.createElement('ul');
	notice.setAttribute('id', 'spiNotices');
	var item = topDocument.createElement('li');
	var text;
	if (showAsHtml) {
		text = topDocument.createElement('span');
		text.innerHTML = noticeText;
	} else {
		text = topDocument.createTextNode(noticeText);
	}
	var closeButton = topDocument.createElement('span');

	contentElement.parentNode.insertBefore(notice, contentElement.parentNode.firstChild);
	notice.appendChild(item);
	item.appendChild(text);
	item.appendChild(closeButton);

	closeButton.onclick = function() {
		notice.parentNode.removeChild(notice);
	};

	if (noticeClass === 'failure') {
		noticeClass = 'fail';
	}

	notice.className = 'notice singlepage ' + noticeClass;
	closeButton.className = 'closebutton';

	PbLib.fadeIn(notice, 0.05, 50);
	setTimeout(function() {
		PbLib.fadeOut(notice, 0.05, 50);
	}, 10000);

	setTimeout(function() {
		if (notice.parentNode) {
			notice.parentNode.removeChild(notice);
		}
	}, 12000);
};

PbLib.objectClone = function(obj)
{
	if (obj === null || typeof(obj) != 'object') {
		return obj;
	}

	var tObj = {};
	for (var k in obj) {
		tObj[k] = PbLib.objectClone(obj[k]);
	}
	return tObj;
};

PbLib.getUniqId = (function()
{
	var idBase = 'pblibguid';
	var idBaseNum = 0;
	var guid = 0;
	while (document.getElementById(idBase + (idBaseNum === 0 ? '' : idBaseNum) + '_1')) {
		idBaseNum += 1;
	}
	idBase = idBase + (idBaseNum === 0 ? '' : idBaseNum) + '_';

	return function() {
		return idBase + (++guid);
	};
}());

PbLib.escapeFrame = function()
{
	if (window != window.top) {
		window.top.location.replace(window.location.href);
	}
};
PbLib.module = {};
PbLib.modules = {};
PbLib.curDate = new Date();
PbLib.cacheString = "" + (PbLib.curDate.getFullYear()) + (PbLib.curDate.getMonth() + 1) + (PbLib.curDate.getDate()) + (PbLib.curDate.getHours());
PbLib.module.load = function(modName)
	{
		if (Object.isArray(modName)) {
			var returnval = true;
			for (var i = 0; i < modName.length; i++) {
				returnval = returnval && PbLib.module.load(modName[i]);
			}
			return returnval;
		} else if (!Object.isString(modName)) {
			return false;
		}

		modName = modName.toLowerCase();
		if (Object.isUndefined(PbLib.modules[modName])) {
			PbLib.modules[modName] = {
					loaded: false,
					loading: true,
					dependencies: [],
					dependencyOf: []
				};
		} else if (PbLib.modules[modName].loaded) {
			// Module is loaded
			return true;
		} else if (PbLib.modules[modName].loading) {
			// Module is being loaded
			return true;
		}

		// Load module content
		new Ajax.Request(PbLib.getNewURI(PbLib.self.pathName + "/" + modName + '.js?' + PbLib.cacheString), {
			'evalJS'		: false,
			'method'		: 'get',
			'asynchronous'	: false,
			'onSuccess'		: function (transport)
				{
					if (transport.responseText) {
						eval(transport.responseText);
					}
				}
		});

		return PbLib.modules[modName].loaded;
	};

PbLib.module.loadDependencies = function(modName, dependencyString)
	{
		var modName = modName.toLowerCase();
		if (Object.isUndefined(PbLib.modules[modName])|| Object.isUndefined(PbLib.modules[modName].loaded) || (!PbLib.modules[modName].loading && !PbLib.modules[modName].loaded)) return false;

		var dependencies = dependencyString.toLowerCase().split(',');

		for (var i = 0; i < dependencies.length; i++) {
			PbLib.modules[modName].dependencies.push(dependencies[i]);
			if (PbLib.module.load(dependencies[i])) {
				PbLib.modules[dependencies[i]].dependencyOf.push(modName);
			} else {
				return false;
			}
		}

		return true;
	};
PbLib.module.setLoaded = function(modName)
	{
		modName = modName.toLowerCase();
		if (Object.isUndefined(PbLib.modules[modName])) {
			PbLib.modules[modName] = {
					loaded: true,
					loading: false,
					dependencies: [],
					dependencyOf: []
				};
		} else {
			PbLib.modules[modName].loading = false;
			PbLib.modules[modName].loaded = true;
		}
	};

// Dialog code
PbLib.dialog = {};
PbLib.dialog.eventElem;
PbLib.dialog.scrollElem	= null;
PbLib.dialog.scrollElemIsArray = false;
PbLib.dialog.container = null;
PbLib.dialog.reqSize = null;
PbLib.dialog.origReqSize = null;
PbLib.dialog.chromeSize = null;
PbLib.dialog.dragPosDiff = null;
PbLib.dialog.dragShield = null;
PbLib.dialog.dragStartTimeout = null;
PbLib.dialog.doDragInterval = null;
PbLib.dialog.defaultOptions = {
		enableMaximize: true,
		enableDragging: true,
		enableResize: true,
		enableScrollBars: true,
		shadeWindow: true,
		blockerIsTransparent: true,
		showCloseButton: true,
		showMaximizeButton: true,
		waitForPageReady: false,
		openMaximized: false,
		title: '',
		icon: ''
	};
PbLib.dialog.resizing = null;
PbLib.dialog.topWindow = (function(){
	var myHost = window.location.host;
	var pWin = window;
	var pHost;
	while (true) {
		if (!pWin.parent || pWin.parent == pWin) break;
		try {
			pHost = pWin.parent.location.host;
			if (pHost != myHost) break;
		} catch (e) {
			break;
		}
		pWin = pWin.parent;
	}
	return pWin;
})();
PbLib.dialog.windowStack = [];
PbLib.dialog.mousePos = {x:0,y:0};
PbLib.createDialog = function (url, reqWidth, reqHeight, options)
{
	if (typeof options != 'object') options = {};

	var myOptions = Object.extend(PbLib.objectClone(PbLib.dialog.defaultOptions), options);

	if (PbLib.dialog.container) {
		PbLib.destroyDialog();
	}

	PbLib.dialog.addToStack(window);

	if (myOptions.shadeWindow) {
		PbLib.dialog.createBlocker(!!(myOptions.blockerIsTransparent));
	}

	return PbLib.dialog.createElement(url, reqWidth, reqHeight, myOptions);
};
PbLib.createConfirmDialog = function (reqWidth, reqHeight, options)
{
	if (typeof options != 'object') options = {'submitOnly' : false};

	if (!options.submitOnly) {
		options.submitOnly = false;
	}

	var myOptions = Object.extend(PbLib.objectClone(PbLib.dialog.defaultOptions), options);

	if (PbLib.dialog.container) {
		PbLib.destroyDialog();
	}

	PbLib.dialog.addToStack(window);

	if (myOptions.shadeWindow) {
		PbLib.dialog.createBlocker(!!(myOptions.blockerIsTransparent));
	}

	var div = PbLib.dialog.createElement('', reqWidth, reqHeight, myOptions);

	if (options.notices) {
		options.notices.each(function(noticeObject) {
			var notice = window.top.document.createElement('ul');
			var item = window.top.document.createElement('li');
			var text = window.top.document.createTextNode(noticeObject.last())
			var closeButton = window.top.document.createElement('span');

			div.insert(notice);
			notice.appendChild(item);
			item.appendChild(text);
			item.appendChild(closeButton);
			closeButton.onclick = function() {notice.parentNode.removeChild(notice);}

			noticeClass = noticeObject.first();
			switch(noticeClass)
			{
				case 'info':
				case 'question':
				case 'warning':
				case 'success':
					break;
				case 'failure':
					noticeClass = 'fail';
				default:
				break;
			}

			notice.className = 'notice ' + noticeClass;
			closeButton.className = 'closebutton';
		});
	}

	if (options.html) {
		div.insert(options.html);
	}

	/*
	 * create submit fields
	 */
	if (!options.submitTitle) {
		options.submitTitle = PbLib.g('Submit');
	}
	if (!options.cancelTitle) {
		options.cancelTitle = PbLib.g('Cancel');
	}

	//buttons section
	var submitButton = window.top.document.createElement('button');
		submitButton.tabindex = "2";
		$(submitButton).addClassName("submit pri");
		submitButton.name = "submitButton";
		submitButton.accesskey = options.submitTitle.substring(0,1);

	var submitSpan = window.top.document.createElement('span');
	submitSpan.appendChild( window.top.document.createTextNode(options.submitTitle.substring(0,1)));
	submitButton.appendChild(submitSpan);
	submitButton.appendChild(window.top.document.createTextNode(options.submitTitle.substring(1,options.submitTitle.length)));

	$(submitButton).observe('click', function(event) {
		window.top.PbLib.destroyDialog();

		if (options.submitFunction) {
			options.submitFunction();
		}
	});

	var cancelButton = window.top.document.createElement('button');
		cancelButton.tabindex = "3";
		$(cancelButton).addClassName("cancel sec");
		cancelButton.name = "cancel";
		cancelButton.accesskey = options.cancelTitle.substring(0,1);

	var cancelSpan = window.top.document.createElement('span');
	cancelSpan.appendChild( window.top.document.createTextNode(options.cancelTitle.substring(0,1)));
	cancelButton.appendChild(cancelSpan);
	cancelButton.appendChild(window.top.document.createTextNode(options.cancelTitle.substring(1,options.cancelTitle.length)));

	$(cancelButton).observe('click', function(event) {
		window.top.PbLib.destroyDialog();

		if (options.cancelFunction) {
			options.cancelFunction();
		}
	});

	var divSubmitField = window.top.document.createElement('div');
	$(divSubmitField).addClassName('submit field last wide widetitle');

	var divFieldInput = window.top.document.createElement('div');
	$(divFieldInput).addClassName('fieldinput');

	divFieldInput.appendChild(submitButton);

	if (options.submitOnly == false) {
		divFieldInput.appendChild(cancelButton);
	}

	divSubmitField.appendChild(divFieldInput);

	var fieldSep = window.top.document.createElement('div');
	$(fieldSep).addClassName('field_sep');
	divSubmitField.appendChild(fieldSep);

	div.insert(divSubmitField);

	return div;
};
PbLib.dialog.getOpener = function ()
{
	if (window != PbLib.dialog.topWindow) {
		return PbLib.dialog.topWindow.PbLib.dialog.getOpener();
	} else if (PbLib.dialog.windowStack.length == 0) {
		return PbLib.dialog.topWindow;
	} else {
		return PbLib.dialog.windowStack[PbLib.dialog.windowStack.length - 1];
	}
};
PbLib.dialog.addToStack = function (subWindow)
{
	if (window != PbLib.dialog.topWindow) {
		PbLib.dialog.topWindow.PbLib.dialog.addToStack(subWindow);
	} else {
		PbLib.dialog.windowStack.push(subWindow);
	}
};
PbLib.dialog.getScrollElem = function ()
{
	if (!PbLib.dialog.scrollElem) {
		var htmlElem = PbLib.dialog.topWindow.document.getElementsByTagName('html')[0];
		PbLib.dialog.scrollElem = [htmlElem, PbLib.dialog.topWindow.document.body];
		PbLib.dialog.scrollElemIsArray = true;
	}

	if (PbLib.dialog.scrollElemIsArray) {
		for (var i = 0; i < PbLib.dialog.scrollElem.size; i++) {
			if (PbLib.dialog.scrollElem[i].scrollLeft > 0 || PbLib.dialog.scrollElem[i].scrollTop > 0) {
				PbLib.dialog.scrollElem = PbLib.dialog.scrollElem[i];
				PbLib.dialog.scrollElemIsArray = false;
				return PbLib.dialog.scrollElem;
			}
		}
		return PbLib.dialog.scrollElem[0];
	}
	return PbLib.dialog.scrollElem;
}
PbLib.destroyDialog = function (force)
{
	var force = !!(force);

	if (!force) {
		if (window == PbLib.dialog.topWindow) {
			var subWindow = PbLib.dialog.windowStack.pop();
			return subWindow.PbLib.destroyDialog(true);
		} else {
			return PbLib.dialog.topWindow.PbLib.destroyDialog();
		}
	}

	$(PbLib.dialog.eventElem).fire('dialog:close');
	PbLib.dialog.eventElem.closed = true;

	if (Prototype.Browser.IE) {
		if (PbLib.dialog.container.dialogOptions.shadeWindow)
			PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow, 'resize', PbLib.dialog.resizeBlocker);

		PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow, 'scroll', PbLib.dialog.repositionNoAni);
		document.body.focus();
	}
	PbLib.dialog.dragPosDiff = null;

	PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow, 'resize', PbLib.dialog.repositionNoAni);
	PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow.document, 'keypress', PbLib.dialog.handleKeys);

	PbLib.dialog.destroyBlocker();
	PbLib.dialog.destroyElement();
};

PbLib.dialog.createElement = function (url, reqWidth, reqHeight, myOptions)
{
	if (reqWidth * 1 == reqWidth) {
		reqWidth = reqWidth * 1;
	}
	if (reqHeight * 1 == reqHeight) {
		reqHeight = reqHeight * 1;
	}
	if (reqWidth == 'fit' || reqHeight == 'fit') {
		myOptions.waitForPageReady = true;
	}

	// Create dialog: 4 divs to create rounded corners and a content div
	PbLib.dialog.container = PbLib.dialog.topWindow.document.body.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	PbLib.dialog.container = $(PbLib.dialog.container);
	PbLib.dialog.container.className = 'pbdialogcontainer';
	Object.extend(PbLib.dialog.container.style, {
			position: 'fixed',
			zIndex: '399999',
			padding: 0,
			margin: 0,
			visibility: 'hidden'
		});
	PbLib.dialog.container.dialogOptions = myOptions;

	if (myOptions.enableResize) {
		Event.observe(PbLib.dialog.container, 'mousemove', function(event){
			if (PbLib.dialog.frame.maximized) return true;

			var dialogSize		= this.getDimensions();
			var dialogOffset	= {left: this.offsetLeft, top: this.offsetTop};
			var scroll = document.viewport.getScrollOffsets();
			if (PbLib.dialog.container.getStyle('position') != 'fixed') {
				dialogOffset.left -= scroll.left;
				dialogOffset.top -= scroll.top;
			}
			var pointer = {
				x: Event.pointerX(event) - scroll.left,
				y: Event.pointerY(event) - scroll.top
			};
			var relativePos = {
				left: pointer.x - dialogOffset.left,
				top: pointer.y - dialogOffset.top
			};

			var hoverWidth = 9;
			var cursor = '';
			if (relativePos.top < hoverWidth) {
				cursor += 'n';
			} else if (relativePos.top > (dialogSize.height - hoverWidth)) {
				cursor += 's';
			}
			if (relativePos.left < hoverWidth) {
				cursor += 'w';
			} else if (relativePos.left > (dialogSize.width - hoverWidth)) {
				cursor += 'e';
			}

			this.style.cursor = cursor ? cursor + '-resize' : '';
		});
	}

	var tempElem, button, topBar;
	tempElem = topBar = PbLib.dialog.container.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	tempElem.className = 'top';
	if (myOptions.title || myOptions.icon) {
		var topBarTitle = topBar.appendChild(PbLib.dialog.topWindow.document.createElement('span'));
		topBarTitle.className = 'title';

		if (myOptions.icon) {
			var topBarIcon = topBarTitle.appendChild(PbLib.dialog.topWindow.document.createElement('img'));
			topBarIcon.src = myOptions.icon;
		}
		if (myOptions.title) {
			topBarTitle.appendChild(PbLib.dialog.topWindow.document.createTextNode(myOptions.title));
		}
		topBarTitle.onselectstart = function(){
			return false;
		};
		topBarTitle.onmousedown = function(){
			return false;
		};
	}

	var buttons = tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('span'));
	buttons.className = 'buttons';
	if (myOptions.showMaximizeButton && myOptions.enableMaximize) {
		button = buttons.appendChild(PbLib.dialog.topWindow.document.createElement('a'));
		button.className = 'maximize';
		button.setAttribute('href', 'javascript:void(0);');
		button.onclick = function () {PbLib.dialog.toggleMaximize();};
		$(button).observe('mousedown', function (e) {e.stop();});
	}
	if (myOptions.showCloseButton) {
		button = buttons.appendChild(PbLib.dialog.topWindow.document.createElement('a'));
		button.className = 'close';
		button.setAttribute('href', 'javascript:void(0);');
		button.onclick = function () {PbLib.destroyDialog();};
		$(button).observe('mousedown', function (e) {e.stop();});
	}

	tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('div'));

	tempElem = PbLib.dialog.container.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	tempElem.className = 'middle1';
	tempElem.onselectstart = function(){
			return false;
		};
	tempElem = tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	tempElem.className = 'middle2';
	PbLib.dialog.frame = tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	PbLib.dialog.frame.className = 'middle3';
	tempElem.onselectstart = function(){
			return false;
		};
	PbLib.dialog.frame.style.position = 'relative';

	tempElem = PbLib.dialog.container.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	tempElem.className = 'bottom';
	tempElem.onselectstart = function(){
			return false;
		};
	tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('div'));

	if (myOptions.enableResize) {
		var resizeRidge = $(tempElem.appendChild(PbLib.dialog.topWindow.document.createElement('span')));
		resizeRidge.className = 'resize-ridge';
		Event.observe(resizeRidge, 'mousedown', function (e) {
			PbLib.dialog.startResize(e, {v: 'd', h: 'r'});
			Event.stop(e);
			return false;
		});
	}

	var setOnloadEvent = false;
	if (url) {
		var iframeElem = PbLib.dialog.topWindow.document.createElement('iframe');
		iframeElem.frameBorder = 0;
		iframeElem.border = 0;
		iframeElem.scrolling = (myOptions.enableScrollBars) ? 'auto' : 'no';
		PbLib.dialog.frame.appendChild(iframeElem);
		Object.extend(iframeElem.style, {
				border: '0px',
				width: '100%',
				height: '100%',
				padding: 0,
				margin: 0
			});

		if (!Object.isUndefined(iframeElem.contentWindow)) {
			if (myOptions.waitForPageReady) {
				//iframeElem.contentWindow.onload = function(){PbLib.dialog.scaleToContent(false); PbLib.dialog.reposition(false);};
				$(iframeElem).observe('load', function(){
						PbLib.dialog.reqSize.h = PbLib.dialog.origReqSize.h;
						PbLib.dialog.reqSize.w = PbLib.dialog.origReqSize.w;
						PbLib.dialog.scaleToContent(false);
						PbLib.dialog.reposition(false);
					});
				PbLib.dialog.topWindow.setTimeout(function(){PbLib.dialog.scaleToContent(false);PbLib.dialog.reposition(false);}, 2000);
				setOnloadEvent = true;
			}
			if (myOptions.startMaximized) {
				$(iframeElem).observe('load', function(){
					PbLib.dialog.toggleMaximize();
				});
			}
			iframeElem.contentWindow.onkeypress = PbLib.dialog.handleKeys;
		}
		iframeElem.src = url;

		PbLib.dialog.eventElem = iframeElem;
	} else {
		// Add space for Internet Explorer
		PbLib.dialog.frame.appendChild(PbLib.dialog.topWindow.document.createTextNode(' '));
		PbLib.dialog.eventElem = PbLib.dialog.frame;

		PbLib.dialog.frame.style.overflow = (myOptions.enableScrollBars) ? 'auto' : 'hidden';
		if (PbLib.dialog.blocker) {
			PbLib.dialog.blocker.className = PbLib.dialog.blocker.className.replace(/(^|\s)dialogblockerwait(\s|$)/, ' ');
		}
	}
	PbLib.dialog.eventElem.closed = false;

	PbLib.dialog.chromeSize = {};
	PbLib.dialog.chromeSize.w = PbLib.dialog.container.offsetWidth - PbLib.dialog.frame.offsetWidth;
	PbLib.dialog.chromeSize.h = PbLib.dialog.container.offsetHeight - PbLib.dialog.frame.offsetHeight;

	if (!url) {
		while (PbLib.dialog.frame.firstChild) {
			PbLib.dialog.frame.removeChild(PbLib.dialog.frame.firstChild);
		}
	}

	PbLib.dialog.origReqSize = {w: reqWidth, h: reqHeight};
	PbLib.dialog.reqSize = {w: PbLib.dialog.origReqSize.w, h: PbLib.dialog.origReqSize.h};

	PbLib.dialog.reposition(false, false, myOptions.waitForPageReady);
	PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow, 'resize', PbLib.dialog.repositionNoAni);
	PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow, 'keypress', PbLib.dialog.handleKeys);

	if (myOptions.enableDragging || myOptions.enableResize) {
		Event.observe(PbLib.dialog.container, 'mousedown', function(e) {
			if (myOptions.enableResize) {
				var dialogSize		= this.getDimensions();
				var dialogOffset	= {left: this.offsetLeft, top: this.offsetTop};
				var scroll = document.viewport.getScrollOffsets();
				if (PbLib.dialog.container.getStyle('position') != 'fixed') {
					dialogOffset.left -= scroll.left;
					dialogOffset.top -= scroll.top;
				}
				var pointer = {
					x: Event.pointerX(e) - scroll.left,
					y: Event.pointerY(e) - scroll.top
				};
				var relativePos = {
					left: pointer.x - dialogOffset.left,
					top: pointer.y - dialogOffset.top
				};

				var hoverWidth = 9;
				var resizeDir = {v: false, h: false};
				if (relativePos.top < hoverWidth) {
					resizeDir.v = 'u';
				} else if (relativePos.top > (dialogSize.height - hoverWidth)) {
					resizeDir.v = 'd';
				}
				if (relativePos.left < hoverWidth) {
					resizeDir.h = 'l';
				} else if (relativePos.left > (dialogSize.width - hoverWidth)) {
					resizeDir.h = 'r';
				}

				if (resizeDir.h || resizeDir.v) {
					PbLib.dialog.startResize(e, resizeDir);
					Event.stop(e);
					return false;
				}
			}
			if (myOptions.enableDragging) {
				var tmp = e.element();
				while (tmp != topBar) {
					if (!tmp.parentNode) return true;
					tmp = tmp.parentNode;
				}
				PbLib.dialog.startDrag(e, true);
				Event.stop(e);
				return false;
			}
		});
	}

	if (myOptions.enableMaximize)
		PbLib.dialog.topWindow.Event.observe(topBar, 'dblclick', function(){PbLib.dialog.toggleMaximize();});

	if (Prototype.Browser.IE) {
		PbLib.dialog.container.style.position = 'absolute';
		PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow, 'scroll', PbLib.dialog.repositionNoAni);
	}

	return $(PbLib.dialog.eventElem);
};
PbLib.dialog.startDrag = function (e, firstCall)
{
	var dragOpts = {};
	var firstCall = !!(firstCall);

	if (PbLib.dialog.doDragInterval) return true;

	if (firstCall) {
		dragOpts.setStartPos = true;
		PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow.document, 'mouseup', PbLib.dialog.stopDrag);
	}

	if (!firstCall || !PbLib.dialog.frame.maximized) {
		PbLib.dialog.dragStartTimeout = null;
		if (PbLib.dialog.frame.maximized) {
			dragOpts.unMaximize = true;
			dragOpts.resetSize = true;
		}

		dragOpts.followMouse = true;

		PbLib.dialog.startDragResize(e, dragOpts);
		PbLib.dialog.doDragInterval = PbLib.dialog.topWindow.setInterval(function () {
			PbLib.dialog.doDrag();
			Object.extend(PbLib.dialog.oldMouseKeys, PbLib.dialog.mouseKeys);
		}, 1);
	} else {
		PbLib.dialog.startDragResize(e, dragOpts);
		PbLib.dialog.dragStartTimeout = PbLib.dialog.topWindow.setTimeout(function(){PbLib.dialog.startDrag(null, false);}, 200);
	}
};
PbLib.dialog.oldResizeDir;
PbLib.dialog.startResize = function (e, directions)
{
	var dragOpts = {};
	if (PbLib.dialog.doResizeInterval) return true;
	if (PbLib.dialog.frame.maximized) return true;

	dragOpts.setStartPos	= true;
	PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow.document, 'mouseup', PbLib.dialog.stopResize);
	dragOpts.unMaximize		= true;
	dragOpts.followMouse	= true;
	PbLib.dialog.startDragResize(e, dragOpts);
	PbLib.dialog.dragPosDiff.resizeDir = directions;
	PbLib.dialog.doResizeInterval = PbLib.dialog.topWindow.setInterval(function() {
		PbLib.dialog.doResize();
		Object.extend(PbLib.dialog.oldMouseKeys, PbLib.dialog.mouseKeys);
	}, 1);
};
PbLib.dialog.startDragResize = function (e, opts)
{
	var opts = Object.extend({
		unMaximize: false,
		resetSize: false,
		setStartPos: false,
		followMouse: false
	}, opts);

	if (opts.setStartPos) {
		var e = e || event;
		PbLib.dialog.followMouse(e);
		PbLib.dialog.dragPosDiff = {
				x: PbLib.dialog.mousePos.x - PbLib.dialog.currentPos.x,
				y: PbLib.dialog.mousePos.y - PbLib.dialog.currentPos.y,
				start: PbLib.objectClone(PbLib.dialog.mousePos)
			};
	}

	if (opts.unMaximize && PbLib.dialog.frame.maximized) {
		if (opts.resetSize) {
			var curTop = parseInt(PbLib.dialog.container.style.top);
			var startPos = PbLib.dialog.dragPosDiff;

			PbLib.dialog.toggleMaximize(true, true);

			// Adjust left position so the mouse ends up in the middle
			PbLib.dialog.dragPosDiff = {
					x: ((PbLib.dialog.frame.offsetWidth + PbLib.dialog.chromeSize.w) / 2),
					y: startPos.y,
					start: startPos.start
				};
			var curLeft = PbLib.dialog.dragPosDiff.start.x - PbLib.dialog.dragPosDiff.x;

			PbLib.dialog.currentPos.x = curLeft;
			PbLib.dialog.currentPos.y = curTop;
			PbLib.dialog.container.style.left = curLeft + 'px';
			PbLib.dialog.container.style.top = curTop + 'px';
		} else {
			PbLib.dialog.reqSize = PbLib.dialog.origReqSize;
			PbLib.dialog.toggleMaximize(true, true);
		}
	}

	if (opts.followMouse) {
		// Create shield to catch mousemove above iframes
		PbLib.dialog.dragShield = PbLib.dialog.frame.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
		Object.extend(PbLib.dialog.dragShield.style, {
				position: 'absolute',
				top: 0,
				left: 0,
				width: PbLib.dialog.frame.style.width,
				height: PbLib.dialog.frame.style.height
			})

		PbLib.dialog.topWindow.document.observe('mousemove', PbLib.dialog.followMouse);
	}
};
PbLib.dialog.mouseKeys = {
		ctrl: false,
		alt: false,
		shift: false
	};
PbLib.dialog.oldMouseKeys = {
		ctrl: false,
		alt: false,
		shift: false
	};
PbLib.dialog.lastMouseEvent;
PbLib.dialog.followMouse = function (e)
{
	var e = e || event;
	PbLib.dialog.lastMouseEvent = {
			clientX: + e.clientX,
			clientY: + e.clientY,
			ctrlKey: !!(e.ctrlKey),
			altKey: !!(e.altKey),
			shiftKey: !!(e.shiftKey)
		};
	PbLib.dialog.mousePos = {x:Event.pointerX(e), y:Event.pointerY(e)};
	PbLib.dialog.mouseKeys.ctrl = e.ctrlKey;
	PbLib.dialog.mouseKeys.alt = e.altKey;
	PbLib.dialog.mouseKeys.shift = e.shiftKey;
}
PbLib.dialog.doDrag = function (e)
{
	if (PbLib.dialog.oldMouseKeys.alt != PbLib.dialog.mouseKeys.alt) {
		if (PbLib.dialog.oldMouseKeys.alt && PbLib.dialog.oldResizeDir) {
			Object.extend(PbLib.dialog.oldMouseKeys, PbLib.dialog.mouseKeys);
			PbLib.dialog.stopDrag(PbLib.dialog.lastMouseEvent);
			PbLib.dialog.startResize(PbLib.dialog.lastMouseEvent, PbLib.dialog.oldResizeDir);
			return true;
		} else {
			PbLib.dialog.oldResizeDir = null;
		}
	}

	if (!PbLib.dialog.dragPosDiff) return true;

	PbLib.dialog.currentPos.x = PbLib.dialog.mousePos.x - PbLib.dialog.dragPosDiff.x;
	PbLib.dialog.currentPos.y = PbLib.dialog.mousePos.y - PbLib.dialog.dragPosDiff.y;

	PbLib.dialog.container.style.left = PbLib.dialog.currentPos.x + 'px';
	PbLib.dialog.container.style.top = PbLib.dialog.currentPos.y + 'px';
};
PbLib.dialog.doResize = function (e)
{
	// Alt moves
	if (!PbLib.dialog.oldMouseKeys.alt && PbLib.dialog.mouseKeys.alt) {
		PbLib.dialog.oldResizeDir = PbLib.objectClone(PbLib.dialog.dragPosDiff.resizeDir);
		Object.extend(PbLib.dialog.oldMouseKeys, PbLib.dialog.mouseKeys);
		PbLib.dialog.stopResize(PbLib.dialog.lastMouseEvent);
		PbLib.dialog.startDrag(PbLib.dialog.lastMouseEvent, true);
		return true;
	}

	if (!PbLib.dialog.dragPosDiff) return true;
	if (!PbLib.dialog.dragPosDiff.startSize) {
		PbLib.dialog.dragPosDiff.startSize = {
				w: PbLib.dialog.reqSize.w * 1,
				h: PbLib.dialog.reqSize.h * 1
			};

		var windowSize = PbLib.dialog.topWindow.document.viewport.getDimensions();
		var match = Object.isString(PbLib.dialog.reqSize.w) && PbLib.dialog.reqSize.w.match(/^(\d+)%$/);
		if (match) PbLib.dialog.dragPosDiff.startSize.w = (windowSize.width * match[1]) / 100;
		match = Object.isString(PbLib.dialog.reqSize.h) && PbLib.dialog.reqSize.h.match(/^(\d+)%$/);
		if (match) PbLib.dialog.dragPosDiff.startSize.h = (windowSize.height * match[1]) / 100;
	}

	var opts = PbLib.dialog.dragPosDiff;
	var mouseX = + PbLib.dialog.mousePos.x;
	var mouseY = + PbLib.dialog.mousePos.y;
	if (opts.resizeDir.v == 'u') {
		PbLib.dialog.currentPos.y	= mouseY - opts.y;
		if (PbLib.dialog.mouseKeys.ctrl) {
			PbLib.dialog.reqSize.h		= opts.startSize.h + (2 * (opts.start.y - mouseY));
		} else {
			PbLib.dialog.reqSize.h		= opts.startSize.h + (opts.start.y - mouseY);
		}

		if (PbLib.dialog.reqSize.h < 50) {
			if (PbLib.dialog.mouseKeys.ctrl) {
				PbLib.dialog.currentPos.y -= ((50 - PbLib.dialog.reqSize.h) / 2);
			} else {
				PbLib.dialog.currentPos.y -= (50 - PbLib.dialog.reqSize.h);
			}
			PbLib.dialog.reqSize.h = 50;
		}
	} else if (opts.resizeDir.v == 'd') {
		if (PbLib.dialog.mouseKeys.ctrl) {
			PbLib.dialog.currentPos.y	= opts.start.y - opts.y - (mouseY - opts.start.y);
			PbLib.dialog.reqSize.h		= opts.startSize.h + (2 * (mouseY - opts.start.y));
		} else {
			PbLib.dialog.reqSize.h		= opts.startSize.h + (mouseY - opts.start.y);
		}
		if (PbLib.dialog.reqSize.h < 50) {
			if (PbLib.dialog.mouseKeys.ctrl) {
				PbLib.dialog.currentPos.y	-= ((50 - PbLib.dialog.reqSize.h) / 2);
			}
			PbLib.dialog.reqSize.h = 50;
		}
	} else {
		PbLib.dialog.reqSize.h = opts.startSize.h;
	}

	if (opts.resizeDir.h == 'l') {
		PbLib.dialog.currentPos.x	= mouseX - opts.x;
		if (PbLib.dialog.mouseKeys.ctrl) {
			PbLib.dialog.reqSize.w		= opts.startSize.w + (2 * (opts.start.x - mouseX));
		} else {
			PbLib.dialog.reqSize.w		= opts.startSize.w + (opts.start.x - mouseX);
		}

		if (PbLib.dialog.reqSize.w < 100) {
			if (PbLib.dialog.mouseKeys.ctrl) {
				PbLib.dialog.currentPos.x -= ((100 - PbLib.dialog.reqSize.w) / 2);
			} else {
				PbLib.dialog.currentPos.x -= (100 - PbLib.dialog.reqSize.w);
			}
			PbLib.dialog.reqSize.w = 100;
		}
	} else if (opts.resizeDir.h == 'r') {
		if (PbLib.dialog.mouseKeys.ctrl) {
			PbLib.dialog.currentPos.x	= opts.start.x - opts.x - (mouseX - opts.start.x);
			PbLib.dialog.reqSize.w		= opts.startSize.w + (2 * (mouseX - opts.start.x));
		} else {
			PbLib.dialog.reqSize.w		= opts.startSize.w + (mouseX - opts.start.x);
		}
		if (PbLib.dialog.reqSize.w < 100) {
			if (PbLib.dialog.mouseKeys.ctrl) {
				PbLib.dialog.currentPos.x	-= ((100 - PbLib.dialog.reqSize.w) / 2);
			}
			PbLib.dialog.reqSize.w = 100;
		}
	} else {
		PbLib.dialog.reqSize.w = opts.startSize.w;
	}

	PbLib.dialog.container.style.left = PbLib.dialog.currentPos.x + 'px';
	PbLib.dialog.container.style.top = PbLib.dialog.currentPos.y + 'px';
	PbLib.dialog.reposition(false, true);
};
PbLib.dialog.stopDrag = function (e)
{
	if (PbLib.dialog.dragStartTimeout) {
		PbLib.dialog.topWindow.clearTimeout(PbLib.dialog.dragStartTimeout);
		PbLib.dialog.dragStartTimeout = null;
		PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow.document, 'mouseup', PbLib.dialog.stopDrag);
		return true;
	}

	if (!PbLib.dialog.dragShield) return;

	if (PbLib.dialog.doDragInterval) {
		PbLib.dialog.topWindow.clearInterval(PbLib.dialog.doDragInterval);
		PbLib.dialog.doDragInterval = false;
	}
	PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow.document, 'mouseup', PbLib.dialog.stopDrag);
	PbLib.dialog.topWindow.document.stopObserving('mousemove', PbLib.dialog.followMouse);

	var e = e || event;
	PbLib.dialog.doDrag(e);

	PbLib.dialog.frame.removeChild(PbLib.dialog.dragShield);
	PbLib.dialog.dragShield = null;
};
PbLib.dialog.stopResize = function (e)
{
	if (!PbLib.dialog.dragShield) return;
	if (PbLib.dialog.doResizeInterval) {
		PbLib.dialog.topWindow.clearInterval(PbLib.dialog.doResizeInterval);
		PbLib.dialog.doResizeInterval = false;
	}
	PbLib.dialog.topWindow.Event.stopObserving(PbLib.dialog.topWindow.document, 'mouseup', PbLib.dialog.stopResize);
	PbLib.dialog.topWindow.document.stopObserving('mousemove', PbLib.dialog.followMouse);

	var e = e || event;
	PbLib.dialog.doResize(e);

	PbLib.dialog.origReqSize = Object.extend({}, PbLib.dialog.reqSize);

	PbLib.dialog.frame.removeChild(PbLib.dialog.dragShield);
	PbLib.dialog.dragShield = null;
};
PbLib.dialog.handleKeys = function (e)
{
	var e = e || event;

	//if (e.keyCode == 27 && PbLib.dialog.container.dialogOptions.showCloseButton) PbLib.destroyDialog();
};
PbLib.dialog.destroyElement = function ()
{
	if (typeof PbLib.dialog.eventElem == 'object') {
		if (PbLib.dialog.eventElem.tagName) {
			if (PbLib.dialog.eventElem.tagName.toLowerCase() == 'iframe') {
				if (PbLib.dialog.eventElem.src != 'about:blank') {
					PbLib.dialog.eventElem.src = 'about:blank';
				}

				// Use try catch to prevent crosssite scripting error
				try {
					if (PbLib.dialog.eventElem.contentWindow) {
						if (PbLib.dialog.eventElem.contentWindow.document.body) {
							if (PbLib.dialog.eventElem.contentWindow.document.body.childNodes.length != 0) {
								window.setTimeout(function(){PbLib.dialog.destroyElement();}, 50);
								return false;
							}
						}
					}
				} catch (e) {
				}
			}
		}
	}

	PbLib.dialog.container.parentNode.removeChild(PbLib.dialog.container);
	PbLib.dialog.container = null;
	PbLib.dialog.frame = null;
	PbLib.dialog.chromeSize = null;
};
PbLib.dialog.toggleMaximize = function (noAnimation, scaleOnly)
{
	var noAnimation = !!(noAnimation);
	var scaleOnly = !!(scaleOnly);

	PbLib.dialog.dragPosDiff = null;
	if (PbLib.dialog.frame.maximized) {
		PbLib.dialog.reqSize = Object.extend({}, PbLib.dialog.origReqSize);
		PbLib.dialog.frame.maximized = false;
	} else {
		PbLib.dialog.reqSize = {w: '100%', h: '100%'};
		PbLib.dialog.frame.maximized = true;
	}
	PbLib.dialog.reposition(!noAnimation, scaleOnly);
};
PbLib.dialog.createBlocker = function (transparent)
{
	var transparent = (Object.isUndefined(transparent)) || !!(transparent);
	if (PbLib.dialog.topWindow.PbLib.dialog.windowStack.length > 1) {
		PbLib.dialog.topWindow.PbLib.dialog.windowStack[PbLib.dialog.topWindow.PbLib.dialog.windowStack.length - 2].PbLib.dialog.container.style.zIndex = 399997;
		return true;
	}

	if (Prototype.Browser.IE) {
		// Hide all selectboxes
		var boxes = document.getElementsByTagName('select');
		for (var i = 0; i < boxes.length; i++) {
			boxes[i].preDialogVis = "" + boxes[i].style.visibility;
			boxes[i].style.visibility = 'hidden';
		}
	}

	PbLib.dialog.blocker = PbLib.dialog.topWindow.document.body.appendChild(PbLib.dialog.topWindow.document.createElement('div'));
	PbLib.dialog.blocker.className = 'dialogblocker dialogblockerwait';
	Element.setStyle(PbLib.dialog.blocker, {
			position: 'fixed',
			top: '0px',
			left: '0px',
			width: '100%',
			height: '100%',
			zIndex: '399998',
			opacity: 0});
	if (transparent) {
		Element.setOpacity(PbLib.dialog.blocker, 1);
		PbLib.dialog.blocker.className += ' transparent';
	} else {
		PbLib.dialog.blocker.style.visibility = 'visible';
	}

	if (Prototype.Browser.IE) {
		PbLib.dialog.blocker.style.position = 'absolute';
		PbLib.dialog.resizeBlocker();
		PbLib.dialog.topWindow.Event.observe(PbLib.dialog.topWindow, 'resize', PbLib.dialog.resizeBlocker);
	}
};
PbLib.dialog.destroyBlocker = function ()
{
	if (PbLib.dialog.topWindow.PbLib.dialog.windowStack.length > 0) {
		PbLib.dialog.topWindow.PbLib.dialog.windowStack[PbLib.dialog.topWindow.PbLib.dialog.windowStack.length - 1].PbLib.dialog.container.style.zIndex = 399999;
		return true;
	}

	if (PbLib.dialog.container.dialogOptions.shadeWindow) {
		if (Prototype.Browser.IE) {
			// Show all selectboxes
			var boxes = document.getElementsByTagName('select');
			for (var i = 0; i < boxes.length; i++) {
				boxes[i].style.visibility = boxes[i].preDialogVis ? boxes[i].preDialogVis : '';
			}
		}

		PbLib.dialog.blocker.parentNode.removeChild(PbLib.dialog.blocker);
	}

	PbLib.dialog.blocker = null;
};
PbLib.dialog.resizeBlocker = function ()
{
	PbLib.dialog.blocker.style.width = PbLib.dialog.getScrollElem().scrollWidth + 'px';
	PbLib.dialog.blocker.style.height = PbLib.dialog.getScrollElem().scrollHeight + 'px';
};
PbLib.dialog.repositionNoAni = function () {PbLib.dialog.reposition();};
PbLib.dialog.repositionAni = function () {PbLib.dialog.reposition(true);};
PbLib.dialog.reposition = function (animate, scaleOnly, keepHidden)
{
	if (animate) {
		return PbLib.dialog.animateReposition();
	}

	var animate = false; // crappy on many pc's !!(animate);
	var scaleOnly = !!(scaleOnly);
	var keepHidden = !!(keepHidden);
	var windowSize = PbLib.dialog.topWindow.document.viewport.getDimensions();

	// Calculate size, reposition and scale
	var size = {};
	if (PbLib.dialog.reqSize.w == 'fit') {
		size.w = 0;
	} else {
		var match = Object.isString(PbLib.dialog.reqSize.w) && PbLib.dialog.reqSize.w.match(/^(\d+)%$/);
		size.w = (match ? (windowSize.width * match[1]) / 100 : PbLib.dialog.reqSize.w);
	}
	if (PbLib.dialog.reqSize.h == 'fit') {
		size.h = 0;
	} else {
		match = Object.isString(PbLib.dialog.reqSize.h) && PbLib.dialog.reqSize.h.match(/^(\d+)%$/);
		size.h = match ? (windowSize.height * match[1]) / 100 : PbLib.dialog.reqSize.h;
	}

	var width = size.w * 1;
	var height = size.h * 1;

	size.w += PbLib.dialog.chromeSize.w;
	size.h += PbLib.dialog.chromeSize.h;

	if (size.w > windowSize.width) {
		size.w = windowSize.width;
		width = size.w - PbLib.dialog.chromeSize.w;
	}
	if (size.h > windowSize.height) {
		size.h = windowSize.height;
		height = size.h - PbLib.dialog.chromeSize.h;
	}

	var doPosition = !scaleOnly && PbLib.dialog.dragPosDiff == null;
	if (doPosition) {
		var left = Math.round((windowSize.width - size.w) / 2);
		var top = Math.round((windowSize.height - size.h) / 2);
		if (Prototype.Browser.IE) {
			left += PbLib.dialog.getScrollElem().scrollLeft;
			top += PbLib.dialog.getScrollElem().scrollTop;
		}
		PbLib.dialog.currentPos = {x: left, y: top};
	}

	if (animate && !keepHidden) {
		if (!doPosition) {
			var left	=  parseInt(PbLib.dialog.container.style.left);
			var top		= parseInt(PbLib.dialog.container.style.top);
		}
		PbLib.dialog.container.style.visibility = 'visible';
		PbLib.dialog.animate(left, top, width, height, 4, 5);
	} else {
		if (doPosition) {
			PbLib.dialog.container.style.left = left + 'px';
			PbLib.dialog.container.style.top = top + 'px';
		}
		PbLib.dialog.frame.style.width = width + 'px';
		PbLib.dialog.frame.style.height = height + 'px';
		PbLib.dialog.container.style.width = width + PbLib.dialog.chromeSize.w + 'px';
		PbLib.dialog.container.style.height = height + PbLib.dialog.chromeSize.h + 'px';
		if (!keepHidden) {
			PbLib.dialog.container.style.visibility = 'visible';
		}
	}

	if (PbLib.dialog.blocker) {
		PbLib.dialog.blocker.className = PbLib.dialog.blocker.className.replace(/(^|\s)dialogblockerwait(\s|$)/, ' ');
	}
};
PbLib.dialog.animateReposition = function()
{
	var width = PbLib.dialog.reqSize.w;
	var height = PbLib.dialog.reqSize.h;

	var windowSize = PbLib.dialog.topWindow.document.viewport.getDimensions();
	var match = Object.isString(width) && width.match(/^(\d+)%$/);
	var newWidth = (match ? (windowSize.width * match[1]) / 100 : width);
	var match = Object.isString(height) && height.match(/^(\d+)%$/);
	var newHeight = (match ? (windowSize.height * match[1]) / 100 : height);

	var oldWidth = parseInt(parent.PbLib.dialog.frame.style.width);
	var oldHeight = parseInt(parent.PbLib.dialog.frame.style.height);

	var count = 5;
	var index = 0;
	var time = 0.2;

	new PeriodicalExecuter(function(pe)
		{
			index++;

			var currentWidth = oldWidth + (index / count) * (newWidth - oldWidth);
			var currentHeight = oldHeight + (index / count) * (newHeight - oldHeight);

			parent.PbLib.dialog.resize(currentWidth, currentHeight);

			if (index == count) {pe.stop();}
		},
		(1 / count) * time);
}

PbLib.dialog.resize = function (toWidth, toHeight, animate)
{
	PbLib.dialog.reqSize.w = toWidth;
	PbLib.dialog.reqSize.h = toHeight;
	PbLib.dialog.reposition(!!animate);
};

PbLib.dialog.reScaleToContent = function(reposition)
{
	PbLib.dialog.reqSize.h = PbLib.dialog.origReqSize.h;
	PbLib.dialog.reqSize.w = PbLib.dialog.origReqSize.w;

	PbLib.dialog.scaleToContent(reposition);
}

PbLib.dialog.scaleToContent = function (reposition)
{
	if (PbLib.dialog.reqSize.h == 'fit') var scaleHeight	= true;
	if (PbLib.dialog.reqSize.w == 'fit') var scaleWidth		= true;

	if (!scaleWidth && !scaleHeight) return true;

	if (PbLib.dialog.eventElem == PbLib.dialog.frame) {
		var elem = $(PbLib.dialog.eventElem);
		if (scaleWidth) {
			var targetWidth = Math.max(elem.getWidth(), elem.scrollWidth);

			if (targetHeight > PbLib.availScreenHeight) {
				PbLib.dialog.eventElem.style.overflow = 'auto';
			}
			PbLib.dialog.reqSize.w = Math.min(PbLib.availScreenWidth, targetWidth);
		}
		if (scaleHeight) {
			var targetHeight = Math.max(elem.getHeight(), elem.scrollHeight);

			if (targetHeight > PbLib.availScreenHeight) {
				PbLib.dialog.eventElem.style.overflow = 'auto';
			}
			PbLib.dialog.reqSize.h = Math.min(PbLib.availScreenHeight, targetHeight);
		}
	} else {
		var win = PbLib.dialog.eventElem.contentWindow;
		var doc = win.document;
		if (!doc.body) return false;

		var dimensions = $(PbLib.dialog.eventElem).getDimensions();
		var targetWidth = dimensions.width;
		var targetHeight = dimensions.height;

		if (scaleWidth) {
			var curScroll = 0;
			if (doc.all) {
				do {
					curScroll += 200;
					win.scrollTo(curScroll, 0);
				} while (Math.max(doc.body.scrollLeft, doc.body.parentNode.scrollLeft) >= curScroll);
				targetWidth += Math.max(doc.body.scrollLeft, doc.body.parentNode.scrollLeft);
			} else {
				do {
					curScroll += 200;
					win.scrollTo(curScroll, 0);
				} while (win.scrollX >= curScroll);
				targetWidth += win.scrollX;
			}
			win.scrollTo(0,0);

			if (targetWidth >= document.viewport.getWidth()) {
				PbLib.dialog.eventElem.scrolling = true;
			}
			PbLib.dialog.reqSize.w  = Math.min(PbLib.availScreenWidth, targetWidth + 1);
		}
		if (scaleHeight) {
			var curScroll = 0;
			var stopAt = Math.max(document.viewport.getHeight(), PbLib.availScreenHeight);

			if (doc.all) {
				do {
					curScroll += 200;
					win.scrollTo(0, curScroll);
				} while ((targetHeight + curScroll) < stopAt && Math.max(doc.body.scrollTop, doc.body.parentNode.scrollTop) >= curScroll);
				targetHeight += Math.max(doc.body.scrollTop, doc.body.parentNode.scrollTop);
			} else {
				do {
					curScroll += 200;
					win.scrollTo(0, curScroll);
				} while ((targetHeight + curScroll) < stopAt && win.scrollY >= curScroll);
				targetHeight += win.scrollY;
			}
			win.scrollTo(0,0);

			if (targetHeight >= document.viewport.getHeight()) {
				$(PbLib.dialog.eventElem).writeAttribute('scrolling', 'auto');
			}
			PbLib.dialog.reqSize.h = Math.min(PbLib.availScreenHeight, targetHeight + 1);
		}
	}

	if (reposition !== false) {
		PbLib.dialog.reposition(false);
	}

	// Fix width and height (in IE these properties get set to '0%' which prevents the content from being shown)
	if (PbLib.dialog.eventElem.style.height == '0%') {
		PbLib.dialog.eventElem.style.height = '100%';
	}
	if (PbLib.dialog.eventElem.style.width == '0%') {
		PbLib.dialog.eventElem.style.width = '100%';
	}
};

PbLib.dialog.animate = function (toLeft, toTop, toWidth, toHeight, steps, timePerStep)
{
	if (Object.isUndefined(PbLib.dialog.frame.style)) return false;
	if (Object.isUndefined(PbLib.dialog.container.style)) return false;

	if (toLeft != null) {
		var curLeft = parseInt(PbLib.dialog.container.style.left);
		var diffLeft = Math.round((toLeft - curLeft) / steps);
		PbLib.dialog.container.style.left = (curLeft + diffLeft) + 'px';

		if ((curLeft + diffLeft) == toLeft) toLeft = null;
	}
	if (toTop != null) {
		var curTop = parseInt(PbLib.dialog.container.style.top);
		var diffTop = Math.round((toTop - curTop) / steps);
		PbLib.dialog.container.style.top = (curTop + diffTop) + 'px';

		if ((curTop + diffTop) == toTop) toTop = null;
	}
	if (toWidth != null) {
		var curWidth = parseInt(PbLib.dialog.frame.style.width);
		var diffWidth = (toWidth - curWidth) / steps;
		PbLib.dialog.frame.style.width = (curWidth + diffWidth) + 'px';
		PbLib.dialog.container.style.width = (curWidth + diffWidth + PbLib.dialog.chromeSize.w) + 'px';

		if ((curWidth + diffWidth) == toWidth) toWidth = null;
	}
	if (toHeight != null) {
		var curHeight = parseInt(PbLib.dialog.frame.style.height);
		var diffHeight = (toHeight - curHeight) / steps;
		PbLib.dialog.frame.style.height = (curHeight + diffHeight) + 'px';
		PbLib.dialog.container.style.height = (curHeight + diffHeight + PbLib.dialog.chromeSize.h) + 'px';

		if ((curHeight + diffHeight) == toHeight) toHeight = null;
	}

	if (steps > 1) {
		steps--;
		PbLib.dialog.topWindow.setTimeout(function(){PbLib.dialog.animate(toLeft, toTop, toWidth, toHeight, steps, timePerStep);}, timePerStep);
	}
};

/**
 * Fade an element in or out
 * @param string elem 		The html element to fade
 * @param string from		The opacity percentage to start with (0-1)
 * @param string to 		The opacity  percentage to end with (0-1)
 * @param string fadeTime 	The total time of the fade
 * @param string onFinished The function call to execute when fading is done
 * @param string frameRate 	The amount of steps per second to take
 */
PbLib.fade = function (elem, from, to, fadeTime, onFinished, frameRate)
	{
		if (!elem) {
			return false;
		} else if (!elem.parentNode) {
			return false;
		}

		if (Prototype.Browser.IE) {
		//IE element needs to have layout for alpha filter to work
		elem.style.zoom = '1';
		}

		if (!frameRate) {frameRate = 12;}
		fadeTime = Math.max(1, parseInt(fadeTime));
		from	 = Math.min(1, parseInt(from));
		to		 = Math.max(0, parseInt(to));

		time = 1000 / frameRate;
		step = (to-from) / ((fadeTime/1000)*frameRate) ;

		stop = false;
		if (typeof(elem.curOpacity) == 'undefined') {
			elem.curOpacity = from;
		} else {
			elem.curOpacity += step;
			if (to > from) {
				if (elem.curOpacity >= to) {
					elem.curOpacity = to;
					stop = true;
				}
			} else {
				if (elem.curOpacity <= to) {
					elem.curOpacity = to;
					stop = true;
				}
			}
		}

		if (elem.curOpacity > 0) {
			if (elem.style.display == 'none') {
				elem.style.display = '';
			}
			if (elem.style.visibility == 'hidden') {
				elem.style.visibility = 'visible';
			}
		}

		Element.setOpacity(elem, elem.curOpacity);

		if (stop) {
			if (onFinished) {
				onFinished(elem);
			}
			return;
		}
		setTimeout(function(){PbLib.fade(elem, from, to, fadeTime, onFinished, frameRate);}, time);
	};

/**
 * DEPRICATED FUNCTION - exists only for backwards compatibility
 *
 * Fade an element in
 * @param string elem	 	HTML element to fade in
 * @param string step		Opacity to increase per step (0-1)
 * @param string time 		Time in milliseconds per step
 */
PbLib.fadeIn = function (elem, step, time)
	{
		PbLib.fade(elem, 0, 1, step*time, false, 1000/time );
	};
/**
 * DEPRICATED FUNCTION - exists only for backwards compatibility
 *
 * Fade an element out
 * @param string elem	 	HTML element to fade out
 * @param string step		Opacity to decrease per step (0-1)
 * @param string time 		Time in milliseconds per step
 */
PbLib.fadeOut = function (elem, step, time, removeAfter)
	{
		var onFinished = false;
		if (removeAfter) {
			onFinished = function (elem) {if (elem.parentNode) elem.parentNode.removeChild(elem);};
		}
		PbLib.fade(elem, 1, 0, step*time, onFinished, 1000/time );
	};

PbLib.setPos = function(elem, posLeft, posTop)
{
	if (!posTop && typeof posLeft == 'object') {
		// Result of getPos given
		var posTop	= posLeft.top;
		var posLeft	= posLeft.left;
	}

	if (Object.isUndefined(elem.posDiff)) {
		elem = $(elem);
		var startPos = elem.cumulativeOffset();

		elem.absolutize();

		var curPos = elem.cumulativeOffset();
		elem.posDiff = {left:curPos.left - startPos.left,top:curPos.top - startPos.top};
	}

	elem.setStyle({
		'left':	parseInt(posLeft) + elem.posDiff.left + 'px',
		'top':	parseInt(posTop) + elem.posDiff.top + 'px'});
}

// Window module
PbLib.getWindowSize = function (win)
{
	if (!win) var win = window;

	if (Object.isUndefined(win.chromeSize)) {
		PbLib.setChromeSize(win);
	}

	var size = {x:win.chromeSize.x,y:win.chromeSize.y};
	if (!Object.isUndefined(win.innerWidth)) {
		size.x += win.innerWidth;
		size.y += win.innerHeight;
	} else if (!Object.isUndefined(win.document.clientWidth)) {
		size.x += win.document.clientWidth;
		size.y += win.document.clientHeight;
	} else if (!Object.isUndefined(win.documentElement)) {
		if (!Object.isUndefined(win.documentElement.clientWidth)) {
			size.x += win.documentElement.clientWidth;
			size.y += win.documentElement.clientHeight;
		}
	} else if (!Object.isUndefined(win.document.html.clientWidth)) {
		size.x += win.document.html.clientWidth;
		size.y += win.document.html.clientHeight;
	}

	return size;
}
PbLib.getWindowPos = function (win)
{
	if (!win) var win = window;

	return {x:win.screenX, y:win.screenY}
}
PbLib.setWindowSize = function (width, height, win)
{
	if (!win) var win = window;

	win.resizeTo(parseInt(width), parseInt(height));
}
PbLib.setChromeSize = function (win)
{
	if (!win) var win = window;
	win.chromeSize = {x:0,y:0};

	var startSize = PbLib.getWindowSize(win);
	PbLib.setWindowSize(startSize.x, startSize.y, win);
	var curSize = PbLib.getWindowSize(win);

	win.chromeSize = {x:startSize.x - curSize.x, y:startSize.y - curSize.y};

	PbLib.setWindowSize(startSize.x + win.chromeSize.x, startSize.y + win.chromeSize.y, win);
}
PbLib.availScreenWidth	= screen.availWidth ? screen.availWidth : 1024;
PbLib.availScreenHeight	= screen.availHeight ? screen.availHeight : 768;
PbLib.centerWindow = function (win)
{
	if (!win) var win = window;

	var winS = PbLib.getWindowSize(win);
	win.moveTo((PbLib.availScreenWidth - winS.x) / 2, (PbLib.availScreenHeight - winS.y) / 2);
}
PbLib.scaleWindowToContent = function (scaleWidth, scaleHeight, win)
{
	if (!win) var win = window;
	if (Object.isUndefined(scaleHeight)) var scaleHeight	= true;
	if (Object.isUndefined(scaleWidth)) var scaleWidth		= false;

	var doc = win.document;
	if (!doc.body) return false;

	if (!scaleWidth && !scaleHeight) return true;

	var curSize = PbLib.getWindowSize(win);
	var targetWidth = curSize.x;
	var targetHeight = curSize.y;

	if (scaleWidth) {
		var curScroll = 0;
		if (doc.all) {
			do {
				curScroll += 200;
				win.scrollTo(curScroll, 0);
			} while (Math.max(doc.body.scrollLeft, doc.body.parentNode.scrollLeft) >= curScroll);
			targetWidth += Math.max(doc.body.scrollLeft, doc.body.parentNode.scrollLeft);
		} else {
			do {
				curScroll += 200;
				win.scrollTo(curScroll, 0);
			} while (win.scrollX >= curScroll);
			targetWidth += win.scrollX;
		}
		win.scrollTo(0,0);
		targetWidth = Math.min(PbLib.availScreenWidth, targetWidth + 1);
		win.moveTo((PbLib.availScreenWidth - targetWidth) / 2, (PbLib.availScreenHeight - targetHeight) / 2);
		win.resizeTo(targetWidth, targetHeight);
	}
	if (scaleHeight) {
		var curScroll = 0;
		if (doc.all) {
			do {
				curScroll += 200;
				win.scrollTo(0, curScroll);
			} while (Math.max(doc.body.scrollTop, doc.body.parentNode.scrollTop) >= curScroll);
			targetHeight += Math.max(doc.body.scrollTop, doc.body.parentNode.scrollTop);
		} else {
			do {
				curScroll += 200;
				win.scrollTo(0, curScroll);
			} while (win.scrollY >= curScroll);
			targetHeight += win.scrollY;
		}
		win.scrollTo(0,0);
		targetHeight = Math.min(PbLib.availScreenHeight, targetHeight + 1);
	}

	win.moveTo((PbLib.availScreenWidth - targetWidth) / 2, (PbLib.availScreenHeight - targetHeight) / 2);
	win.resizeTo(targetWidth, targetHeight);
}

PbLib.gCache = {};
PbLib.g = function(string, context)
	{
		var lookUpString = string;
		if (context != null && !Object.isUndefined(context)) {
			lookUpString += '\007' + context;
		}
		if (PbLib.gCache[lookUpString]) {
			return PbLib.gCache[lookUpString];
		}
		return string;
	};

Element.addMethods({'isInDialog': function(elem)
{
	elem = $(elem);
	if (elem.up("div.pbdialogcontainer")) {
		return true;
	}

	var found = false;
	window.top.$$("div.pbdialogcontainer iframe").each( function(frame) {
		if (frame.contentWindow == window) {
			found = true;
		}
	});
	return found;
}});

(function () {

	if (!PbLib.isDebug()) {
		// wrap all eventhandlers in a try/catch to enable centralized error logging for eventhandlers
		var prototypeObserve = Event.observe;
		var pbObserve = function (element, eventName, handler) {

			handler.logger = function () {

				try {
					handler.apply(this, arguments);
				} catch (e) {
					PbLib.logException(e, element, eventName)
				}
			}

			return prototypeObserve(element, eventName, handler.logger);
		};

		var prototypeStopObserve = Event.stopObserving;
		var pbStopObserve = function (element, eventName, handler) {
			return prototypeStopObserve(element, eventName || null, (handler && handler.logger) || handler || null);
		}

		// replace the default prototype functions
		Object.extend(Event, {observe: pbObserve, stopObserving: pbStopObserve});
		Element.addMethods({observe: pbObserve, stopObserving: pbStopObserve});
		Object.extend(document, {observe: pbObserve.methodize(), stopObserving: pbStopObserve.methodize()});
	}
})();