
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-09-11 02:38:31 +0000 (Tue, 11 Sep 2007) $
 * $Rev: 3238 $
 *
 * Version: @VERSION
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this[ name.toLowerCase() ]() + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return this[ name.toLowerCase() ]()
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

var num = function(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);
(function($)
{
	//If the UI scope is not availalable, add it
	$.ui = $.ui || {};

	$.fn.dialog = function(o) {
		return this.each(function() {
			if (!$(this).is(".ui-dialog")) new $.ui.dialog(this, o);
		});
	}
	$.fn.dialogOpen = function() {
		return this.each(function() {
			var contentEl;
			if ($(this).parents(".ui-dialog").length) contentEl = this;
			if (!contentEl && $(this).is(".ui-dialog")) contentEl = $('.ui-dialog-content', this)[0];
			$.ui.dialogOpen(contentEl)
		});
	}
	$.fn.dialogClose = function() {
		return this.each(function() {
			var contentEl;
			if ($(this).parents(".ui-dialog").length) contentEl = this;
			if (!contentEl && $(this).is(".ui-dialog")) contentEl = $('.ui-dialog-content', this)[0];
			$.ui.dialogClose(contentEl);
		});
	}

	$.ui.dialog = function(el, o) {
		
		var options = {
			width: 300,
			height: 200,
			position: 'center',
			buttons: [],
			modal: false,
			drag: true,
			resize: true,
			shadow: false // It's quite slow
		};
		var o = o || {}; $.extend(options, o); //Extend and copy options
		this.element = el; var self = this; //Do bindings
		$.data(this.element, "ui-dialog", this);

		var uiDialogContent = $(el).addClass('ui-dialog-content')
			.wrap(document.createElement('div'))
			.wrap(document.createElement('div'));
		var uiDialogContainer = uiDialogContent.parent().addClass('ui-dialog-container').css({position: 'relative'});
		var uiDialog = uiDialogContainer.parent()
			.addClass('ui-dialog').addClass(uiDialogContent.attr('className'))
			.css({position: 'absolute', width: options.width, height: options.height});
    
        if (options.modal == false && options.resize == true) {
		    uiDialog.append("<div class='ui-resizable-n ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-s ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-e ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-w ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-ne ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-se ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-sw ui-resizable-handle'></div>")
                .append("<div class='ui-resizable-nw ui-resizable-handle'></div>");
      
		    uiDialog.resizable();
		}

		uiDialogContainer.prepend('<div class="ui-dialog-titlebar"></div>');
		var uiDialogTitlebar = $('.ui-dialog-titlebar', uiDialogContainer);
		var title = (options.title) ? options.title : (uiDialogContent.attr('title')) ? uiDialogContent.attr('title') : '';
		uiDialogTitlebar.append('<span class="ui-dialog-title">' + title + '</span>');
		uiDialogTitlebar.append('<div class="ui-dialog-titlebar-close"></div>');
		$('.ui-dialog-titlebar-close', uiDialogTitlebar)
			.hover(function() { $(this).addClass('ui-dialog-titlebar-close-hover'); }, 
			       function() { $(this).removeClass('ui-dialog-titlebar-close-hover'); })
			.mousedown(function(ev) {
				ev.stopPropagation();
			})
			.click(function() {
				self.close();
			});
		var l = 0;
		$.each(options.buttons, function() { l = 1; return false; });
        if (l == 1) {
		    uiDialog.append('<div class="ui-dialog-buttonpane"></div>');
		    var uiDialogButtonPane = $('.ui-dialog-buttonpane', uiDialog);
		    $.each(options.buttons, function(name, value) {
		    	var btn = $(document.createElement('button')).text(name).click(value);
		    	uiDialogButtonPane.append(btn);
		    });
		}
        
        if (options.modal == false && options.drag == true) {
		    uiDialog.draggable({ handle: '.ui-dialog-titlebar' });
        }
        
		this.open = function() {
			var wnd = $(window), top = 0, left = 0;
			switch (options.position) {
				case 'center':
					top = (wnd.height() / 2) - (uiDialog.height() / 2);
					left = (wnd.width() / 2) - (uiDialog.width() / 2);
					break;
				case 'left':
				    top = (wnd.height() / 2) - (uiDialog.height() / 2);
				    left = 0;
				    break;
				case 'top':
    			    top = 0;
					left = (wnd.width() / 2) - (uiDialog.width() / 2);
					break;
			}
			uiDialog.css({top: top, left: left});
			uiDialog.appendTo('body').show();
		};

		this.close = function() {
			uiDialog.hide();
		};

		uiDialog.show();
		this.open();
        if (options.shadow && $.fn.shadow != undefined) {
            uiDialog.shadow();
        }
	}

	$.ui.dialogOpen = function(el) {
		$.data(el, "ui-dialog").open();
	}

	$.ui.dialogClose = function(el) {
		$.data(el, "ui-dialog").close();
	}

})(jQuery);

(function($) {

	//Make nodes selectable by expression
	$.extend($.expr[':'], { resizable: "(' '+a.className+' ').indexOf(' ui-resizable ')" });

	
	$.fn.resizable = function(o) {
		return this.each(function() {
			if(!$(this).is(".ui-resizable")) new $.ui.resizable(this,o);	
		});
	}

	//Macros for external methods that support chaining
	var methods = "destroy,enable,disable".split(",");
	for(var i=0;i<methods.length;i++) {
		var cur = methods[i], f;
		eval('f = function() { var a = arguments; return this.each(function() { if(jQuery(this).is(".ui-resizable")) jQuery.data(this, "ui-resizable")["'+cur+'"](a); if(jQuery(this.parentNode).is(".ui-resizable")) jQuery.data(this, "ui-resizable")["'+cur+'"](a); }); }');
		$.fn["resizable"+cur.substr(0,1).toUpperCase()+cur.substr(1)] = f;
	};
	
	//get instance method
	$.fn.resizableInstance = function() {
		if($(this[0]).is(".ui-resizable") || $(this[0].parentNode).is(".ui-resizable")) return $.data(this[0], "ui-resizable");
		return false;
	};
	
	
	$.ui.resizable = function(el,o) {
		
		var options = {}; o = o || {}; $.extend(options, o); //Extend and copy options
		this.element = el; var self = this; //Do bindings
		$.data(this.element, "ui-resizable", this);
		
		if(options.proxy) {
			var helper = function(e,that) {
				var helper = $('<div></div>').css({
					width: $(this).width(),
					height: $(this).height(),
					position: 'absolute',
					left: that.options.co.left,
					top: that.options.co.top
				}).addClass(that.options.proxy);
				return helper;
			}	
		} else {
			var helper = "original";	
		}
		
		//Destructive mode wraps the original element
		if(el.nodeName.match(/textarea|input|select|button|img/i)) options.destructive = true;
		if(options.destructive) {
			
			$(el).wrap('<div class="ui-wrapper"  style="position: relative; width: '+$(el).outerWidth()+'px; height: '+$(el).outerHeight()+';"></div>');
			var oel = el;
			el = el.parentNode; this.element = el;
			
			//Move margins to the wrapper
			$(el).css({ marginLeft: $(oel).css("marginLeft"), marginTop: $(oel).css("marginTop"), marginRight: $(oel).css("marginRight"), marginBottom: $(oel).css("marginBottom")});
			$(oel).css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
			
			o.proportionallyResize = o.proportionallyResize || [];
			o.proportionallyResize.push(oel);
			
			var b = [parseInt($(oel).css('borderTopWidth')),parseInt($(oel).css('borderRightWidth')),parseInt($(oel).css('borderBottomWidth')),parseInt($(oel).css('borderLeftWidth'))];
		} else {
			var b = [0,0,0,0];	
		}
		
		if(options.destructive || !$(".ui-resizable-handle",el).length) {
			//Adding handles (disabled not so common ones)
			var t = function(a,b) { $(el).append("<div class='ui-resizable-"+a+" ui-resizable-handle' style='"+b+"'></div>"); };
			//t('n','top: '+b[0]+'px;');
			t('e','right: '+b[1]+'px;'+(options.zIndex ? 'z-index: '+options.zIndex+';' : ''));
			t('s','bottom: '+b[1]+'px;'+(options.zIndex ? 'z-index: '+options.zIndex+';' : ''));
			//t('w','left: '+b[3]+'px;');
			t('se','bottom: '+b[2]+'px; right: '+b[1]+'px;'+(options.zIndex ? 'z-index: '+options.zIndex+';' : ''));
			//t('sw','bottom: '+b[2]+'px; left: '+b[3]+'px;');
			//t('ne','top: '+b[0]+'px; right: '+b[1]+'px;');
			//t('nw','top: '+b[0]+'px; left: '+b[3]+'px;');
		}
		
		
		
		//If other elements should be modified, we have to copy that array
		options.modifyThese = [];
		if(o.proportionallyResize) {
			options.proportionallyResize = o.proportionallyResize.slice(0);
			var propRes = options.proportionallyResize;

			for(var i in propRes) {
				
				if(propRes[i].constructor == String)
					propRes[i] = $(propRes[i], el);
				
				if(!$(propRes[i]).length) continue;
				
				var x = $(propRes[i]).width() - $(el).width();
				var y = $(propRes[i]).height() - $(el).height();
				options.modifyThese.push([$(propRes[i]),x,y]);
			}

		}
		
		options.handles = {};
		if(!o.handles) o.handles = { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' };
		
		for(var i in o.handles) { options.handles[i] = o.handles[i]; } //Copying the object
		
		for(var i in options.handles) {
			
			if(options.handles[i].constructor == String)
				options.handles[i] = $(options.handles[i], el);
			
			if(!$(options.handles[i]).length) continue;
				
			$(options.handles[i]).bind('mousedown', function(e) {
				self.interaction.options.axis = this.resizeAxis;
			})[0].resizeAxis = i;
			
		}
		
		//If we want to auto hide the elements
		if(o.autohide)
			$(this.element).addClass("ui-resizable-autohide").hover(function() { $(this).removeClass("ui-resizable-autohide"); }, function() { if(self.interaction.options.autohide && !self.interaction.init) $(this).addClass("ui-resizable-autohide"); });
	

		$.extend(options, {
			helper: helper,
			nonDestructive: true,
			dragPrevention: 'input,button,select',
			minHeight: options.minHeight || 50,
			minWidth: options.minWidth || 100,
			startCondition: function(e) {
				if(self.disabled) return false;
				for(var i in options.handles) {
					if($(options.handles[i])[0] == e.target) return true;
				}
				return false;
			},
			_start: function(h,p,c,t,e) {
				self.start.apply(t, [self, e]); // Trigger the start callback				
			},
			_beforeStop: function(h,p,c,t,e) {
				self.stop.apply(t, [self, e]); // Trigger the stop callback
			},
			_drag: function(h,p,c,t,e) {
				self.drag.apply(t, [self, e]); // Trigger the start callback
			}			
		});
		
		//Initialize mouse interaction
		this.interaction = new $.ui.mouseInteraction(el,options);
		
		//Add the class for themeing
		$(this.element).addClass("ui-resizable");
		
	}
	
	$.extend($.ui.resizable.prototype, {
		plugins: {},
		prepareCallbackObj: function(self) {
			return {
				helper: self.helper,
				resizable: self,
				axis: self.options.axis,
				options: self.options
			}			
		},
		destroy: function() {
			$(this.element).removeClass("ui-resizable").removeClass("ui-resizable-disabled");
			this.interaction.destroy();
		},
		enable: function() {
			$(this.element).removeClass("ui-resizable-disabled");
			this.disabled = false;
		},
		disable: function() {
			$(this.element).addClass("ui-resizable-disabled");
			this.disabled = true;
		},
		start: function(that, e) {
			this.options.originalSize = [$(this.element).width(),$(this.element).height()];
			this.options.originalPosition = $(this.element).css("position");
			this.options.originalPositionValues = $(this.element).position();

			this.options.modifyThese.push([$(this.helper),0,0]);
			
			$(that.element).triggerHandler("resizestart", [e, that.prepareCallbackObj(this)], this.options.start);			
			return false;
		},
		stop: function(that, e) {			
			
			var o = this.options;

			$(that.element).triggerHandler("resizestop", [e, that.prepareCallbackObj(this)], this.options.stop);	

			if(o.proxy) {
				$(this.element).css({
					width: $(this.helper).width(),
					height: $(this.helper).height()
				});
				
				if(o.originalPosition == "absolute" || o.originalPosition == "fixed") {
					$(this.element).css({
						top: $(this.helper).css("top"),
						left: $(this.helper).css("left")
					});					
				}
			}
			return false;
			
		},
		drag: function(that, e) {

			var o = this.options;
			var rel = (o.originalPosition != "absolute" && o.originalPosition != "fixed");
			var co = rel ? o.co : this.options.originalPositionValues;
			var p = o.originalSize;

			this.pos = rel ? [this.rpos[0]-o.cursorAt.left, this.rpos[1]-o.cursorAt.top] : [this.pos[0]-o.cursorAt.left, this.pos[1]-o.cursorAt.top];

			var nw = p[0] + (this.pos[0] - co.left);
			var nh = p[1] + (this.pos[1] - co.top);
		
			if(o.axis) {
				switch(o.axis) {
					case 'e':
						nh = p[1];
						break;
					case 's':
						nw = p[0];
						break;
					case 'n':
					case 'ne':

						
						if(!o.proxy && (o.originalPosition != "absolute" && o.originalPosition != "fixed"))
							return false;
						
						if(o.axis == 'n') nw = p[0];
						var mod = (this.pos[1] - co.top); nh = nh - (mod*2);
						mod = nh <= o.minHeight ? p[1] - o.minHeight : (nh >= o.maxHeight ? 0-(o.maxHeight-p[1]) : mod);
						$(this.helper).css('top', co.top + mod);
						break;
						
					case 'w':
					case 'sw':

						if(!o.proxy && (o.originalPosition != "absolute" && o.originalPosition != "fixed"))
							return false;
						
						if(o.axis == 'w') nh = p[1];
						var mod = (this.pos[0] - co.left); nw = nw - (mod*2);
						mod = nw <= o.minWidth ? p[0] - o.minWidth : (nw >= o.maxWidth ? 0-(o.maxWidth-p[0]) : mod);
						$(this.helper).css('left', co.left + mod);
						break;
						
					case 'nw':
						
						if(!o.proxy && (o.originalPosition != "absolute" && o.originalPosition != "fixed"))
							return false;
	
						var modx = (this.pos[0] - co.left); nw = nw - (modx*2);
						modx = nw <= o.minWidth ? p[0] - o.minWidth : (nw >= o.maxWidth ? 0-(o.maxWidth-p[0]) : modx);
						
						var mody = (this.pos[1] - co.top); nh = nh - (mody*2);
						mody = nh <= o.minHeight ? p[1] - o.minHeight : (nh >= o.maxHeight ? 0-(o.maxHeight-p[1]) : mody);

						$(this.helper).css({
							left: co.left + modx,
							top: co.top + mody
						});
						
						break;
				}	
			}

			if(e.shiftKey) nh = nw * (p[1]/p[0]);
			
			if(o.minWidth) nw = nw <= o.minWidth ? o.minWidth : nw;
			if(o.minHeight) nh = nh <= o.minHeight ? o.minHeight : nh;
			
			if(o.maxWidth) nw = nw >= o.maxWidth ? o.maxWidth : nw;
			if(o.maxHeight) nh = nh >= o.maxHeight ? o.maxHeight : nh;
			
			if(e.shiftKey) nh = nw * (p[1]/p[0]);

			var modifier = $(that.element).triggerHandler("resize", [e, that.prepareCallbackObj(this)], o.resize);
			if(!modifier) modifier = {};
			
			for(var i in this.options.modifyThese) {
				var c = this.options.modifyThese[i];
				c[0].css({
					width: modifier.width ? modifier.width+c[1] : nw+c[1],
					height: modifier.height ? modifier.height+c[2] : nh+c[2]
				});
			}
			return false;
			
		}
	});

})($);

(function($) {
	
	//If the UI scope is not availalable, add it
	$.ui = $.ui || {};
	
	//Add methods that are vital for all mouse interaction stuff (plugin registering)
	$.extend($.ui, {
		plugin: {
			add: function(w, c, o, p) {
				var a = $.ui[w].prototype; if(!a.plugins[c]) a.plugins[c] = [];
				a.plugins[c].push([o,p]);
			},
			call: function(instance, name, arguments) {
				var c = instance.plugins[name]; if(!c) return;
				var o = instance.interaction ? instance.interaction.options : instance.options;
				var e = instance.interaction ? instance.interaction.element : instance.element;
				
				for (var i = 0; i < c.length; i++) {
					if (o[c[i][0]]) c[i][1].apply(e, arguments);
				}	
			}	
		}
	});
	
	$.fn.mouseInteractionDestroy = function() {
		this.each(function() {
			if($.data(this, "ui-mouse")) $.data(this, "ui-mouse").destroy(); 	
		});
	}
	
	$.ui.mouseInteraction = function(el,o) {
	
		if(!o) var o = {};
		this.element = el;
		$.data(this.element, "ui-mouse", this);
		
		this.options = {};
		$.extend(this.options, o);
		$.extend(this.options, {
			handle : o.handle ? ($(o.handle, el)[0] ? $(o.handle, el) : $(el)) : $(el),
			helper: o.helper || 'original',
			preventionDistance: o.preventionDistance || 0,
			dragPrevention: o.dragPrevention ? o.dragPrevention.toLowerCase().split(',') : ['input','textarea','button','select','option'],
			cursorAt: { top: ((o.cursorAt && o.cursorAt.top) ? o.cursorAt.top : 0), left: ((o.cursorAt && o.cursorAt.left) ? o.cursorAt.left : 0), bottom: ((o.cursorAt && o.cursorAt.bottom) ? o.cursorAt.bottom : 0), right: ((o.cursorAt && o.cursorAt.right) ? o.cursorAt.right : 0) },
			cursorAtIgnore: (!o.cursorAt) ? true : false, //Internal property
			appendTo: o.appendTo || 'parent'			
		})
		o = this.options; //Just Lazyness
		
		if(!this.options.nonDestructive && (o.helper == 'clone' || o.helper == 'original')) {

			// Let's save the margins for better reference
			o.margins = {
				top: parseInt($(el).css('marginTop')) || 0,
				left: parseInt($(el).css('marginLeft')) || 0,
				bottom: parseInt($(el).css('marginBottom')) || 0,
				right: parseInt($(el).css('marginRight')) || 0
			};

			// We have to add margins to our cursorAt
			if(o.cursorAt.top != 0) o.cursorAt.top = o.margins.top;
			if(o.cursorAt.left != 0) o.cursorAt.left += o.margins.left;
			if(o.cursorAt.bottom != 0) o.cursorAt.bottom += o.margins.bottom;
			if(o.cursorAt.right != 0) o.cursorAt.right += o.margins.right;
			
			
			if(o.helper == 'original')
				o.wasPositioned = $(el).css('position');
			
		} else {
			o.margins = { top: 0, left: 0, right: 0, bottom: 0 };
		}
		
		var self = this;
		this.mousedownfunc = function(e) { // Bind the mousedown event
			return self.click.apply(self, [e]);	
		}
		o.handle.bind('mousedown', this.mousedownfunc);
		
		//Prevent selection of text when starting the drag in IE
		if($.browser.msie) $(this.element).attr('unselectable', 'on');
		
	}
	
	$.extend($.ui.mouseInteraction.prototype, {
		plugins: {},
		currentTarget: null,
		lastTarget: null,
		timer: null,
		slowMode: false,
		init: false,
		destroy: function() {
			this.options.handle.unbind('mousedown', this.mousedownfunc);
		},
		trigger: function(e) {
			return this.click.apply(this, arguments);
		},
		click: function(e) {

			var o = this.options;
			
			window.focus();
			if(e.which != 1) return true; //only left click starts dragging
		
			// Prevent execution on defined elements
			var targetName = (e.target) ? e.target.nodeName.toLowerCase() : e.srcElement.nodeName.toLowerCase();
			for(var i=0;i<o.dragPrevention.length;i++) {
				if(targetName == o.dragPrevention[i]) return true;
			}

			//Prevent execution on condition
			if(o.startCondition && !o.startCondition.apply(this, [e])) return true;

			var self = this;
			this.mouseup = function(e) { return self.stop.apply(self, [e]); }
			this.mousemove = function(e) { return self.drag.apply(self, [e]); }

			var initFunc = function() { //This function get's called at bottom or after timeout
				$(document).bind('mouseup', self.mouseup);
				$(document).bind('mousemove', self.mousemove);
				self.opos = [e.pageX,e.pageY]; // Get the original mouse position
			}
			
			if(o.preventionTimeout) { //use prevention timeout
				if(this.timer) clearInterval(this.timer);
				this.timer = setTimeout(function() { initFunc(); }, o.preventionTimeout);
				return false;
			}
		
			initFunc();
			return false;
			
		},
		start: function(e) {
			
			var o = this.options; var a = this.element;
			o.co = $(a).offset(); //get the current offset
				
			this.helper = typeof o.helper == 'function' ? $(o.helper.apply(a, [e,this]))[0] : (o.helper == 'clone' ? $(a).clone()[0] : a);

			if(o.appendTo == 'parent') { // Let's see if we have a positioned parent
				var cp = a.parentNode;
				while (cp) {
					if(cp.style && ($(cp).css('position') == 'relative' || $(cp).css('position') == 'absolute')) {
						o.pp = cp;
						o.po = $(cp).offset();
						o.ppOverflow = !!($(o.pp).css('overflow') == 'auto' || $(o.pp).css('overflow') == 'scroll'); //TODO!
						break;	
					}
					cp = cp.parentNode ? cp.parentNode : null;
				};
				
				if(!o.pp) o.po = { top: 0, left: 0 };
			}
			
			this.pos = [this.opos[0],this.opos[1]]; //Use the relative position
			this.rpos = [this.pos[0],this.pos[1]]; //Save the absolute position
			
			if(o.cursorAtIgnore) { // If we want to pick the element where we clicked, we borrow cursorAt and add margins
				o.cursorAt.left = this.pos[0] - o.co.left + o.margins.left;
				o.cursorAt.top = this.pos[1] - o.co.top + o.margins.top;
			}



			if(o.pp) { // If we have a positioned parent, we pick the draggable relative to it
				this.pos[0] -= o.po.left;
				this.pos[1] -= o.po.top;
			}
			
			this.slowMode = (o.cursorAt && (o.cursorAt.top-o.margins.top > 0 || o.cursorAt.bottom-o.margins.bottom > 0) && (o.cursorAt.left-o.margins.left > 0 || o.cursorAt.right-o.margins.right > 0)) ? true : false; //If cursorAt is within the helper, set slowMode to true
			
			if(!o.nonDestructive) $(this.helper).css('position', 'absolute');
			if(o.helper != 'original') $(this.helper).appendTo((o.appendTo == 'parent' ? a.parentNode : o.appendTo)).show();

			// Remap right/bottom properties for cursorAt to left/top
			if(o.cursorAt.right && !o.cursorAt.left) o.cursorAt.left = this.helper.offsetWidth+o.margins.right+o.margins.left - o.cursorAt.right;
			if(o.cursorAt.bottom && !o.cursorAt.top) o.cursorAt.top = this.helper.offsetHeight+o.margins.top+o.margins.bottom - o.cursorAt.bottom;
		
			this.init = true;	

			if(o._start) o._start.apply(a, [this.helper, this.pos, o.cursorAt, this, e]); // Trigger the start callback
			this.helperSize = { width: outerWidth(this.helper), height: outerHeight(this.helper) }; //Set helper size property
			return false;
						
		},
		stop: function(e) {			
			
			var o = this.options; var a = this.element; var self = this;

			$(document).unbind('mouseup', self.mouseup);
			$(document).unbind('mousemove', self.mousemove);

			if(this.init == false) return this.opos = this.pos = null;
			if(o._beforeStop) o._beforeStop.apply(a, [this.helper, this.pos, o.cursorAt, this, e]);

			if(this.helper != a && !o.beQuietAtEnd) { // Remove helper, if it's not the original node
				$(this.helper).remove(); this.helper = null;
			}
			
			if(!o.beQuietAtEnd) {
				//if(o.wasPositioned)	$(a).css('position', o.wasPositioned);
				if(o._stop) o._stop.apply(a, [this.helper, this.pos, o.cursorAt, this, e]);
			}

			this.init = false;
			this.opos = this.pos = null;
			return false;
			
		},
		drag: function(e) {

			if (!this.opos || ($.browser.msie && !e.button)) return this.stop.apply(this, [e]); // check for IE mouseup when moving into the document again
			var o = this.options;
			
			this.pos = [e.pageX,e.pageY]; //relative mouse position
			if(this.rpos && this.rpos[0] == this.pos[0] && this.rpos[1] == this.pos[1]) return false;
			this.rpos = [this.pos[0],this.pos[1]]; //absolute mouse position
			
			if(o.pp) { //If we have a positioned parent, use a relative position
				this.pos[0] -= o.po.left;
				this.pos[1] -= o.po.top;	
			}
			
			if( (Math.abs(this.rpos[0]-this.opos[0]) > o.preventionDistance || Math.abs(this.rpos[1]-this.opos[1]) > o.preventionDistance) && this.init == false) //If position is more than x pixels from original position, start dragging
				this.start.apply(this,[e]);			
			else {
				if(this.init == false) return false;
			}
		
			if(o._drag) o._drag.apply(this.element, [this.helper, this.pos, o.cursorAt, this, e]);
			return false;
			
		}
	});

	var num = function(el, prop) {
		return parseInt($.css(el.jquery?el[0]:el,prop))||0;
	};
	function outerWidth(el) {
		var $el = $(el), ow = $el.width();
		for (var i = 0, props = ['borderLeftWidth', 'paddingLeft', 'paddingRight', 'borderRightWidth']; i < props.length; i++)
			ow += num($el, props[i]);
		return ow;
	}
	function outerHeight(el) {
		var $el = $(el), oh = $el.width();
		for (var i = 0, props = ['borderTopWidth', 'paddingTop', 'paddingBottom', 'borderBottomWidth']; i < props.length; i++)
			oh += num($el, props[i]);
		return oh;
	}

 })($);

(function($) {

	//Make nodes selectable by expression
	$.extend($.expr[':'], { draggable: "(' '+a.className+' ').indexOf(' ui-draggable ')" });


	//Macros for external methods that support chaining
	var methods = "destroy,enable,disable".split(",");
	for(var i=0;i<methods.length;i++) {
		var cur = methods[i], f;
		eval('f = function() { var a = arguments; return this.each(function() { if(jQuery(this).is(".ui-draggable")) jQuery.data(this, "ui-draggable")["'+cur+'"](a); }); }');
		$.fn["draggable"+cur.substr(0,1).toUpperCase()+cur.substr(1)] = f;
	};
	
	//get instance method
	$.fn.draggableInstance = function() {
		if($(this[0]).is(".ui-draggable")) return $.data(this[0], "ui-draggable");
		return false;
	};

	$.fn.draggable = function(o) {
		return this.each(function() {
			new $.ui.draggable(this, o);
		});
	}
	
	$.ui.ddmanager = {
		current: null,
		droppables: [],
		prepareOffsets: function(t, e) {
			var dropTop = $.ui.ddmanager.dropTop = [];
			var dropLeft = $.ui.ddmanager.dropLeft;
			var m = $.ui.ddmanager.droppables;
			for (var i = 0; i < m.length; i++) {
				if(m[i].item.disabled) continue;
				m[i].offset = $(m[i].item.element).offset();
				if (t && m[i].item.options.accept(t.element)) //Activate the droppable if used directly from draggables
					m[i].item.activate.call(m[i].item, e);
			}
		},
		fire: function(oDrag, e) {
			
			var oDrops = $.ui.ddmanager.droppables;
			var oOvers = $.grep(oDrops, function(oDrop) {
				
				if (!oDrop.item.disabled && $.ui.intersect(oDrag, oDrop, oDrop.item.options.tolerance))
					oDrop.item.drop.call(oDrop.item, e);
			});
			$.each(oDrops, function(i, oDrop) {
				if (!oDrop.item.disabled && oDrop.item.options.accept(oDrag.element)) {
					oDrop.out = 1; oDrop.over = 0;
					oDrop.item.deactivate.call(oDrop.item, e);
				}
			});
		},
		update: function(oDrag, e) {
			
			if(oDrag.options.refreshPositions) $.ui.ddmanager.prepareOffsets();
			
			var oDrops = $.ui.ddmanager.droppables;
			var oOvers = $.grep(oDrops, function(oDrop) {
				if(oDrop.item.disabled) return false; 
				var isOver = $.ui.intersect(oDrag, oDrop, oDrop.item.options.tolerance)
				if (!isOver && oDrop.over == 1) {
					oDrop.out = 1; oDrop.over = 0;
					oDrop.item.out.call(oDrop.item, e);
				}
				return isOver;
			});
			$.each(oOvers, function(i, oOver) {
				if (oOver.over == 0) {
					oOver.out = 0; oOver.over = 1;
					oOver.item.over.call(oOver.item, e);
				}
			});
		}
	};
	
	$.ui.draggable = function(el, o) {
		
		var options = {};
		$.extend(options, o);
		var self = this;
		$.extend(options, {
			_start: function(h, p, c, t, e) {
				self.start.apply(t, [self, e]); // Trigger the start callback				
			},
			_beforeStop: function(h, p, c, t, e) {
				self.stop.apply(t, [self, e]); // Trigger the start callback
			},
			_drag: function(h, p, c, t, e) {
				self.drag.apply(t, [self, e]); // Trigger the start callback
			},
			startCondition: function(e) {
				return !(e.target.className.indexOf("ui-resizable-handle") != -1 || self.disabled);	
			}			
		});
		
		$.data(el, "ui-draggable", this);
		
		if (options.ghosting == true) options.helper = 'clone'; //legacy option check
		$(el).addClass("ui-draggable");
		this.interaction = new $.ui.mouseInteraction(el, options);
		
	}
	
	$.extend($.ui.draggable.prototype, {
		plugins: {},
		currentTarget: null,
		lastTarget: null,
		destroy: function() {
			$(this.interaction.element).removeClass("ui-draggable").removeClass("ui-draggable-disabled");
			this.interaction.destroy();
		},
		enable: function() {
			$(this.interaction.element).removeClass("ui-draggable-disabled");
			this.disabled = false;
		},
		disable: function() {
			$(this.interaction.element).addClass("ui-draggable-disabled");
			this.disabled = true;
		},
		prepareCallbackObj: function(self) {
			return {
				helper: self.helper,
				position: { left: self.pos[0], top: self.pos[1] },
				offset: self.options.cursorAt,
				draggable: self,
				options: self.options	
			}			
		},
		start: function(that, e) {
			
			var o = this.options;
			$.ui.ddmanager.current = this;
			
			$.ui.plugin.call(that, 'start', [e, that.prepareCallbackObj(this)]);
			$(this.element).triggerHandler("dragstart", [e, that.prepareCallbackObj(this)], o.start);
			
			if (this.slowMode && $.ui.droppable && !o.dropBehaviour)
				$.ui.ddmanager.prepareOffsets(this, e);
			
			return false;
						
		},
		stop: function(that, e) {			
			
			var o = this.options;
			
			$.ui.plugin.call(that, 'stop', [e, that.prepareCallbackObj(this)]);
			$(this.element).triggerHandler("dragstop", [e, that.prepareCallbackObj(this)], o.stop);

			if (this.slowMode && $.ui.droppable && !o.dropBehaviour) //If cursorAt is within the helper, we must use our drop manager
				$.ui.ddmanager.fire(this, e);

			$.ui.ddmanager.current = null;
			$.ui.ddmanager.last = this;

			return false;
			
		},
		drag: function(that, e) {

			var o = this.options;

			$.ui.ddmanager.update(this, e);

			this.pos = [this.pos[0]-o.cursorAt.left, this.pos[1]-o.cursorAt.top];

			$.ui.plugin.call(that, 'drag', [e, that.prepareCallbackObj(this)]);
			var nv = $(this.element).triggerHandler("drag", [e, that.prepareCallbackObj(this)], o.drag);

			var nl = (nv && nv.left) ? nv.left : this.pos[0];
			var nt = (nv && nv.top) ? nv.top : this.pos[1];
			
			$(this.helper).css('left', nl+'px').css('top', nt+'px'); // Stick the helper to the cursor
			return false;
			
		}
	});

})($);

(function($) {

	//If the UI scope is not available, add it
	$.ui = $.ui || {};
	
	//Make nodes selectable by expression
	$.extend($.expr[':'], { shadowed: "(' '+a.className+' ').indexOf(' ui-shadowed ')" });
	
	$.fn.shadowEnable = function() { if($(this[0]).next().is(".ui-shadow")) $(this[0]).next().show(); }
	$.fn.shadowDisable = function() { if($(this[0]).next().is(".ui-shadow")) $(this[0]).next().hide(); }
	
	$.fn.shadow = function(options) {
		
		options = options || {};
		options.offset = options.offset ? options.offset : 0;
		options.opacity = options.opacity ? options.opacity : 0.2;
		
		return this.each(function() {
			
			var cur = $(this);
			
			//Create a shadow element
			var shadow = $("<div class='ui-shadow'></div>"); cur.after(shadow);
			
			//Figure the base height and width
			var baseWidth = cur.outerWidth();
			var baseHeight = cur.outerHeight();
			
			//get the offset
			var position = cur.position();
			
			//Append smooth corners
			$('<div class="ui-shadow-color ui-shadow-layer-1"></div>').css({ opacity: options.opacity-0.05, left: 5+options.offset, top: 5+options.offset, width: baseWidth+1, height: baseHeight+1 }).appendTo(shadow);
			$('<div class="ui-shadow-color ui-shadow-layer-2"></div>').css({ opacity: options.opacity-0.1, left: 7+options.offset, top: 7+options.offset, width: baseWidth, height: baseHeight-3 }).appendTo(shadow);
			$('<div class="ui-shadow-color ui-shadow-layer-3"></div>').css({ opacity: options.opacity-0.1, left: 7+options.offset, top: 7+options.offset, width: baseWidth-3, height: baseHeight }).appendTo(shadow);
			$('<div class="ui-shadow-color ui-shadow-layer-4"></div>').css({ opacity: options.opacity, left: 6+options.offset, top: 6+options.offset, width: baseWidth-1, height: baseHeight-1 }).appendTo(shadow);
			
			//If we have a color, use it
			if(options.color)
				$("div.ui-shadow-color", shadow).css("background-color", options.color);
			
			//Determine the stack order (attention: the zIndex will get one higher!)
			if(!cur.css("zIndex") || cur.css("zIndex") == "auto") {
				var stack = 0;
				cur.css("position", (cur.css("position") == "static" ? "relative" : cur.css("position"))).css("z-index", "1");
			} else {
				var stack = parseInt(cur.css("zIndex"));
				cur.css("zIndex", stack+1);
			}
			
			//Copy the original z-index and position to the clone
			//alert(shadow); If you insert this alert, opera will time correctly!!
			shadow.css({
				position: "absolute",
				zIndex: stack,
				left: position.left,
				top: position.top,
				width: baseWidth,
				height: baseHeight,
				marginLeft: cur.css("marginLeft"),
				marginRight: cur.css("marginRight"),
				marginBottom: cur.css("marginBottom"),
				marginTop: cur.css("marginTop")
			});
			
			
			function rearrangeShadow(el,sh) {
				var $el = $(el);
				$(sh).css($el.position());
				$(sh).children().css({ height: $el.outerHeight()+"px", width: $el.outerWidth()+"px" });
			}
			
			if($.browser.msie) {
				//Add dynamic css expressions
				shadow[0].style.setExpression("left","parseInt(jQuery(this.previousSibling).css('left'))+'px' || jQuery(this.previousSibling).position().left");
				shadow[0].style.setExpression("top","parseInt(jQuery(this.previousSibling).css('top'))+'px' || jQuery(this.previousSibling).position().top");
			} else {
				//Bind events for good browsers
				this.addEventListener("DOMAttrModified",function() { rearrangeShadow(this,shadow); },false);
			}

				
		});
	};
	

})($);
/*
 * jQuery ifixpng plugin
 * renamed from pngfix to ifixpng due to naming conflict 
 * with another plugin
 * Version 1.7  (18/09/2007)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {
	
	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var base = $('base').attr('href'); // need to use this in case you are using rewriting urls
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
					// use source tag value if set 
					var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
					// apply filter
					$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
					  .attr({src:$.ifixpng.getPixel()});
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
          .positionFix();

				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "img/loading.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = 'img/loading.gif';
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src=\"img/actions/cross.png\" alt=\"\"/></a></div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src=\"img/actions/cross.png\" alt=\"\"/></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src=\"img/actions/cross.png\" alt=\"\"/></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   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, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}



OMapConfig = new function() {
    this.baseurl = '/campusmap/';
    this.siteurl = 'http://oregonstate.edu/campusmap/';
    this.center = new GLatLng(44.563628, -123.281407);
    this.defaultMapType = G_NORMAL_MAP;
    this.defaultZoom = 16;
    this.tileMinZoom = 13;
    this.tileMaxZoom = 20;
    this.encodeZoomFactor = 2;
    this.encodeNumLevels = 20;
    this.defaultLayers = [1,204]; 
    this.icons = {'layer' : this.baseurl+'img/leftnav/layers', 'location' : this.baseurl+'img/leftnav/building', 'building' : this.baseurl+'img/leftnav/building', 'route' : this.baseurl+'img/leftnav/car', 'art' : this.baseurl+'img/leftnav/photos', 'select' : this.baseurl+'img/leftnav/tick', 'remove' : this.baseurl+'img/leftnav/cross' } ;

    this.add = this.set = function(key, val) { this[key] = val; };
}();
function Window(window_element)
{
  this.window_element = $(window_element);
  this.window_class = '.window';
  this.titlebar_class = '.window_titlebar';
  this.content_class = '.window_content';
  this.close_class = '.window_close';
  this.init = function() {
    this.window_element.draggable({ handle:this.titlebar_class });
    // Set the height of the window_content so the scroll bar works correctly.
      this.window_element.children(this.content_class).each(function() {
          $(this).height(
            $($(this).parents(this.window_class)[0]).outerHeight()- $($($(this).parents(this.window_class)[0]).children(this.window_titlebar)[0]).outerHeight()-6);
        })
      .end()
      .resizable({ proportionallyResize: [this.content_class] })
      .find(this.close_class)
      .bind( 
        'click',
        {window_class:this.window_class},
        function(event) {
          $(this).parents(event.data.window_class).hide(); 
        }
      );
  };

  this.init();
}

function Legend(legend_id)
{
  this.content_area = $(legend_id).children('#legend_content');
  this.legendElements = new Object();
  this.generateMapElementId = function(map_element) { 
    var map_element_id = "legend_element_"+map_element.type+'_'+map_element.name.replace(/[\s\/]+/g, '_');
    return map_element_id;
  }
}

Legend.prototype.addLegendElement = function(map_element) {
  var map_element_id = this.generateMapElementId(map_element);
  if (this.legendElements[map_element_id] == null) {
    this.legendElements[map_element_id] = { map_element: map_element, references: 1 };
    var map_element_icon = $(map_element.icon_html).addClass('legend_icon');
    var li = $('<li></li>');
    li.attr({ id: map_element_id, style: 'clear:both;line-height:16px;' }).addClass(map_element.type).append(map_element_icon).append($('<label>'+map_element.name+'</label>'));
    var legend_area = $(this.content_area).find('#legend_'+map_element.type+'s');
    var legend_area_ul = legend_area.find('ul');
    if (legend_area_ul.length == 0) {
      legend_area_ul = $('<ul></ul>');
      legend_area.append(legend_area_ul);
    }
    legend_area_ul.append(li)

    if (IE6) {
      if ($('#legend_window').css('display') == 'block') {
        this.content_area.find('img').ifixpng();
      }
    }
  }
  else {
    this.legendElements[map_element_id].references++;
  }
};

Legend.prototype.removeLegendElement = function(map_element) {
  var map_element_id = this.generateMapElementId(map_element);
  if (this.legendElements[map_element_id] &&
      this.legendElements[map_element_id].references > 1) {
      this.legendElements[map_element_id].references--;
      return;
  }
  $('#'+map_element_id).remove();
  delete(this.legendElements[map_element_id]);
};

OMap = new function() {
    var map;
    var layers = new Object();
    // holds the arrays for IE6 when resizing
    this.tmp_layers = new Array(); 
    var locations = new Object();
    var routes = new Object();
    this.clickedPoint;
    this.control;
    this.typecontrol;
    this.legend;
    this.print_window;
    this.embedded = false;
    this.enable_infowindow = true;
    this.event = function(type, handler) { GEvent.addListener(map, type, handler); };

    this.init = function(container, center, zoom, type, embedded, enable_infowindow) {

       if (typeof(embedded) == 'undefined')
         this.embedded = false;
       else
         this.embedded = embedded;
      
       if (typeof(enable_infowindow) == 'undefined')
         this.enable_infowindow = true;
       else
         this.enable_infowindow = enable_infowindow;

        if (GBrowserIsCompatible()) { 
            map = new GMap2(container); 
            if (!this.embedded){ 
              this.control = new GLargeMapControl();   
              this.typecontrol = new GMapTypeControl(); 
              this.overviewcontrol= new GOverviewMapControl(new GSize(150,150));

              map.addControl(this.typecontrol);
              map.addControl(this.overviewcontrol);
              this.overviewcontrol.hide();
            }
            else
              this.control = new GSmallMapControl();            

            map.setCenter(center, zoom, type); 
            map.enableContinuousZoom();
            map.enableDoubleClickZoom();
            map.addControl(this.control);
            this.legend = new Legend('#legend_window');
        }
    };

    this.getMap = function() { return map; };

    this.getLayers = function() { return layers; };

    this.getLocations = function() { return locations; };

    this.getRoutes = function() { return routes; };

    this.mapElementOnMap = function(mapElement) {
        switch (mapElement.type) {
            case 'layer':
                return layers[mapElement.getId()]; 
                break;
            case 'route':
                return routes[mapElement.getId()]; 
                break;
            case 'location':
                return locations[mapElement.getId()]; 
                break;
        }
        return false;
    };

    this.getBookmarkParams = function () 
    {
        var type;
        switch(OMap.getMap().getCurrentMapType().getName()) {
          case 'Map':
            type = 'normal';
            break;
          case 'Satellite':
            type = 'satellite';
            break;
          case 'Hybrid':
            type = 'hybrid';
            break;
          default:
            type = 'normal';
            break;
        }
        var url = '?zoom='+OMap.getMap().getZoom();
        url += '&type='+type;
        url += '&centerlat='+OMap.getMap().getCenter().lat();
        url += '&centerlng='+OMap.getMap().getCenter().lng();
        url += '&layers=';
        for (i in layers) {
            if (layers[i]) {
                url += i+",";
            }
        }

        var url_locations = '';
        for (i in locations) {
            if (locations[i]) {
                url_locations += i+",";
            }
        }
        if (url_locations != '')  {
            url += '&locations=' + url_locations;
        }

        var url_routes = '';
        for (i in routes) {
            if (routes[i]) {
                url_routes += i+",";
            }
        }
        if (url_routes != '')  {
            url += '&routes=' + url_routes;
        }

        return url;
    };

    this.openPrintWindow = function () 
    {
        var print_url = OMapConfig.baseurl;
        print_url += 'print';
        print_url += OMap.getBookmarkParams();
        var window_features = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
        this.print_window = window.open(print_url, 'OSUCampusMapPrint', window_features)
    };

    var mapElementClick = function(overlay, point) {

        if (!overlay) {
            OMap.clickedPoint = point;
            var ids = new Array();
            for (var i in layers) {
                if (layers[i].enabled) {
                    ids.push(i);
                }
            }
            $.getJSON(
                OMapConfig.baseurl + 'map/click?' +
                    'lat=' + point.lat() + 
                    '&lng=' + point.lng() +
                    '&zoom=' + map.getZoom() +
                    '&layers=' + ids.join(','), 
                OMap.mapElementClickHandler
            );
        }
    };

    this.mapElementClickHandler = function(data) { 
       
        if (data) {
            var map_element = OMap.createElementFromJson(data);
            if (map_element != null) {
                map_element.clicked();
            }
        }
    };

    this.createElementFromJson = function(json) {
        if (json) {
            switch (json.type) {
                case 'layer':
                    var el = new OMapLayer(json);
                    break;
                case 'location':
                    var el = new OLocation(json);
                    break;
                case 'route':
                    var el = new ORoute(json);
                    break;
            }
            if (element = OMap.mapElementOnMap(el)) {
              return element;
            } else {
              return el;
            }
        }
        return null;
    };

    this.addMapElement = function(data, click) {
        
        var map_element = OMap.createElementFromJson(data);

        if (map_element != null) {
            if (click !== undefined && click === false) {
                map_element.enable();
            } else {
                map_element.clicked();
            }
        }
    };

    /**
     * Takes an Object full of map element ids and creates them based upon 
     * their types.
     * @param data Object: formatted by: 'layers':[],'routes':[],'locations':[]
     * arrays contain ids of the respective type.
     * @return null
     */
    this.addMapElements = function(data, click) {
        var types = ['layers','routes','locations'];
        var params = [];
        for (var type_index in types) {
            var type = types[type_index];
            if (data[type] && data[type].length > 0) {
                params.push(type+'='+data[type].join(','));
            }
        }
        $.getJSON(OMapConfig.baseurl + 'map/element?' + params.join('&'), 
          function(data) {
              for (var data_type in data) {
                  var type_singular = data_type.slice(0,-1); //Removes the 's'
                  for (var index in data[data_type]) {
                      OMap.addMapElement(
                        {type: type_singular, data: data[data_type][index]},
                        click);
                  }
              }
          }
        );
        return true; 
    }; 

    var hide_bookmark_window = function() { 
        var bookmark_window = $('#bookmark_window');
        if (bookmark_window.css('display') == 'block') { bookmark_window.hide(); }
    };

    this.registerElementClickHandler = function() { 
        GEvent.addListener(map, 'click', mapElementClick);
        GEvent.addListener(map, 'click', hide_bookmark_window); 
    };
    this.registerMoveStartHandler = function() { GEvent.addListener(map, 'movestart', hide_bookmark_window); };
    this.registerAddOverlayHandler = function() { GEvent.addListener(map, 'addoverlay', hide_bookmark_window); };
    this.registerRemoveOverlayHandler = function() { GEvent.addListener(map, 'removeoverlay', hide_bookmark_window); };
    this.registerAddMapTypeHandler = function() { GEvent.addListener(map, 'addmaptype', hide_bookmark_window); };
    this.registerMapTypeChangedHandler = function() { GEvent.addListener(map, 'maptypechanged', hide_bookmark_window); };

}();

//IE6 bug: js error is thrown when the user resizes the window and layers are enabled.
$(window).bind( 'resize', function () {
    if (IE6) {
        var layers = OMap.getLayers();
        for (var i in layers) {
            OMap.tmp_layers.push(layers[i]);
            if(layers[i].overlay) {
                layers[i].disable();
            }
        }
        window.setTimeout(function() { 
          for ( var i in OMap.tmp_layers ) {
            OMap.tmp_layers[i].enable(); 
          }
          OMap.tmp_layers = new Array();
        }, 25);
    }
});

/**
 * A tile layer.  Inherits GTileLayer.
 *
 * @param layer an OMapLayer object
 * @param copyright a GCopyrightCollection, if you are using a custom map type
 * @param minZoom the minimum zoom where this tile applies
 * @param maxZoom the maximum zoom where this tile applies
 * @author Barry Chen
 */
function OTileLayer(layer, copyright, minZoom, maxZoom)
{
    this.layer = layer;
    GTileLayer.call(this, copyright, minZoom, maxZoom);

    this.getTileUrl = function(tile, zoom) { 
        var layerBoundaries = this.layer.getBoundaries();

        if ( zoom >= OMapConfig.tileMinZoom && zoom <= OMapConfig.tileMaxZoom &&
             Math.floor(layerBoundaries.west / 256) <= tile.x &&
             Math.ceil(layerBoundaries.east / 256) > tile.x &&
             Math.floor(layerBoundaries.north / 256) <= tile.y &&
             Math.ceil(layerBoundaries.south / 256) > tile.y ) {
            return OMapConfig.baseurl + 'img/tiles/' + this.layer.getId() + '/' + zoom + '/' + tile.x + '_' + tile.y + '.png'; 
        }

        return OMapConfig.baseurl + 'img/tiles/blank.png';
    };
    this.isPng = function() { return true; };
    this.getOpacity = function() { return 1; };
}
OTileLayer.prototype = GTileLayer.prototype;

function OMapElement(jsonData)
{
    if (jsonData) {
        this.type = jsonData.type;
        for (var i in jsonData.data) {
            this[i] = jsonData.data[i];
        }
    }
    this.shapes = [];
    this.enabled = false;
    this.marker = this.createMarker();

    GEvent.addListener(this, 'beforepan', function(marker_location) {
        if (!OMap.getMap().getBounds().containsLatLng(marker_location)) {
            OMap.getMap().panTo(marker_location);
        }
    });
}

OMapElement.prototype.clicked = function() {
    var marker_location = new GLatLng(this.marker_location[1], this.marker_location[0]);
    GEvent.trigger(this, 'beforepan', marker_location);

    this.addToMap();
    OMap.getMap().panTo(marker_location); 

    if (OMap.enable_infowindow) {
        this.showInfoWindow();
    }
    else{
      if (this.isAbsoluteUrl(this.icon_path))
        parent.window.location = "http://oregonstate.edu/campusmap/virtualtour/locations/view/" + this.id;
    }
    if (typeof SelectedItems != 'undefined') {
      SelectedItems.add(this);            
    }
};

/**
 * Adds a map element to the map.
 * Does not add the element to anything else.
 */
OMapElement.prototype.addToMap = function() {};

/**
 * Removes the map element from the map.
 * Does not remove it from anywhere else
 */
OMapElement.prototype.removeFromMap = function() {};

/**
 * Enables the polygon for the map element and shows the marker.
 */
OMapElement.prototype.enable = function() {
    this.drawGPoly();
    this.addMarker();
    this.enabled = true;
};

/**
 * Removes the polygons and marker for the map element. 
 */
OMapElement.prototype.disable = function() {
    this.removeMarker();
    this.removeShapes();
    this.enabled = false;
};

OMapElement.prototype.addMarker = function() {
    this.addOverlay(this.marker);
};

OMapElement.prototype.removeMarker = function() {
    OMap.getMap().removeOverlay(this.marker);
};

OMapElement.prototype.removeShapes = function() {
    for (var i in this.shapes) {
        OMap.getMap().removeOverlay(this.shapes[i]);
        delete this.shapes[i];
    }
    this.shapes = [];
};

OMapElement.prototype.showInfoWindow = function() {
    this.marker.openInfoWindowTabsHtml(
        [ new GInfoWindowTab('Info', this.getInfoWindowText()) ]
    );
};

OMapElement.prototype.bindInfoWindow = function() {
  if (OMap.enable_infowindow) {
    this.marker.bindInfoWindowTabsHtml(
        [ new GInfoWindowTab('Info', this.getInfoWindowText()) ]
    );
  }
};

OMapElement.prototype.addOverlay = function(g) {
    OMap.getMap().addOverlay(g);
    this.shapes.push(g);
    with(this){
        GEvent.addListener(g, 'click',  function(point) { clicked(); } );
    }
};
OMapElement.prototype.createMarker = function() {};
OMapElement.prototype.drawGPoly = function() {};
OMapElement.prototype.drawPolygon = function(polylines) {
    var lines = [];

    for (var line in polylines) {
        lines.push({
            color:      '#0000ff', 
            weight:     1, 
            opacity:    1, 
            points:     polylines[line][0], 
            levels:     polylines[line][1], 
            zoomFactor: OMapConfig.encodeZoomFactor, 
            numLevels:  OMapConfig.encodeNumLevels
        });
    }

    var polygon = new GPolygon.fromEncoded({polylines: lines, fill: true, color: '#aeaeff', opacity: 0.4, outline: true});

    this.addOverlay(polygon);
};
OMapElement.prototype.drawLinestring = function(line) {
    var polyline = new GPolyline.fromEncoded({
        color:      this.color != null ? this.color : '#0000ff', 
        weight:     4, 
        opacity:    0.4, 
        points:     line[0], 
        levels:     line[1], 
        zoomFactor: OMapConfig.encodeZoomFactor, 
        numLevels:  OMapConfig.encodeNumLevels});

    this.addOverlay(polyline);
};
OMapElement.prototype.isAbsoluteUrl = function(path){

  if (path.indexOf("http://") >= 0)
    return true;
  else
    return false;

}
OMapElement.prototype.getName = function() { return this.name; };
OMapElement.prototype.toString = function() { return this.type + '_' + this.id; };
OMapElement.prototype.getId = function() { return this.id; };

OMapLayer.prototype = new OMapElement();
OMapLayer.constructor = OMapLayer;

function OMapLayer(jsonData)
{
    this.routes = new Object();
    for( r in jsonData["data"]["Route"] ) {
        this.routes[jsonData["data"]["Route"][r].id] = new ORoute({'type': 'route', 'data': jsonData["data"]["Route"][r]});
    }
    this.locations = new Object();
    for( l in jsonData["data"]["Location"] ) {
        this.locations[jsonData["data"]["Location"][l].id] = new OLocation({'type': 'location', 'data': jsonData["data"]["Location"][l]});
    }
    OMapElement.call(this, jsonData);
    this.overlay;
    this.boundaries = new Array();

    this.type = 'layer';
    this.getId = function() { return this.id; };
    this.icon_html = '<div style="background-color:'+this.color_fill+';border:2px solid '+this.color_border+';"></div>';
}

OMapLayer.prototype.addToMap = function() {
    layers = OMap.getLayers();
    layers[this.id] = this;
    this.enable();
};
OMapLayer.prototype.removeFromMap = function() {
    this.disable();
    layers = OMap.getLayers();
    delete layers[this.id];
};
/**
 * Adds the tile overlay to the map
 */
OMapLayer.prototype.enable =  function() {
    if (this.enabled == true) { return; } 
    map = OMap.getMap();
    if(this.tiles_enabled == 1) {
        if(this.overlay === undefined) {
            this.overlay = new GTileLayerOverlay(new OTileLayer(this, null, OMapConfig.tileMinZoom, OMapConfig.tileMaxZoom));
        }
        map.addOverlay(this.overlay);
    }
    for (var route in this.routes) { 
        this.routes[route].enable();
    }
    for (var loc in this.locations) { 
        if (this.locations[loc].icon_path != null) {
            this.locations[loc].enable();
            this.locations[loc].bindInfoWindow();
        }
    }
    if(this.tiles_enabled == 1) {
        OMap.legend.addLegendElement(this);
    }
    this.enabled = true;
};
OMapLayer.prototype.getInfoWindowText = function() {
    output = '<div class="gmap_info_window">';
    output += '<h3>' + this.name + '</h3>';
    output += '</div>';

    return output;
};
OMapLayer.prototype.disable = function() {
    if (this.enabled == false) { return; } 
    map = OMap.getMap();
    if(this.tiles_enabled == 1) {
        map.removeOverlay(this.overlay);
        delete this.overlay;
    }
    for (var route in this.routes) { 
        this.routes[route].disable();
    }
    for (var loc in this.locations) { 
        if (this.locations[loc].icon_path != null) {
            this.locations[loc].disable();
        } 
    }
    if(this.tiles_enabled == 1) {
        OMap.legend.removeLegendElement(this);
    }
    this.enabled = false;
};
  
OMapLayer.prototype.getBoundaries = function() {
    if (!this.boundaries[OMap.getMap().getZoom()]) {
        var bounds = this.boundaries;
        var zoom = OMap.getMap().getZoom();
        bounds[zoom] = this.pixelBounds(this.bounding_box, zoom);
    }
    return this.boundaries[OMap.getMap().getZoom()];
};
OMapLayer.prototype.pixelBounds = function(bounding_box, zoom) {
    var pixels = []
    var projection = OMap.getMap().getCurrentMapType().getProjection();
    for (var box_index in bounding_box[0]) {
        var corner = bounding_box[0][box_index];
        pixels.push(projection.fromLatLngToPixel(new GLatLng(corner[1], corner[0]), zoom));
    }

    var east = null;
    var south = null;
    var west = null;
    var north = null;
    for (var pixel_index in pixels) {
        var corner = pixels[pixel_index];
        if (east == null || corner.x > east) {
            east = corner.x;
        }
        if (south == null || corner.y > south) {
            south = corner.y;
        }
        if (west == null || corner.x < west) {
            west = corner.x;
        }
        if (north == null || corner.y < north) {
            north = corner.y;
        }
    }
    return {'east':east,'south':south,'west':west,'north':north}
};

OMapLayer.prototype.drawLinestring = function() {};
OMapLayer.prototype.clicked = function() {
    this.addToMap();
    if (typeof SelectedItems != 'undefined') {
      SelectedItems.add(this);            
    }
};
OMapLayer.prototype.createMarker = function() { return null; };
OMapLayer.prototype.showMarker = function() {};
OMapLayer.prototype.showInfoWindow = function() {};

OLocation.prototype = new OMapElement();
OLocation.constructor = OLocation;

function OLocation(jsonData)
{
    OMapElement.call(this, jsonData);

    if (this.icon_path) { 
      var full_icon_path = OMapConfig.baseurl + "img/" + this.icon_path;
      this.icon_html = '<img src="'+full_icon_path+'" alt=""/>';
    } else {
      this.icon_html = '<img src="'+OMapConfig.baseurl+'img/leftnav/building.png" alt=""/>';
    }
}

OLocation.prototype.repairMarkerLocation = function(marker){
  
  if (marker.constructor.toString().indexOf("Array") == -1){
    marker = this.marker_location.split(',');
    return marker;
  }
  else
    return marker;
}

OLocation.prototype.createMarker = function() {
    this.marker_location = this.repairMarkerLocation(this.marker_location); 
    var markerLocation = new GLatLng(this.marker_location[1], this.marker_location[0]);

    if(this.icon_path != null) {
        var locationIcon = new GIcon();
        locationIcon.iconSize = new GSize(16,16);
        locationIcon.iconAnchor = new GPoint(8, 8);
        locationIcon.infoWindowAnchor = new GPoint(16, 0);
        locationIcon.infoShadowAnchor = new GPoint(16, 0);
        if (this.isAbsoluteUrl(this.icon_path)) //shayne shayne
          locationIcon.image = this.icon_path;
        else
          locationIcon.image = OMapConfig.baseurl + "img/" + this.icon_path;
        var markerOptions = { icon:locationIcon, title: this.name };
        return new GMarker(markerLocation, markerOptions);
    } else {
        var nullIcon = new GIcon();
        nullIcon.iconSize = new GSize(0,0);
        nullIcon.iconAnchor = new GPoint(0,0);
        nullIcon.infoWindowAnchor = new GPoint(0, 0);
        nullIcon.infoShadowAnchor = new GPoint(0, 0);
        nullIcon.image = OMapConfig.baseurl+'img/spacer.png';
        var markerOptions = { icon:nullIcon };
        return new GMarker(markerLocation, markerOptions);
    }
};
OLocation.prototype.drawGPoly = function() {
    for (var i in this.perimeter) {
        switch (this.perimeter[i].type) {
            case 'polygon':
                this.drawPolygon(this.perimeter[i].data);
                break;
            case 'linestring':
                this.drawLinestring(this.perimeter[i].data);
                break;
            case 'point':
                break;
        }
    }
};
OLocation.prototype.addToMap = function() {
    if (!OMap.mapElementOnMap(this)) {
        locations = OMap.getLocations();
        locations[this.id] = this;
        this.enable();
    }
};
OLocation.prototype.removeFromMap = function() {
    this.disable();
    locations = OMap.getLocations();
    delete locations[this.id];
};
OLocation.prototype.enable = function() {
    if (this.enabled == true) { return; } 
    OMapElement.prototype.enable.call(this);
    if (this.icon_path != null) {
        OMap.legend.addLegendElement(this);
    }
}
OLocation.prototype.disable = function() {
    if (this.enabled == false) { return; } 
    OMapElement.prototype.disable.call(this);
    if (this.icon_path != null) {
        OMap.legend.removeLegendElement(this);
    }
}

OLocation.prototype.getInfoWindowText = function() {

    output = '<div class="gmap_info_window">';
    // the two if statements below were added because the bus stops didn't have 
    // any metadata associated when they are retrieved from a db
    // using an ajax call (cedenoj 3/12/2008)

    // check to make sure that we have metadata to display
    if (typeof(this.metadata) != 'undefined' && this.metadata.thumbnail_image != '') {
       if (this.isAbsoluteUrl(this.metadata.thumbnail_image)) //shayne shayne
          output += '<img src="' + this.metadata.thumbnail_image + '" alt="thumnail image of element in map" />';
        else {
          output += '<img src="' + OMapConfig.baseurl + 'img/metadata/';
          output += this.metadata.thumbnail_image + '" alt="thumnail image of element in map" />';
        }
    }

    output += '<h3>' + this.name + '</h3>';

    // check to make sure that we have metadata to display
    if (typeof(this.metadata) != 'undefined') {
        if (typeof(this.metadata.virtual_tour) != 'undefined'){ //shayne shayne shayne
           output += '<p>' + this.metadata.virtual_tour.header + '</p>';
           output += this.metadata.virtual_tour.body;
           output += '<br /><br /><p><a href="' + this.metadata.virtual_tour.link + '" >Virtual Tour for ' + this.name + '</a></p>'; 
        }
        else{ 
          output += '<p>'+this.metadata.physical_address+'</p>';
          output += this.metadata.short_description;
        }
    }

    // check to make sure that we have more metadata info to display
    if (typeof(this.metadata) != 'undefined' && this.metadata.has_more_info == true) {
        escaped_name = this.name.replace(/'/, "&#39;");
        output += '<p><a href="' + OMapConfig.baseurl + 'locations/info/' + this.id;
        output += '" id="more_location_info" title="' + escaped_name + '"';
        output += ' onclick=\'tb_show("' + escaped_name + '", "'  + OMapConfig.baseurl + 'locations/info/' + this.id + '", false);return false;\'';
        output += '>More Information ...</a></p>';

    }

    output += '</div>';

    return output;

};

ORoute.prototype = new OMapElement();
ORoute.constructor = ORoute;

function ORoute(jsonData)
{
    this.locations = new Object();
    for( l in jsonData["data"]["Location"] ) {
        this.locations[jsonData["data"]["Location"][l].id] = new OLocation({'type': 'location', 'data': jsonData["data"]["Location"][l]});
    }
    OMapElement.call(this, jsonData);

    this.icon_html = '<div style="border-top:4px solid '+this.color+';"></div>';
}

ORoute.prototype.addToMap = function() {
    if (!OMap.mapElementOnMap(this)) {
        routes = OMap.getRoutes();
        routes[this.id] = this;
        this.enable();
    }
};
ORoute.prototype.getInfoWindowText = function() {
    output = '<div class="gmap_info_window">';
    output += '<h3>' + this.name + '</h3>';

    // check to make sure that we have metadata to display
    if (typeof(this.metadata) != 'undefined') {
        output += '<p>'+this.metadata.physical_address+'</p>';
        output += this.metadata.short_description;
    }

    // check to make sure that we have more metadata info to display
    if (typeof(this.metadata) != 'undefined' && this.metadata.has_more_info == true) {
        escaped_name = this.name.replace(/'/, "&#39;");
        output += '<p><a href="' + OMapConfig.baseurl + 'locations/info/' + this.id;
        output += '" id="more_location_info" title="' + escaped_name + '"';
        output += ' onclick=\'tb_show("' + escaped_name + '", "'  + OMapConfig.baseurl + 'locations/info/' + this.id + '", false);return false;\'';
        output += '>More Information ...</a></p>';

    }

    output += '</div>';

    return output;
};
ORoute.prototype.removeFromMap = function() {
    this.disable();
    routes = OMap.getRoutes();
    delete routes[this.id];
};
/**
 * In addition to the normal enable of drawing the polygon for a route and
 * a marker for a route, this enable function draws the route's related 
 * locations
 */
ORoute.prototype.enable = function() {
    if (this.enabled == true) { return; } 
    OMapElement.prototype.enable.call(this);
    OMap.legend.addLegendElement(this);
    for (var loc in this.locations) { 
        this.locations[loc].enable();
        this.locations[loc].bindInfoWindow();
    }
};
ORoute.prototype.disable = function() {
    if (this.enabled == false) { return; } 
    OMapElement.prototype.disable.call(this);
    OMap.legend.removeLegendElement(this);
    for (var loc in this.locations) { 
        this.locations[loc].disable();
    }
};
ORoute.prototype.drawGPoly = function() {
    for (var i in this.path) {
        this.drawLinestring(this.path[i]);
    }
};
OMapElement.prototype.createMarker = function() {
    var point = new GLatLng(this.marker_location[1], this.marker_location[0]);
    var nullIcon = new GIcon();
    nullIcon.iconSize = new GSize(0,0);
    nullIcon.iconAnchor = new GPoint(0,0);
    nullIcon.infoWindowAnchor = new GPoint(0, 0);
    nullIcon.infoShadowAnchor = new GPoint(0, 0);
    nullIcon.image = OMapConfig.baseurl+'img/spacer.png';
    var markerOptions = { icon:nullIcon };
    return new GMarker(point, markerOptions);
};

$('document').ready( function() {

/**
 * A accordion widget. Will become the full height of whatever element is 
 * supplied as the root
 * 
 * The accordion is made up of a main outter div and subsequent inner "fold" divs
 * which can be expanded when either their heading is clicked, or an event calls 
 * expandFold();
 *
 * Default open fold is denoted with .default
 * Headings of folds are denoted with .heading
 * Fold content is denoted with .content
 
 * Example setup:
 * 
 <div class="accordion">
   <div class="fold default">
     <h2 class="heading"></h2>
     <div class="content">
     </div>
   </div>
   <div class="fold">
     <h2 class="heading"></h2>
     <div class="content">
     </div>
   </div>
 </div>
 * @param element block element to turn into an accordion.
 * @author George Harkin
 */
Accordion = new function () {
	var accordions = $('.accordion');
	for(var i = 0; i < accordions.length; i++) {
		var accordion = $(accordions[i]);
		var folds = accordion.children('.fold');
		folds.children('.heading').click( function() {
			Accordion.expandFold(accordion, $(this).parent());
		});
		
        $(window).bind( 'resize', function () {
            if (Sidebar.sidebar.css('display') != 'none') {
        	    Accordion.updateSize();
            }
        });
	}

	/**
	 * Expands the supplied fold element and collapses the other folds
	 *
	 * @param accordion The accordion div (jQuery Object).
	 * @param fold A fold in the accordion (jQuery Object). Must be an element within the 
	 * accordion or will not work correctly.
	 * @return null or Exception
	 */
	this.expandFold = function(accordion, fold) {
		if(accordion.height() == 0) return;
		current_fold = accordion.children('.current').not(fold);
		if(current_fold.lenght == 0) return;
		var accordion_height = accordion.outerHeight();
		var heading_height = accordion.find('.heading').outerHeight();
		var folds = accordion.children('.fold').not(fold);
		current_fold.children('.content').height(0);
		current_fold.removeClass('current');
		
		fold.children('.content')
			.height((accordion_height)-((folds.length+1)*heading_height));
		fold.addClass('current');
	};
	
	this.updateSize = function() {
		for(var i = 0; i < accordions.length; i++) {
			var accordion = $(accordions[i]);
			Accordion.expandFold(accordion, accordion.children('.current'));
		}
	};
}();

});

$('document').ready( function() {

Sidebar = new function() {
    this.sidebar = $('#sidebar');
    var content = $('#content');
    var edge = $('#sidebar_edge');
    edge.css('display', 'block');
    var selected_items = this.sidebar.find('#selected_items');
    this.show_sidebar = $('#show_sidebar');
    this.hide_sidebar = $('#hide_sidebar');
    
   	$(window).bind( 'resize', function () {
        if (Sidebar.sidebar.css('display') != 'none') {
            Sidebar.update_selected_items_height();
        }
	});

    this.show = function() {
        content.css('left','200px');
        edge.css('marginLeft', '180px');
        Sidebar.sidebar.show();
        if(IE6){
            content.css('width', (document.documentElement.clientWidth - 200) + 'px')
                   .css('height', (document.documentElement.clientHeight - 86) + 'px');
            edge.css('width', '20px')
                .css('height', (document.documentElement.clientHeight - 86) + 'px');
            Sidebar.sidebar.css('left', '0px')
                   .css('width', '180px')
                   .css('height', (document.documentElement.clientHeight - 115) + 'px');
        }
        Sidebar.show_sidebar.hide();
        Sidebar.hide_sidebar.show();
        if(OMap.getMap() !== undefined) {
            OMap.getMap().checkResize();
        }
        Accordion.updateSize();
        Sidebar.update_selected_items_height();
        edge.unbind('click');
        edge.click(Sidebar.hide);
        if (IE6) {
          Sidebar.sidebar.find('img').ifixpng();
        }
    };
    
    this.hide = function() {
        Sidebar.sidebar.hide();
        content.css('left', '20px');
        edge.css('marginLeft','0');
        if(IE6){
            content.css('width', (document.documentElement.clientWidth - 20) + 'px')
                   .css('height', (document.documentElement.clientHeight - 86) + 'px');
            edge.css('left', '0px')
                .css('width', '20px')
                .css('height', (document.documentElement.clientHeight - 86) + 'px');
        }
        Sidebar.show_sidebar.show();
        Sidebar.hide_sidebar.hide();
        if(OMap.getMap() !== undefined) {
            OMap.getMap().checkResize();
        }
        edge.unbind('click');
        edge.click(Sidebar.show);
    };
    
    this.update_selected_items_height = function() { 
		selected_items.find('.content').height(
			selected_items.outerHeight()-
			selected_items.find('.heading').outerHeight()
		);
    };

    edge.click(this.show);
    edge.hover(function(){edge.css('backgroundColor','#222');}, function(){edge.css('backgroundColor','#000');});

}();

});

$('document').ready( function() {

Search = new function() {
	this.search_form = $('#search');
	var search_query = this.search_form.find('#search_query');
	var search_url = OMapConfig.baseurl+'search/';
	this.search_results = $('#search_results');
	var search_loading = this.search_results.find('#search_loading');
	var search_content = this.search_results.find('#search_content');
	this.search = function() {
        var searched_text = search_query.val();
        if (searched_text.search(/help/i) != -1) {
            $('#help_link').click();
        } else {
            var query = search_query.val().replace(' ', '+');
            var url = search_url+query;
            search_content.empty();		
            Sidebar.show();
            Accordion.expandFold($('#selectables'), $('#search_fold'));
            search_loading.show();

            GDownloadUrl(url, showResults);	
        }
    };

    var showResults = function(response) {
        search_content.empty();
        search_loading.hide();
        var search_info = eval('('+response+')');
        $('#search_fold > div.heading').html('Search Results: ' + search_info['hits']);
        search_content.append('<ul></ul>');
        var ul = search_content.children('ul').get(0);
        var li, div, img;
        for (var i in search_info['results']) {
            li = document.createElement('li'); 
            div = document.createElement('div');
            li.className = 'search_result';
            li.id = search_info['results'][i]['type']+'_'+search_info['results'][i]['id'];
            div.className = search_info['results'][i]['type'];
            div.innerHTML += search_info['results'][i]['name'];
            li.appendChild(div);
            ul.appendChild(li);
        }
        $('.location, .route, .layer').slideDown();
        if (IE6) {
            $('#search_content img').ifixpng();
            $('#search_content ul li').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        }
        if (search_info['hits'] > search_info['perpage']) {
            var pages = Math.ceil(search_info['hits'] / search_info['perpage']);
            var current = Math.ceil(search_info['offset'] / search_info['perpage']) + 1;
            if (search_info['offset'] != 0) {
                search_content.append('<a class="pagination" href="' +search_url +search_info['query']+'/' +(search_info['offset']-search_info['perpage'])+'/' +search_info['perpage']+'">Previous</a>');
            } else {
                search_content.append('<span class="disabled">Previous</span>');
            }
            search_content.append('('+current+' of '+pages+')');
            var next_offset = parseInt(search_info['offset']) + parseInt(search_info['perpage']);
            if (next_offset <= search_info['hits']) {
                search_content.append('<a class="pagination" href="' +search_url +search_info['query']+'/' +next_offset+'/' +search_info['perpage']+'">Next</a> ');
            } else {
                search_content.append('<span class="disabled">Next</span>');
            }
            $('.pagination').click(function() {
                Search.pagination($(this).attr('href'));
                return false;
            });
            $('.pagination').css('padding', '0 4px');
            search_content.children('.disabled').css('color', '#333').css('padding', '0 4px');
        }
        $('.search_result').click( function() {
            parts = this.id.split('_');
            type = parts[0];
            id = parts[1];
            Search.clickedResult(type, id);
        });
        if (search_info.direct_hit) {
            Search.clickedResult(search_info.direct_hit.type, search_info.direct_hit.id);
        }
    };

    this.pagination = function (url) {
        search_content.html('');		
        Sidebar.show();
        Accordion.expandFold($('#selectables'), $('#search_fold'));
        search_loading.show();

        GDownloadUrl(url, showResults);
    };

    this.clickedResult = function (type, id) {
        if (typeof(type) != undefined && typeof(id) != undefined) {
            list = new Object();
            list[type+'s'] = [id];
            OMap.addMapElements( list ); 
        }
    };
}();
	
Search.search_form.submit(Search.search);

});

$('document').ready( function() {

SelectedItems = new function() {
    var items = [];
    var rows = [];
    var content = $('#selected_items .content');
    var icons = OMapConfig.icons;

    this.add = function(map_element) {
        if (!items[map_element.toString()]) {
            content.show();
            items[map_element.toString()] = map_element;

            var selected_item_li = $('<li></li>');
            var selected_item_name = $('<span></span>');
            var selected_item_remove = $('<img />');

            selected_item_li.addClass('selected-item');
            selected_item_li.addClass(map_element.type);
            selected_item_name.addClass('selected-item-name');
            selected_item_name.html(map_element.getName());
            selected_item_remove.addClass('selected-item-remove');
            selected_item_remove.attr('src', icons['remove']+'.png');
            selected_item_remove.attr('title', 'Remove from map.');
            selected_item_li.append(selected_item_remove);
            selected_item_li.append(selected_item_name);

            var content_ul = content.find('ul');
            if (content_ul.length == 0) {
              content_ul = $('<ul></ul>');
              content.append(content_ul);
            }
            content_ul.append(selected_item_li);
            
            rows[map_element.toString()] = selected_item_li;

            selected_item_name.click(function() { map_element.clicked(); });
            selected_item_remove.click(function() { SelectedItems.remove(map_element); });

            if (IE6) {
                if (Sidebar.sidebar.css('display') == 'block') {
                  selected_item_li.find('img').ifixpng();
                }
                selected_item_remove.hover(
                    function() {
                        $(this).css('cursor', 'pointer');
                    },
                    function() {
                        $(this).css('cursor', '');
                    }
                );
                selected_item_name.hover(
                    function() {
                        $(this).css({'cursor':'pointer', 'text-decoration':'underline'});
                    },
                    function() {
                        $(this).css({'cursor':'', 'text-decoration':''});
                    }
                );
            }
        }
        else {
          //The item is already in the list
        }
    };

    this.remove = function(map_element) {
        if (items[map_element.toString()]) {
            rows[map_element.toString()].remove();
            items[map_element.toString()].removeFromMap();
            delete items[map_element.toString()];
            delete rows[map_element.toString()];
        }
    }

    this.elementSelected = function(map_element) {
        for (var i in items) {
            if (items[i].type == 'route') {
                for (var j in items[i].locations) {
                    if (items[i].locations[j].toString() == map_element.toString() && items[i].locations[j].enabled) {
                        return true;
                    }
                }
            }
            if (items[i].type == 'layer') {
                for (var j in items[i].locations) {
                    if (items[i].locations[j].toString() == map_element.toString() && items[i].locations[j].enabled) {
                        return true;
                    }
                }
                for (var j in items[i].routes) {
                    if (items[i].routes[j].toString() == map_element.toString() && items[i].routes[j].enabled) {
                        return true;
                    }
                }
            }

        }
        return false;
    }
}();

});

$('document').ready( function() {

Buildings = new function() {
    this.search_results = $('#buildings_results');
    var buildings_content = this.search_results.find('#buildings_content');

    this.showBuildings = function() {
        var ul = buildings_content.children('ul').get(0);
        var li, div, img;

        if (IE6) {
            $('#buildings_content ul li').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        }

        $('.buildings_result').click( function() {
            parts = this.id.split('_');
            type = 'location';
            id = parts[1];
            Search.clickedResult(type, id);
        });
    };

}();

Buildings.showBuildings();

});

$('document').ready( function() {

Transportation = new function() {
    this.search_results = $('#transportation_results');
    var transportation_content = this.search_results.find('#transportation_content');

    this.showTransportation = function() {
        var ul = transportation_content.children('ul').get(0);
        var li, div, img;

        if (IE6) {
            $('#transportation_content ul li').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        }

        $('.transportation_result').click( function() {
            parts = this.id.split('_');
            type = parts[0];
            id = parts[1];
            Search.clickedResult(type, id);
        });
    };

}();

Transportation.showTransportation();

});

$(document).ready( function() {
  $('#font_size_selector').children().bind('click', function() { 
      var current_size = parseInt($('body').css('font-size'));
      var new_size;
      if($(this).attr('id') != 'reset') {
        if($(this).attr('id') == 'decrease') {
          new_size = current_size-1; 
        } else {
          new_size = current_size+1; 
        }
        $('body').css('font-size', new_size.toString() + "px"); 
      } else {
        $('body').css('font-size', ''); 
      }
      Accordion.updateSize();
    });

  new Window('#legend_window');
  var legend_window = $('#legend_window');
  legend_window.css({ right: '3px' });
  legend_window.hide();
  $('#legend_link').bind(
    'click',
    function() {
      $('#legend_window').toggle();
      if (IE6) {
        $('#legend_window img').ifixpng();
        $('#legend_window > div > div.window_close').ifixpng();
      }
      return false;
    }
  );

  $('#print_link').bind('click', function() {
      OMap.openPrintWindow();
      return false;
  });

  new Window('#bookmark_window');
  var bookmark_window = $('#bookmark_window');
  bookmark_window.css({ left: '25%' });
  bookmark_window.hide();
  $('#bookmark_link').bind(
    'click',
    function() {
      var bookmark_link_text= $('#bookmark_link_text');
      bookmark_link_text.val(OMapConfig.siteurl+OMap.getBookmarkParams());
      $('#bookmark_window').toggle();
      bookmark_link_text.focus();
      bookmark_link_text.select();
      bookmark_link_text.click(function(){this.select()});
      if (IE6) {
        $('#bookmark_window > div > div.window_close').ifixpng();
        $('#bookmark_window img').ifixpng();
      }
      return false;
    }
  );
});

var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

$('document').ready( function() {
  
    if (typeof(embedded) == 'undefined')
      OMap.init(document.getElementById('content'), OMapConfig.center, OMapConfig.defaultZoom, OMapConfig.defaultMapType);
    else
      OMap.init(document.getElementById('content'), OMapConfig.center, OMapConfig.defaultZoom, OMapConfig.defaultMapType, true, false);

    OMap.registerElementClickHandler();
    OMap.registerMoveStartHandler();
    OMap.registerAddOverlayHandler();
    OMap.registerRemoveOverlayHandler();
    OMap.registerAddMapTypeHandler();
    OMap.registerMapTypeChangedHandler();

    if (IE6) {
        /** PNG FIX **/
        $.ifixpng('img/pixel.gif');
        $('#sidebar_edge > div > img').ifixpng();
        $('#utility_links > ul > li > a > img').ifixpng();
        $('#search_submit').ifixpng();

        if (typeof(embedded) == 'undefined' || embedded == false) {
            /** CONTENT AREA FIXES **/
            /* IE doesn't resize the map area correctly,
             *  so we need to force an update and redraw of the area
             */
            var windowHeight;
            var windowWidth;
            function fixMapSize() {
                if(windowHeight != document.documentElement.clientHeight ||
                    windowWidth != document.documentElement.clientWidth) {
                    if( Sidebar.sidebar.css('display') == 'block' ) {
                        Sidebar.show();
                    } else {
                        Sidebar.hide();
                    }
                }
                windowHeight = document.documentElement.clientHeight;
                windowWidth = document.documentElement.clientWidth;
            }
            $(window).bind( 'resize', fixMapSize );
        }
    } 
    //Keep here or ie won't display the collapse images correctly
   	Sidebar.hide_sidebar.hide(); 

    $('document').bind( 'unload', function() { GUnload(); } );

    LoadParams = new function() {
        this.loadLocations = function (ids, click) {
            return this.loadType('locations', ids, click)();
        };
        this.loadRoutes = function (ids, click) {
            return this.loadType('routes', ids, click)();
        };
        this.loadLayers= function (ids) {
            return this.loadType('layers', ids, true)();
        };
        this.loadType = function(type, ids, click) {
            return function() {
                var data = new Object();
                data[type] = ids;
                OMap.addMapElements(data, click);
            };
        };

        this.drawMarker = function (lat, lng, title) {
            OMap.marker.hide();

            star_marker = new GMarker(new GLatLng(lat, lng), G_DEFAULT_ICON);
            OMap.getMap().addOverlay(star_marker);
            if (typeof(title) != 'undefined' && title != '') {
                OMap.getMap().closeInfoWindow();
                star_marker.openInfoWindowHtml(title);
                GEvent.addListener(star_marker, 'click', function () {
                        star_marker.openInfoWindowHtml(title);
                });

            }
        };
    };

    // the default value in the search field is "Search..."
    $('#search_query').focus(function() {
        if ($(this)[0].value == 'Search...') {
            $(this)[0].value = '';
        }
    });
    
    if (document.width && document.height) {
        var footer_link_dimensions = function() {
            var footer_link_ids = ['disclaimer_link', 'about_link', 'help_link', 'visitors_link', 'map-list-link', 'comments-link'];
            var tb_width = Math.round(0.8 * document.width);
            var tb_height = Math.round(0.8 * document.height);
            for (var i in footer_link_ids) {
                var link = $('#'+footer_link_ids[i]);
                var href = link.attr('href');
                if (href.indexOf('width=') > 0) {
                    href = href.replace(/&{0,1}width=\d+/, '');
                }
                if (href.indexOf('height=') > 0) {
                    href = href.replace(/&height=\d+/, '');
                }
                link.attr('href',  href + ((href.indexOf('?') >= 0) ? '&' : '?') + 'width=' + tb_width + '&height=' + tb_height);
            }
        };
        footer_link_dimensions();
        GEvent.addDomListener(window, 'resize', footer_link_dimensions);
    }
});
