/* PicLens code appeared to be loading slowly from their site, so pulled it in here. Probably should check occasionally to see if it has been updated at http://lite.piclens.com/current/piclens_optimized.js
 * PicLens Lite: version 1.3.1 (14221)
 * Copyright (c) 2008 Cooliris, Inc.  All Rights Reserved.
 * 
 * The JavaScript part of PicLens Lite (i.e., this file) is BSD licensed (see: http://lite.piclens.com/bsdlicense)
 * This launcher includes and interacts with SWFObject (MIT), BrowserDetect (BSD Compatible), and Lytebox (CC Attribution 3.0).
 * 
 * There are two versions of this JS: 
 * http://lite.piclens.com/current/piclens.js				full commented file 		(~39KB)
 * http://lite.piclens.com/current/piclens_optimized.js		lighter deployment file		(~21KB)
 */
var PicLensLite = {
	// PUBLIC API

	// PicLens Lite can be deployed in one of two ways:
	// 1) include http://lite.piclens.com/current/piclens.js in the <head> of your webpage
	// 2) download the zip file and deploy it on your own website (unzip it anywhere, and point to the JS file in the <head> of your page)
	//    see: http://lite.piclens.com/releases/current.zip
	// 
	// For example: the directory layout looks like:
	//	 lite.piclens.com/current/ contains the SWF, JS, and image files
	//					 /lytebox/ contains slideshow support for browsers w/o Flash
	// 
	// Pointing to the JS directly will configure Lite relative to that URL.
	// Alternatively, you can customize the URLs with PicLensLite.setLiteURLs
	
	// 1) Call PicLensLite.start() to launch the default feed (specified in the head)
	// 2) Call PicLensLite.start({feedUrl:'http://myWebsite.com/myFeed.rss', ...}) to launch a specific feed
	//	Option 2 supports the following named arguments:
	//		feedUrl  : String  // is the URL to the specific Media RSS feed you want to launch
	//		feedData : String  // is the Media RSS feed itself (do not use feedUrl if you want to programmatically generate & pass in the feed text)
	//		guid	 : String  // starts from the item in the feed that is tagged w/ this unique id
	//		maxScale : Number  // normally, images fill the stage; 0 -> never scale up; any other positive number S --> scale up to S times the original size of the photo (but never bigger than the stage)
	//		loadFeedInFlash : Boolean // if true, we ask Flash to load the feed, instead of AJAX (expert option)
	//		loop	 : Boolean // if true, we turn looping on by default
	//		paused	 : Boolean // if true, we start the slideshow in paused mode
	// To enable smoothing for images. a crossdomain.xml file is required at the root of your image server.
	// Lite detects this crossdomain.xml and applies smoothing automatically.
	start : function (namedArgs) {
		this.determineBrowserParams();
		clearTimeout(this.REMOVE_TIMER_ID);
		clearTimeout(this.AUTO_CLOSE_TIMER_ID);
		this.ARGS = {}; // clear out previous args

		// handle named arguments
		if (typeof namedArgs !== "undefined" && namedArgs !== null) {
			this.ARGS = namedArgs;

			// if feedUrl is specified, it launches immediately
			if (namedArgs.feedUrl) {
				this.THE_FEED_URL = namedArgs.feedUrl;
				if (this.checkForPluginAndLaunchIfPossible(namedArgs.feedUrl, namedArgs.guid)) {
					return;
				}
				if (namedArgs.loadFeedInFlash) {
					// read up on flash crossdomain.xml if you choose this option
					// Flash can only load feeds from servers hosting a crossdomain.xml
					// pass the URL as a FlashVar, and load the contents via a GET request
					this.showFlashUI("");
				} else {
					// load the contents of the URL via AJAX, and launch the Flash UI afterward....
					this.loadViaXHR(namedArgs.feedUrl);
				}
			}
			// pass in the feed XML directly through Javascript
			// use feedUrl OR feedData, but not both!
			if (typeof namedArgs.feedData !== 'undefined') {
				this.showFlashUI(namedArgs.feedData);
			}
			
		} else {
			// find the feed from the header, since none was specified
			// build list of XML feeds
			var feeds = this.indexFeeds();
			if (feeds.length !== 0) { // view the first feed, if available
				var feed = feeds[0];
				this.THE_FEED_URL = feed.url;
				if (this.checkForPluginAndLaunchIfPossible(feed.url)) {
					return;
				}
				this.loadViaXHR(feed.url);
			}
		}
	},
	// check if the slideshow is currently running
	isRunning : function () {
		return this.LITE_IS_RUNNING;
	},
	// check if the browser plug-in is installed
	hasClient : function () {
		return this.hasCooliris();
	},
	// call this before starting lite. we currently support a single custom button
	// the icon is a 24x24 PNG
	// we will perform a GET request of a provided URL (w/ the item's GUID) when the user clicks
	// http://yourwebserver.com/buttonURL?itemGUID=guidVal
	addCustomButton : function (buttonRESTUrl, buttonLabel, buttonIcon) {
		this.CUSTOM_BUTTON = {targetURL: buttonRESTUrl, labelText: buttonLabel, iconImage: buttonIcon};
	},
	// OPTIONAL: provide callbacks to be notified in certain situations. Call this BEFORE PicLensLite.start(...)
	// 	onNoPlugins():Boolean
	//		is called when the user invokes Lite but does not have PicLens / Flash installed
	// 	onExit(itemUID):void
	//		is called when the user exits from Lite
	//		we provide the item's GUID if it exists, and the item's content URL otherwise
	//		itemUID is undefined if the user exited before Lite launched, or if the user did not have Flash
	setCallbacks : function (args) {
		if (args.onNoPlugins) {
			this.ON_NO_PLUGINS = args.onNoPlugins;
		}
		if (args.onExit) {
			this.ON_EXIT = args.onExit;
		}
	},
	// OPTIONAL: customize the location of resources. Call this BEFORE PicLensLite.start(...)
	// Normally, we locate the PicLensLite files relative to the JS file 
	// To use this function, pass in an object with the following named arguments:
	// args = {
	//		lite	: other paths can be determined from this (make sure it ends in a slash)
	//		swf		: the URL of the SWF file					1
	//		button	: image allowing users to download piclens	1
	//		lbox	: where to find lytebox						1
	//		lboxcss	: the CSS file								2
	//		lboxjs	: the JS file								2
	// }
	// 1: Can be determined from args.lite
	// 2: Can be determined from args.lbox or args.lite
	setLiteURLs : function (args) {
		if (!this.LITE_URL) {
			if (args.swf) {
				this.LITE_URL = args.swf;
			} else if (args.lite) {
				this.LITE_URL = args.lite + "PicLensLite.swf";
			} // if both lite & swf aren't set, it won't work
		}
		if (!this.BUTTON_URL) {
			if (args.button) {
				this.BUTTON_URL = args.button;
			} else if (args.lite) {
				this.BUTTON_URL = args.lite + "NoFlash.jpg";
			}
		}

		var lboxUrl = "";
		if (args.lbox) {
			lboxUrl = args.lbox;
		} else if (args.lite) {
			lboxUrl = args.lite + "../lytebox/";
		}
		
		if (!this.LBOX_CSS_URL) {
			if (args.lboxcss) {
				this.LBOX_CSS_URL = args.lboxcss;
			} else if (lboxUrl != "") {
				this.LBOX_CSS_URL = lboxUrl + "lytebox.css";
			}
		}

		if (!this.LBOX_JS_URL) {
			if (args.lboxjs) {
				this.LBOX_JS_URL = args.lboxjs;
			} else if (lboxUrl != "") {
				this.LBOX_JS_URL = lboxUrl + "lytebox.js";
			}
		}
	},



	//////////////////////////////////////////////////////////////////////////////////////////////////////////
	// The PRIVATE API is below
	// DO NOT USE these functions/variables directly; they WILL change in future releases
	// Email us to request changes to the public API
	ARGS			: {},
	DEBUG_NOCLIENT	: false,	// if true, we will NEVER launch the PicLens Client (for testing Lite)
	DEBUG_NOFLASH	: false,	// if true, we will assume the user does not have Flash (for testing Lite)
	HPAD			: 60,		// horizontal padding
	VPAD			: 20,		// vertical padding
	LITE_BG_DIV		: null,		// the grey/black background overlay
	LITE_FG_DIV		: null,		// the foreground div that contains the flash component
	LITE_URL		: null,		// the location of PicLensLite.SWF
	BUTTON_URL		: null,		// image to display if the user doesn't have flash
	LBOX_CSS_URL	: null,		// where to find lytebox css/js files
	LBOX_JS_URL		: null,
	LBOX_COUNT		: 0,		// try to start lytebox, but if it doesn't exist after a few tries, give up...
	SHOW_LBOX		: false,	// if true, skip flash altogether
	OS_WIN			: false,	// OS Detect
	OS_MAC			: false,	// sadly, sometimes we have to do something different depending on our Browser/OS/Configuration
	BROWSER_FFX		: false,	// Browser Detect
	BROWSER_SAF		: false,
	BROWSER_IE		: false,
	BROWSER_IE6		: false,
	OLD_B_MARGIN	: null,
	OLD_B_OVERFLOW	: null,
	OLD_B_HEIGHT	: null,
	OLD_H_OVERFLOW	: null,
	OLD_H_HEIGHT	: null,
	THE_FEED		: "",			// the feed text
	THE_FEED_URL	: "",			// the feed url
	LITE_IS_RUNNING		: false,	// use isRunning()
	piclensIsRunning_	: false,	// maintain compatibility with the Wordpress Plugin for a few iterations...
	FLASH_ID_1		: "pllflash1",	// outer
	FLASH_ID_2		: "pllflash2",	// inner
	FLASH_VER		: null,			// the version of Flash we're running 
	FLASH_URL		: "http://www.adobe.com/go/getflashplayer",
	PL_URL			: "http://download.piclens.com/partner/",   // downloads PL immediately
	PLC				: null,			// PicLens Client
	LEARN_PL_URL	: "http://affiliate.piclens.com/partner/",  // landing page to read about / download PL
	FONT			: "font-family: Lucida Grande, Myriad Pro, Verdana, Helvetica, Arial, sans-serif;",
	KEY_HANDLERS	: "",	// save the old key handlers, if any
	ON_NO_PLUGINS	: null, // callback
	ON_EXIT			: null, // callback
	AUTO_CLOSE_TIMER_ID		: 0,	// 
	REMOVE_TIMER_ID			: 0,	// the timer for removing the children...
	RESIZE_TIMER_IE6		: null,	// every second, autoresizes the UI
	RESIZE_HANDLER_EXISTS	: false,// add a handler to detect user resize events in safari
	CUSTOM_BUTTON			: null,	// add an action to the UI

	addKeyHandlers : function() {
		var self = this;
		if (typeof document.onkeydown !== 'undefined') { // save & later restore key handlers...
			this.KEY_HANDLERS = document.onkeydown;
		}
		document.onkeydown = function(e) {
			var keycode;
			if (typeof e === "undefined" || e === null) { // ie
				keycode = window.event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			var val=self.handleKeyPress(keycode);
			if (typeof e != "undefined" && e != null) {
				e.returnValue = val;
			}
			return val;
		};
	},
	addMouseHandlers : function() {
		if (window.addEventListener) {		// Firefox/Opera
			window.addEventListener("DOMMouseScroll", this.handleMouseWheel, false);
		} else if (document.attachEvent) {	// IE
			document.attachEvent("onmousewheel", this.handleMouseWheel);
		}
		// must be outside of the if-else
        window.onmousewheel = document.onmousewheel = this.handleMouseWheel; // Safari & Others
	},
	// call this at the last possible moment (especially for Win/Firefox)
	appendElementsToDocument : function() { 
		if (this.BROWSER_FFX && this.OS_MAC) {	// avoid redraw bug by not showing the background
			this.LITE_BG_DIV.style.display = "none";
		}
		document.body.appendChild(this.LITE_BG_DIV);
		document.body.appendChild(this.LITE_FG_DIV);
	},
	autoResize : function() { // for the IE6 auto resize
		if (!this.isRunning()) {
			// unregister the timer
			clearInterval(this.RESIZE_TIMER_IE6);
			return;
		}
		
		// resize the BG and FG divs
		var size = this.getPageSize();
		var bg = this.LITE_BG_DIV;
		if (bg) {
			bg.style.height = size.h + 'px';
			bg.style.width  = size.w + 'px';
		}
		if (this.LITE_FG_DIV) {
			var fgs = this.LITE_FG_DIV.style;
			this.resizeToPaddedBox(fgs);
			this.resizeToFitPaddedBox(fgs, size);
			this.resizeFlashToFitPaddedBox();
		}
	},
	checkForPluginAndLaunchIfPossible : function (url, guid) {
		// if we have the correct version of piclens, pass it onto the client and do not use LITE
		if (this.hasCooliris()) {
			if (typeof(guid) != "undefined") {
				this.PLC.launch(url,'uid',guid);
			} else {
				this.PLC.launch(url,'','');
			}

			return true; // launched!
		}
		return false;
	},
	createBackgroundOverlay : function () {
		// create a background that covers the page
		var bg = document.createElement('div');
		this.LITE_BG_DIV = bg;
		bg.id = "lite_bg_div";
		
		var bgs = bg.style;
		bgs.position = 'fixed';

		// stick to the sides when the window resizes
		bgs.width = bgs.height = "100%";

		if (this.BROWSER_IE6) {
			var b = document.body;
			var bs = b.currentStyle;
			var de = document.documentElement;
			var ds = de.currentStyle;
			
			// save previous document styles
			this.OLD_B_MARGIN = bs.margin;
			this.OLD_B_OVERFLOW = bs.overflow;
			this.OLD_B_HEIGHT = bs.height;
			this.OLD_H_OVERFLOW = ds.overflow;
			this.OLD_H_HEIGHT = ds.height;
			this.OLD_SCROLL_Y = de.scrollTop;
			
			// simulate position:fixed...
			b.style.margin = "0";
			b.style.overflow = "auto";
			b.style.height = "100%";
			de.style.overflow = "auto";
			de.style.height = "100%";

			bgs.position = 'absolute';
			var page = this.getPageSize();
			bgs.height = page.h + 'px';
			bgs.width  = page.w + 'px';
		}
		
		bgs.left = bgs.right = bgs.top = bgs.bottom = '0';
		bgs.backgroundColor = '#000';
		bgs.zIndex = 1000;
		bgs.opacity = '0.5';
		bgs.filter = 'alpha(opacity=50)';		// IE7

		var self = this;
		bg.onclick = function () {
			self.exitPicLensLite();
		};
	},
	createForegroundFlashComponent : function () { // configure the box
		var fg = document.createElement('div');
		this.LITE_FG_DIV = fg;
		fg.id = "lite_fg_div";

		var fgs = fg.style;
		fgs.backgroundColor = '#000';
		fgs.position = 'fixed';
		fgs.border = '2px solid #555';
		fgs.zIndex = 1001;	   // above the bg

		this.resizeToPaddedBox(fgs);

		if (this.BROWSER_IE6) {
			fgs.position = 'absolute';
			this.resizeToFitPaddedBox(fgs);
		}
	},
	// this just removes the HTML elements
	// we call this from Flash (thus, we need to allow the function to return before removing the children)
	closeFlashUI : function (itemID) {
		var doc = document;
		
		// remove the keyboard & mouse handlers...
		doc.onkeydown = this.KEY_HANDLERS;
		window.onmousewheel = doc.onmousewheel = "";
		if (window.removeEventListener) {
			window.removeEventListener("DOMMouseScroll", this.handleMouseWheel, false);
		}
		if (doc.detachEvent) { // IE/Opera
			doc.detachEvent("onmousewheel", this.handleMouseWheel);
		}

		// hide the div now; remove them later
		this.LITE_BG_DIV.style.display = this.LITE_FG_DIV.style.display = 'none';
		this.REMOVE_TIMER_ID = setTimeout(function (){PicLensLite.removeChildren();}, 150); // 0.15s

		if (this.BROWSER_IE6) { // restore styles
			var b = document.body;
			var de = document.documentElement;
			b.style.margin = this.OLD_B_MARGIN;
			b.style.overflow = this.OLD_B_OVERFLOW;
			b.style.height = this.OLD_B_HEIGHT;
			de.style.overflow = this.OLD_H_OVERFLOW;
			de.style.height = this.OLD_H_HEIGHT;
			window.scrollTo(0, this.OLD_SCROLL_Y);
		}

		if (this.ON_EXIT !== null) {
			this.ON_EXIT(itemID); // call on exit
		}
		this.setRunningFlag(false);
	},
	// for handling cross-browser quirks...
	determineBrowserParams : function () {
		// BrowserDetect {.OS, .browser, .version} e.g., "Mac Firefox 2" and "Windows Explorer 7"
		var os = BrowserDetect.OS;
		var b = BrowserDetect.browser;
		this.OS_MAC = (os == "Mac");
		this.OS_WIN = (os == "Windows");
		this.BROWSER_FFX = (b == "Firefox");
		this.BROWSER_SAF = (b == "Safari");
		this.BROWSER_IE = (b == "Explorer");
		this.BROWSER_IE6 = (this.BROWSER_IE && BrowserDetect.version == "6");
		this.FLASH_VER = swfobjlite.getFlashPlayerVersion(); // what version of Flash is the browser running?
	},
	// we should tell Flash we are exiting when this is called...
	// this should only be called when the user clicks outside of the flash component
	// all other exits are handled through Flash
	exitPicLensLite : function () {
		var fl = this.getFlash();
		if (fl !== null && fl.fl_exitPicLensLite) {	// binding exists
			// tell flash that we are quitting
			fl.fl_exitPicLensLite();
			// close after .5 seconds, if nothing happened
			// TODO: make sure this doesn't crash any browsers
			// TODO: Check the Return Value to Fire this Timer?
			this.AUTO_CLOSE_TIMER_ID = setTimeout(function (){ if (PicLensLite.isRunning()) { PicLensLite.closeFlashUI();}}, 500); // 0.5s
		} else {
			// if it's not running already, we just remove the DIVs (flash isn't defined)
			this.closeFlashUI();
		}
	},
	// a website should include the absolute URL of the piclens.js in its header
	// This function looks for the script tag and extracts the ROOT_URL
	// <script type="text/javascript" src="ROOT_URL/piclens.js"></script>
	// we assume the SWF and JPEG/PNG/GIF files are relative to this ROOT_URL...
	findScriptLocation : function () {
		var scriptTags = document.getElementsByTagName("script");
		for (var i = 0; i != scriptTags.length; ++i) {
			var script = scriptTags[i];
			var type = script.getAttribute("type");
			if (type == "text/javascript") {
				var src = script.getAttribute("src");
				if (src === null) {
					continue;
				}
				var index = src.indexOf("piclens.js"); 
				if (index != -1) {
					this.setLiteURLs({lite:src.substring(0,index)});
					return;
				} else {
					index = src.indexOf("piclens_optimized.js");
					if (index != -1) {
						this.setLiteURLs({lite:src.substring(0,index)});
						return;
					}
				}
			}
		}
	},
	// returns an object describing the page size of the browser window
	getPageSize : function () {
		var xScroll, yScroll, winW, winH;
		var doc = document;
		var body = doc.body;
		var html;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = doc.scrollWidth;
			yScroll = (this.isFrame ? parent.innerHeight : self.innerHeight) + (this.isFrame ? parent.scrollMaxY : self.scrollMaxY);
		} else if (body.scrollHeight > body.offsetHeight){
			xScroll = body.scrollWidth;
			yScroll = body.scrollHeight;
		} else {
			html = doc.getElementsByTagName("html").item(0);
			xScroll = html.offsetWidth;
			yScroll = html.offsetHeight;
			xScroll = (xScroll < body.offsetWidth) ? body.offsetWidth : xScroll;
			yScroll = (yScroll < body.offsetHeight) ? body.offsetHeight : yScroll;
		}
		var docElement = doc.documentElement;
		if (self.innerHeight) {
			winW = (this.isFrame) ? parent.innerWidth : self.innerWidth;
			winH = (this.isFrame) ? parent.innerHeight : self.innerHeight;
		} else if (docElement && docElement.clientHeight) {
			winW = docElement.clientWidth;
			winH = docElement.clientHeight;
		} else if (body) {
			html = doc.getElementsByTagName("html").item(0);
			winW = html.clientWidth;
			winH = html.clientHeight;
			winW = (winW == 0) ? body.clientWidth : winW;
			winH = (winH == 0) ? body.clientHeight : winH;
		}
		var pageHeight = (yScroll < winH) ? winH : yScroll;
		var pageWidth = (xScroll < winW) ? winW : xScroll;
		return {pw:pageWidth, ph:pageHeight, w:winW, h:winH}; // pw and ph are the larger pair. use w and h.
	},
	getElementsFromXMLFeed : function () {
		var xmlDoc;
		if (window.ActiveXObject) { // IE
		  	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  	xmlDoc.async=false;
		  	xmlDoc.loadXML(PicLensLite.THE_FEED);
		} else { // Mozilla, Firefox, Opera, etc.
			var parser = new DOMParser();
			xmlDoc = parser.parseFromString(PicLensLite.THE_FEED, "text/xml");
		}
		var elements = xmlDoc.getElementsByTagName('*');
		return elements;
	},
	getBasicSlideShowHTML : function () {
		if (!this.LBOX_JS_URL || !this.LBOX_CSS_URL) {
			return "";
		}
		
		// make sure the lytebox JS is included
		var head = document.getElementsByTagName('head').item(0);

		// add the script tag
		var script  = document.createElement('script');
		script.src  = this.LBOX_JS_URL;
		script.type = 'text/javascript';
		head.appendChild(script);
		
		// add the lytebox CSS too
		var link = document.createElement('link');
		link.rel = "stylesheet";
		link.href = this.LBOX_CSS_URL;
		link.type = "text/css";
		link.media = "screen";
		head.appendChild(link);

		// find all image URLs from the feed.
		var xmlElements = this.getElementsFromXMLFeed();

		var i;
		var hiddenURLs = "";
		for (i = 0; i < xmlElements.length; i++) {
			if (xmlElements[i].nodeName == "media:content") {	// what about the namespace?
				var url = xmlElements[i].getAttribute("url");
				if (url.indexOf(".flv") == -1) {				// images only... avoid FLV files
					hiddenURLs += '<a id="lboxImage" href="' + url + '" rel="lytebox[lite]"></a> ';
				}
			}
		}
		// rel="lytebox[lite]"
		var basicSlideShow = "<div id='lightbox_images' align='center' style='display: none; padding-top:10px; color:#FFFFFF; font-size:.8em; " +this.FONT+ " color:#999999;'>";
		basicSlideShow +=  '( Alternatively, <a onclick="javascript:PicLensLite.invokeLytebox();return false;" href="#" style="color:#656588">click here for a basic slideshow</a>. )';
		basicSlideShow += hiddenURLs;
		basicSlideShow += "</div><br/>";

		return basicSlideShow;
	},
	generateAlternativeContent : function () {
		var altContentHTML = '<div id="altContent" style="text-align:center; margin: 0 0 0 0; padding: 0 0 0 0; background-color: #000; min-width:860px;">';
		altContentHTML += '<div align="center" style="width: 100%; padding-top:60px; '+this.FONT+'">';

		var v = this.FLASH_VER;
		var flashMessage;
		if (v.major > 0) { // has some version of Flash
			flashMessage = "update your Flash Player from version "+ v.major + '.' + v.minor + '.' + v.release + " to version 9.0.28 or newer";
		} else {
			flashMessage = "install the most recent Flash Player";
		}
		
		var basicSlideShow = "";
		if (this.THE_FEED !== "") {   // do this if we've loaded the feed in AJAX
			basicSlideShow = this.getBasicSlideShowHTML();
		}
		
		var downloadPL = this.PL_URL;
		var learnPL = this.LEARN_PL_URL;
		var pid = this.ARGS.pid;
		if (pid) {
			downloadPL += pid + "/";
			learnPL += pid + "/";
		} else {
			var x = "000000000001/";
			downloadPL += x;
			learnPL += x;
		}
		
		if (this.SHOW_LBOX) {
			// don't show the image, because we will invoke lytebox immediately
		} else {
			var sp = "<span style='padding-left:25px; color:#C6C6C6; font-size:";
			altContentHTML += 
				"<div style='padding:10px;'>" + 
					sp+"1.5em; font-weight: bold; " +this.FONT+ "'>You're clicks away from going full screen!</span><br/>" + 
					sp+".9em; padding-bottom: 15px; " +this.FONT+ "'>You must get the <a href='"+downloadPL+"' style='color:#656588'>Cooliris</a> browser plugin, or "+flashMessage+".</span>" +
				"</div>";
			if (!this.BUTTON_URL) {
				altContentHTML +=
				'<a href="' + downloadPL + '" style="color:#ACD">Get Cooliris Now!</a>';
			} else {
				var area = '<area shape="rect" coords=';
				altContentHTML +=
				'<img src="'+this.BUTTON_URL+'" alt="" border="0" usemap="#Map">' + 
				'<map name="Map" id="Map">' + 
					area+'"0,0,33,33" href="#" onclick="javascript:PicLensLite.closeFlashUI();" />' +
					area+'"35,35,325,325" href="' + downloadPL +'" />' +
					area+'"593,209,825,301" href="' + this.FLASH_URL +'" />' +
					area+'"327,148,448,178" href="' + learnPL +'" />' +
				'</map>';
			}
		}

		altContentHTML += '</div>';
		altContentHTML += basicSlideShow;
		altContentHTML += '<div align="center" style="color:#666666; font-size:11px; '+this.FONT+'">&copy; 2008 Cooliris, Inc. All trademarks are property of their respective holders.<br/><br/><br/></div>';
		altContentHTML += '</div>';
		return altContentHTML;		
	},
	generateFlashVars : function () {
		var fv = '';
		var args = this.ARGS;
		if (typeof args.guid !== 'undefined') {
			fv += "&startItemGUID=" + args.guid;
		}
		if (args.loadFeedInFlash) {
			fv += "&feedURL=" + encodeURIComponent(this.THE_FEED_URL);	// may need crossdomain.xml to allow loading of feed
		}
		if (args.paused) {
			fv += "&paused=" + args.paused;
		}
		if (args.loop) {
			fv += "&loop=" + args.loop;
		}
		if (args.delay) { // seconds: from 1-10
			fv += "&delay=" + args.delay;
		}
		if (args.pid) {
			fv += "&pid=" + args.pid;
		}
		if (typeof args.maxScale != 'undefined') {	// allow 0
			fv += "&maxScale=" + args.maxScale;
		}
		if (typeof args.overlayToolbars != 'undefined') {
			fv += "&overlayToolbars=" + args.overlayToolbars;
		}
		var cb = this.CUSTOM_BUTTON;
		if (cb != null) {
			fv += "&cButtonURL=" + encodeURIComponent(cb.targetURL);
			if (cb.labelText != null) {
				fv += "&cButtonLabel=" + encodeURIComponent(cb.labelText);
			}
			if (cb.iconImage != null) {
				fv += "&cButtonIcon=" + encodeURIComponent(cb.iconImage);
			}
		}
		fv += "&swfURL="+encodeURIComponent(this.LITE_URL);
		fv = fv.substring(1); // kill the first &
		return fv;
	},
	// does the right thing for each browser
	// returns the Flash object, so we can communicate with it over the ExternalInterface
	getFlash : function () {
		// we should determine which one to pass back depending on Browser/OS configuration
		if (this.BROWSER_SAF || this.BROWSER_IE) {
			return document.getElementById(this.FLASH_ID_1); // outer <object>
		} else {
			return document.getElementById(this.FLASH_ID_2); // inner <object>
		}
	},
	getWindowSize : function () { // inner size
		var docElement = document.documentElement;
		var docBody = document.body;
		var w = 0, h = 0;
		if (typeof(window.innerWidth) == 'number') {
			// not IE
			w = window.innerWidth;
			h = window.innerHeight;
		} else if (docElement && (docElement.clientWidth || docElement.clientHeight)) {
			// IE 6+ in 'standards compliant mode'
			w = docElement.clientWidth;
			h = docElement.clientHeight;
		} else if (docBody && (docBody.clientWidth || docBody.clientHeight)) {
			// IE 4 compatible
			w = docBody.clientWidth;
			h = docBody.clientHeight;
		}
		return {w:w, h:h};
	},
	handleKeyPress : function (code) {
		if (!this.isRunning()) { return true; }
		var fl = this.getFlash();
		if (fl != null && fl.fl_keyPressed) {
			fl.fl_keyPressed(code); // forward to Flash
		} else {
			if (code == 27) { // ESC to close
				this.closeFlashUI();
				return false;
			}
		}
		if (code == 9 || code == 13) { // trap tab, enter
			return false;
		}
		return true; // allow the browser to process the key
	},
	handleMouseWheel : function (e) {
		// e.wheelDelta
		// Safari/Windows (MouseWheel Up is +120; Down is -120)
		var delta = 0;
		if (!e) {
			e = window.event;
		}
		if (e.wheelDelta) { // IE/Opera
			delta = e.wheelDelta/120;
			if (window.opera) {
				delta = -delta;
			}
		} else if (e.detail) { // Firefox/Moz
			var d = e.detail;
			// on mac, don't divide by 3...
			if (Math.abs(d) < 3) {
				delta = -d;
			} else {
				delta = -d/3;
			}
		}
		if (delta) {
			// don't send abs values < 1; otherwise, you can only scroll next
			PicLensLite.sendMouseScrollToFlash(delta);		
		}
		if (e.preventDefault) {
			e.preventDefault();
		}
		e.returnValue = false;
		return false;
	},
	hasPicLensClient : function () { // DEPRECATED! Use hasClient()
		return this.hasCooliris();
	},
	// check if Cooliris Client is available
	hasCooliris : function () {
		// a flag to turn off the client
		if (this.DEBUG_NOCLIENT) {
			return false;
		}
		
		// check if the bridge has already been defined
		var clientExists = false;
		if (this.PLC) {
			clientExists = true;
		} else if (window.piclens && window.piclens.launch) {
			this.PLC = window.piclens;
			clientExists = true;
		} else { // if not, try to define it here...
			var context = null;
			if (typeof PicLensContext != 'undefined') { // Firefox
				context = new PicLensContext();
			} else {									
				try { 
					context = new ActiveXObject("PicLens.Context"); // IE
				} catch (e) {
					if (navigator.mimeTypes['application/x-cooliris']) { // Safari
						context = document.createElement('object');
						context.style.height="0px";
						context.style.width="0px";
						context.type = 'application/x-cooliris';
						document.documentElement.appendChild(context);
					} else {
						context = null;
					}
				}
			}
			
			this.PLC = context;
			if (this.PLC) {
				clientExists = true;
			}
		}
		
		if (clientExists) { // check the version number
			if (this.BROWSER_SAF) { // for Safari, we just return true (the first v. was 1.8)
				return true;
			}
				
			var version;
			try { version = this.PLC.version; } catch (e) { return false; }
						
			var parts = version.split('.'); // minimum ver. is: 1.6.0.824
			if (parts[0] > 1) {			    // a ver. 2.X product
				return true;
			} else if (parts[0] == 1) {	    // a 1.X product
				if (parts[1] > 6) {		    // a 1.7.X product
					return true;
				} else if (parts[1] == 6) { // a 1.6 product
					if (parts[2] > 0) {	    // a 1.6.1.X product
						return true;
					} else if (parts[2] == 0) {
						if (parts[3] >= 824) { // 1.6.0.824 or newer...
							return true;
						}
					}
				}
			}
			return false; // a 0.X product
		} else {
			return false;
		}
	},
	invokeLytebox : function () {
		this.SHOW_LBOX = true; // user has specified that she wants to use the basic slideshow
		myLytebox.start(document.getElementById("lboxImage"), false, false);
		this.closeFlashUI();
	},
	showLyteboxLink : function () {
		myLytebox.updateLyteboxItems();
		myLytebox.doAnimations = false;
		var lboxImages = document.getElementById('lightbox_images');
		if (lboxImages != null) {
			lboxImages.style.display = "block";
			if (this.SHOW_LBOX && this.getFlash()==null) { // the user has clicked on lbox once, so we assume it going forward
				this.invokeLytebox();
			}
		}
	},
	startLytebox : function () { // allows us to include lytebox, unmodified
		if (typeof myLytebox != "undefined") {
			this.showLyteboxLink();
		} else {
			if (typeof initLytebox != "undefined") {
				initLytebox();
				this.showLyteboxLink();
			} else {
				if (this.LBOX_COUNT >= 4) {
					return; // give up after 600 ms
				}
				setTimeout(function (){PicLensLite.startLytebox();}, 150); // try again in 150 ms
				this.LBOX_COUNT++;
			}
		}
	},
	injectFlashPlayer : function () {
		var fg = this.LITE_FG_DIV;
		
		// determine the width and height of the flash component
		var flashWInner;
		var flashHInner;
		flashWInner = flashHInner = '100%';
		if (this.BROWSER_IE6) {
			flashWInner = flashHInner = '0';
		}
		
		var flashVars = this.generateFlashVars();
		var altContentHTML = this.generateAlternativeContent(); // non-flash content

		if (this.meetsReqs()) {
			var par = '<param name=';
			fg.innerHTML = 
				'<object id="'+ this.FLASH_ID_1 +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%">' + // SAF & IE
					par+'"movie" value="' + this.LITE_URL + '" />' +
					par+'"quality" value="high"/> ' +
					par+'"bgcolor" value="#000000"/> ' +
					par+'"allowScriptAccess" value="always"/> ' +
					par+'"FlashVars" value="' + flashVars + '"/> ' +
					par+'"allowFullScreen" value="true"/> ' +
					par+'"wmode" value="window"/> ' +
					par+'"scale" value="noscale"/> ' +
						'<object type="application/x-shockwave-flash" data="' + this.LITE_URL + '" width="'+flashWInner+'" height="'+flashHInner+'" ' + // NOT IE
							'quality="high" ' +
							'bgcolor="#000000" id="'+ this.FLASH_ID_2 + '" ' + 
							'quality="high" ' +
							'FlashVars="' + flashVars + '" ' +
							'allowFullScreen="true" ' +
							'scale="noscale" ' + 
							'wmode="window" ' +
							'allowScriptAccess="always">' +
							altContentHTML + // IE
						'</object>'+ // NOT IE
				'</object>';
		} else {
			if (this.ON_NO_PLUGINS) {
				this.ON_NO_PLUGINS(); // callback instead of showing NoFlash.jpg
			} else {
				fg.innerHTML = altContentHTML;
				fg.style.minWidth = "860px";
				fg.style.minHeight = "550px";
			}
		}
		
		if (this.BROWSER_SAF) {
			this.resizeUI(); // fixes layout 
		}
	},
	// find the RSS feeds on this page, and return an array
	indexFeeds : function () {
		var linkTags = document.getElementsByTagName("link");
		var feeds = [];
		for (var i = 0; i != linkTags.length; ++i) {
			var link = linkTags[i], type = link.getAttribute("type");
			if (type == "application/rss+xml" || type == "text/xml") {
				feeds.push({ title: link.getAttribute("title"), url: link.getAttribute("href") });
			}
		}
		return feeds;
	},
	// once we get the response text, we launch flash
	loadViaXHR : function (url) {
		var self = this;
		var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
		try {
			request.open("GET", url, true);
			request.onreadystatechange = function () {
				if (request.readyState == 4) {
					if ((request.status == 200 || request.status == 0)) { // 0 -> File System Testing
						if (request.responseText) {
							// at this point, we have the text
							self.showFlashUI(request.responseText);
						}
					} else {
						if (console) {console.log("PicLens Lite could not load the RSS Feed: " + url);}
					}
				}
			};
			request.send("");
		} catch (err) { // probably a crossdomain issue, so ask flash to try loading
			this.ARGS.loadFeedInFlash = true;
			this.showFlashUI("");
		}
	},
	meetsReqs : function () {
		if (this.DEBUG_NOFLASH) {
			return false;
		}
		// if IE7 and Flash detect returns v0, we show the Flash
		var ie7FlashDetectionWorkaround = (this.FLASH_VER.major == 0) && this.BROWSER_IE;
		var hasFlash = swfobjlite.hasFlashPlayerVersion("9.0.28");
		return hasFlash || ie7FlashDetectionWorkaround;
	},
	removeChildren : function () {
		this.REMOVE_TIMER_ID = 0;
		// remove the divs after a timeout
		if (this.LITE_BG_DIV !== null) {
			document.body.removeChild(this.LITE_BG_DIV);
			this.LITE_BG_DIV = null;
		}
		if (this.LITE_FG_DIV !== null) {
			document.body.removeChild(this.LITE_FG_DIV);
			this.LITE_FG_DIV = null;
		}
	},
	resizeFlashToFitPaddedBox : function () {
		var flash = this.getFlash();
		if (flash) {
			var size = this.getPageSize();
			var w = size.w - this.HPAD * 2;
			var h = size.h - this.VPAD * 2;
			flash.style.width = w; flash.style.height = h;
			flash.width = w; flash.height = h;
		}
	},
	resizeToFitPaddedBox : function (s, size) {
		if (typeof size == 'undefined') {
			size = this.getPageSize();
		}
		s.width = (size.w - this.HPAD * 2) + 'px';
		s.height = (size.h - this.VPAD * 2) + 'px';
	},
	resizeToPaddedBox : function (s) {
		s.left = s.right = this.HPAD + 'px';
		s.top = s.bottom = this.VPAD + 'px';
	},
	resizeUI : function () { // resize handler for Safari
		if (this.LITE_FG_DIV) {
			var fgs = this.LITE_FG_DIV.style;
			this.resizeToPaddedBox(fgs);
			this.resizeToFitPaddedBox(fgs);
			this.resizeFlashToFitPaddedBox();
		}
	},
	setRunningFlag : function (flag) {
		this.LITE_IS_RUNNING = flag;
		this.piclensIsRunning_ = flag;
	},
	setResizeHandler : function () { // for safari
		if (!this.RESIZE_HANDLER_EXISTS && this.BROWSER_SAF) {
			var self = this;
			window.addEventListener('resize', function () { self.resizeUI(); }, false);
			this.RESIZE_HANDLER_EXISTS = true;
		}
	},
	setResizeTimer : function () { // only do it for IE6...
		if (this.BROWSER_IE6) {
			this.RESIZE_TIMER_IE6 = setInterval(function () { PicLensLite.autoResize(); }, 1000);
		}
	},
	showFlashUI : function (feedText) {
		this.THE_FEED = feedText; // is "" if we are loading the feed in Flash
		this.findScriptLocation();
		this.createBackgroundOverlay();
		this.createForegroundFlashComponent();
		if (this.BROWSER_IE) {
			this.appendElementsToDocument();
		}
		this.injectFlashPlayer();
		if (!this.BROWSER_IE) {
			// Win Firefox needs this to be last
			// Other Browsers are OK with this
			this.appendElementsToDocument(); 
		}
		this.addKeyHandlers();
		this.addMouseHandlers();
		this.setRunningFlag(true);
		this.setResizeTimer();
		this.setResizeHandler();
		this.startLytebox();
	},
	sendMouseScrollToFlash : function (delta) {
		if (!this.isRunning()) { return; }
		var fl = this.getFlash();
		if (fl != null && fl.fl_mouseMoved) {
			fl.fl_mouseMoved(delta);
		}
	}
	// don't end the last function with a comma; it messes up IE7
};




/* SWFObject v2.0 <http://code.google.com/p/swfobject/> / Copyright 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis / MIT License */
var swfobjlite = function() {
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		win = window,
		doc = document,
		nav = navigator;
	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF && typeof doc.appendChild != UNDEF
					&& typeof doc.replaceChild != UNDEF && typeof doc.removeChild != UNDEF && typeof doc.cloneNode != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d) {
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";  // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");  // Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	return { // PUBLIC API
		hasFlashPlayerVersion : function(rv) {
			var pv = ua.pv, v = rv.split(".");
			v[0] = parseInt(v[0], 10);
			v[1] = parseInt(v[1], 10);
			v[2] = parseInt(v[2], 10);
			return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
		},
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		}
	};
}();




	
/* BrowserDetect: http://www.quirksmode.org/js/detect.html */
var BrowserDetect={
	init:function() { this.browser = this.searchString(this.dataBrowser) || "Unknown Browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown Version"; this.OS = this.searchString(this.dataOS) || "Unknown OS"; },
	searchString:function(data) { for (var i=0;i<data.length;i++)	{ var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) {return data[i].identity;} } else if (dataProp) { return data[i].identity; } } },
	searchVersion:function(dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) {return;} return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); },
	dataBrowser:[
		{ string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },
		{ string: navigator.vendor, subString: "Apple", identity: "Safari" },
		{ prop: window.opera, identity: "Opera" },
		{ string: navigator.vendor, subString: "iCab", identity: "iCab" },
		{ string: navigator.vendor, subString: "KDE", identity: "Konqueror" },
		{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
		{ string: navigator.vendor, subString: "Camino", identity: "Camino" },
		{ string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, // newer Netscapes (6+)
		{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" },
		{ string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },
		{ string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } // older Netscapes (4-)
	],
	dataOS:[{ string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ]
};
BrowserDetect.init();
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;



/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();/* 
 * Auto Expanding Text Area (1.2.2)
 * by Chrys Bader (www.chrysbader.com)
 * chrysb@gmail.com
 *
 * Special thanks to:
 * Jake Chapa - jake@hybridstudio.com
 * John Resig - jeresig@gmail.com
 *
 * Copyright (c) 2008 Chrys Bader (www.chrysbader.com)
 * Licensed under the GPL (GPL-LICENSE.txt) license. 
 *
 *
 * NOTE: This script requires jQuery to work.  Download jQuery at www.jquery.com
 *
 */
 
(function(jQuery) {
		  
	var self = null;
 
	jQuery.fn.autogrow = function(o)
	{	
		return this.each(function() {
			new jQuery.autogrow(this, o);
		});
	};
	

    /**
     * The autogrow object.
     *
     * @constructor
     * @name jQuery.autogrow
     * @param Object e The textarea to create the autogrow for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/autogrow
     */
	
	jQuery.autogrow = function (e, o)
	{
		this.options		  	= o || {};
		this.dummy			  	= null;
		this.interval	 	  	= null;
		this.line_height	  	= this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
		this.min_height		  	= this.options.minHeight || parseInt(jQuery(e).css('min-height'));
		this.max_height		  	= this.options.maxHeight || parseInt(jQuery(e).css('max-height'));;
		this.textarea		  	= jQuery(e);
		
		if(this.line_height == NaN)
		  this.line_height = 0;
		
		// Only one textarea activated at a time, the one being used
		this.init();
	};
	
	jQuery.autogrow.fn = jQuery.autogrow.prototype = {
    autogrow: '1.2.2'
  };
	
 	jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
	
	jQuery.autogrow.fn.extend({
						 
		init: function() {			
			var self = this;			
			this.textarea.css({overflow: 'hidden', display: 'block'});
			this.textarea.bind('focus', function() { self.startExpand() } ).bind('blur', function() { self.stopExpand() });
			this.checkExpand();	
		},
						 
		startExpand: function() {				
		  var self = this;
			this.interval = window.setInterval(function() {self.checkExpand()}, 400);
		},
		
		stopExpand: function() {
			clearInterval(this.interval);	
		},
		
		checkExpand: function() {
			
			if (this.dummy == null)
			{
				this.dummy = jQuery('<div></div>');
				this.dummy.css({
												'font-size'  : this.textarea.css('font-size'),
												'font-family': this.textarea.css('font-family'),
												'width'      : this.textarea.css('width'),
												'padding'    : this.textarea.css('padding'),
												'line-height': this.line_height + 'px',
												'overflow-x' : 'hidden',
												'position'   : 'absolute',
												'top'        : 0,
												'left'		 : -9999
												}).appendTo('body');
			}
			
			// Strip HTML tags
			var html = this.textarea.val().replace(/(<|>)/g, '');
			
			// IE is different, as per usual
			if ($.browser.msie)
			{
				html = html.replace(/\n/g, '<BR>new');
			}
			else
			{
				html = html.replace(/\n/g, '<br>new');
			}
			
			if (this.dummy.html() != html)
			{
				this.dummy.html(html);	
				
				if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height))
				{
					this.textarea.css('overflow-y', 'auto');	
				}
				else
				{
					this.textarea.css('overflow-y', 'hidden');
					if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height()))
					{	
						this.textarea.animate({height: (this.dummy.height() + this.line_height) + 'px'}, 100);	
					}
				}
			}
		}
						 
	 });
})(jQuery);



/* Copyright (c) 2006 Brandon Aaron (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$
 * $Rev$
 *
 * Version 2.1.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE6 
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s) 
 * with a tabIndex and zIndex of -1.
 * 
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by 
 * the expressions used to calculate the elements width, height and 
 * borders. Some have reported it is due to the opacity filter. All 
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative 
 *      number representing the border-top-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative 
 *      number representing the border-left-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change 
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="javascript:false;"'+ // christian's note: just inserted the default value instead of s.src
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);



/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 * 
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 * 
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 * 
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 * 
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 1;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

	/**
	 * Adds a given method under the given name 
	 * to the Date prototype if it doesn't
	 * currently exist.
	 *
	 * @private
	 */
	function add(name, method) {
		if( !Date.prototype[name] ) {
			Date.prototype[name] = method;
		}
	};
	
	/**
	 * Checks if the year is a leap year.
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isLeapYear();
	 * @result true
	 *
	 * @name isLeapYear
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isLeapYear", function() {
		var y = this.getFullYear();
		return (y%4==0 && y%100!=0) || y%400==0;
	});
	
	/**
	 * Checks if the day is a weekend day (Sat or Sun).
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekend();
	 * @result false
	 *
	 * @name isWeekend
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekend", function() {
		return this.getDay()==0 || this.getDay()==6;
	});
	
	/**
	 * Check if the day is a day of the week (Mon-Fri)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekDay();
	 * @result false
	 * 
	 * @name isWeekDay
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekDay", function() {
		return !this.isWeekend();
	});
	
	/**
	 * Gets the number of days in the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDaysInMonth();
	 * @result 31
	 * 
	 * @name getDaysInMonth
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDaysInMonth", function() {
		return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
	});
	
	/**
	 * Gets the name of the day.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName();
	 * @result 'Saturday'
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName(true);
	 * @result 'Sat'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getDayName", function(abbreviated) {
		return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
	});

	/**
	 * Gets the name of the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName();
	 * @result 'Janurary'
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName(true);
	 * @result 'Jan'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getMonthName", function(abbreviated) {
		return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
	});

	/**
	 * Get the number of the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayOfYear();
	 * @result 11
	 * 
	 * @name getDayOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDayOfYear", function() {
		var tmpdtm = new Date("1/1/" + this.getFullYear());
		return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
	});
	
	/**
	 * Get the number of the week of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getWeekOfYear();
	 * @result 2
	 * 
	 * @name getWeekOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getWeekOfYear", function() {
		return Math.ceil(this.getDayOfYear() / 7);
	});

	/**
	 * Set the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.setDayOfYear(1);
	 * dtm.toString();
	 * @result 'Tue Jan 01 2008 00:00:00'
	 * 
	 * @name setDayOfYear
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("setDayOfYear", function(day) {
		this.setMonth(0);
		this.setDate(day);
		return this;
	});
	
	/**
	 * Add a number of years to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addYears(1);
	 * dtm.toString();
	 * @result 'Mon Jan 12 2009 00:00:00'
	 * 
	 * @name addYears
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addYears", function(num) {
		this.setFullYear(this.getFullYear() + num);
		return this;
	});
	
	/**
	 * Add a number of months to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMonths(1);
	 * dtm.toString();
	 * @result 'Tue Feb 12 2008 00:00:00'
	 * 
	 * @name addMonths
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMonths", function(num) {
		var tmpdtm = this.getDate();
		
		this.setMonth(this.getMonth() + num);
		
		if (tmpdtm > this.getDate())
			this.addDays(-this.getDate());
		
		return this;
	});
	
	/**
	 * Add a number of days to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addDays(1);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addDays
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addDays", function(num) {
		this.setDate(this.getDate() + num);
		return this;
	});
	
	/**
	 * Add a number of hours to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addHours(24);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addHours
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addHours", function(num) {
		this.setHours(this.getHours() + num);
		return this;
	});

	/**
	 * Add a number of minutes to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMinutes(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 01:00:00'
	 * 
	 * @name addMinutes
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMinutes", function(num) {
		this.setMinutes(this.getMinutes() + num);
		return this;
	});
	
	/**
	 * Add a number of seconds to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addSeconds(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name addSeconds
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addSeconds", function(num) {
		this.setSeconds(this.getSeconds() + num);
		return this;
	});
	
	/**
	 * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
	 * 
	 * @example var dtm = new Date();
	 * dtm.zeroTime();
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name zeroTime
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("zeroTime", function() {
		this.setMilliseconds(0);
		this.setSeconds(0);
		this.setMinutes(0);
		this.setHours(0);
		return this;
	});
	
	/**
	 * Returns a string representation of the date object according to Date.format.
	 * (Date.toString may be used in other places so I purposefully didn't overwrite it)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.asString();
	 * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name asString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("asString", function() {
		var r = Date.format;
		return r
			.split('yyyy').join(this.getFullYear())
			.split('yy').join((this.getFullYear() + '').substring(2))
			.split('mmm').join(this.getMonthName(true))
			.split('mm').join(_zeroPad(this.getMonth()+1))
			.split('dd').join(_zeroPad(this.getDate()));
	});
	
	/**
	 * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
	 * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
	 *
	 * @example var dtm = Date.fromString("12/01/2008");
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name fromString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	Date.fromString = function(s)
	{
		var f = Date.format;
		var d = new Date('01/01/1977');
		var iY = f.indexOf('yyyy');
		if (iY > -1) {
			d.setFullYear(Number(s.substr(iY, 4)));
		} else {
			// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
			d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
		}
		var iM = f.indexOf('mmm');
		if (iM > -1) {
			var mStr = s.substr(iM, 3);
			for (var i=0; i<Date.abbrMonthNames.length; i++) {
				if (Date.abbrMonthNames[i] == mStr) break;
			}
			d.setMonth(i);
		} else {
			d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
		}
		d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
		if (isNaN(d.getTime())) {
			return false;
		}
		return d;
	};
	
	// utility method
	var _zeroPad = function(num) {
		var s = '0'+num;
		return s.substring(s.length-2)
		//return ('0'+num).substring(-2); // doesn't work on IE :(
	};
	
})();


/**
 * Copyright (c) 2007 Kelvin Luck (http://www.kelvinluck.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $Id: java.js,v 1.121.2.323 2010/02/25 22:25:11 christian Exp $
 **/

(function($){
    
	$.fn.extend({
/**
 * Render a calendar table into any matched elements.
 * 
 * @param Object s (optional) Customize your calendars.
 * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render. Default is today's year.
 * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
 * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name renderCalendar
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#calendar-me').renderCalendar({month:0, year:2007});
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
 *
 * @example
 * var testCallback = function($td, thisDate, month, year)
 * {
 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
 *		var d = thisDate.getDate();
 *		$td.bind(
 *			'click',
 *			function()
 *			{
 *				alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
 *			}
 *		).addClass('thursday');
 *	} else if (thisDate.getDay() == 5) {
 *		$td.html('Friday the ' + $td.html() + 'th');
 *	}
 * }
 * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
 * 
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
 **/
		renderCalendar  :   function(s)
		{
			var dc = function(a)
			{
				return document.createElement(a);
			};
			
			s = $.extend(
				{
					month			: null,
					year			: null,
					renderCallback	: null,
					showHeader		: $.dpConst.SHOW_HEADER_SHORT,
					dpController	: null,
					hoverClass		: 'dp-hover'
				}
				, s
			);
			
			if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
				var headRow = $(dc('tr'));
				for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
					var weekday = i%7;
					var day = Date.dayNames[weekday];
					headRow.append(
						jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
					);
				}
			};
			
			var calendarTable = $(dc('table'))
									.attr(
										{
											'cellspacing':2,
											'className':'jCalendar'
										}
									)
									.append(
										(s.showHeader != $.dpConst.SHOW_HEADER_NONE ? 
											$(dc('thead'))
												.append(headRow)
											:
											dc('thead')
										)
									);
			var tbody = $(dc('tbody'));
			
			var today = (new Date()).zeroTime();
			
			var month = s.month == undefined ? today.getMonth() : s.month;
			var year = s.year || today.getFullYear();
			
			var currentDate = new Date(year, month, 1);
			
			
			var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
			if (firstDayOffset > 1) firstDayOffset -= 7;
			var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
			currentDate.addDays(firstDayOffset-1);
			
			var doHover = function()
			{
				if (s.hoverClass) {
					$(this).addClass(s.hoverClass);
				}
			};
			var unHover = function()
			{
				if (s.hoverClass) {
					$(this).removeClass(s.hoverClass);
				}
			};
			
			var w = 0;
			while (w++<weeksToDraw) {
				var r = jQuery(dc('tr'));
				for (var i=0; i<7; i++) {
					var thisMonth = currentDate.getMonth() == month;
					var d = $(dc('td'))
								.text(currentDate.getDate() + '')
								.attr('className', (thisMonth ? 'current-month ' : 'other-month ') +
													(currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
													(thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
								)
								.hover(doHover, unHover)
							;
					if (s.renderCallback) {
						s.renderCallback(d, currentDate, month, year);
					}
					r.append(d);
					currentDate.addDays(1);
				}
				tbody.append(r);
			}
			calendarTable.append(tbody);
			
			return this.each(
				function()
				{
					$(this).empty().append(calendarTable);
				}
			);
		},
/**
 * Create a datePicker associated with each of the matched elements.
 *
 * The matched element will receive a few custom events with the following signatures:
 *
 * dateSelected(event, date, $td, status)
 * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
 * 
 * dpClosed(event, selected)
 * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
 *
 * dpMonthChanged(event, displayedMonth, displayedYear)
 * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
 *
 * dpDisplayed(event, $datePickerDiv)
 * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
 *
 * @param Object s (optional) Customize your date pickers.
 * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render when the date picker is opened. Default is today's year.
 * @option String startDate The first date date can be selected.
 * @option String endDate The last date that can be selected.
 * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
 * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
 * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
 * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
 * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
 * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
 * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
 * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
 * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
 * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
 * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
 * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type jQuery
 * @name datePicker
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('input.date-picker').datePicker();
 * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
 *
 * @example demo/index.html
 * @desc See the projects homepage for many more complex examples...
 **/
		datePicker : function(s)
		{			
			if (!$.event._dpCache) $.event._dpCache = [];
			
			// initialise the date picker controller with the relevant settings...
			s = $.extend(
				{
					month				: undefined,
					year				: undefined,
					startDate			: undefined,
					endDate				: undefined,
					inline				: false,
					renderCallback		: [],
					createButton		: true,
					showYearNavigation	: true,
					closeOnSelect		: true,
					displayClose		: false,
					selectMultiple		: false,
					clickInput			: false,
					verticalPosition	: $.dpConst.POS_TOP,
					horizontalPosition	: $.dpConst.POS_LEFT,
					verticalOffset		: 0,
					horizontalOffset	: 0,
					hoverClass			: 'dp-hover'
				}
				, s
			);
			
			return this.each(
				function()
				{
					var $this = $(this);
					var alreadyExists = true;
					
					if (!this._dpId) {
						this._dpId = $.event.guid++;
						$.event._dpCache[this._dpId] = new DatePicker(this);
						alreadyExists = false;
					}
					
					if (s.inline) {
						s.createButton = false;
						s.displayClose = false;
						s.closeOnSelect = false;
						$this.empty();
					}
					
					var controller = $.event._dpCache[this._dpId];
					
					controller.init(s);
					
					if (!alreadyExists && s.createButton) {
						// create it!
						controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
								.bind(
									'click',
									function()
									{
										$this.dpDisplay(this);
										this.blur();
										return false;
									}
								);
						$this.after(controller.button);
					}
					
					if (!alreadyExists && $this.is(':text')) {
						$this
							.bind(
								'dateSelected',
								function(e, selectedDate, $td)
								{
									this.value = selectedDate.asString();
								}
							).bind(
								'change',
								function()
								{
									var d = Date.fromString(this.value);
									if (d) {
										controller.setSelected(d, true, true);
									}
								}
							);
						if (s.clickInput) {
							$this.bind(
								'click',
								function()
								{
									$this.dpDisplay();
								}
							);
						}
						var d = Date.fromString(this.value);
						if (this.value != '' && d) {
							controller.setSelected(d, true, true);
						}
					}
					
					$this.addClass('dp-applied');
					
				}
			)
		},
/**
 * Disables or enables this date picker
 *
 * @param Boolean s Whether to disable (true) or enable (false) this datePicker
 * @type jQuery
 * @name dpSetDisabled
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisabled(true);
 * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
 **/
		dpSetDisabled : function(s)
		{
			return _w.call(this, 'setDisabled', s);
		},
/**
 * Updates the first selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the first selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetStartDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetStartDate('01/01/2000');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
 **/
		dpSetStartDate : function(d)
		{
			return _w.call(this, 'setStartDate', d);
		},
/**
 * Updates the last selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the last selectable date (formatted according to Date.format).
 * @type jQuery
 * @name dpSetEndDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetEndDate('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
 **/
		dpSetEndDate : function(d)
		{
			return _w.call(this, 'setEndDate', d);
		},
/**
 * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
 *
 * @type Array
 * @name dpGetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * alert($('.date-picker').dpGetSelected());
 * @desc Will alert an empty array (as nothing is selected yet)
 **/
		dpGetSelected : function()
		{
			var c = _getController(this[0]);
			if (c) {
				return c.getSelected();
			}
			return null;
		},
/**
 * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
 *
 * @param String d A string representing the date you want to select (formatted according to Date.format).
 * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
 * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
 * @type jQuery
 * @name dpSetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetSelected('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetSelected : function(d, v, m)
		{
			if (v == undefined) v=true;
			if (m == undefined) m=true;
			return _w.call(this, 'setSelected', Date.fromString(d), v, m);
		},
/**
 * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
 *
 * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
 * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
 * @type jQuery
 * @name dpSetDisplayedMonth
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisplayedMonth(10, 2008);
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetDisplayedMonth : function(m, y)
		{
			return _w.call(this, 'setDisplayedMonth', Number(m), Number(y));
		},
/**
 * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
 *
 * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
 * @type jQuery
 * @name dpDisplay
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpDisplay();
 * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
 **/
		dpDisplay : function(e)
		{
			return _w.call(this, 'display', e);
		},
/**
 * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
 *
 * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
 * @type jQuery
 * @name dpSetRenderCallback
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
 * {
 * 	// do stuff as each td is rendered dependant on the date in the td and the displayed month and year
 * });
 * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
 **/
		dpSetRenderCallback : function(a)
		{
			return _w.call(this, 'setRenderCallback', a);
		},
/**
 * Sets the position that the datePicker will pop up (relative to it's associated element)
 *
 * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
 * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
 * @type jQuery
 * @name dpSetPosition
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
 **/
		dpSetPosition : function(v, h)
		{
			return _w.call(this, 'setPosition', v, h);
		},
/**
 * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
 *
 * @param Number v The vertical offset of the created date picker.
 * @param Number h The horizontal offset of the created date picker.
 * @type jQuery
 * @name dpSetOffset
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetOffset(-20, 200);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
 **/
		dpSetOffset : function(v, h)
		{
			return _w.call(this, 'setOffset', v, h);
		},
/**
 * Closes the open date picker associated with this element.
 *
 * @type jQuery
 * @name dpClose
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-pick')
 *		.datePicker()
 *		.bind(
 *			'focus',
 *			function()
 *			{
 *				$(this).dpDisplay();
 *			}
 *		).bind(
 *			'blur',
 *			function()
 *			{
 *				$(this).dpClose();
 *			}
 *		);
 * @desc Creates a date picker and makes it appear when the relevant element is focused and disappear when it is blurred.
 **/
		dpClose : function()
		{
			return _w.call(this, '_closeCalendar', false, this[0]);
		},
		// private function called on unload to clean up any expandos etc and prevent memory links...
		_dpDestroy : function()
		{
			// TODO - implement this?
		}
	});
	
	// private internal function to cut down on the amount of code needed where we forward
	// dp* methods on the jQuery object on to the relevant DatePicker controllers...
	var _w = function(f, a1, a2, a3)
	{
		return this.each(
			function()
			{
				var c = _getController(this);
				if (c) {
					c[f](a1, a2, a3);
				}
			}
		);
	};
	
	function DatePicker(ele)
	{
		this.ele = ele;
		
		// initial values...
		this.displayedMonth		=	null;
		this.displayedYear		=	null;
		this.startDate			=	null;
		this.endDate			=	null;
		this.showYearNavigation	=	null;
		this.closeOnSelect		=	null;
		this.displayClose		=	null;
		this.selectMultiple		=	null;
		this.verticalPosition	=	null;
		this.horizontalPosition	=	null;
		this.verticalOffset		=	null;
		this.horizontalOffset	=	null;
		this.button				=	null;
		this.renderCallback		=	[];
		this.selectedDates		=	{};
		this.inline				=	null;
		this.context			=	'#dp-popup';
	};
	$.extend(
		DatePicker.prototype,
		{	
			init : function(s)
			{
				this.setStartDate(s.startDate);
				this.setEndDate(s.endDate);
				this.setDisplayedMonth(Number(s.month), Number(s.year));
				this.setRenderCallback(s.renderCallback);
				this.showYearNavigation = s.showYearNavigation;
				this.closeOnSelect = s.closeOnSelect;
				this.displayClose = s.displayClose;
				this.selectMultiple = s.selectMultiple;
				this.verticalPosition = s.verticalPosition;
				this.horizontalPosition = s.horizontalPosition;
				this.hoverClass = s.hoverClass;
				this.setOffset(s.verticalOffset, s.horizontalOffset);
				this.inline = s.inline;
				if (this.inline) {
					this.context = this.ele;
					this.display();
				}
			},
			setStartDate : function(d)
			{
				if (d) {
					this.startDate = Date.fromString(d);
				}
				if (!this.startDate) {
					this.startDate = (new Date()).zeroTime();
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setEndDate : function(d)
			{
				if (d) {
					this.endDate = Date.fromString(d);
				}
				if (!this.endDate) {
					this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
				}
				if (this.endDate.getTime() < this.startDate.getTime()) {
					this.endDate = this.startDate;
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setPosition : function(v, h)
			{
				this.verticalPosition = v;
				this.horizontalPosition = h;
			},
			setOffset : function(v, h)
			{
				this.verticalOffset = parseInt(v) || 0;
				this.horizontalOffset = parseInt(h) || 0;
			},
			setDisabled : function(s)
			{
				$e = $(this.ele);
				$e[s ? 'addClass' : 'removeClass']('dp-disabled');
				if (this.button) {
					$but = $(this.button);
					$but[s ? 'addClass' : 'removeClass']('dp-disabled');
					$but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
				}
				if ($e.is(':text')) {
					$e.attr('disabled', s ? 'disabled' : '');
				}
			},
			setDisplayedMonth : function(m, y)
			{
				if (this.startDate == undefined || this.endDate == undefined) {
					return;
				}
				var s = new Date(this.startDate.getTime());
				s.setDate(1);
				var e = new Date(this.endDate.getTime());
				e.setDate(1);
				
				var t;
				if ((!m && !y) || (isNaN(m) && isNaN(y))) {
					// no month or year passed - default to current month
					t = new Date().zeroTime();
					t.setDate(1);
				} else if (isNaN(m)) {
					// just year passed in - presume we want the displayedMonth
					t = new Date(y, this.displayedMonth, 1);
				} else if (isNaN(y)) {
					// just month passed in - presume we want the displayedYear
					t = new Date(this.displayedYear, m, 1);
				} else {
					// year and month passed in - that's the date we want!
					t = new Date(y, m, 1)
				}
				
				// check if the desired date is within the range of our defined startDate and endDate
				if (t.getTime() < s.getTime()) {
					t = s;
				} else if (t.getTime() > e.getTime()) {
					t = e;
				}
				this.displayedMonth = t.getMonth();
				this.displayedYear = t.getFullYear();
			},
			setSelected : function(d, v, moveToMonth)
			{
				if (this.selectMultiple == false) {
					this.selectedDates = {};
					$('td.selected', this.context).removeClass('selected');
				}
				if (moveToMonth) {
					this.setDisplayedMonth(d.getMonth(), d.getFullYear());
				}
				this.selectedDates[d.toString()] = v;
			},
			isSelected : function(d)
			{
				return this.selectedDates[d.toString()];
			},
			getSelected : function()
			{
				var r = [];
				for(s in this.selectedDates) {
					if (this.selectedDates[s] == true) {
						r.push(Date.parse(s));
					}
				}
				return r;
			},
			display : function(eleAlignTo)
			{
				if ($(this.ele).is('.dp-disabled')) return;
				
				eleAlignTo = eleAlignTo || this.ele;
				var c = this;
				var $ele = $(eleAlignTo);
				var eleOffset = $ele.offset();
				
				var $createIn;
				var attrs;
				var attrsCalendarHolder;
				var cssRules;
				
				if (c.inline) {
					$createIn = $(this.ele);
					attrs = {
						'id'		:	'calendar-' + this.ele._dpId,
						'className'	:	'dp-popup dp-popup-inline'
					};
					cssRules = {
					};
				} else {
					$createIn = $('body');
					attrs = {
						'id'		:	'dp-popup',
						'className'	:	'dp-popup'
					};
					cssRules = {
						'top'	:	eleOffset.top + c.verticalOffset,
						'left'	:	eleOffset.left + c.horizontalOffset
					};
					
					var _checkMouse = function(e)
					{
						var el = e.target;
						var cal = $('#dp-popup')[0];
						
						while (true){
							if (el == cal) {
								return true;
							} else if (el == document) {
								c._closeCalendar();
								return false;
							} else {
								el = $(el).parent()[0];
							}
						}
					};
					this._checkMouse = _checkMouse;
				
					this._closeCalendar(true);
				}
				
				
				$createIn
					.append(
						$('<div></div>')
							.attr(attrs)
							.css(cssRules)
							.append(
								$('<h2></h2>'),
								$('<div class="dp-nav-prev"></div>')
									.append(
										$('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 0, -1);
												}
											),
										$('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, -1, 0);
												}
											)
									),
								$('<div class="dp-nav-next"></div>')
									.append(
										$('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 0, 1);
												}
											),
										$('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 1, 0);
												}
											)
									),
								$('<div></div>')
									.attr('className', 'dp-calendar')
							)
							.bgIframe()
						);
					
				var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');
				
				if (this.showYearNavigation == false) {
					$('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
				}
				if (this.displayClose) {
					$pop.append(
						$('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
							.bind(
								'click',
								function()
								{
									c._closeCalendar();
									return false;
								}
							)
					);
				}
				c._renderCalendar();
				
				$(this.ele).trigger('dpDisplayed', $pop);
				
				if (!c.inline) {
					if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
						$pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
					}
					if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
						$pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
					}
					$(document).bind('mousedown', this._checkMouse);
				}
			},
			setRenderCallback : function(a)
			{
				if (a && typeof(a) == 'function') {
					a = [a];
				}
				this.renderCallback = this.renderCallback.concat(a);
			},
			cellRender : function ($td, thisDate, month, year) {
				var c = this.dpController;
				var d = new Date(thisDate.getTime());
				
				// add our click handlers to deal with it when the days are clicked...
				
				$td.bind(
					'click',
					function()
					{
						var $this = $(this);
						if (!$this.is('.disabled')) {
							c.setSelected(d, !$this.is('.selected') || !c.selectMultiple);
							var s = c.isSelected(d);
							$(c.ele).trigger('dateSelected', [d, $td, s]);
							$(c.ele).trigger('change');
							if (c.closeOnSelect) {
								c._closeCalendar();
							} else {
								$this[s ? 'addClass' : 'removeClass']('selected');
							}
						}
					}
				);
				
				if (c.isSelected(d)) {
					$td.addClass('selected');
				}
				
				// call any extra renderCallbacks that were passed in
				for (var i=0; i<c.renderCallback.length; i++) {
					c.renderCallback[i].apply(this, arguments);
				}
				
				
			},
			// ele is the clicked button - only proceed if it doesn't have the class disabled...
			// m and y are -1, 0 or 1 depending which direction we want to go in...
			_displayNewMonth : function(ele, m, y) 
			{
				if (!$(ele).is('.disabled')) {
					this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y);
					this._clearCalendar();
					this._renderCalendar();
					$(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
				}
				ele.blur();
				return false;
			},
			_renderCalendar : function()
			{
				// set the title...
				$('h2', this.context).html(Date.monthNames[this.displayedMonth] + ' ' + this.displayedYear);
				
				// render the calendar...
				$('.dp-calendar', this.context).renderCalendar(
					{
						month			: this.displayedMonth,
						year			: this.displayedYear,
						renderCallback	: this.cellRender,
						dpController	: this,
						hoverClass		: this.hoverClass
					}
				);
				
				// update the status of the control buttons and disable dates before startDate or after endDate...
				// TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
				if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
					$('.dp-nav-prev-year', this.context).addClass('disabled');
					$('.dp-nav-prev-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > 20) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.startDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-prev-year', this.context).removeClass('disabled');
					$('.dp-nav-prev-month', this.context).removeClass('disabled');
					var d = this.startDate.getDate();
					if (d > 20) {
						// check if the startDate is last month as we might need to add some disabled classes...
						var sd = new Date(this.startDate.getTime());
						sd.addMonths(1);
						if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
							$('dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Number($this.text()) < d) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
				if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
					$('.dp-nav-next-year', this.context).addClass('disabled');
					$('.dp-nav-next-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < 14) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.endDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-next-year', this.context).removeClass('disabled');
					$('.dp-nav-next-month', this.context).removeClass('disabled');
					var d = this.endDate.getDate();
					if (d < 13) {
						// check if the endDate is next month as we might need to add some disabled classes...
						var ed = new Date(this.endDate.getTime());
						ed.addMonths(-1);
						if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
							$('.dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Number($this.text()) > d) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
			},
			_closeCalendar : function(programatic, ele)
			{
				if (!ele || ele == this.ele)
				{
					$(document).unbind('mousedown', this._checkMouse);
					this._clearCalendar();
					$('#dp-popup a').unbind();
					$('#dp-popup').empty().remove();
					if (!programatic) {
						$(this.ele).trigger('dpClosed', [this.getSelected()]);
					}
				}
			},
			// empties the current dp-calendar div and makes sure that all events are unbound
			// and expandos removed to avoid memory leaks...
			_clearCalendar : function()
			{
				// TODO.
				$('.dp-calendar td', this.context).unbind();
				$('.dp-calendar', this.context).empty();
			}
		}
	);
	
	// static constants
	$.dpConst = {
		SHOW_HEADER_NONE	:	0,
		SHOW_HEADER_SHORT	:	1,
		SHOW_HEADER_LONG	:	2,
		POS_TOP				:	0,
		POS_BOTTOM			:	1,
		POS_LEFT			:	0,
		POS_RIGHT			:	1
	};
	// localisable text
	$.dpText = {
		TEXT_PREV_YEAR		:	'Previous year',
		TEXT_PREV_MONTH		:	'Previous month',
		TEXT_NEXT_YEAR		:	'Next year',
		TEXT_NEXT_MONTH		:	'Next month',
		TEXT_CLOSE			:	'Close',
		TEXT_CHOOSE_DATE	:	'Choose date'
	};
	// version
	$.dpVersion = '$Id: java.js,v 1.121.2.323 2010/02/25 22:25:11 christian Exp $';

	function _getController(ele)
	{
		if (ele._dpId) return $.event._dpCache[ele._dpId];
		return false;
	};
	
	// make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
	// comments to only include bgIframe where it is needed in IE without breaking this plugin).
	if ($.fn.bgIframe == undefined) {
		$.fn.bgIframe = function() {return this; };
	};


	// clean-up
	$(window)
		.bind('unload', function() {
			var els = $.event._dpCache || [];
			for (var i in els) {
				$(els[i].ele)._dpDestroy();
			}
		});
		
	
})(jQuery);



/* 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-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.19={P:\'1.2\'};$.u([\'j\',\'w\'],5(i,d){$.q[\'O\'+d]=5(){p(!3[0])6;g a=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';6 3.B(\':y\')?3[0][\'L\'+d]:4(3,d.x())+4(3,\'n\'+a)+4(3,\'n\'+e)};$.q[\'I\'+d]=5(b){p(!3[0])6;g c=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';b=$.F({t:Z},b||{});g a=3.B(\':y\')?3[0][\'8\'+d]:4(3,d.x())+4(3,\'E\'+c+\'w\')+4(3,\'E\'+e+\'w\')+4(3,\'n\'+c)+4(3,\'n\'+e);6 a+(b.t?(4(3,\'t\'+c)+4(3,\'t\'+e)):0)}});$.u([\'m\',\'s\'],5(i,b){$.q[\'l\'+b]=5(a){p(!3[0])6;6 a!=W?3.u(5(){3==h||3==r?h.V(b==\'m\'?a:$(h)[\'U\'](),b==\'s\'?a:$(h)[\'T\']()):3[\'l\'+b]=a}):3[0]==h||3[0]==r?S[(b==\'m\'?\'R\':\'Q\')]||$.N&&r.M[\'l\'+b]||r.A[\'l\'+b]:3[0][\'l\'+b]}});$.q.F({z:5(){g a=0,f=0,o=3[0],8,9,7,v;p(o){7=3.7();8=3.8();9=7.8();8.f-=4(o,\'K\');8.k-=4(o,\'J\');9.f+=4(7,\'H\');9.k+=4(7,\'Y\');v={f:8.f-9.f,k:8.k-9.k}}6 v},7:5(){g a=3[0].7;G(a&&(!/^A|10$/i.16(a.15)&&$.14(a,\'z\')==\'13\'))a=a.7;6 $(a)}});5 4(a,b){6 12($.11(a.17?a[0]:a,b,18))||0}})(X);',62,72,'|||this|num|function|return|offsetParent|offset|parentOffset|||||borr|top|var|window||Height|left|scroll|Left|padding|elem|if|fn|document|Top|margin|each|results|Width|toLowerCase|visible|position|body|is|Right|Bottom|border|extend|while|borderTopWidth|outer|marginLeft|marginTop|client|documentElement|boxModel|inner|version|pageYOffset|pageXOffset|self|scrollTop|scrollLeft|scrollTo|undefined|jQuery|borderLeftWidth|false|html|curCSS|parseInt|static|css|tagName|test|jquery|true|dimensions'.split('|'),0,{}));



/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : 'Images/facebox_loading.gif',
	  /*closeImage   : 'Images/facebox_closelabel.gif',*/
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="facebox_content"> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="footer_body"> \
                <div class="facebox_footer"> \
                  <a href="#" class="close"> \
                    Close \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .facebox_content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img alt="loading..." src="'+$.facebox.settings.loadingImage+'"/></div>')

      if ($.browser.msie && $.browser.version < 8)
        $('#facebox').css({
          top:	getPageScroll()[1] + (getPageHeight() / 20),
	  left:	$(document).width()/2 - 350
        }).show()

      else
        $('#facebox').css({
          top:	getPageScroll()[1] + (getPageHeight() / 20),
          left:	$(document).width()/2 - 205
        }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .facebox_content').addClass(klass)
      $('#facebox .facebox_content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image() ]//, new Image() ]
		    //preload[0].src = $.facebox.settings.closeImage
    preload[0].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .facebox_content').removeClass().addClass('facebox_content')
      hideOverlay()
      $('#facebox .loading').remove()
      $('#facebox').removeClass('facebox_black')
    })
  })

})(jQuery);



﻿/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);



/**
 * jQuery.LocalScroll - Animated scrolling navigation, using anchors.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 6/3/2008
 * @author Ariel Flesler
 * @version 1.2.6
 **/
;(function($){var g=location.href.replace(/#.*/,''),h=$.localScroll=function(a){$('body').localScroll(a)};h.defaults={duration:1e3,axis:'y',event:'click',stop:1};h.hash=function(a){a=$.extend({},h.defaults,a);a.hash=0;if(location.hash)setTimeout(function(){i(0,location,a)},0)};$.fn.localScroll=function(b){b=$.extend({},h.defaults,b);return(b.persistent||b.lazy)?this.bind(b.event,function(e){var a=$([e.target,e.target.parentNode]).filter(c)[0];a&&i(e,a,b)}):this.find('a,area').filter(c).bind(b.event,function(e){i(e,this,b)}).end().end();function c(){var a=this;return!!a.href&&!!a.hash&&a.href.replace(a.hash,'')==g&&(!b.filter||$(a).is(b.filter))}};function i(e,a,b){var c=a.hash.slice(1),d=document.getElementById(c)||document.getElementsByName(c)[0],f;if(d){e&&e.preventDefault();f=$(b.target||$.scrollTo.window());if(b.lock&&f.is(':animated')||b.onBefore&&b.onBefore.call(a,e,d,f)===!1)return;if(b.stop)f.queue('fx',[]).stop();f.scrollTo(d,b).trigger('notify.serialScroll',[d]);if(b.hash)f.queue(function(){location=a.hash;$(this).dequeue()})}}})(jQuery);



/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);



/*
 * Superfish v1.3.1 - jQuery menu widget
 *
 * Copyright (c) 2007 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * YOU MAY DELETE THIS CHANGELOG:
 * v1.2.1 altered: 2nd July 07. added hide() before animate to make work for jQuery 1.1.3.
 * v1.2.2 altered: 2nd August 07. changed showSuperfishUl function .find('ul') to .find('>ul') for smoother animations
 * v1.2.3 altered: jQuery 1.1.3.1 broke keyboard access - had to rewrite quite a few things
 * v1.3	 altered:  Pretty much a complete overhaul to make all original features work in 1.1.3.1 and above.
 * v1.3.1 altered: 'li[ul]' to $('li:has(ul)') to work with jQuery 1.2
 */

(function($){
	$.fn.superfish = function(o){
		var $sf = this,
			defaults = {
			hoverClass	: 'sfHover',
			pathClass	: 'overideThisToUse',
			delay		: 800,
			animation	: {opacity:'show'},
			speed		: 'normal'
		},
			over = function(){
				clearTimeout(this.sfTimer);
				clearTimeout($sf[0].sfTimer);
				$(this)
				.showSuperfishUl()
				.siblings()
				.hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this);
				if ( !$$.is('.'+o.bcClass) ) {
					this.sfTimer=setTimeout(function(){
						$$.hideSuperfishUl();
						if (!$('.'+o.hoverClass,$sf).length) { 
							over.call($currents.hideSuperfishUl());
						}
					},o.delay);
				}		
			};
		$.fn.extend({
			hideSuperfishUl : function(){
				return this
					.removeClass(o.hoverClass)
					.find('ul:visible')
						.hide()
					.end();
			},
			showSuperfishUl : function(){
				return this
					.addClass(o.hoverClass)
					.find('>ul:hidden')
						.animate(o.animation,o.speed)
					.end();
			},
			applySuperfishHovers : function(){
				return this[($.fn.hoverIntent) ? 'hoverIntent' : 'hover'](over,out);
			}
		});
		o = $.extend({bcClass:'sfbreadcrumb'},defaults,o || {});
		var $currents = $('li:has(ul)',this).filter('.'+o.pathClass);
		if ($currents.length) {
			$currents.each(function(){
				$(this).removeClass(o.pathClass).addClass(o.hoverClass+' '+o.bcClass);
			});
		}
		var $sfHovAr=$('li:has(ul)',this)
			.applySuperfishHovers(over,out)
			.find('a').each(function(){
				var $a = $(this), $li = $a.parents('li');
				$a.focus(function(){
					over.call($li);
					return false;
				}).blur(function(){
					$li.removeClass(o.hoverClass);
				});
			})
			.end()
			.not('.'+o.bcClass)
				.hideSuperfishUl()
			.end();
		$(window).unload(function(){
			$sfHovAr.unbind('mouseover').unbind('mouseout');
		});
		return this.addClass('superfish').blur(function(){
			out.call(this);
		});
	};
})(jQuery);



/*
 * jQuery Timer Plugin
 * http://www.evanbot.com/article/jquery-timer-plugin/23
 *
 * @version      1.0
 * @copyright    2009 Evan Byrne (http://www.evanbot.com)
 */ 

jQuery.timer = function(time,func,callback){
	var a = {timer:setTimeout(func,time),callback:null}
	if(typeof(callback) == 'function'){a.callback = callback;}
	return a;
};

jQuery.clearTimer = function(a){
	clearTimeout(a.timer);
	if(typeof(a.callback) == 'function'){a.callback();};
	return this;
};/*
Uploadify v2.0.2
Release Date: July 29, 2009

Copyright (c) 2009 Ronnie Garcia, Travis Nickels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

if(jQuery){(function(a){a.extend(a.fn,{uploadify:function(b){a(this).each(function(){settings=a.extend({id:a(this).attr("id"),uploader:"uploadify.swf",script:"uploadify.php",expressInstall:null,folder:"",height:30,width:110,cancelImg:"cancel.png",wmode:"opaque",scriptAccess:"sameDomain",fileDataName:"Filedata",method:"POST",queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:"percentage",onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},b);var e=location.pathname;e=e.split("/");e.pop();e=e.join("/")+"/";var f={};f.uploadifyID=settings.id;f.pagepath=e;if(settings.buttonImg){f.buttonImg=escape(settings.buttonImg)}if(settings.buttonText){f.buttonText=escape(settings.buttonText)}if(settings.rollover){f.rollover=true}f.script=settings.script;f.folder=escape(settings.folder);if(settings.scriptData){var g="";for(var d in settings.scriptData){g+="&"+d+"="+settings.scriptData[d]}f.scriptData=escape(g.substr(1))}f.width=settings.width;f.height=settings.height;f.wmode=settings.wmode;f.method=settings.method;f.queueSizeLimit=settings.queueSizeLimit;f.simUploadLimit=settings.simUploadLimit;if(settings.hideButton){f.hideButton=true}if(settings.fileDesc){f.fileDesc=settings.fileDesc}if(settings.fileExt){f.fileExt=settings.fileExt}if(settings.multi){f.multi=true}if(settings.auto){f.auto=true}if(settings.sizeLimit){f.sizeLimit=settings.sizeLimit}if(settings.checkScript){f.checkScript=settings.checkScript}if(settings.fileDataName){f.fileDataName=settings.fileDataName}if(settings.queueID){f.queueID=settings.queueID}if(settings.onInit()!==false){a(this).css("display","none");a(this).after('<div id="'+a(this).attr("id")+'Uploader"></div>');swfobject.embedSWF(settings.uploader,settings.id+"Uploader",settings.width,settings.height,"9.0.24",settings.expressInstall,f,{quality:"high",wmode:settings.wmode,allowScriptAccess:settings.scriptAccess});if(settings.queueID==false){a("#"+a(this).attr("id")+"Uploader").after('<div id="'+a(this).attr("id")+'Queue" class="uploadifyQueue"></div>')}}a(this).bind("uploadifySelect",{action:settings.onSelect,queueID:settings.queueID},function(j,h,i){if(j.data.action(j,h,i)!==false){var k=Math.round(i.size/1024*100)*0.01;var l="KB";if(k>1000){k=Math.round(k*0.001*100)*0.01;l="MB"}var m=k.toString().split(".");if(m.length>1){k=m[0]+"."+m[1].substr(0,2)}else{k=m[0]}if(i.name.length>20){fileName=i.name.substr(0,20)+"..."}else{fileName=i.name}queue="#"+a(this).attr("id")+"Queue";if(j.data.queueID){queue="#"+j.data.queueID}a(queue).append('<div id="'+a(this).attr("id")+h+'" class="uploadifyQueueItem"><div class="cancel"><a href="javascript:jQuery(\'#'+a(this).attr("id")+"').uploadifyCancel('"+h+'\')"><img src="'+settings.cancelImg+'" border="0" /></a></div><span class="fileName">'+fileName+" ("+k+l+')</span><span class="percentage"></span><div class="uploadifyProgress"><div id="'+a(this).attr("id")+h+'ProgressBar" class="uploadifyProgressBar"><!--Progress Bar--></div></div></div>')}});if(typeof(settings.onSelectOnce)=="function"){a(this).bind("uploadifySelectOnce",settings.onSelectOnce)}a(this).bind("uploadifyQueueFull",{action:settings.onQueueFull},function(h,i){if(h.data.action(h,i)!==false){alert("The queue is full.  The max size is "+i+".")}});a(this).bind("uploadifyCheckExist",{action:settings.onCheck},function(m,l,k,j,o){var i=new Object();i=k;i.folder=e+j;if(o){for(var h in k){var n=h}}a.post(l,i,function(r){for(var p in r){if(m.data.action(m,l,k,j,o)!==false){var q=confirm("Do you want to replace the file "+r[p]+"?");if(!q){document.getElementById(a(m.target).attr("id")+"Uploader").cancelFileUpload(p,true)}}}if(o){document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(n,true)}else{document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(null,true)}},"json")});a(this).bind("uploadifyCancel",{action:settings.onCancel},function(l,h,k,m,j){if(l.data.action(l,h,k,m,j)!==false){var i=(j==true)?0:250;a("#"+a(this).attr("id")+h).fadeOut(i,function(){a(this).remove()})}});if(typeof(settings.onClearQueue)=="function"){a(this).bind("uploadifyClearQueue",settings.onClearQueue)}var c=[];a(this).bind("uploadifyError",{action:settings.onError},function(l,h,k,j){if(l.data.action(l,h,k,j)!==false){var i=new Array(h,k,j);c.push(i);a("#"+a(this).attr("id")+h+" .percentage").text(" - "+j.type+" Error");a("#"+a(this).attr("id")+h).addClass("uploadifyError")}});a(this).bind("uploadifyProgress",{action:settings.onProgress,toDisplay:settings.displayData},function(j,h,i,k){if(j.data.action(j,h,i,k)!==false){a("#"+a(this).attr("id")+h+"ProgressBar").css("width",k.percentage+"%");if(j.data.toDisplay=="percentage"){displayData=" - "+k.percentage+"%"}if(j.data.toDisplay=="speed"){displayData=" - "+k.speed+"KB/s"}if(j.data.toDisplay==null){displayData=" "}a("#"+a(this).attr("id")+h+" .percentage").text(displayData)}});a(this).bind("uploadifyComplete",{action:settings.onComplete},function(k,h,j,i,l){if(k.data.action(k,h,j,unescape(i),l)!==false){a("#"+a(this).attr("id")+h+" .percentage").text(" - Completed");a("#"+a(this).attr("id")+h).fadeOut(250,function(){a(this).remove()})}});if(typeof(settings.onAllComplete)=="function"){a(this).bind("uploadifyAllComplete",{action:settings.onAllComplete},function(h,i){if(h.data.action(h,i)!==false){c=[]}})}})},uploadifySettings:function(f,j,c){var g=false;a(this).each(function(){if(f=="scriptData"&&j!=null){if(c){var i=j}else{var i=a.extend(settings.scriptData,j)}var l="";for(var k in i){l+="&"+k+"="+escape(i[k])}j=l.substr(1)}g=document.getElementById(a(this).attr("id")+"Uploader").updateSettings(f,j)});if(j==null){if(f=="scriptData"){var b=unescape(g).split("&");var e=new Object();for(var d=0;d<b.length;d++){var h=b[d].split("=");e[h[0]]=h[1]}g=e}return g}},uploadifyUpload:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").startFileUpload(b,false)})},uploadifyCancel:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").cancelFileUpload(b,true,false)})},uploadifyClearQueue:function(){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").clearFileUploadQueue(false)})}})})(jQuery)};/***
   * title:            Concert Co-Op JavaScript - Common Functions
   * site:             www.concertcoop.com
   * file:             java-coop.js
   * primary author:   Operative C
   * email:            operativec@thenumbersstation.com
   * secondary author: Junichi Furukawa
   * email:            junichi@thenumbersstation.com
   *
   * All contents copyright 2007 The Numbers Station LLC, all rights reserved.
   * User access subject to The Concert Co-Op(TM) Site Terms of Use, available at http://www.concertcoop.com/terms.php
 ***/
//ONLOAD FUNCTION ========================================================

$(document).ready(function() {
    //load common functions for each page
    $("ul.metronav").superfish();
    coolirisCheck();
    $("ul.nav").superfish();
    Date.firstDayOfWeek = 7;
    Date.format = "mm/dd/yyyy";
    setReveals();
    set_ajax_links();
    setForms();
    setReviewButtons();
    nav_search_prep();
    set_search_reveal()
    setFutureDatePicker();
    if ($.browser.msie)
      $("textarea").css("height","120px");
    else
      $("textarea").autogrow();
    
    //initialize function loads
    if ( initialize_bandPrep_for_bandList )
      bandPrep("bandList");
    if ( initialize_bandPrep_for_search )
      bandPrep("searchBands");
    if ( initialize_check_all_table )
      setCheckAllTable();
    if ( initialize_cooliris_links_for_image_lists )
      setImageListCoolirisLinks();
    if ( initialize_crop_controls )
      setCropControls();
    if ( initialize_datepicker )
      setDatePicker();
    if ( initialize_gallery_forms )
      setGalleryForms();
    if ( initialize_google_map )
      initializeGoogleMap();
    if ( initialize_listings )
      buildDOM();
    if ( initialize_any_datepicker )
      setAnyDatePicker();
    if ( initialize_past_datepicker )
      setPastDatePicker();
    if ( initialize_future_datepicker )
      setFutureDatePicker();
    if ( initialize_interest )
      set_interest();
    if ( initialize_photo_select )
      setBatchSelect();
    if ( initialize_post_rate )
      set_post_rate();
    if ( initialize_interest )
      set_interest();
    if ( initialize_quick_fills )
      setQuickFills();
    if ( initialize_rating_bands )
      setRatingBands();
    if ( initialize_strike_throughs )
      set_strike_throughs();
    if ( initialize_ticket_datepicker )
      setTicketDatePicker();
    if ( initialize_uploadify )
      setUploadify();

    // set after everything else in case DOM has changed
    setHeightConstraints();
    setImageScaling();
    stickyNav();
    setStarDivs();
    setPops();
    setAlbums();
    setAmazonWidgets();
    setRadioButtons();
    setCheckboxButtons();
    setOrderedListControls();
    setTokens();
    set_ajax_forms();

    //Put last to give Flickr some time
    if ( initialize_flickr_gallery )
      setFlickrGallery();
  });
//  Mouse Helper Functions - Capture coordinates relative to the object 
function mouseCoords(ev){
  if(ev.pageX || ev.pageY){
    return {x:ev.pageX, y:ev.pageY};
  }
  return {
  x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
      y:ev.clientY + document.body.scrollTop  - document.body.clientTop
      };
}

function getPosition(e){
  var left = 0;
  var top  = 0;
  
  while (e.offsetParent){
    left += e.offsetLeft;
    top  += e.offsetTop;
    e     = e.offsetParent;
  }
  
  left += e.offsetLeft;
  top  += e.offsetTop;
  
  return {x:left, y:top};
}

function getMouseOffset(target, ev){
  ev = ev || window.event;
  
  var docPos    = getPosition(target);
  var mousePos  = mouseCoords(ev);
  return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

/* Finds the position an object for a particular side */
function findPos( obj, side ){
  var c = 0;
  while( obj ){
    c += obj[side];
    obj = obj.offsetParent;
  }
  return c;
}

// recursive function to copy all children from the obj to the new parent
function copyChildren(parent, obj){
  if( obj ){
    parent.appendChild( obj.cloneNode(true) );
  }
}
//SHORTHAND FUNCTIONS ====================================================

function gE(v){return document.getElementById(v);}

function gA(o,att){
  if (o.getAttribute(att))
    return o.getAttribute(att);
  else
    return 0;
}
// returns an array of elements with specific class name - runs faster if you specify what tag to look for and an element to look within
function getElementsByClass(className, tag, elm){
  var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
  var tag = tag || "*";
  var elm = elm || document;
  var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
  var returnElements = [];
  var current;
  var length = elements.length;
  for(var i=0; i<length; i++){
    current = elements[i];
    if(testClass.test(current.className)){
      returnElements.push(current);
    }
  }
  return returnElements;
}
// returns the xth child of an element
function getXChild(obj, childNum) {
  var x;
  for ( var i=0; i < childNum; i++ ) {
    if ( i == 0 )
      x = obj.firstChild;
    else
      x = x.nextSibling;
    while ( x.nodeType != 1 )
      x = x.nextSibling;
  }
  return x;
}
// reveal and unreveal items... used to all have an unbind event, but I think it goes away with the live command
function setReveals() {
  $("*[reveal],*[unreveal]").live("click", function () {
      var rev_ele = ( $(this).attr("reveal") )? $(this).attr("reveal") : "tag_not_set";
      var un_rev_ele = ( $(this).attr("unreveal") )? $(this).attr("unreveal") : "tag_not_set";
      
      $('#'+un_rev_ele+',.'+un_rev_ele+',*[reveal='+rev_ele+'],*[unreveal='+un_rev_ele+']')
	.find("input[type!='submit']").val("").end()
	.find("select").val("0").end()
	.fadeOut('normal',function(){
	    $('#'+rev_ele+',.'+rev_ele+',*[unreveal='+rev_ele+'],*[reveal='+un_rev_ele+']')
	      .fadeIn()
	      .find('input:first').focus();
	  });
      return false;
    });
  $("*[tog_reveal]").live("click", function() {
      var ele = $(this).attr("tog_reveal");
      $(ele).toggle();
      $(window).trigger("resize");
    });
}
// AJAX ENABLING/HELPER FUNCTIONS ==========================================

// Check Browswer Function and set xmlhttp to the proper setting
function getXMLHttp () {
  
  var xmlhttp = false;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

//Process AJAX request; and send request to server; result is pushed into obj.
var in_flight = false;
function processAJAX(serverPage, obj, getOrPost, str){

  if( in_flight == true){return false;}
  in_flight = true; 

  var xmlhttp = getXMLHttp();
  serverPage = web_root + serverPage;

  if( getOrPost == "get"){
    xmlhttp.open("GET", serverPage, true);
  } else{
    xmlhttp.open("POST", serverPage, true);
    xmlhttp.setRequestHeader("Content-Type", 
			     "application/x-www-form-urlencoded;charset=UTF-8");
  }
  xmlhttp.onreadystatechange = function() {
    if( xmlhttp.readyState == 4 ){
      if( xmlhttp.status == 200 || xmlhttp.status == 304 ){
	in_flight = false;
	obj.innerHTML = xmlhttp.responseText;
      }
    }
  };
  if( getOrPost == "get"){
    xmlhttp.send(null);
  }
  else{
    xmlhttp.send(str);
  }
}

// Send AJAX request; result is empty


// Helper functions to submit a form data through AJAX
function getFormValues( fobj ){
  
  var str = "";
  var val;

  for( var i=0; i < fobj.elements.length; i++ ){
    if ( $(fobj.elements[i]).attr('type') != "checkbox" || fobj.elements[i].checked )
      str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
  }
  return str;
}


function submitForm( form, approvals ){
  var serverPage = $(form).attr("action");
  var str  = getFormValues(form);
  $.ajax({
    type: 'POST',
	url: serverPage,
	data: str,
	contentType: "application/x-www-form-urlencoded;charset=UTF-8",
	success: function() {
	  if ( approvals ) {
	    jQuery.facebox(function() {
		var approval_url = web_root + "images.php?page=image_approval_sequence&pop";
		$.get(approval_url, function(data) { $.facebox(data); });
	      });
	  }
	  else
	    popFormClose('<div class="facebox_title">Saved</div>');
      },
	error: function(xhr) {
	popFormClose('<div class="facebox_title">There was an error. Data not saved. Error: '+xhr+'</div>');
      }
    });
}


function emptyAJAX(serverPage){
  var xmlhttp = getXMLHttp();
  serverPage = web_root + serverPage;

  xmlhttp.open("GET", serverPage, false);
  xmlhttp.send(null);
}
// AMAZON SAMPLE PLAYER FUNCTIONS ========================================
// Code below is modified from Amazon.com Copyrighted code


var de_ws_url = "http://ws.amazon.de";
var us_ws_url = "http://ws.amazon.com";
var fr_ws_url = "http://ws.amazon.fr";
var ca_ws_url = "http://ws.amazon.ca";
var gb_ws_url = "http://ws.amazon.co.uk";
var jp_ws_url = "http://ws.amazon.co.jp";


function escapeParam(param){
	param = encodeURIComponent(param);
	param=param.replace("+", "%20");
	param=param.replace("/", "%2F");
	return param;
}


function createAmazonSampleWidget(obj) {
  var amzn_wdgt={ widget:'MP3Clips' };
  amzn_wdgt.tag = $(obj).attr('amzn_tag');
  amzn_wdgt.widgetType = $(obj).attr('amzn_widgetType');
  amzn_wdgt.ASIN = $(obj).attr('amzn_asin');
  amzn_wdgt.title = $(obj).attr('amzn_title');
  amzn_wdgt.width = $(obj).attr('amzn_width');
  amzn_wdgt.height = $(obj).attr('amzn_height');
  amzn_wdgt.shuffleTracks = $(obj).attr('amzn_shuffleTracks');

  var amzn_MarketPlace = amzn_wdgt["marketPlace"];
  if( amzn_MarketPlace == null ||  amzn_MarketPlace == "" )
    amzn_MarketPlace= "US";

  var amzn_ws_url = us_ws_url;
  switch(amzn_MarketPlace){
	case "US": amzn_ws_url = us_ws_url;break;
	case "DE": amzn_ws_url = de_ws_url;break;
	case "GB": amzn_ws_url = gb_ws_url;break;
	case "CA": amzn_ws_url = ca_ws_url;break;
	case "FR": amzn_ws_url = fr_ws_url;break;
	case "JP": amzn_ws_url = jp_ws_url;break;
	default: amzn_ws_url = us_ws_url;
  }

  var amzn_ws_path = amzn_ws_url + "/widgets/q?";
  var swfObject = new SWFObject(amzn_ws_path, "amzn_widget", amzn_wdgt.width, amzn_wdgt.height);
  swfObject.addVariable("MarketPlace", amzn_MarketPlace);
  swfObject.addVariable("Operation", "GetDisplayTemplate");
  swfObject.addVariable("ServiceVersion", "20070822");
  swfObject.addVariable("WS", "1");
  swfObject.addVariable("ID", amzn_wdgt["widget"]);
  swfObject.setAttribute('swf', amzn_ws_path + swfObject.getVariablePairs().join("&"));
  for( i in amzn_wdgt){
    if(!amzn_wdgt.hasOwnProperty(i))continue;
    var j = i.substr(1);
    var k = i.charAt(0).toUpperCase() + j;
    if(k == "Widget"){
      k = "ID";
    }
    swfObject.addVariable(k, escapeParam(amzn_wdgt[i]));
  }
  swfObject.addParam("quality" ,"high");
  swfObject.addParam("bgcolor","#222222");
  swfObject.addParam("allowscriptaccess" ,"always");

  $(obj).html(swfObject.getSWFHTML());
}


function setAmazonWidgets() {
  $("div.amazon_ASINList").each(function() {
      createAmazonSampleWidget(this);      
    });
}

// COMMENTING FUNCTIONS ==================================================


function commentLeave(obj,clearSet,fadeIn){
  var comment_box = $(obj).parent();
  var type = $(comment_box).parent().attr('type');
  var event_id = $(comment_box).parent().attr('eid');

  if ( fadeIn ) {
    var comment = $(comment_box).attr('comment');
    if ( comment && !clearSet)
      $('#comment_leave').find('textarea').html(comment);
    else
      $('#comment_leave').find('textarea').html("");
    var comment_dummy = $('#comment_leave').find('dd').clone(true);
    if ( type == 'r' )
      $(comment_dummy).find('i').html('leave a message about this show for your subscribers');
    $(comment_dummy).hide('fast',function() {
	$(comment_box).fadeOut('fast',function(){
	    $(comment_box).replaceWith(comment_dummy);
	    $(comment_dummy).fadeIn();
	  });
      });
  }
  else
    $(comment_box).find('textarea').val("");
  if ( clearSet )
    messageSend(event_id,type,"");
  return false;
}


//sets a comment
function commentSet(obj){
  var comment_box = $(obj).parent();
  var type = $(comment_box).parent().attr('type');
  var event_id = $(comment_box).parent().attr('eid');
  var comment_dummy = $('#comment_set').find('dd').clone(true);
  var comment = $(comment_box).find('textarea:first').val();
  if ( comment == "" )
    commentDelete(obj);
  else {
    $(comment_dummy)
      .attr('comment',comment)
      .prepend(comment)
      .hide('fast',function() {
	  $(comment_box).fadeOut('fast',function(){
	      $(comment_box).replaceWith(comment_dummy);
	      $(comment_dummy).fadeIn();
	    });
	});
    messageSend(event_id,type,comment);
    return false;
  }
}


//looks for a strike of the return key to set a comment
function checkRet(e,obj){ 
  var key = e.which;
  if( !key ){
    key = e.keyCode; 
  }
  if(key == 13){ 
    commentSet(obj);
    return false;
  }
  else{
    return true;
  }
}

function checkCR(e){
  var key = e.which;
  if( !key ){
    key = e.keyCode; 
  }
  if(key == 13){ 
    document.write("&#13;");
  }
  else{
    return true;
  }
}

function messageSend(event_id,type,message) {
var serverPage = "user_event_status.php?event_id="+event_id+"&"+type+"com="+message;
emptyAJAX(serverPage);
}

// COOLIRIS ==========================================================

// checks whether cooliris is present, and occasionally sends a prompt if there's no error or prompt set

function coolirisCheck() {
  if ( PicLensLite.hasClient()) {
    $(".cooliris_get").remove();
  }  
  else {
    $(".cooliris_launch, .q").remove();
    $(".cooliris_get").show();
  }
}

// sets cooliris links in an image list

function setImageListCoolirisLinks() {
  $(".image_list div.q")
    .click(function(){
	PicLensLite.start({feedUrl:$(this).attr("ci"), paused:true});
      });
}
// CHECKBOX FUNCTIONS ================================================

//sets up checkall buttons
function setCheckboxButtons() {
  $(".check_container")
    .find(".check_all").live('click', function(){
	$(this).coopCheckAllButton();
      });
}





// jQuery extension to handle checkbox types
// takes an argument, setType, to handle various configurations
(function($) {
  $.fn.coopCheckboxHandler = function(setType, setBlur) {
    $(this).each( function() {
	$(this).attr("check_container",1);

	//change the color of all boxes if necessary and bind the change function to state change
	$(this).find(":checkbox")
	  .coopCheckboxColorAdjust()
	  .click( function() {
	      $(this).coopCheckboxColorAdjust();
	    });

	//if setType is "all", then takes the first checkbox in the group as the all toggle button
	if (setType == "all") {
	  $(this)
	    .find(":checkbox:first").click( function() {
		$(this).coopCheckAll();
	      }).end()
	    .find(":checkbox:not(:first)").click( function() {
		$(this).coopCheckSlave();
	      }).end();
	  //if (setBlur)
	  //$(this).find(":checkbox").bind("blur", function() {
	  //	$(this).coopCheckBlurAll();
	  //  });
	}

	//if setType is "one", then only one box can be checked at a time
	else if (setType == "one") {
	  $(this).find(":checkbox").click( function() {
	      $(this).coopCheckOne();
	    })
	    .parent().find("input:text").click( function() {
		$(this).parents("li:first").find(":checkbox").coopCheckboxCheck();
	      });
	  //if (setBlur)
	  //$(this).find(":checkbox").bind("blur", function() {
	  //	$(this).coopCheckBlurOne();
	  //  });
	}

	    //$(checkbox_set).click( function() {
	    //if ( this.checked )
	    //$(checkbox_set).not(this).coopCheckboxCheck(false);
	    //});
      });
    return this;
  }
 }) (jQuery);


// jQuery extension to check everything but the first
(function($) {
  $.fn.coopCheckAll = function() {
    $(this).each( function() {
	var box = $(this).filter(":checkbox:first");
	$(this).parents("*[check_container]:first").find(":checkbox:not(:first)")
	  .coopCheckboxCheck( box[0].checked )
      });
  }
  return this;
 }) (jQuery);


// jQuery extension to check everything in the parent check_container
(function($) {
  $.fn.coopCheckAllButton = function() {
    $(this).each( function() {
	var first_box = $(this).parents(".check_container:first").find(":checkbox:first");
	$(this).parents(".check_container:first").find(":checkbox")
	  .coopCheckboxCheck( !first_box[0].checked );
      });
  }
  return this;
 }) (jQuery);


// jQuery extension to uncheck the first checkbox
(function($) {
  $.fn.coopCheckSlave = function() {
    $(this).each( function() {
	var box = $(this).filter(":checkbox:first");
	if ( box[0].checked == false ) {
	  $(this).parents("*[check_container]:first").find(":checkbox:first")
	    .coopCheckboxCheck( false );
	}
      });
  }
  return this;
 }) (jQuery);


// jQuery extension for a blur on an all field, if nothing is checked, checks all
(function($) {
  $.fn.coopCheckBlurAll = function() {
    $(this).each( function() {
	var checked_boxes = $(this).parents("*[check_container]:first").find(":checkbox:checked");
	if ( !checked_boxes[0] )
	  $(this).parents("*[check_container]:first").find(":checkbox:first")
	    .coopCheckboxCheck()
	    .coopCheckAll();
      });
    return this;
  }
 }) (jQuery);


// jQuery extension to uncheck all other checkboxes
(function($) {
  $.fn.coopCheckOne = function() {
    $(this).each( function() {
	var box = $(this).filter(":checkbox:first");
	if ( box[0].checked )
	  $(this).parents("*[check_container]:first").find(":checkbox").not(box)
	    .coopCheckboxCheck( false );
      });
  }
 }) (jQuery);


// jQuery extension for a blur on an one field, if nothing is checked, checks the first
(function($) {
  $.fn.coopCheckBlurOne = function() {
    $(this).each( function() {
	var checked_boxes = $(this).parents("*[check_container]:first").find(":checkbox:checked");
	if ( !checked_boxes[0] )
	  $(this).parents("*[check_container]:first").find(":checkbox:first")
	    .coopCheckboxCheck();
      });
    return this;
  }
 }) (jQuery);


// jQuery extension to check a checkbox or a group of checkboxes
(function($) {
  $.fn.coopCheckboxCheck = function(check_state) {
    $(this).each( function() {
	if ( check_state == null )
	  check_state = true;
	$(this)
	  .filter(":checkbox").each( function() {
	      this.checked = check_state;
	    }).end()//.coopCheckboxColorAdjust().end()
	  .find(":checkbox").each( function() {
	      this.checked = check_state;
	    });//.coopCheckboxColorAdjust();
      });
    return this;
  }
 }) (jQuery);


// jQuery extension to change colors based on checking a checkbox
// changes the parent color to gray if the passed checkbox is unchecked, and black if checked
(function($) {
  $.fn.coopCheckboxColorAdjust = function() {
    $(this).each( function() {
	var box = $(this).filter(":checkbox");
	if ( box[0] && box[0].checked ) {
	  $(this).parent().addClass("checked")
	    .find("input:text").css("opacity", 1.0);
	}
	else {
	  $(this).parent().removeClass("checked")
	    .find("input:text").css("opacity", 0.5);
	}
      });
    return this;
  }
 }) (jQuery);
/* -----------------
   CROPPING CONTROLS
   ----------------- */

// sets up cropping
function setCropControls() {
  toggleCropControls( '#crop_header' );
  toggleCropControls( '#crop_footer' );
  $("span[crop_move]")
    .click(function() {
	var shift = parseInt($(this).attr("crop_move"));
	if ( $(this).parents('.crop_area:first').hasClass("cropFooter") )
	  backgroundMove('#crop_footer',shift);
	else
	  backgroundMove('#crop_header',shift);	  
      });
}

function toggleCropControls(image_id) {
  var image_y = parseInt($(image_id).attr('back_y_pos')); // negative position value
  var image_height = parseInt($(image_id).attr('back_height'));
  var window_height = 185;
  if ( $(image_id).parent().hasClass("imageFooter") )
    window_height = 120;
  
  var max_up =  window_height - image_y - image_height;
  var max_down = 0 - image_y;
  
  $(image_id).parents(".crop_area:first").find("span[crop_move]")
    .each(function(){
	var shift = parseInt($(this).attr("crop_move"));
	if ( ( shift < 0 && shift >= max_up ) || ( shift > 0 && shift <= max_down ) )
	  $(this).removeClass('disableCrop');
	else
	  $(this).addClass('disableCrop');	  
      });
}

function backgroundMove(image_id,shift) {
  var obj = $(image_id);
  var footer = $(obj).parent().hasClass("imageFooter");
  var image_y = parseInt($(obj).attr('back_y_pos'));
  var image_height = parseInt($(obj).attr('back_height'));
  var new_y = image_y + shift;
  var window_height = 185;
  if (footer)
    window_height = 120;
  if ( new_y > 0 )
    new_y = 0;
  else if ( new_y < window_height - image_height)
    new_y =  window_height - image_height;
  var set_new_position = "0px "+new_y+"px";
  $(obj)
    .animate({backgroundPosition: set_new_position})
    .attr('back_y_pos',new_y);
  new_y = new_y*(-1);
  $(obj).parents(".crop_area:first").find("input[name='crop_y']").val(new_y);
  toggleCropControls(image_id);
}
function noYear(ele) {
  var obj = $(ele);
  obj.value = obj.value.slice(0,5);
}
// checks for an enter then executes convertMoney
function moneyPress(obj, e) {
  var key = e.which;
  if (!key)
    key = e.keyCode;
  if ( key == 13 )
    convertMoney(obj);
}


// takes a cost field as an object, determines whether it has one or two prices inputted, passes those values to parseCost, and then reformats the field
function convertMoney(obj) {
  var string = obj.value.toLowerCase();
  if ( string.match('free') )
    obj.value = "free";
  else if ( string.match('tba') )
    obj.value = "tba";
  else {
    stringLen = string.length;
    var newValue = '';
    for ( i=0; i < stringLen; i++ )
      if ( string.charAt(i) == '.' || ( parseFloat(string.charAt(i)) || parseFloat(string.charAt(i)) == "0" ) )
	newValue = newValue + string.charAt(i);
    if ( newValue == '' )
      obj.value = "";
    else 
      obj.value = '$' + parseFloat(newValue).toFixed(2);
  }
}
/*********************
 ORDERED LIST CONTROLS new
*********************/

// sets controls for a sequenced ordered list 
function setOrderedListControls() {


  //adds an item to an ordered list
  $('.add_item').live("click", function(){

      //find the list
      var list_container = $(this).parents(".input_list:first");
      var list_ul = $(list_container).children("ul:first");
      var num_items = $(list_ul).children().length;

      //clone the item
      var item_copy = $(list_container).children('.input_list_element:first').children(':first').clone(true);
      $(item_copy)
	//hide the cloned item
	.hide()
	//add the item to the bottom of the list
	.appendTo(list_ul);

      //fix the list
      listAdjust(list_ul);

      $(item_copy)
	//reveal the item
	.slideDown('normal',function() {
	    //focus on the first input in the item
	    $(item_copy).find('input:first').focus();
	  });
    });


  $('.move_item').live("click", function(){ //moves an item up one position
      clearSuggest(1);
      var item = $(this).parents(".list_item:first");
      var list = $(item).parent();
      var prevSibs = $(item).prevAll();
      if ( prevSibs[0] ) { //check to see if there are any items to move above
	var itemCopy = $(item).clone(true); //clone container
	$(itemCopy).hide(); //hide clone
	var itemBefore = $(item).prev(); //get the item before
	$(item).slideUp('normal',function(){ //hide item
	    $(this).remove(); //remove it
	    $(itemBefore[0]).before(itemCopy); //insert the copy
	    listAdjust(list); //fix the list
	    $(itemCopy).slideDown(); //reveal the copy
	  });
      }
    });


  $('.delete_item').live("click", function() { //deletes an item
      clearSuggest(1);
      var item = $(this).parents(".list_item:first");
      var list = $(item).parent();
      var items = $(list).children(".list_item");
      var next_level_item = $(list).parent(".list_item:first");
      $(item)
	.find('input').val("").end() //clear inputs in the item
	.find('select').val('0').end() //clear selects in the item
	.find('.list_attr input').remove().end()
	.find('.list_attr_active').removeClass('list_attr_active');
      if ( items[1] ) //check to see if there's more than 1 item
	$(item).slideUp('normal', function(){ //hide the item
	    $(this).remove(); //remove the item
	    //fix the list
	    listAdjust(list); 	    
	  });
      else {
	$(item).find('.input_list').children('.list_item:not(:first)').slideUp('normal',function() {
	    //find all the children of any lists inside and remove all but one of them	    
	    $(this).remove();
	  });
	$(item).find("input:first").focus();
	//fix the list
	listAdjust(list); 	    
      }
    });


  $('.list_attr').live("click", function() {
      var attr_value = $(this).attr("attr_value");
      var list_name = $(this).attr("list_name");
      if ( $(this).hasClass("list_attr_active") )
	$(this)
	  .removeClass("list_attr_active")
	  .find("input").remove();
      else
	$(this)
	  .addClass("list_attr_active")
	  .append('<input type="hidden" name="' + list_name + '[]" value="' + attr_value + '">')
	  .siblings()
	    .removeClass("list_attr_active")
	    .find("input").remove();
    });
}


//adjust lastItem class, and calls any list specific changes
function listAdjust(list) {
  var label = $(list).attr("label_name");
  var number_labels = $(list).attr("number_labels");
  var number_labels_reverse = $(list).attr("number_labels_reverse");
  var alt_first_item_number = $(list).attr("alt_first_item_number");
  var items = $(list).children();
  var item_count = items.length;
  var new_label;
  var new_label_number;
  var new_id;

  for (i=0; i < item_count; i++) { //loop items

    // fix labels
    if ( label ) {
      if ( number_labels_reverse )
	new_label_number = numSuffix(item_count-i);
      else if ( number_labels )
	new_label_number = numSuffix(i+1);
      
      if ( ( i==0 && item_count > 1 ) && alt_first_item_number )
	new_label = alt_first_item_number + " " + label.toLowerCase();
      else if ( ( ( i==0 && item_count > 1 ) && number_labels ) ||
		( i!=0 && number_labels ) )
	new_label = new_label_number + " " + label.toLowerCase();
      else
	new_label = label;    
      
      $(items[i]).find("label:first").not($(items[i]).find(".input_list").find("label"))
	// change the name of the item
	.html(new_label)
	// fix fors for ids
	.attr("for",label+i);
      
      // fix ids
      $(items[i]).find("input:first").not($(items[i]).find(".input_list").find("input"))
	.attr("id",label+i);
    }
    
    // fix moves and conjunctions
    if ( i==0 )
      $(items[i])
	// right now this is really tailored for the conjunctions, will have adjust to extend
	.find(".list_attr_group").not($(items[i]).find(".input_list").find(".list_attr_group"))
	  .find(".list_attr")
	    .removeClass("list_attr_active")
	    .find("input").remove().end().end()
	  .hide().end().end()
	.find(".move_item").not($(items[i]).find(".input_list").find(".move_item")).hide()
	// this takes care of the pipe
	.next().hide();
    else
      $(items[i])
	// right now this is really tailored for the conjunctions, will have adjust to extend
	.find(".list_attr_group").not($(items[i]).find(".input_list").find(".list_attr_group")).show().end().end()
	.find(".move_item").not($(items[i]).find(".input_list").find(".move_item"))
	// this takes care of the pipe
	.show().next().show();
    
    if ( i == item_count-1 )
      $(items[i])
	// add last_item class to last item
	.addClass("last_item")
	// checks if there's an add button in the item, only for events right now
	.find(".add_item").not($(items[i]).find(".input_list").find(".add_item")).slideDown("fast");
    else  
      $(items[i])
	// remove last_item class
	.removeClass("last_item")
	// checks if there's an add button in the item, only for events right now
	.find(".add_item").not($(items[i]).find(".input_list").find(".add_item")).hide();
  }
}



//adds number suffix to a number
function numSuffix(num) {
  var num = num.toString(); //change from a integer to a string
  var num_length = num.length; //get the number of characters
  var num_tens = num.charAt(num_length-2); //find 10's value
  var num_ones = parseInt(num.charAt(num_length-1)); //find the 1's value
  //return an adjusted number
  if (num_tens == "1" || ( num_ones > 3 || num_ones == 0 ) )
    return num+"th";
  else if (num_ones == 1 )
    return num+"st";
  else if (num_ones == 2 )
    return num+"nd";
  else if (num_ones == 3 )
    return num+"rd";
}

/*********************/
function buildDateElement(selectedDate,dateString) {
  var writeDate = '<b>' + selectedDate.getMonthName(1) + ' ' + selectedDate.getDate() + ', ' + selectedDate.getFullYear() + '</b> (' + selectedDate.getDayName() + ')';
  var dateCopy = $('#hiddenDate').children('li:first').clone();
  $(dateCopy)
    .attr('id',dateString)
    .find('div.dateDate')
      .prepend(writeDate)
      .children('span')
      .click(function() {
	  addTime(this,dateString);
	}).end().end()
    .append(buildTime(dateString));
  return dateCopy;
}

function buildTime(dateString) {

  var doorSet = $('#dates').attr('door');
  var timeSet = $('#dates').attr('time');
  var timeCopy = $('#hiddenTime').children('div.dateTime:first').clone();

  $(timeCopy)
    .children('input[type="hidden"]').val(dateString)
    .next().find('input').attr('value',doorSet).end()
    .next().next().find('input').attr('value',timeSet);
  return timeCopy;
}
/*** swaps from the location select field to an input box ***/
function locationSwitch(obj) {
  if ( $(obj).val() == "other" )
    $('#location_select').fadeOut('normal', function() {
	$('#location_input').fadeIn();
      });
}
function setDatePicker(past){
  var limitDate = new Date().addYears(1).asString();
  if ( past )
    var beginDate = new Date().addYears(-1).asString();
  else
    var beginDate = new Date().asString();

  $('#datepicker')
    .siblings(".pseudo_link")
      .click(function() {
	  setDatePicker(1);
	}).end()
    .datePicker({
	inline:true,
	  selectMultiple:true,
	  showYearNavigation:false,
	  endDate:limitDate,
	  startDate:beginDate
	  })
    .unbind('dateSelected')
    .bind(
	  'dateSelected',
	  function(e, selectedDate, $td, state)
	  {
	    var dateString = selectedDate.getFullYear()*10000 + (selectedDate.getMonth()+1)*100 + selectedDate.getDate();
	    var dateEles = $('#dates').find('li');
	    var dateElesLen = dateEles.length;
	    
	    for ( i = 0; i < dateElesLen; i++)
	      if ( dateString == dateEles[i].id )
		state = 0;
	    
	    if ( state ) {
	      var content = buildDateElement(selectedDate,dateString);
	      if ( !dateEles[0] )
		$('#dates').append(content);
	      else {
		for ( i = 0; i < dateElesLen; i++) {
		  if ( dateString < dateEles[i].id ) {
		    $(content).insertBefore(dateEles[i]);
		    i = dateElesLen;
		  }
		  else if ( i == dateElesLen - 1 )
		    $('#dates').append(content);
		}
	      }
	      $('#' + dateString).slideDown('normal')
		.find('#door-' + dateString + ',#time-' + dateString);
	    }
	    else {
	      var classDateString = '.' + dateString;
	      $('#' + dateString).slideUp('medium', function(){
		  $(this).remove();
		});
	    }
	  });
}
function setTicketDatePicker() {
  var limitDate = new Date().addYears(1).asString();
  $('#on_sale')
    .datePicker({
      clickInput:true,
	  showYearNavigation:false,
	  endDate:limitDate,
	  createButton:false
	  });
}
// SUGGEST BOX FUNCTIONS =================================================

/* Suggestion functions */
var select = 0;
var sugNum = 0;
var sugType = '';
var sugForm = null;


function setTokens() {
  $("div.token div[kill]").live("click", function() {
      $(this).parent().remove();
    });
  $("a[quick_tokens]").live("click", function(event) {
      event.preventDefault();
      var token_type = $(this).attr("quick_tokens");
      var token_container = $(this).attr("token_container");
      var token_name = $(this).html();
      var token_val = $(this).attr("token_val");
      tokenize( token_name, token_val, token_type, token_container );
    });
}


function clearSuggest( immediate ){
  var obj  = $("#suggest");
  if (obj) {
    var time_delay = 400;

    if ( immediate )
      time_delay = 0;
    
    var clear = function(){
      $(obj)
      .css("visibility","hidden")
      .css("width","0px")
      .html("");
    };
    setTimeout(clear,time_delay);
    select = 0;
  }
}

/* fillSuggest Helper function - looks to be obsolete
function fS( obj, name, input ){
  if( name.search("genre") == -1 && gA(obj, input) == 0 ){
    $(name).value = "";
  }
  else{
    $(name).value = gA(obj, input);
  }
  $(name).style.color = "#000";
  }*/

// Fill form with selected suggest
function fillSuggest( index, name, token ){
  var token_val = $("#suggest_"+index).attr("token_val");

  if ( token_val ) {
    if ( !token )
      var token = name;
    var token_name = $("#suggest_"+index).text();
    tokenize(token_name, token_val, token);
  }
  else {
    clearSuggest( );
    $(sugForm).val($("#suggest_"+index).text());
  }
}


//creates and places the token
function tokenize ( token_name, token_val, token, token_container ) {
  var new_val = 0;
  var tokens_box;
  if ( !token_name ) {
    token_name = $(sugForm).val();
    token_val = token_name;
    new_val = 1;
  }

  if ( ( token == "friend" && new_val ) && !validate_email( token_val ) ) {
    alert("Email address is invalid.");
    return false;
  }

  else {
    clearSuggest(1);

    var token_piece = '<div class="token"><div>'+token_name+'<input type="hidden" name="'+token+'_val[]" value="'+token_val+'" /></div><div kill="1">x</div></div>';

    if (sugForm) {
      tokens_box = $(sugForm).parents(".token_box:first").find(".tokens");
      $(sugForm).val("");
    }
    else
      tokens_box = $("#"+token_container).find(".tokens");

    var duplicate = 0;

    $(tokens_box).find("div.token").each(function() {
	if ( $(this).html() == $(token_piece).html() )
	  duplicate = 1;
      });

    if ( !duplicate )
      $(tokens_box).append(token_piece);
  }
}


function validate_email(str) {
  var at="@";
  var dot=".";
  var lat=str.indexOf(at);
  var lstr=str.length;
  var ldot=str.indexOf(dot);
  
  if ( (str.indexOf(at)==-1) ||
       (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) ||
       (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) ||
       (str.indexOf(at,(lat+1))!=-1) ||
       (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) ||
       (str.indexOf(dot,(lat+2))==-1) ||
       (str.indexOf(" ")!=-1) ) {
    return false;
  }
  else
    return true;
}


// Set Select
function setSelect( a ){
  var os = select;
  select = ( select < 0 ) ? 0 : a;

  if( select > 0 ){
    var o;
    if( o = gE("suggest_"+select) ) {
      $(o).attr("class","suggest_sel");
      if( os > 0 )
	$( "#suggest_" + os ).attr("class","suggest");
    }
    else {
      select = os;
    }
  }

  else if ( os > 0 )
    $( "#suggest_" + os ).attr("class","suggest");
}


// Send AJAX suggestion query 
function suggest( name, form, e, token ){
  
  var obj = $("#suggest");
  var serverPage = "suggest.php?subject="+name;
  var value = form.value;
  var metro = $("#metro_select");
  if ( metro )
    var metro_num = $(metro).attr("value");
  sugNum = (name == 'band' ) ? form.id.substr(4) : '';
  sugType = name;
  sugForm = form;
  var key;
    
  if ( window.event )
    key = window.event.keyCode;
  else if (e.which)
    key = e.which;

  if( key==38 ||  key==63232 ){ // Up arrow
    setSelect(select-1); return;
  }
  else if( key==40 || key==63233 ){ // Down arrow
    setSelect(select+1); return;
  }
  else if( key==13 ) { // Enter
    if( select > 0 )
      fillSuggest(select, name, token);
    else
      tokenize(0, 0, token);
    return false;
  }
  else if( key==9 || key==16 ){ // Tab or Shift
    return;
  }
  else if( token && ( key==32 ) ) //Token and space
    tokenize(0, 0, token);


  if( key == 8 ) {  // Backspace
    if( value.length > 1 )
      serverPage += "&q=" + value.substr(0, (value.length-1));

    else{ // Empty
      clearSuggest();
      return;
    }
  }

  else  // normal char
    serverPage += "&q=" + value + String.fromCharCode( key );

  //set metro
  if ( metro )
    serverPage += "&m=" + metro_num;

  $(obj)
    .css("visibility","visible")
    .css("width", form.offsetWidth-2 + "px")
    .css("left", findPos(form,"offsetLeft")+"px")
    .css("top", findPos(form,"offsetTop") + form.offsetHeight-1+"px");
  
  $.get( serverPage, function(data){
      $(obj).html(data);
    });
}
//TIME FUNCTIONS ==========================================================


/*** creates a time object from a text field ***/
function time_ele(obj) {
  var timeEle = new timeParse( $(obj).val() );
  this.hour = timeEle.hour;
  this.minute = timeEle.minute;
  this.minute = timeEle.minuteWrite;
  this.meridian = timeEle.meridian;
  this.compare = timeEle.compare;
  this.obj = obj;
  this.val = $(obj).val();
  if ( $(obj).hasClass("door") || $(obj).attr('id') == 'door')
    this.type = "door";
  else
    this.type = "time";
  this.timeAdjust = timeAdjust; //resets the field as per what was interpretted
}


/*** parses a time string and returns values ***/
function timeParse( time_string ) {
  if ( time_string == "midnight" )
    time_string = "12:00 am";
  else if (  time_string == "noon" )
    time_string = "12:00 pm";

  var colon = time_string.search(':'); //find a colon
  var hour;
  var minute;
  var compare = null;
  var time_string_len = time_string.length;
  var num_string = "";
  var w_hour;
  var w_minute;
  var meridian = "pm";
  if ( time_string.match('a') || time_string.match('A') )
    meridian = 'am';

  if ( colon > 0 ) {
    w_hour = (colon == 1 ) ? time_string.charAt(0) : time_string.slice(0,colon);
    hour = parseFloat(w_hour); // string to float
    if ( hour > 12 && hour < 25 ) { // converts from military time
      hour = hour - 12;
      meridian = "pm";
    }
    else if ( hour < 1 || hour > 24 ) // check to see if the hour is a bad value
      hour = null;
    w_minute = time_string.charAt(colon+1) + time_string.charAt(colon+2); // takes the minute as the next two characters after the colon
    minute = parseFloat(w_minute); // string to float
    if ( !( minute >= 0 && minute < 60 ) ) { // checks if the minute is a bad value
      minute = 0;
    }
  }

  else if (time_string) {
    for ( i=0; i < time_string_len; i++) {
      if ( time_string.charAt(i) >= 0 && time_string.charAt(i) <= 9 )
	num_string += time_string.charAt(i);
    }

    if ( num_string.length >= 4 ) {
      w_hour = num_string.slice(0,2);
      w_minute = num_string.slice(2,4);
    }
    else if ( num_string.length == 3 ) {
      w_hour = num_string.charAt(0);
      w_minute = num_string.slice(1,3);
    }
    else if ( num_string ) {
      w_hour = num_string;
      w_minute = 0;
    }
    else {
      w_hour = 0;
      w_minute = 0;
    }

    hour = parseFloat(w_hour); // string to float
    minute = parseFloat(w_minute); // string to float
    
    if ( hour > 12 && hour < 25 ) { // converts from military time
      hour = hour - 12;
      meridian = "pm";
    }
    else if ( hour < 1 || hour > 24 ) // check to see if the hour is a bad value
      hour = null;

    if ( !( minute >= 0 && minute < 60 ) ) { // checks if the minute is a bad value
      minute = 0;
    }
  }

  if ( hour ) { // creates the comparison value - 5am is 0, 4:30am is 2330
    if ( meridian == "pm" && hour < 12)
      compare = (hour + 7)*100 + minute;
    else if ( meridian == "am" && hour == 12 )
      compare = 1900 + minute;
    else if ( hour < 5 )
      compare = (hour + 19)*100 + minute;
    else
      compare = (hour - 5)*100 + minute;
  }
  else {
    hour = null;
    minute = null;
    meridian = null;
    compare = null;
  }

  this.hour = hour;
  this.minute = minute;
  if ( minute < 10) // creates a minute variable that will always have two digits
    this.minuteWrite = "0" + minute;
  else
    this.minuteWrite = minute;
  this.meridian = meridian;
  this.compare = compare;

}


/*** adjusts the time in a time field ***/
function timeAdjust(time, up, increment) {
  var time_value = new timeParse(time);
  var new_value;

  if ( !time_value.hour )
    new_value = ""; //dumps if the field is clear
  else // sets the field to the time value
    new_value = time_value.hour + ":" + time_value.minuteWrite + " " + time_value.meridian;
  
  for ( i=0; i<increment; i++ ) // adjust up or down if set
    if ( up )
      new_value = timeUp(new_value);
    else
      new_value = timeDown(new_value);

  if ( new_value == "12:00 am" )
    new_value = "midnight";
  else if ( new_value == "12:00 pm" )
    new_value = "noon";
  
  $(this.obj).val(new_value); // sets the new value
  this.val = new_value; // corrects the value on the time object
}


/*** moves the time up half an hour ***/
function timeUp(value) {
  var timeVal = new timeParse(value);
  var hour = timeVal.hour;
  var minute = timeVal.minute;
  var meridian = timeVal.meridian;

  if ( hour ) {
    if (minute < 30) {
      return hour + ':30 ' + meridian;
    }
    else {
      if (hour < 11) {
	hour++;
	return hour + ':00 ' + meridian;
      }
      else if (hour == 11) {
	  meridian = (meridian == 'am') ? 'pm' : 'am';
	  return '12:00 ' + meridian;
      }
      else
	return '1:00 ' + meridian;
    }
  }
  else 
    return "";
}


/*** moves the time down half an hour ***/
function timeDown(value) {
  var timeVal = new timeParse(value);
  var hour = timeVal.hour;
  var minute = timeVal.minute;
  var meridian = timeVal.meridian;

  if ( hour ) {
    if (minute > 0 && minute <= 30) {
      return hour + ':00 ' + meridian;
    }
    else if (minute > 30){
      return hour + ':30 ' + meridian;
    }
    else {
      if (hour > 1 && hour < 12) {
	hour--;
	return hour + ':30 ' + meridian;
      }
      else if (hour == 12) {
	meridian = (meridian == 'am') ? 'pm' : 'am';
	return '11:30 ' + meridian;
      }
      else
	return '12:30 ' + meridian;
    }
  }
  else 
    return ""; 
}


/* checks if a focused field doesn't have a value
 * if the other field has a value, moves an hour off
 * else sets the default time
 */
function timeFocus(obj) {
  var this_time = new time_ele(obj);
  var other_time = timeOther(obj);
  if ( this_time.val == "" ) {
    if ( this_time.type == "door" ) {
      if ( other_time.hour ) // if the other field is set
	this_time.timeAdjust(other_time.val, 0, 2); // -1hr
      else
	this_time.timeAdjust('8:00 pm'); // defaults to 8pm
    }
    else {
      if ( other_time.hour ) // if the other field is set
	this_time.timeAdjust(other_time.val, 1, 2); // +1hr
      else
	this_time.timeAdjust('9:00 pm'); // defaults to 9pm
    }
  }
}


/*** finds the other field's time value ***/
function timeOther(obj) {
  var this_time = new time_ele(obj);
  var capsule = $(obj).parents('.time_container:first');
  if ( this_time.type == "door" )
    return new time_ele($(capsule).find(".time:first")); // looks ahead for an input field
  else
    return new time_ele($(capsule).find(".door:first")); // looks behind for an input field


  //  if ( $(obj).parent().parent().hasClass('dateTime') ) //checks for submission page structure - might want to normalize these at some point
  //if ( this_time.type == "door" )
  //  return new time_ele($(obj).nextAll("input:first")); // looks ahead for an input field
  //else
  //  return new time_ele($(obj).prevAll("input:first")); // looks behind for an input field
  //else
  //if ( $(obj).hasClass('id') == 'door')
  //  return new time_ele( $('#time') );
  //else
  //  return new time_ele( $('#door') );
}


/* adjusts the other time field to jive with the new value in the selected field
 * door times must be equal to or less than the show times
 * no more than 18hrs difference is allowed (1800)
 * sets the default value to the other field value
 */
function timeJive(obj) {
  var this_time = new time_ele(obj);
  var other_time = timeOther(obj);

  if ( ( this_time.hour && other_time.hour ) && 
       ( ( this_time.type == "door" && ( this_time.compare > other_time.compare ||
					 other_time.compare - this_time.compare > 1800 ) ) ||
	 ( this_time.type == "time" && ( this_time.compare < other_time.compare ||
					 this_time.compare - other_time.compare > 1800 ) )
	 ) ) {
    other_time.timeAdjust(this_time.val);
    $('#dates').attr(other_time.type,this_time.val); // sets new default time
  }
}


/* when a time field is blurred
 * corrects the field to the interpretted time
 * looks for other blank time fields of the same type and sets them to the same time
 * sets or clears the default time for the type
 */
function timeBlur(obj) {
  var this_time = new time_ele(obj);

  if ( this_time.hour ) {
    this_time.timeAdjust(this_time.hour + ":" + this_time.minute + " " + this_time.meridian);
    var timeInstances = $('#dates').find('input.'+this_time.type); // finds other fields of the same type
    var timeLen = timeInstances.length;
    for ( i=0; i < timeLen; i++)
      if ( !$(timeInstances[i]).attr('value') ) // checks to see if it's blank
	$(timeInstances[i]).attr('value',this_time.val); // sets to the same value
    $('#dates').attr(this_time.type,this_time.val); // sets new default time
  }
  else {
    $(obj).val("");
    $('#dates').removeAttr(this_time.type); // clears default time if blank
  }

  timeJive(obj);
}


/* looks for an arrow key press and sends the field to timeAdjust
 * does a timeJive if there's an adjust
 */
function timePress(obj, e) {
  var this_time = new time_ele(obj);
  var new_value = 0;
  var key;
    
  if ( window.event )
    key = window.event.keyCode;
  else if(e.which)
    key = e.which;

  if( key==38 || key==63232 ) {
    this_time.timeAdjust(this_time.val, 1, 1);
    timeJive(obj);
  }
  else if( key==40 || key==63233 ) {
    this_time.timeAdjust(this_time.val, 0, 1);
    timeJive(obj);
  }
}





// takes the value entered in a time field, guesses at the value, and returns that time to the field
function convertTime( objValue ) {
  objValue = objValue.toLowerCase();
  var hour = 0;
  var minute = 0;
  var meridian = 0;
  if ( objValue.match('p') || objValue.match('pm') )
    meridian = 'PM';
  else if ( objValue.match('a') || objValue.match('am') )
    meridian = 'AM';
  var hours = ['noon','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','midnight'];
  for ( i=0; i<14; i++ )
    if ( objValue.match(hours[i]) )
      if ( i==0 ){
	hour = 12;
	meridian = 'PM';
      }
      else if ( i==14 ){
	hour = 12;
	meridian = 'AM';
      }
      else
	hour = i;
  var minutes = ['clock','fifteen','thirty','five','forty'];
  for ( i=0; i<5; i++ )
    if ( objValue.match(minutes[i]) )
      if ( i==1 ){
	minute = 15;
      }
      else if ( i==2 ){
	minute = 30;
      }
      else if ( i==3 || i==4 ){
	minute = 45;
      }
  objValueLen = objValue.length;
  var newValue = '';
  for ( i=0; i < objValueLen; i++ )
    if ( ( objValue.charAt(i) == '.' || objValue.charAt(i) == ':' ) || parseFloat(objValue.charAt(i)) )
      newValue = newValue + objValue.charAt(i);
  if ( newValue != '' || parseFloat(newValue) ){

    determineNumbers();

  }


  returnFindings();


}


function addTime(obj,dateString) {
  var content = buildTime(dateString,1);
  $(obj).parent().parent().append(content);
  $(obj).parent().parent().find('div.dateTime:last').slideDown();
}


function removeTime(obj) {
  var dateElement = $(obj).parent().parent();
  var times = $(dateElement).find('.dateTime');
  $(obj).parent()
    .find('input[name^=door]').attr('value','').end()
    .find('input[name^=time]').attr('value','');
  if ( times[1] )
    $(obj).parent().slideUp('normal',function(){
	$(this).remove();
      });
  else {
    $(dateElement).slideUp('normal',function(){
	$(this).remove();
      });
    //$('#datepicker').dpSetSelected(dateRemove,0,1);
  }
}

//set radio label states
function radioColor(obj,name){
  var ele = $(obj).parent();
  var initialSelect = $(ele).attr('sel');
  var newSelect = $('#' + $(obj).attr('for')).attr('value');
  $(ele).find('label').removeClass('radioselect');
  if (initialSelect == newSelect) {
    $(ele).attr('sel','0');
    $('#' + name + 'kill').attr('value','1');
  }
  else {
    $(obj).addClass('radioselect');
    $(ele).attr("sel",newSelect);
    $('#' + name + 'kill').attr('value','0');
  }
}
// checks to see if return has been pressed, and returns false if so to avoid form submission
function setForms (e) {
  
  $("form.noEnter, #hiddenBand, #hiddenDate, #hiddenTime").find("input[type!='submit'],select,option").keypress(function (e) {
      var key;
      
      if ( window.event )
	key = window.event.keyCode;
      else if(e.which)
	key = e.which;
      
      if(key == 13 ) 
	return false;
      else
	return true;
      });
}
// sets any date pickers with the class 'pastDate' a date picker so any dates in the past can be entered
function setPastDatePicker() {
  var limitDate = new Date().asString();
  $('input.pastDate')
    .datePicker({
      clickInput:true,
	  startDate:"01/01/1900",
	  endDate:limitDate,
	  createButton:false
	  });
}


// sets any date pickers with the class 'futureDate' a date picker so any dates in the future can be entered
function setFutureDatePicker() {
  var limitDate = new Date().asString();
  $('input.futureDate').datePicker({
    clickInput:true,
	startDate:limitDate,
	createButton:false
	});
}


// sets any date pickers with the class 'anyDate' a date picker so any dates can be entered
function setAnyDatePicker() {
  $('input.anyDate').datePicker({
    startDate:'01/01/2000',
    clickInput:true,
	createButton:false
	});
}
function setQuickFills() {
  $('*[quickFill]').click(function(){
      var newContent = $(this).attr('quickFill');
      var target = $(this).parents('p:first').find('input:first');
      var curContent = $(target).val();
      if ( newContent == curContent)
	$(target).attr('value','');
      else
	$(target).attr('value',newContent);
    });
}
//RADIO BUTTONS ====================================================

//makes it so you can turn off a radio button set by clicking a set radio button
function setRadioButtons() {
  $("input:radio")
    .click(function(event) {
	if ( $(this).attr("wasSelected") ) {
	  this.checked = false;
	  $(this).removeAttr("wasSelected");
	}
	else {
	  this.checked = true;
	  $(this).attr("wasSelected","1").parent().siblings().find("input").removeAttr("wasSelected");
	}
      })
    .filter(":checked").attr("wasSelected","1");
}
// GOOGLE MAP FUNCTIONS ===================================================

// basic initialization function

var map;
var gdir = null;
var geocoder = null;
var venuePoint;

function initializeGoogleMap() {
  if (GBrowserIsCompatible()) {
    var map_canvas = $("#map_canvas");
    var vlat = $(map_canvas).attr("lat");
    var vlong = $(map_canvas).attr("long");

    venuePoint = new GLatLng( vlat, vlong );
    map = new GMap2( document.getElementById("map_canvas") );
    map.setCenter(venuePoint, 13);
    map.addControl(new GSmallZoomControl());
    map.addOverlay(new GMarker(venuePoint));
  }
}

//our function to determine if the default is set and hasn't changed, and that there is a lat/long
function parseDirections(obj) {
  var userAddress = obj.fromAddress.value;
  var directionsPanel;
  var userPoint;

  if ( !geocoder )
    geocoder = new GClientGeocoder();
  if ( !gdir ) {
    directionsPanel = document.getElementById("map_directions");
    gdir = new GDirections(map, directionsPanel);
    GEvent.addListener(gdir, "error", handleErrors );
  }

  if ( userAddress ) {
    userPoint = geocoder.getLatLng( userAddress,
					function(point) {
					  map.clearOverlays();
					  $('#map_directions').show();
					  gdir.loadFromWaypoints( [point, venuePoint],
								  { locale:"en_US" });
					});
  }
}

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
  
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

  //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
  //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
  else alert("An unknown error occurred.");
  
}
/* IMAGE SCALING ===================================================== */


function setImageScaling() {
  scaleImages();
  $(window).resize(function() {
      scaleImages();
    });
}

function scaleImages() {
  $("img.window_scale").each( function() {
      var image_height = $(this).attr("actual_height");
      var image_width = $(this).attr("actual_width");
      if ( !image_height ) {
	image_height = $(this).attr("height");
	image_width = $(this).attr("width");
	$(this).attr("actual_height", image_height);
	$(this).attr("actual_width", image_width);
      }

      var img_facebox = $(this).parents('#facebox');
      var window_adjust; 

      if ( img_facebox[0] )
	window_adjust = $('#facebox').find('.secondary_header').height() + $(window).height()/20 + 60;
      else
	window_adjust = $("#navigation_bar").height()

      var window_height = $(window).height() - window_adjust - 30;
      var org_width = image_width;

      image_height = ( image_height * 640 ) / image_width;
      image_width = 640;

      if ( image_height > window_height ) {
	image_width = ( image_width * window_height ) / image_height;
	image_height = window_height;
      }
      
      if ( org_width != image_width && ( image_height > 74 && image_width > 74 ) )
	$(this)
	  .attr("height", image_height)
	  .attr("width", image_width);
    });
}
// BAND LISTING FUNCTIONS =================================================

// set band elements on ratings page
function setRatingBands() {
  $("td.b_td").each(function() {
      readyBandsDOM(this);
    });
}

function bandPrep( bandUL ) {
  var eventID = $("#"+bandUL).attr("eID");
  $("#"+bandUL+" li").each(function() {
      readyBandsDOM(this, eventID);
    });
}

// take a band element and build it out with note links and stars
function readyBandsDOM(ele, eventID) {
  $(ele).one("mousemove", function(){
      var bandID = $(ele).attr('i');
      var performer_name = $(ele).find("a:not([vd])").html();
  
      $(this).find("div.u").addClass("r");

      $(ele)
	.find("a:not([vd])").attr("title","go to the "+performer_name+" page").end()
	.find("div.j")
	  .attr("title","listen to samples of "+performer_name)
	  .click(function(event) {
	      launch_sample(bandID, eventID);
	    }).end()
	.find("div.k")
	  .attr("title","listen to samples of "+performer_name+" on another site")
	  .parent()
            .attr("href","it.php?id="+bandID)
            .attr("target","_blank")
            .click(function(event) {
		reload_sample();
	      }).end().end()
	.find("div.o").parent().each(function() {
	    var videoCode = $(this).attr("vd");
	    $(this)
	      .attr("title","watch a video of "+performer_name)
	      .attr("pop_vid",videoCode);
	  }).end().end()
	.find("div.q")
	  .attr("title","view media from everyone in the show in 3D")
	  .click(function(){
	      PicLensLite.start({feedUrl:web_root + "shows/" + eventID + "/media/rss", paused:true});
	    });
    });
}
function nav_search_prep () {
  $(".navdiv form input")
    .live("click", function() {
	  $(".navdiv form").addClass("active");
      })
    .blur(function() {
	$(".navdiv form").removeClass("active");
      });
}
/* POP-UPS =========================================================== */


$(document).ready(function(){
    $(document).bind('reveal.facebox', function() { 
	coolirisCheck();
      });
  });


//takes a domain and re-casts it as the domain root to avoid cross-domain issues
function true_domain(cur_domain) {
  var coop_pos = cur_domain.search("concertcoop");
  if (coop_pos >= 0)
    return web_root + cur_domain.slice(coop_pos + 16);
  else
    return cur_domain;
}

    
function setPops() {
  $("a[pop_vid]").unbind().live("click", function() {
      $(document).one('reveal.facebox', function() {
	  $('#facebox').addClass("facebox_black");
	});
      var video_obj = new videoObj( $(this).attr('pop_vid') );
      jQuery.facebox(video_obj.code);
      $("#facebox_queue").html("");
      reload_sample();
      jQuery.get( web_root + "videos.php?id=" + video_obj.id + "&type=" + video_obj.type + "&pop=1&ajax", function(data) {
	  $(".facebox_content").prepend(data);
	});
      //jQuery.get( web_root + "videos.php?id=" + video_obj.id + "&type=" + video_obj.type + "&page=video_directories", function(data) {
      //  $("#facebox_queue").html(data);
      //});
      return false;
    });

  $("a[pop_img]").unbind().live("click", function(event) {
      event.preventDefault();

      var dest_url = true_domain( $(this).attr('href') );
      
      $(document).one('reveal.facebox', function() {
	  $('#facebox').addClass("facebox_black");
	});

      if ( dest_url.search('\\?') == -1 )
	dest_url = dest_url + "?pop=1";
      else if ( dest_url.charAt(dest_url.length-1) == "&" )
	dest_url = dest_url + "pop=1";
      else
	dest_url = dest_url + "&pop=1";
      
      var img_id_start = dest_url.indexOf('id=') + 3;
      var img_id_end = dest_url.indexOf('&',img_id_start);
      var img_id;
      if ( img_id_end == -1 )
	img_id = dest_url.substring(img_id_start);
      else
	img_id = dest_url.substring(img_id_start,img_id_end);

      var window_height = $(window).height() - 300;
      var link_string;

      var prev_image_id = $(this).attr('prev_img');
      if ( !prev_image_id && $(this).prev().is("a") )
	prev_image_id = $(this).prev().attr("id");
      if ( prev_image_id )
	prev_image_id = "&prev_image_id=" + prev_image_id;
      else
	prev_image_id = "";

      var next_image_id = $(this).attr('next_img');
      if ( !next_image_id && $(this).next().is("a") )
	next_image_id = $(this).next().attr("id");
      if ( next_image_id )
	next_image_id = "&next_image_id=" + next_image_id;
      else
	next_image_id = "";

      var dest_url = dest_url + "&ajax&window_height=" + window_height + prev_image_id + next_image_id;
      
      jQuery.facebox(function() {
	  jQuery.get( dest_url, function(data) {
	      $.facebox(data);

	      $(".facebox_content span[submit_contest]").click(function() {
		  var ele = this;
		  $(this).html("submitting...");
		  $.ajax({
		    type: "GET",
		  	url: web_root + "images.php?id=" + img_id + "&submit_contest=" + $(this).attr('submit_contest'),
		  	success: function() {
		  	$(".facebox_content span[submit_contest]")
		  	  .removeClass("pseudo_link")
		  	  .unbind("click")
		  	  .html('Submitted');
		      },
		  	failure: function() {
		  	$(".facebox_content span[submit_contest]").html('Unsuccessful - click to try again');
		      }
		    });
		});
	    });
	});
      return false;
    });
  
  $("span[pop_id]").unbind().live("click", function() {
      $( "#" + $(this).attr("pop_id") ).trigger("click");
    });

  $("a[pop_link]").unbind().live("click", function(event) {
      event.preventDefault();
      var dest_url =  $(this).attr('href');

      var facebox_black =  $(this).attr('pop_black');
    
      if ( dest_url.charAt(dest_url.length-1) == "&" )
	dest_url = dest_url + "pop=1";
      else if ( dest_url.search('\\?') > -1 || dest_url.search('&') > -1 )
	dest_url = dest_url + "&pop=1";
      else
	dest_url = dest_url + "?pop=1";

      dest_url = dest_url + "&ajax";

      if ( $(this).attr('pop_link') != '1' )
	dest_url = $(this).attr('pop_link');

      jQuery.facebox({ ajax: dest_url });
      if ( facebox_black )
	$(document).one('reveal.facebox', function() {
	    $('#facebox').addClass("facebox_black");
	  });
      else
	$('#facebox').removeClass('facebox_black');
      return false;
    });

  $("span[pop_div], a[pop_div]").unbind().live("click", function() {
      var div_id = "#" + $(this).attr('pop_div');
      var facebox_black =  $(this).attr('pop_black');
      if ( facebox_black )
	$(document).one('reveal.facebox', function() {
	    $('#facebox').addClass("facebox_black");
	  });
      else
	$('#facebox').removeClass('facebox_black');

      var content = $(div_id).html();
      if ( content )
	jQuery.facebox(content);
      return false;
    });

  //things to run before facebox launches
  $(document).bind('loading.facebox', function() {
      //if the facebox_black class has been added, removes it
      $('#facebox').removeClass('facebox_black');
    });


  //things to run on facebox launch
  $(document).bind('reveal.facebox', function() {
      //focuses on the first input field - currently not working on hidden fields in first position
      $('#facebox')
	.find("textarea").autogrow().end()
	.find(':input').filter(':visible').filter(':first').focus();
      scaleImages();
      setHeightConstraints();
      setUploadify("_pop");
      setCropControls();
    });

  $(window)
    .resize(function() {
	var left_pos = ( $(window).width() -  $('#facebox').width() ) / 2;
	$('#facebox').css( {left: left_pos});
      });
}


//takes the code we send for a video and parses it
//format is xxxHyyyTzzz - x is optional width (default is 600) - y is height - t is type - z is id
//embed code is also located in Elements/video_embed_.tpl
function videoObj( video_string ) {
  var id_loc = video_string.indexOf("I");

  if ( id_loc != 1 ) {
    var height_loc = video_string.indexOf("H");
    if ( height_loc > 0 )
      this.width = video_string.slice( 0, height_loc );
    this.height = video_string.slice( height_loc + 1, height_loc + 4 );
  }
  this.id = video_string.slice( id_loc + 1 );
  var typeChar = video_string.charAt( id_loc - 1 );

  if ( typeChar == "V" ) {
    if ( !this.width ) {
      this.width = 504;
    }
    this.type = "vimeo";
    this.url = "http://vimeo.com/moogaloop.swf?clip_id=" + this.id + "&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=FF6600";
    this.code = '<div class="box fiveSixths"><p class="center"><object type="application/x-shockwave-flash" width="' + this.width + '" height="' + this.height + '" data="' + this.url + '"><param name="quality" value="best" /><param name="allowfullscreen" value="true" /><param name="scale" value="showAll" /><param name="movie" value="' + this.url + '" /></object></p></div>';
  }
  else if ( typeChar == "Y" ) {
    if ( id_loc == 1 ) {
      this.width = 480;
      this.height = 385;
    }
    this.type = "youtube";
    this.url = "http://www.youtube.com/v/" + this.id;
    this.code = '<div class="box fiveSixths"><p class="center"><object width="' + this.width + '" height="' + this.height + '"><param name="movie" value="' + this.url + '"></param><param name="wmode" value="transparent"></param><embed src="' + this.url + '" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object></p></div>';
  }
}


function popFormClose(response) {
  if ( response ) {
    jQuery.facebox(response);
    setTimeout("jQuery(document).trigger('close.facebox')",1000)
  }
  else
    jQuery(document).trigger('close.facebox');
}
// REVIEW FUNCTIONS =========================================================

//preps good/bad review buttons
function setReviewButtons() {
  $('span.vote')
    .find('span.vote_yes, span.vote_no, span.voted_yes, span.voted_no')
    .click(function() {
	var topSpan = $(this).parents('span.vote:first');
	var postID = $(topSpan).attr('postID');
	
	if ( $(this).hasClass('vote_yes') ) {
	  $(topSpan)
	    .find('span.vote_record').fadeOut('normal',function(){
		$(this).siblings('span.voted_yes').fadeIn();
		voteAdjust(topSpan,1);
	      });
	  emptyAJAX('post.php?id='+postID+'&vote=1');
	}

	else if ( $(this).hasClass('vote_no') ) {
	  $(topSpan)
	    .find('span.vote_record').fadeOut('normal',function(){
		$(this).siblings('span.voted_no').fadeIn();
	      });
	  emptyAJAX('post.php?id='+postID+'&vote=2');
	}
	
	else {
	  if ( $(this).hasClass('voted_yes') )
	    voteAdjust(topSpan,-1);
	  $(this).fadeOut('normal',function(){
	      $(topSpan).find('span.vote_record').fadeIn();
	    });
	  emptyAJAX('post.php?id='+postID+'&vote=0');
	}
      });
}

function voteAdjust(obj, vote) {
  $(obj)
    .find('span.vote_total').each(function () {

	var current_total = parseFloat($(this).find("span:first").html());

	if ( vote == 1 ) {
	  current_total += 1;
	  $(this).find("span:first").html(current_total);
	  if ( current_total == 1 )
	    $(this).fadeIn();
	  else if ( current_total == 2 )
	    $(this).html($(this).html().slice(0,-13)+"s&nbsp;|&nbsp;");
	}

	else if ( vote == -1 ) {
	  current_total -= 1;
	  if ( !current_total ) {
	    current_total = "0";
	    $(this).fadeOut('normal',function() {
		$(this).find("span:first").html(current_total);
	      });
	  }
	  else {
	    if ( current_total == 1 )
	      $(this).html( $(this).html().slice(0,-14)+"&nbsp;|&nbsp;" );
	    $(this).find("span:first").html(current_total);
	  }
	}
      });
}
// STAR FUNCTIONS ==========================================================


// sets the stars that aren't in the listings
function setStarDivs() {
  $("div.r")
    .live( "mousemove", function(event) { 
	if ( $(this).attr("s") == null ) {
	  var class_string = $(this).attr("class");
	  var community_stars = (class_string.charAt(3)) ? class_string.charAt(3):0;
	  var user_stars = (class_string.charAt(4)) ? class_string.charAt(4):0;
	  var review_id;

	  if ( $(this).attr("i") == null )
	    $(this).attr("i", $(this).parents("[i]:first").attr('i') );

	  $(this)
	    .attr("s", community_stars)
	    .attr("m", user_stars);
	}
	starMove(this,event);
      })
    .live( "mouseout", function(event){ starReset(this,event); })
    .live( "click", function(event){ 
	starSet(this,event);
	return false;
      });
}


// prepares a star div by attaching the actions on a mouseover
function prepStar(obj,id) {
  $(obj).unbind().one('mousemove', function() {
      var class_string = $(this).attr("class");
      var community_stars = (class_string.charAt(3)) ? class_string.charAt(3):0;
      var user_stars = (class_string.charAt(4)) ? class_string.charAt(4):0;
      var review_id = id;

      if (!review_id) {
	if (  $(this).attr("i") )
	  review_id =  $(this).attr("i");
	else
	  review_id = $(this).parents("[i]:first").attr('i');
      }
      
      $(this)
	.attr("s", community_stars)
	.attr("m", user_stars)
	.mousemove( function(event){ starMove(this,event); })
	.mouseout( function(event){ starReset(this,event); })
	.click( function(event){ 
	    starSet(this,event,review_id);
	    return false;
	  });
    });
}


// would eventually like to replace these with a common function that handles any star element encountered

function starPosition(commStars, userStars, outlines) {
  var xCoord;
  var yCoord;
  if ( commStars == 0 && userStars == 0) {
    xCoord = 0;
    yCoord = 0;
  }
  else if ( userStars == 0 ) {
    xCoord = 5 - commStars;
    yCoord = 15;
  }
  else if ( outlines && commStars == 0) {
    xCoord = 0;
    yCoord = userStars;
  }
  else if ( commStars == 0 ) {
    xCoord = 5 - userStars;
    yCoord = 5;
  }
  else if ( userStars >= commStars ) {
    var diff = userStars - commStars;
    xCoord = 5 - userStars;
    yCoord = 6 + diff;
  }
  else if ( userStars < commStars ) {
    var diff =  commStars - userStars;
    xCoord = 5 - commStars;
    yCoord = 10 + diff;
  }
  return "-" + ( xCoord*14 ) + "px -" + ( yCoord*15 ) + "px";
}

// Function calculate stars 
function numStars(obj, ev){
  var mo = getMouseOffset(obj, ev);
  var star = Math.floor(mo.x/14) + 1;
  if( star > 5 )
    star = 5;    
  return star;
}

//sets star values
function setStarPosition(starDiv, community_stars, user_stars) {
  $(starDiv)
    .attr("m", user_stars)
    .attr("s", community_stars)
    .css("backgroundPosition", starPosition(community_stars, user_stars));
}

// Function sets stars to last user state 
function starReset(obj,ev){
  var user_stars = $(obj).attr("m");
  var community_stars = $(obj).attr("s");
  $(obj).css("backgroundPosition", starPosition(community_stars, user_stars));
}

// handle user moving over stars
function starMove(obj, ev){
  var mouse_stars = numStars(obj,ev);
  var community_stars = $(obj).attr("s");
  var user_stars = ( $(obj).attr("m") > 0 )? 0:1;
  $(obj).css("backgroundPosition", starPosition(community_stars, mouse_stars, user_stars));
}

// Function saves user's star rating
function starSet(obj,ev) {
  var new_stars = numStars(obj,ev);
  var current_stars = $(obj).attr("m");
  var community_stars = $(obj).attr("s");
  var id = $(obj).attr("i");

  if ( new_stars == current_stars)
    new_stars = 0;

  $("div[i="+id+"]").each(function() {
      setStarPosition(this, community_stars, new_stars);

      if ( new_stars > 3 )
	$(this).parent().find(".i a").addClass('l');
      else
	$(this).parent().find(".i a").removeClass('l');
    });

  var serverPage = "user_star.php?id=" + id + "&stars=" + new_stars + "&ajax";

  if (logged_in) {
    $.get(serverPage);
    return true;
  }
  else 
    location.href = serverPage + "&redirect";
}
/* STICKY NAVIGATION AND FIXED POSITION ====================================== */

// sets the sticky navigation
function stickyNav(){
  if ($.browser.msie && $.browser.version < 7) {
    $("#sticky_nav").remove();
    $("#sticky_sidebar").remove();
  }

  else {
    $("#sticky_nav").append($("#navigation_bar").contents().clone(true));
    keep_aligned( $("#sticky_nav"), "top", "center_coop", 0, 0, "header_plus_message");

    $("#sticky_sidebar").append($("#right_sidebar").contents().clone(true));
    keep_aligned( $("#sticky_sidebar"), "top", "sidebar", 0, 0, "header_plus_message");
  }

  setScroll();
}


function setScroll() {
  var offset_px = 1-$("#navigation_bar").height();
  $.localScroll({ offset: offset_px });
}


// makes adjustments to an object based on viewport movement
function keep_aligned(obj, vertical, horizontal, top_adj, left_adj, start_line) {
  $(window)
    .scroll(function() {
	set_obj_position(obj, vertical, horizontal, top_adj, left_adj, start_line);
      })
    .resize(function() {
	set_obj_position(obj, vertical, horizontal, top_adj, left_adj, start_line);
      });
}

// sets the position of an object
function set_obj_position(obj, vertical, horizontal, top_adj, left_adj, start_line) {
  var top_pos = top_adj;
  var left_pos = left_adj;
  var start_line_pos;

  // start line
  if ( start_line == "header_plus_message" )
    start_line_pos = $("#header_plus_message").height();

  // vertical
  if ( vertical == "bottom" )
    top_pos = top_pos + $(window).height() - $(obj).height();

  //horizontal
  if ( horizontal == "right" )
    left_pos = left_pos + $(window).width() - $(obj).width();
  else if ( horizontal == "center" )
    left_pos = left_pos + $(window).width()/2 - $(obj).width()/2;
  else if ( horizontal == "center_coop" )
    left_pos = left_pos + $(document).width()/2 - $(obj).width()/2 - $(window).scrollLeft() - 47.5;
  else if ( horizontal == "sidebar" )
    left_pos = left_pos + $(document).width()/2 - $(obj).width()/2 - $(window).scrollLeft() + 367.5;

  // body is padded - corrects for the right pad disappearing if window is small
  if ( $(window).width() < $(document).width() )
    left_pos = left_pos + 5;

  // corrects for IE8
  if ( $.browser.msie && $.browser.version == 8 )
    left_pos = left_pos - 16;

  // corrects for <IE7
  if ($.browser.msie && $.browser.version < 7) {
    top_pos = top_pos + $(document).scrollTop();
    left_pos = left_pos + $(document).scrollLeft();
  }



  $(obj).css({
    top:  top_pos,
    left: left_pos
	});

    if ( $(window).scrollTop() < start_line_pos || ( $(window).height() + 20 ) < $(obj).height() )
      $(obj).hide();
    else if ( $(window).scrollTop() >= start_line_pos && $(obj).is(":hidden") )
      $(obj).show();
}


// reloads a sample widget
function reload_sample() {
  $(".amazon_ASINList").each(function() {
      createAmazonSampleWidget(this);      
    });
}


// launches the amazon sample player
function launch_sample(band_id, event_id, album_id) {
  var page_string = web_root+"amazon_widget.php?";
  if ( band_id )
    page_string = page_string + "band_id=" + band_id + "&";
  if ( event_id )
    page_string = page_string + "event_id=" + event_id + "&";
  if ( album_id )
    page_string = page_string + "album_id=" + album_id;

  $.get(page_string, function(data){
      if ($.browser.msie && $.browser.version < 7)
	$("#sample_mini").css("position", "absolute");
      set_obj_position($("#sample_mini"), "top", "right", 0, 0);
      $("#sample_mini")
	.html(data);
      $("#sample_mini").find("div.amazon_ASINList").each(function() {
	  createAmazonSampleWidget(this);      
	}).end()
	.fadeIn("slow");
      keep_aligned($("#sample_mini"), "top", "right", 0, 0);
    });
}
// SCROLLING FUNCTION =====================================================
// prepare the sticky day headers
var dayObjs;
var curDay = -1;

$(document).ready(function() {
    dayObjs = $("div.day");

    if ($.browser.msie && $.browser.version < 7)
      $("#sticky_day").remove();
    else {
      $(window)
	.scroll(function() {
	    sticky_day();
	  })
	.resize(function() {
	    sticky_day();
	  });
    }
  });


function sticky_day() {
  var obj = $("#sticky_day");
  var sticky_nav_height = $("#sticky_nav").height();
  var newDay;

  if ( $(dayObjs[0]).offset().top - $(window).scrollTop() > sticky_nav_height ) {
    $(obj).hide();
    curDay = -1;
    $(".subnavdiv li[dayid]").removeClass("cur");
    $(".subnavdiv li[dayid]:not(.day_inactive):first").addClass("cur");
  }
  else {
    for ( var i=dayObjs.length-1; i >=0 ; i-- ) {
      if ( $(dayObjs[i]).offset().top - $(window).scrollTop() < (sticky_nav_height + 10) ) {
	newDay = i;
	break;
      }
    }
    if ( i != curDay ) {
      var day_elements = $(dayObjs[i]).contents().clone(true);
      $(obj).html( day_elements );
      var day_id = $(obj).attr("id");
      $(".subnavdiv li[dayid]").each(function() {
	  if ( $(this).attr("dayid") == $(dayObjs[i]).attr("id") ) {
	    $(this).addClass("cur")
	      .siblings(".subnavdiv li[dayid]").removeClass("cur");
	  }
	});
      curDay = i;
    }
    set_obj_position(obj, "top", "center_coop", sticky_nav_height, 0);
    $(obj).show();
  }
}
// SUBMIT AJAX ============================================================

function set_ajax_links() {
  $('a[al]').live('click', function(e) {
      e.preventDefault();

      var obj = $(this);
      var url_string = $(obj).attr('href');
      var cur_text = $(obj).html();
      var alt_url_string = $(this).attr("aurl");
      var alt_text = $(this).attr("atxt");
      var confirmed = 1;

      if ( cur_text == "Subscribed" || cur_text == "subscribed" )
	confirmed = confirm("Are you sure you want to unsubscribe from this reviewers picks?");
      else if ( cur_text == "Delete" || cur_text == "delete" || cur_text == "your friend")
	confirmed = confirm("Are you sure you want to delete this friend?");
      else if ( cur_text == "Revoke" || cur_text == "revoke" || cur_text == "pending friend" )
	confirmed = confirm("Are you sure you want to revoke this friend invitation?");

      if ( confirmed ) {
	if ( logged_in ) {
	  $(obj).html("saving...");

	  $.ajax({
	    type: "GET",
		url: url_string + "&ajax",
		success: function(data) {
		$(obj)
		  .attr("href",alt_url_string)
		  .attr("aurl",url_string)
		  .attr("atxt",cur_text)
		  .toggleClass("sel")
                  .html(alt_text);
	      },
		failure: function(){
		alert("There was an error saving your selection.");
		$(obj).html(cur_text);
	      },
		error: function(){
		alert("There was an error saving your selection.");
		$(obj).html(cur_text);
	      }
	    });
	}
	else
	  location.href = url_string + "&redirect";
      }
    });
}
var AudioPlayer=function(){var F=[];var C;var E="";var A={};var D=-1;function B(G){return document.all?window[G]:document[G]}return{setup:function(H,G){E=H;A=G},getPlayer:function(G){return B(G)},embed:function(K,O){var I={};var M;var G;var P;var H;var N={};var J={};var L={};for(M in A){I[M]=A[M]}for(M in O){I[M]=O[M]}if(I.transparentpagebg=="yes"){N.bgcolor="#FFFFFF";N.wmode="transparent"}else{if(I.pagebg){N.bgcolor="#"+I.pagebg}N.wmode="opaque"}N.menu="false";for(M in I){if(M=="pagebg"||M=="width"||M=="transparentpagebg"){continue}J[M]=I[M]}L.name=K;L.style="outline: none";J.playerID=K;audioplayer_swfobject.embedSWF(E,K,I.width.toString(),"24","9",false,J,N,L);F.push(K)},syncVolumes:function(G,I){D=I;for(var H=0;H<F.length;H++){if(F[H]!=G){B(F[H]).setVolume(D)}}},activate:function(G){if(C&&C!=G){B(C).close()}C=G},load:function(I,G,J,H){B(I).load(G,J,H)},close:function(G){B(G).close();if(G==C){C=null}},open:function(G){B(G).open()},getVolume:function(G){return D}}}()/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var audioplayer_swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in audioplayer_swfobject){audioplayer_swfobject[q]=null}audioplayer_swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();// Photo selection


function setBatchSelect() {
  $('#selected_photos .photo_element').live('click', function() {
      $(this)
	.clone().prependTo('#photo_pool');
      $(this)
        .fadeOut('normal', function() {
	    $(this).remove();
	    if ( $('#selected_photos').html() == "" )
	      $('#selected_photos').parents('form:first').find(':submit').attr('disabled','1');
	  });
    });

  $('#photo_pool .photo_element').live('click', function() {
      $(this)
	.clone().appendTo('#selected_photos');
      $(this)
        .fadeOut('normal', function() {
	    $(this).remove();
	  });
      $('#selected_photos').parents('form:first').find(':submit').removeAttr('disabled');
    });

  $('#remove_all').click(function() {
      $('#selected_photos').contents()
	.clone().prependTo('#photo_pool');
      $('#selected_photos').contents()
        .fadeOut('normal', function() {
	    $(this).remove();
	  })
	.parents('form:first').find(':submit').attr('disabled','1');
    });

  $('#add_all').click(function() {
      $('#photo_pool').contents()
	.clone().appendTo('#selected_photos');
      $('#photo_pool').contents()
        .fadeOut('normal', function() {
	    $(this).remove();
	  });
      $('#selected_photos').parents('form:first').find(':submit').removeAttr('disabled');
    });

  $('#pool_selector')
    .find(':submit').hide().end()
    .find('select').change(function() {
	$('#photo_pool').html('<div class="photo_element"><img src="' + web_root + 'Images/facebox_loading.gif" alt="loading..." /></div>');
	$.post(web_root+"fetch", { pool_selection : $(this).val() }, function(data) {
	    $('#photo_pool').html(data);
	    var selected_pool = $('#selected_photos .photo_element');

	    $('#photo_pool .photo_element').each(function() {
		for ( i=0; i < selected_pool.length; i++ )
		  if ( $(this).attr('id') == $(selected_pool[i]).attr('id') )
		    $(this).remove();
	      });
	  });
      });
}
//Flickr Function ==========================================================

function setFlickrGallery() {
   $(".flickr_container").each(function() {
       var payload = $(this).find(".flickr_badge_image");
       if ( payload[0]) {
	 $(this).show();
	 $(this).find(".flickr_badge_image a").attr("target","_blank");
       }
     });
}
// AJAX Form submission


function set_ajax_forms() {
  $(":submit[ajax_submit]").live('click', function() {
      var form_area = $(this).parents("form:first");
      var data_string =  parse_form(form_area);
      var form_action = $(form_area).attr("action");
      var save_message = $(this).attr("save_message");
      var error_message = $(this).attr("error_message");
      var success_action = $(this).attr("success_action");
      var error_action = $(this).attr("error_action");

      $.ajax({
	type: "POST",
	    url: form_action,
	    data: data_string,
	    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
	    success: function() {
  	      if ( save_message ) {
		jQuery.facebox('<p><b>' + save_message + '</b></p>');
	        setTimeout("jQuery(document).trigger('close.facebox')",1000);
	      }
	      if ( success_action )
		ajax_success_action( success_action, data_string );
	  },
	    error: function() {
	      if ( error_message )
		jQuery.facebox('<p><b>' + error_message + '</b></p>');
	      if ( error_action )
		ajax_error_action( error_action, data_string );
	  }
	});
      return false;
    });
}


function parse_form(form_area) {
  var data_string = "";

  $(form_area).find("input, textarea, select").each(function() {
      var ele_name = $(this).attr('name');
      var ele_value = $(this).attr('value');

      if ( $(this).is(":checkbox") ) {
	if ( $(this).is(":checked") )
	  ele_value = 1;
	else
	  ele_value = 0;
      }
      else if ( $(this).is(":radio") && !$(this).is(":checked") )
	ele_value = 0;
      
      if ( ele_name && ele_value )
	data_string += ele_name + "=" + encodeURIComponent(ele_value) + "&";
    });

  return data_string;
}


function ajax_success_action(action, data_string) {
  if ( action == "crop" )
    ajax_crop_action(data_string);    
  else if ( action == "crop_footer" )
    ajax_crop_action(data_string, "header");    
  else if ( action == "crop_header" )
    ajax_crop_action(data_string, "footer");    
}


function ajax_crop_action(data_string, pop_next) {
  var type_start = data_string.indexOf('crop_type=') + 10;
  var type_end = data_string.indexOf('&',type_start);
  var crop_type = data_string.substring(type_start,type_end);

  var id_start = data_string.indexOf('img_id=') + 7;
  var id_end = data_string.indexOf('&',id_start);
  var crop_id = data_string.substring(id_start,id_end);

  var crop_start = data_string.indexOf('crop_y=') + 7;
  var crop_end = data_string.indexOf('&',crop_start);
  var crop_y = data_string.substring(crop_start,crop_end);

  if ( crop_type == "footer" )
    crop_y = crop_y*.558*(-1);
  else
    crop_y = crop_y*.221*(-1);

  var set_new_position = "0px " + Math.round(crop_y) + "px";
    
  $("#" + crop_type + "_" + crop_id)
    .animate({backgroundPosition: set_new_position});
  
  if ( pop_next ) {
    var dest_url = web_root + "images/crop?id=" + crop_id + "&pop=1&crop_type=" + pop_next;
    jQuery.facebox({ ajax: dest_url });
  }
}
function twitter_type(form,e,alt_length) {
  var twitter_length = $(form).parents(".twitter_container:first").find(".twitter_length:first");
  var limit_length = (alt_length)? alt_length : 140;
  var val;
  var length;


  var set_twitter_length = function() {
    val = $(form).val();
    length = val.length;
    $(twitter_length).html(length);
    if ( length > limit_length )
      $(twitter_length).addClass("error_highlight");
    else
      $(twitter_length).removeClass("error_highlight");
  }

  if ( window.event || e.which) {
    setTimeout(set_twitter_length,50);
  }
}
function setHeightConstraints() {
  $("*[constraint_height]").each( function() {
      height_adjust(this);
    });

  secondaryHeaderAdjust();
}


function height_adjust(obj) {
  var constraint_height = $(obj).attr('constraint_height');
  var current_height = $(obj).height();
  var current_size = $(obj).attr('current_size')? $(obj).attr('current_size') : 22;
  var current_line_height = $(obj).attr('current_line_height')? $(obj).attr('current_line_height') : 24;

  if ( current_height > constraint_height && current_size >= 10 ) {
    current_size = current_size - 1;
    current_line_height = current_line_height - 1;
    $(obj)
      .attr("current_size", current_size)
      .css("font-size", current_size + "px")
      .attr("current_line_height", current_line_height)
      .css("line-height", current_line_height + "px");
    height_adjust(obj);
  }
}


function secondaryHeaderAdjust() {
  $("#navigation_bar .secondary_header_left")
    .each( function() {
	var secondary_header_left = $(this);
	var secondary_header_left_width = $(this).width();
	var secondary_header_left_height = $(this).height();
	var header_actions = $(this).find(".header_actions");
	var header_actions_height = $(header_actions).height();
	
	if (secondary_header_left_width < 660) {
	  if ( header_actions_height > 30 ) {
	    $(header_actions).css("font-size", "10px");
	    $("#sticky_nav .header_actions").css("font-size", "10px");
	    header_actions_height = $(header_actions).height();
	  }

	  if ( header_actions_height > 30 ) {
	    var header_actions_clone = $(header_actions).clone();
	    $(header_actions).remove();
	    $("#sticky_nav .header_actions").remove();
	    $("#navigation_bar .sec_header, #sticky_nav .sec_header")
	      .append(header_actions_clone);
	  }
	  
	  else if ( $(this).height() < 101 ) {
	    var action_margin = 101 - $(this).height();
	    $(header_actions).css("margin-top", action_margin + "px");
	    $("#sticky_nav .header_actions").css("margin-top", action_margin + "px");
	  }
	}
      });
  
  $("#facebox .secondary_header_left")
    .each( function() {
	var secondary_header_left = $(this);
	var secondary_header_left_width = $(this).width();
	var secondary_header_left_height = $(this).height();
	var header_actions = $(secondary_header_left).find(".header_actions");
	
	if (secondary_header_left_width < 660) {
	  if ( secondary_header_left_height > 101 ) {
	    $(header_actions).css("font-size", "10px");
	  }
	  if ( $(this).height() < 101 ) {
	    var action_margin = 101 - $(this).height();
	    $(header_actions).css("margin-top", action_margin + "px");
	  }
	}
      });
}
// KEY FILL ===================================================
// could this be rolled in with the common suggest function in java-common.js?

function keySuggest( value, e ){
  if( gE('match0').value == 'band'){  
    var ext = "";
    var obj  = gE( "suggest" );
    var form = gE("match_key0");
    var serverPage = "band_suggest.php";
    var key = e.which;

    if( !key ){
      key = e.keyCode;
    }
    
    if( key==38 ||  key==63232 ){
      setSelect(select-1); return;
    }
    else if( key==40 || key==63223 ){ 
      setSelect(select+1); return;
    } 
    else if( key==13 ) { //Enter
      if( select > 0 ){
	fillSuggest(select,ext);
      }
    return false;
    }
    else if( key==9 ){ // Tab
      return;
    }  
    
    gE("band_id" ).value = "";
    
    if( key == 8 ) {  // Backspace
      if( value.length > 1 ){
	serverPage += "?i=mess&q=" + value.substr(0, (value.length-1));
      }
      else{ // Empty
	clearSuggest();
	return;
      }
    }
    else {  // normal char
      serverPage += "?i=mess&q=" + value + String.fromCharCode( key );
    }
    
    obj.style.visibility = "visible";
    obj.style.width = form.offsetWidth + "px";
    obj.style.left = findPos(form,"offsetLeft")+"px";
    obj.style.top = findPos(form,"offsetTop") + form.offsetHeight-1+"px";
    
    processAJAX( serverPage, obj, "get" );
  }
}


//DOM CONSTRUCTION FUNCTIONS FOR LISTINGS ====================================


// builds out the listing DOM
function buildDOM() {
  $("ul.day_group > li").each(function() {
      var height_differential = $(this).height() - $(this).find(".d:first").height();
      if ( height_differential > 0 )
	$(this).find(".sm:first").css("margin-top", height_differential + "px");

      $(this).one("mousemove", function(){
	  var eventID = $(this).attr("id");
	  $(this)
	    .find('ul.b li').each( function() {
		readyBandsDOM(this, eventID);
	      }).end()

	    .find('div.d:first')
	      .find('div.v:first')
	        .find("a[g]:first").each(function(){
		    $(this)
		      .attr("href","index.php?g="+$(this).attr("g"))
		      .attr("title", "view all upcoming "+$(this).html()+" shows");
		  }).end()

	        .find('a[vp]:first').each(function() {
		    $(this).attr("href","submit_file/?event_id=" + eventID);
		    if ( logged_in )
		      $(this).attr("pop_link","1");
		  }).end()
	        .find('a[sp]:first')
	          .attr("title","View images from this show")
	          .click(function(){
		      PicLensLite.start({feedUrl:web_root + "shows/" + eventID + "/event_media/rss", paused:true});
		    }).end().end()

	    .find('div.sm:first')
	      .each(  function() {
		  prep_interest(this);
		  if ( logged_in )
		    $(this).find('td:not([sm]):first a')
		      .attr('pop_link','1')
		      .attr("title", "Grab a link, or tell friends through email or Twitter");
		  $(this).find('td:not([sm]):last a')
		    .attr("title", "Open show in a new page");
		});
	});
    });

  $("div.day div.q")
    .attr("title","Videos and images from this day")
    .click(function(){
	PicLensLite.start({feedUrl:web_root + "media/rss/" + $(this).attr("ci"), paused:true});
      });
}
/* MAESTRO =========================================================== */


$("a[maestro_link]").live("click", function(event) {
    event.preventDefault();

    var maestro_disable = $(this).attr("maestro_link");
    var maestro_link = $(this).attr("href");
    var scroll_duration = 0;

    if ( maestro_disable != 2 )
      maestro_link = maestro_link + "&maestro_inline=1";
    
    jQuery(document).trigger('close.facebox');
    
    if ( $(document).scrollTop() )
      scroll_duration = 1000;

    $.scrollTo('top:0', scroll_duration, {onAfter:function() {
	$("#header_plus_message")
	  .find(".maestro").slideUp("normal", function() {
	      $(this).remove();
	    });

	$.get(maestro_link, function(data){
	    if ( maestro_disable != 2 )
	      $("#header_plus_message")
		.append(data)
		.find(".maestro").slideDown(function() {
		    $("#header_plus_message")
		      .find(".maestro:not(:first)").remove();
		  });
	  });
	}});
  });


$("a[startup_tips]").live("click", function(event) {
    event.preventDefault();

    var startup_disable = $(this).attr("startup_tips");
    var startup_link = $(this).attr("href");
    
    jQuery(document).trigger('close.facebox');
    
    $.get(startup_link, function(data){
	if ( startup_disable == 2 ) {
	  $("#footer")
	    .find(".startup_tips").slideUp("normal", function() {
		$(this).remove();
	      });

	  $("#header_plus_message")
	    .find(".startup_tips").slideUp("normal", function() {
		$(this).remove();
		alert("Startup tips are off. To turn them back on, click the help button.");
	      });
	}
	
	else
	  alert("Startup tips are enabled.");

      });
  });


// POST FUNCTIONS ===========================================================

// deletes a user's post and fades it out
function postDelete(obj,post_id,post_type) {
  if ( confirm("Are you sure you want to delete your " + post_type + "?") ) {
    $(obj).parents("div[id]:first").fadeOut();
    var serverPage =
      "post.php?id=" + post_id + "&remove";
    emptyAJAX(serverPage);
  }
}
// POST MANIPULATION FUNCTIONS ==============================================

function post_delete(obj) {
  var serverPage = $(obj).attr('href');

  emptyAJAX(serverPage);

  $(obj).parents(".post_container:first")
    .fadeout()
    .remove();
}
function set_post_rate() {
  $("table.pr").each( function() {
      prep_post_rate(this);
    });
}


function prep_post_rate(obj) {
  $(obj)
    .find("td.yes a, td.no a").click( function(event) {
	if (logged_in) {
	  event.preventDefault();

	  var this_container = $(this);
	  var other_container = $(this).parent().siblings("td[class]:first").find("a");
	  var other_href = $(other_container).attr("href");
	  var other_alt_href = $(other_container).attr("aurl");
	  var href = $(this).attr("href");
	  var alt_href = $(this).attr("aurl");
	  var other_selected = $(other_container).hasClass("sel");

	  $.ajax({
	    type: "GET",
		url: href+"&ajax",
		success: function() {
		$(this_container).toggleClass("sel").attr("href",alt_href).attr("aurl",href);
		if ( other_selected )
		  $(other_container).removeClass("sel").attr("href",other_alt_href).attr("aurl",other_href);
	      },
		failure: function() {
		alert("There was a problem saving. Give it another try, or reload the page.");
	      },
		error: function() {
		alert("There was a problem saving. Give it another try, or reload the page.");
	      }
	    });
	}
      });
}
/* SET ALBUMS ================================================================ */

// finds album containers and sets them up
function setAlbums() {
  $("div.media_container span")
    .attr("title","listen to samples")
    .click(function(event) {
	var album_id = $(this).attr("i");
	launch_sample(0,0,album_id);
      });
}
// Checks all the checkboxes in a table
function setCheckAllTable() {
  $(".check_all_table")
    .toggle(
	    function () {
	      $(this).parents('table:first').find("input[type='checkbox']")
		.each( function() {
		    this.checked=true; }).end().end()
		.html("uncheck&nbsp;all");
	    },
	    function () {
	      $(this).parents('table:first').find("input[type='checkbox']")
		.each( function() {
		    this.checked=false; }).end().end()
		.html("check&nbsp;all");
	    });
}
/* ----------------
   Gallery Controls
   ---------------- */

function setGalleryForms() {
  $("table.image_list form")
    .submit(function() {
	$(this).find("input[type='submit']")
	.hide();
      })
    .click(function() {
      $(this).find("input[type='submit']")
	.show();;
      })
    .find("option[value='flagged']").click(function() {
	$(this).parents("form:first").find(".hidden").show();
      });
}
// Set listing filter controls ==============================================
// these are actually defunct, but I'm keeping them around for reference


function setListingFilters() {
  $(".filter_age").coopCheckboxHandler();
  $(".filter_neighborhood, .filter_genres").coopCheckboxHandler("all",1);
  $(".filter_date, .filter_cost, .filter_genre").coopCheckboxHandler("one",1);
  $(".filter_genre label:last").click(function() {
      var box = $(this).find(":checkbox");
      if ( box[0].checked ) {
  	var content = $(this).parents("div:first").find("table.filter_genres").clone().coopCheckboxHandler("all",1).show();
  	$(content).find("label").click(function() {
  	    var pop_table = $(this).parents("table:first");
  	    $("table.filter_genres").not(pop_table).html($(pop_table).contents().clone());
  	  });
  	jQuery.facebox(content);
      }
    });
  
}
// sets the search reveal button

function set_search_reveal() {
  $("a[toggle_search]").click( function(event) {
      event.preventDefault();
      
      $("#header_search").slideToggle("normal");

    });
}
function set_interest() {
  $("div.sm").each( function() {
      prep_interest(this);
    });
}


function prep_interest(obj) {
  $(obj)
    .find("td[sm] a").click( function(event) {
	if (logged_in) {
	  event.preventDefault();

	  var mark_container = $(this).parents(".sm:first");
	  var event_id = $(mark_container).attr("event_id");
		
	  var href = $(this).attr("href") + "&ajax";
	  var current_button_td = $(this).parent();
	  var show_mark = $(current_button_td).attr("sm");
	  var selected = $(current_button_td).hasClass("sel");

	  $.ajax({
	    type: "GET",
		url: href,
		success: function() {
		if ( show_mark != "pick" )
		  $(mark_container).find("td[sm]:not([sm='pick'])")
		    .each(function(){
			set_interest_button(this);
		      });
		
		set_interest_button(current_button_td,!selected);
		adjust_listing_status(current_button_td,!selected);
	      },
		failure: function() {
		alert("There was a problem saving. Give it another try, or reload the page.");
	      },
		error: function() {
		alert("There was a problem saving. Give it another try, or reload the page.");
	      }

	    });
	}
      });
}
	    
	
function set_interest_button(button, selected) {
  var event_id = $(button).parents(".sm:first").attr("event_id");
  var interest = $(button).attr("sm");
  
  if (selected)
    $(button)
      .addClass("sel")
      .find("a").attr("href", "user_event_status.php?event_id="+event_id+"&status=remove");
  else
    $(button)
      .removeClass("sel")
      .find("a").attr("href", "user_event_status.php?event_id="+event_id+"&status="+interest);
}  


function adjust_listing_status(button, selected) {
  var listDiv = $(button).parents("li[class='n'],li[class='n a'],li[class='n a g'],li[class='n g'],li[class='n a wt'],li[class='n wt']");
  var interest = $(button).attr("sm");

  if ( listDiv[0] && interest != "pick") {
    if (selected) {
      if ( interest == 'g')
	$(listDiv[0]).removeClass("wt").addClass("g");
      else if ( interest == 'w' )
	$(listDiv[0]).removeClass("g").addClass("wt");
      else
	$(listDiv[0]).removeClass("wt").removeClass('g');
    }
    else
      $(listDiv[0]).removeClass("wt").removeClass('g');
  }
}
function set_strike_throughs() {
  $(".prep_strike").live("click", function() {
      $(this).addClass("strike");
    });
}
// Email list subscription functions ==================================================


//function subscribes to mailing lists and new show emails
function subscribeEmails(obj,id,email_type,not_logged_in) {

  if ( $(obj).attr('subscribed') ) {
    $(obj).attr('subscribed','0')
    var sub_action = "remove_";
  }
  else {
    $(obj).attr('subscribed','1')
    var sub_action = "add_";
  }


  var serverPage = "user_star.php?id="+id + "&" + sub_action + email_type;

  if (not_logged_in)
    location.href = serverPage + "&redirect";
  else {
    $(obj).find("span[button!='1']").toggleClass('hidden');
    emptyAJAX(serverPage);
    return true;
  }
}
// Uploadify ==========================================================

function setUploadify(pop) {
  var div_id = (pop)? "#uploadify_pop" : "#uploadify";
    
  $(div_id).each(function() {
      var session_id = $(this).attr('session_id');
      var band_id = $(this).attr('band_id');
      var location_id = $(this).attr('location_id');
      var event_id = $(this).attr('event_id');

      $(this)
	.parents("form").find(":submit").hide().end().end()
	.uploadify({
	    'uploader'      : web_root + 'uploadify.swf',
	      'script'        : web_root + 'uploadify.php',
	      'cancelImg'     : web_root + 'Images/uploadify_cancel.png',
	      'buttonImg'     : web_root + 'Images/uploadify_browse.png',
	      'rollover'      : true,
	      'width'         : 116,
	      'height'        : 18,
	      'auto'          : true,
	      'folder'        : '/uploads',
	      'multi'         : true,
	      'fileDesc'      : "Image files",
	      'fileExt'       : '*.jpg;*.jpeg;*.gif;*.png',
	      'scriptData'    : { 'session_id' : session_id,
		'band_id'     : band_id,
		'location_id' : location_id,
		'event_id'    : event_id },
	      'onAllComplete' : function() { location.href = web_root+"images/crop"; }
	  });
    });
}
