var FlagTrack = {
	switchComplaintType: function(mctrl) {
		for (var i = 1; i <= 3; i++) {
			var info_block = $('flag_extra_info_' + i);
			if (info_block) {
				(i == mctrl.value) ? info_block.show() : info_block.hide();
			}
		}
	}
};

var BrowserWarning = Class.create({
	initialize: function() {
		var hdr = $(document.body).down('#our-page-header');
		if (hdr) {
			var bar = new Element('a', {style:'display:none;',href:'/about/old_browser'});
			bar.addClassName('browser-warning');
			bar.innerHTML = 'We recommend you upgrade your browser to enjoy OurStage.com. <span>Click here</span> to find out how.';
			hdr.appendChild(bar);
			Effect.BlindDown(bar, {duration:0.3});
		}
	}
});
document.observe('dom:loaded', function() {
	var ie = navigator.userAgent.match(/MSIE (\d+)\./);
	if (ie) {
		var vers = parseFloat(ie[1]);
		if (vers < 7) {new BrowserWarning();}
	}
})

var UserBar = Class.create({
	initialize: function() {
		var element = $('user-bar');
		if (element && window.userBarURL) {
			new Ajax.Updater(
				element, window.userBarURL, {
					asynchronous:true,
					evalScripts:true
				}
			);
		}
	}
});
document.observe('dom:loaded', function() {new UserBar();});

var NavMenu = Class.create({
	initialize: function(link) {
		this._link = link;
		this._menu = $(link.rel);
		this._hiding = false;
		this._link.onclick = function() {return false;}

		if (this._menu)
		{
			var txt = new Element('span');
			var arw = new Element('span');
			txt.addClassName('txt');
			txt.innerHTML = this._link.innerHTML;
			arw.addClassName('arw');
			arw.innerHTML = '&nbsp;'
			this._link.innerHTML = '';
			this._link.appendChild(txt);
			this._link.appendChild(arw);
			this._link.addClassName('arw');
		}

		this._link.observe('click', this.toggle.bind(this));
		document.observe('mousedown', this.hide.bind(this));
		Event.observe(window, 'blur', this.hide.bind(this));
	},

	toggle: function(event) {
		if (this._menu.visible()) {
			this.hide();
		} else {
			this.show();
		}
	},

	show: function(event) {
		if (!this._menu || this._menu.visible()) {return;}
		if (!this._menu.style.position || this._menu.style.position=='absolute') {
			this._menu.style.position = 'absolute';
			this._menu.clonePosition(this._link, {
				setLeft: false,
				setHeight: false,
				setWidth: false,
				offsetTop: this._link.offsetHeight
			});
		}
		this._link.addClassName('checked');
		Effect.Appear(this._menu, {duration:0.15});
	},

	hide: function(event) {
		if (this._hiding || !this._menu || !this._menu.visible()) {return;}
		var doIt = true;
		if (event) {
			var elt = event.element();
			if (elt.ancestors && ((elt == this._menu) || elt.ancestors().indexOf(this._menu) != -1)) doIt = false;
		}
		if (doIt) {
			this._hiding = true;
			Effect.Fade(this._menu, {duration:0.15, afterFinish:this._finishHide.bind(this)});
		}
	},

	_finishHide: function() {
		this._hiding = false;
		this._link.removeClassName('checked');
	}
});
document.observe('dom:loaded', function() {
	$$('#our-page-header .nav a').each(function(link) {
		if (link.rel) {new NavMenu(link);}
	});
});

var SearchField = Class.create({
	initialize: function() {
		this._field = $(document.body).down('.search input');
		if (this._field) {
			if (Prototype.Browser.WebKit) {
				var old_field = this._field;
				this._field = new Element('input', {
					type:'search',
					value:$F(this._field),
					name:this._field.name,
					placeholder:'Search OurStage',
					results:'0'
				});
				old_field.up().insertBefore(this._field, old_field);
				old_field.up().removeChild(old_field);
			} else {
				this.updatePlaceholder();
				this._field.observe('focus', this.gotFocus.bind(this));
				this._field.observe('blur', this.lostFocus.bind(this));
			}
		}
	},

	gotFocus: function() {
		this._focus = true;
		this.updatePlaceholder();
	},

	lostFocus: function() {
		this._focus = false;
		this.updatePlaceholder();
	},

	updatePlaceholder: function() {
		var value = $F(this._field);
		if (!this._focus && (!value || value.length == 0)) {
			this._field.value = 'Search OurStage';
			this._field.addClassName('empty');
		} else {
			if ($F(this._field) == 'Search OurStage') {
				this._field.value = '';
			}
			this._field.removeClassName('empty');
		}
	}
});
document.observe('dom:loaded', function() {new SearchField();});

var PhotoGallery = Class.create({
	initialize: function(grid, view, selectURL) {
		this.grid = grid;
		this.view = view;
		this.selectURL = selectURL;
		this.selectedIndex = 0;
		this.updateSelection();
		window.gallery = this;
	},

	select: function(index) {
		this.selectedIndex = index;
		this.updateSelection();
		this.grid.scrollGrid.gotoPage(Math.floor(index / 6));
		new Ajax.Updater(this.view, this.selectURL, {method:'get', parameters:{index:index}});
	},

	updateSelection: function() {
		this.grid.select('.gallery-cell').invoke('removeClassName', 'selected');
		var cell = this.grid.down('.gc-' + this.selectedIndex);
		if (cell) cell.addClassName('selected');
	}
});

var OurResizer = Class.create({
	initialize: function() {
		this._playerBar = $('our-player-bar');
		this._scrollPane = $('our-scroll-pane');
		this._content = $('our-content');
		this._header = $('our-page-header');

		if (this._playerBar && this._scrollPane && this._content && this._header) {
			this.measureLayout();
			Event.observe(window, 'resize', this.resizePanes.bind(this));
			window.ourResizer = this;
		}
	},

	resizePanes: function() {
		var h = document.viewport.getHeight() - this._playerHeight;
		this._scrollPane.setStyle({height:h + 'px'});
		if (this._fillWindow) {
			h -= this._headerHeight;
			this._content.setStyle({height:h + 'px'});
		}
	},
	
	measureLayout: function() {
		if (this._playerBar && this._scrollPane && this._content && this._header) {
			this._playerHeight = this._playerBar.getHeight();
			this._headerHeight = this._header.getHeight();
			this._fillWindow = this._content.hasClassName('fill_window');
			this.resizePanes();
		}
	}
	
});
OurResizer.load = function() {
	if (!window.ourResizer) {new OurResizer();}
}
document.observe('dom:loaded', OurResizer.load);

var OurAccordion = Class.create();
OurAccordion.prototype = {
	initialize: function(ul) {
		this._duration = 0.25;
		this._ul = $(ul);
		this._target = $(this._ul.target);
		this._linkClicked = this.linkClicked.bindAsEventListener(this);
		this._ul.select('a').each(function(lnk, i) {
			lnk.subgroup = lnk.next('ul');
			if (lnk.subgroup)
				lnk.subgroup.hide();
			lnk.onclick = function() {return false;};
			lnk.observe('click', this._linkClicked);
		}.bind(this));
		this._ul.removeClassName('our-accordion-raw');
	},

	linkClicked: function(evt) {
		var lnk = Event.element(evt);

		if (lnk.subgroup) {
			this._ul.select('ul').each(function(ul, i) {
				if ((ul != lnk.subgroup) && ul.visible()) {
					Effect.BlindUp(ul, {duration:this._duration});
				}
			}.bind(this));
			if (!lnk.subgroup.visible()) {
				Effect.BlindDown(lnk.subgroup, {duration:this._duration});
			}
		}

		new Ajax.Updater(
			this._target, lnk.href,
			{	asynchronous:true,
				evalScripts:true,
				method:'get'
			}
		);
	}
};
var initializeAccordions = function() {$$('ul.our-accordion-raw').each(function(ul, i) {new OurAccordion(ul);});};
document.observe('dom:loaded', initializeAccordions)

var OurLinkTabs = Class.create();
OurLinkTabs.prototype = {
	initialize: function(ul) {
		ul = $(ul);

		var controls = ul.down('.our-tab-custom-controls');
		var selectedTab = null;

		if (typeof controls != 'undefined') {
			var newCtls = new Element('div');
			newCtls.addClassName('our-tab-custom-controls');
			newCtls.innerHTML = controls.innerHTML;
			ul.removeChild(controls);
			controls = newCtls;
		}

		var tabBar = new Element('div');
		tabBar.addClassName('our-tab-bar');
		ul.select('li').each(function(li, index) {
			var span = li.down('span');
			var link = li.down('a');
			var tab = new Element('div');
			tab.addClassName('our-tab-tab');
			var cap = new Element('div');
			cap.addClassName((index == 0) ? 'our-tab-tab-lcap-first' : 'our-tab-tab-lcap');
			tab.appendChild(cap);
			if (typeof link != 'undefined') {
				link.addClassName('our-tab-tab-content');
				tab.appendChild(link);
			} else if (typeof span != 'undefined') {
				span.addClassName('our-tab-tab-content');
				tab.appendChild(span);
				selectedTab = tab;
			}
			var rcap = new Element('div');
			rcap.addClassName('our-tab-tab-rcap');
			tab.appendChild(rcap);
			tabBar.appendChild(tab);
		});

		if (typeof controls != 'undefined') {
			tabBar.appendChild(controls);
		}

		if (selectedTab != null) {
			var tabs = tabBar.select('.our-tab-tab');
			tabs.invoke('removeClassName', 'our-tab-tab-selected');
			selectedTab.addClassName('our-tab-tab-selected');
			var z = 100;
			var deltaZ = 1;
			for (var i = 0; i < tabs.length; i++) {
				tabs[i].style.zIndex = z;
				if (tabs[i] == selectedTab) {deltaZ = -1;}
				z += deltaZ;
			}
		}

		var up = ul.up();
		up.insertBefore(tabBar, ul);
		up.removeChild(ul);
	}
};

var OurLinkMenu = Class.create();
OurLinkMenu.prototype = {
	initialize: function(ul) {
		ul = $(ul);
		var sel = new Element('select');
		sel.addClassName('our-link-menu');
		ul.select('li').each(function(li, index) {
			var span = li.down('span');
			var link = li.down('a');
			if (typeof link != 'undefined') {
				var opt = new Element('option');
				opt.innerHTML = link.innerHTML;
				opt.value = link.href;
				sel.appendChild(opt);
			} else if (typeof span != 'undefined') {
				var opt = new Element('option');
				opt.innerHTML = span.innerHTML;
				opt.value = '';
				opt.selected = 'selected';
				sel.appendChild(opt);
			}
		});

		this._sel = sel;
		var parent = ul.up();
		parent.insertBefore(this._sel, ul);
		parent.removeChild(ul);

		this._sel.observe('change', this.menuChanged.bindAsEventListener(this));
	},

	menuChanged: function(event) {
		$$('select.our-link-menu').each(function(sel,i) {sel.disable();});
		window.location.href = this._sel.value;
	}
};
var setupLinkMenus = function() {
	$$('ul.our-link-menu-raw').each(function(element, index) {
		new OurLinkMenu(element);
	});
	$$('ul.our-link-tabs-raw').each(function(element, index) {
		new OurLinkTabs(element);
	});
};

document.observe('dom:loaded', setupLinkMenus);

var OurToolbarPopup = Class.create();
OurToolbarPopup.prototype = {
	initialize: function(element) {
		this._popup = $(element);
		this._popup.popup = this;
		this._container = this._popup.up();
		this._link = this._popup.down('.trigger');
		this._hider = this.hide.bindAsEventListener(this);

		this._popup.removeClassName('popup-raw');
		this._popup.addClassName('popup');

		this._container.insertBefore(this._link, this._popup);
		this._container.appendChild(this._popup);

		this._popup.setStyle({
			position:'absolute',
			width:'200px',
			zIndex:10000
		});

		this._link.onclick = function() {return false;}
		this._link.observe('click', this.toggle.bindAsEventListener(this));
	},

	show: function() {
		var right = this._container.offsetWidth - (this._link.offsetLeft + this._link.offsetWidth);
		var top = this._link.offsetTop + this._link.offsetHeight;
		this._popup.setStyle({
			top:top + 'px',
			right:right + 'px'
		});
		$$('.our-item .toolbar .popup').each(function(element, index) {
			if (element.visible())
				Effect.Fade(element, {duration:0.15});
		});
		Effect.Appear(this._popup, {duration:0.15});
	},

	hide: function() {
		Effect.Fade(this._popup, {duration:0.15});
	},

	toggle: function() {
		if (this._popup.visible()) {
			this.hide();
		} else {
			this.show();
		}
	}
};

var Afterburner = Class.create({
	initialize: function() {
		var args = '';
		if (window.footprint) {
			for (var prop in window.footprint) {
				if (args.length > 0) args += '&';
				args += ('fp[' + prop + ']=' + window.footprint[prop]);
			}
			window.footprint = null;
		}
		$$('.ab-raw').each(function(element, index) {
			var hash = element.className.match(/ab-raw ab\-([^\-]+)\-/);
			if (hash) {
				element.select('input[type=hidden]').each(function(input, index) {
					if (args.length > 0) args += '&';
					args += input.serialize();
				});
			}
			element.removeClassName('ab-raw');
			element.addClassName('ab');
		});
		if (args.length > 0) {
			new Ajax.Request(
				'/ui/ignite_afterburner',
				{	asynchronous:true,
					evalScripts:true,
					method:'post',
					parameters:args,
					onComplete: this.didIgnite.bind(this)
				}
			);
		}
	},

	didIgnite: function() {
		document.fire('ourstage:ajaxLoaded');
        if (FB) FB.XFBML.Host.parseDomTree(); 	
    }
});
document.observe('dom:loaded', function() {new Afterburner();});
document.observe('ourstage:ajaxLoaded', function() {new Afterburner();});

var OurDeferredDiv = Class.create();
OurDeferredDiv.prototype = {
	initialize: function(link) {
		this._link = $(link);
		this._div = $(this._link.rel);
		new Ajax.Updater(
			link.rel, link.href,
			{	asynchronous:true,
				evalScripts:true,
				method:'get',
				onComplete: this.loadChildren.bindAsEventListener(this)
			}
		);
	},

	loadChildren: function() {
		setupLinkMenus();
		document.fire('ourstage:ajaxLoaded');
		this._div.getElementsBySelector('.our-div-loader a').each(function(link, index) {
			new OurDeferredDiv(link);
		});
	}
};

document.observe('dom:loaded', function() {
	$$('.our-div-loader a').each(function(link, index) {
		new OurDeferredDiv(link);
	});
});

var hiliteOurListItem = function(cell) {
	cell = $(cell);
	cell.up().getElementsBySelector('.our-list-item').invoke('removeClassName', 'selected-item');
	cell.addClassName('selected-item');
};

var enableSubmits = function(element, enable) {
	var form = $(element).up('form');
	
	form.getElementsBySelector('input.our-submit').each(function(butt) {
		butt.disabled = !enable;
	});
	
	form.getElementsBySelector('a.our-submit').each(function(butt) {
		if (enable) {
			butt.removeClassName('our-submit-disabled');
		} else {
			butt.addClassName('our-submit-disabled');
		}
	});
};

var ourBusy = function(container) {
	container = $(container);
	var busy = new Element('div');
	busy.addClassName('our-busy');
	var msg = new Element('span');
	msg.innerHTML = '&nbsp;&nbsp;&nbsp;Loading&hellip;';
	busy.insert(msg);
	container.update(busy);
};

var OurPlaylistBox = Class.create();
OurPlaylistBox.prototype = {
	initialize: function(container, playlistKey, update_blurb_url) {
		this._container = container;
		this._playlistKey = playlistKey;
		this._update_blurb = update_blurb_url;
		this._player = container + '-player';
		this._grid = container + '-grid';
		this._currentIndex = 0;
		this.container().playlistBox = this;
	},

	container: function() {
		return $(this._container);
	},

	blurb: function() {
		return this.container().down('.blurb');
	},

	player: function() {
		return $(this._player);
	},

	grid: function() {
		return $(this._grid);
	},

	beginPlaylistChange: function() {
		if (this._update_blurb) {
			ourBusy(this.blurb());
		}
		ourBusy(this.grid().up());
	},

	endPlaylistChange: function(playlistKey) {
		this._playlistKey = playlistKey;
		this._currentIndex = 0;
		this.updateSelection(false);
	},

	trackChangedInPlayer: function(event) {
		this._currentIndex = event.index;
		this.updateSelection(true);
	},

	setTrack: function(index) {
		this._currentIndex = index;
		if (this.player()) {
			this.player().setCurrentTrackIndex(index);
		}
		this.updateSelection(false);
	},

	updateSelection: function(scroll) {
		if (this._update_blurb){
			new Ajax.Updater(
				this.blurb(), this._update_blurb,
				{	asynchronous:true,
					evalScripts:true,
                    method:'get',
					parameters:'playlist=' + this._playlistKey + '&index=' + this._currentIndex
				}
			);
		}
		this.grid().getElementsBySelector('.our-item').invoke('removeClassName', 'our-item-selected');
		this.grid().getElementsBySelector('.our-item-' + this._currentIndex).invoke('addClassName', 'our-item-selected');
		if (scroll) {
			var page = Math.floor(this._currentIndex / 6);
			this.grid().scrollGrid.gotoPage(page);
		}
	}
};

Effect.OurScrollTo = function(element) {
	var scroller = $('our-scroll-pane');
	var options = arguments[1] || { };
	if (!scroller) {return Effect.ScrollTo(element, options);}

	var elementOffsets = $(element).cumulativeOffset();

	if (options.offset) elementOffsets[1] += options.offset;
	var start = scroller.scrollTop;
	var end = elementOffsets[1];

	if (start > end) {
		return new Effect.Tween(null, start, end, options, function(p) {
			scroller.scrollTop = p;
		});
	}
};

var CrossfadePagination = Class.create({
	initialize: function(container) {
		this._duration = 0.25;
		this._container = $(container);
		var w = this._container.getWidth();
		var h = this._container.getHeight();
		this._currentPage = new Element('div');
		this._otherPage = new Element('div');
		this._currentPage.innerHTML = this._container.innerHTML;
		this._container.setStyle({
			width:w + 'px',
			height:h + 'px'
		});
		this._container.innerHTML = '';
		this._container.appendChild(this._currentPage);
		this._container.appendChild(this._otherPage);
		this._currentPage.setStyle({width:w + 'px'});
		this._otherPage.setStyle({width:w + 'px'});
		this._otherPage.hide();

		this.linkClicked = this._linkClicked.bind(this);

		this._instrumentLinks();
	},

	update: function(newContent) {
		this._otherPage.update(newContent);
		this._instrumentLinks();

		var sh = this._currentPage.getHeight();
		var eh = this._otherPage.getHeight();
		var container = this._container;

		this._container.setStyle({overflow:'hidden',position:'relative'});
		this._currentPage.setStyle({position:'absolute',top:'0',left:'0'});
		this._otherPage.setStyle({position:'absolute',top:'0',left:'0'});

		Effect.OurScrollTo(this._container, {duration:this._duration});
		new Effect.Tween(null, sh, eh, {duration:this._duration}, function(h) {
			container.setStyle({height:h + 'px'})
		});
		new Effect.Fade(this._currentPage, {duration:this._duration});
		new Effect.Appear(this._otherPage, {duration:this._duration, afterFinish:this._fadeComplete.bind(this)});
		document.fire('ourstage:ajaxLoaded');
	},

	loadPage: function(url) {
	},

	_linkClicked: function(event) {
		var link = event.element();
		new Ajax.Request(link.href, {
			asynchronous:true,
			method:'get',
			onSuccess:this._gotPage.bind(this)
		});
	},

	_gotPage: function(response) {
		this.update(response.responseText);
	},

	_fadeComplete: function() {
		var tmp = this._otherPage;
		this._otherPage = this._currentPage;
		this._currentPage = tmp;
		this._currentPage.setStyle({position:'static'});
		// this._otherPage.setStyle({position:'static'});
		var h = this._currentPage.getHeight();
		this._container.setStyle({
			position:'static',
			overflow:'visible',
			height:h + 'px'
		});
	},

	_instrumentLinks: function() {this._container.select('.pagination a').each(this._instrumentOneLink.bind(this));},
	_instrumentOneLink: function(link) {
		link.onclick = function() {return false;}
		link.stopObserving('click', this.linkClicked);
		link.observe('click', this.linkClicked);
	}
});
CrossfadePagination.instrumentFaders = function() {
	$$('div.crossfade-pagination').each(function(element) {
		if (!element.crossfader) {
			element.crossfader = new CrossfadePagination(element);
		}
	});
};
Event.observe(window, 'load', CrossfadePagination.instrumentFaders);
document.observe('ourstage:ajaxLoaded', CrossfadePagination.instrumentFaders);

var OurScrollGrid = Class.create();
OurScrollGrid.prototype = {

	initialize: function(container, pageURL, currentPage, pageCount, duration) {
		this._container = $(container);
		this._container.scrollGrid = this;
		this._pageURL = pageURL;
		this._currentPage = currentPage;
		this._pageCount = pageCount;
		this._duration = duration;
		this._busy = false;
		this._animating = false;

		this._clipper = this._container.down('.clipper');
		this._prevArrow = this._container.down('.prev');
		this._nextArrow = this._container.down('.next');
		this._page = this._container.down('.page');
		this._otherPage = new Element('div');
		this._otherPage.addClassName('page');
		this._clipper.insert(this._otherPage);

		var pageWidth = this._page.style.width;
		var pageHeight = this._page.style.height;
		var arrowWidth = 24;
		var arrowHeight = 24;
		var gap = 4;

		pageWidth = parseInt(pageWidth.substring(0, pageWidth.length - 2));
		pageHeight = parseInt(pageHeight.substring(0, pageHeight.length - 2));

		this._pageWidth = pageWidth;

		this._container.setStyle({
			width:(arrowWidth + gap + pageWidth + gap + arrowWidth) + 'px',
			height:pageHeight + 'px'
		});

		this._clipper.setStyle({
			width: pageWidth + 'px',
			height: pageHeight + 'px',
			position: 'relative'
		});

		this._page.setStyle({
			position:'absolute',
			top:'0',
			left:'0'
		});

		this._otherPage.setStyle({
			position:'absolute',
			top:'0',
			left:pageWidth + 'px'
		});

		var top = Math.round((pageHeight - arrowHeight) / 2);
		this._prevArrow.setStyle({top:top + 'px'});
		this._nextArrow.setStyle({top:top + 'px'});

		Event.observe(this._prevArrow, 'click', this.previous.bindAsEventListener(this));
		this._prevArrow.onclick = function() {return false;};

		Event.observe(this._nextArrow, 'click', this.next.bindAsEventListener(this));
		this._nextArrow.onclick = function() {return false;};

		this.updateButtons();
	},

	previous: function() {
		if (this._busy || this._prevArrow.hasClassName('arrow-disabled')) {return;}
		this.gotoPage(this._currentPage - 1);
	},

	next: function() {
		if (this._busy || this._nextArrow.hasClassName('arrow-disabled')) {return;}
		this.gotoPage(this._currentPage + 1);
	},

	gotoPage: function(newPage) {
		if ((newPage != this._currentPage) && (newPage >= 0) && (newPage < this._pageCount)) {
			this._busy = true;
			this._pendingPage = newPage;
			this.updateButtons();
			new Ajax.Updater(	this._otherPage,
								this._pageURL,
								{	parameters:'page=' + this._pendingPage,
									asynchronous:true,
									evalScripts:true,
									method:'get',
									onSuccess: this.gotoPageSucceeded.bindAsEventListener(this),
									onComplete: this.gotoPageCompleted.bindAsEventListener(this)
								});
		}
	},

	finishAnimation: function() {
		this._busy = false;
		this._animating = false;

		var tmp = this._page;
		this._page = this._otherPage;
		this._otherPage = tmp;

		this._currentPage = this._pendingPage;
		this.updateButtons();
	},

	gotoPageSucceeded: function() {
		this._animating = true;
		var delta = (this._pendingPage < this._currentPage) ? this._pageWidth : (-1 * this._pageWidth);
		this._otherPage.style.left = (-1 * delta) + 'px';
		new Effect.Move(this._page, {mode:'relative', x:delta, duration:this._duration});
		new Effect.Move(this._otherPage, {mode:'relative', x:delta, duration:this._duration, afterFinish:this.finishAnimation.bindAsEventListener(this)});
	},

	gotoPageCompleted: function() {
		if (!this._animating) {
			this._busy = false;
			this.updateButtons();
		}
		document.fire('ourstage:ajaxLoaded');
	},

	updateButtons: function() {
		if ((this._currentPage <= 0) || this._busy) {
			this._prevArrow.addClassName('arrow-disabled');
		} else {
			this._prevArrow.removeClassName('arrow-disabled');
		}

		if ((this._currentPage >= (this._pageCount - 1)) || this._busy) {
			this._nextArrow.addClassName('arrow-disabled');
		} else {
			this._nextArrow.removeClassName('arrow-disabled');
		}
	}

};

var OurTabs = Class.create();
OurTabs.prototype = {

	initialize: function(tabContainer, tabSelectCallback) {
		tabContainer = $(tabContainer);
		this._tabSelectCallback = tabSelectCallback;
		this._panes = tabContainer.getElementsBySelector('.our-tab-pane');
		var customs = tabContainer.getElementsBySelector('.our-tab-custom-controls');
		var tabBar = document.createElement('div')
		var selectedTab = null;
		var i;

		tabBar.className = 'our-tab-bar';
		tabContainer.insertBefore(tabBar, tabContainer.firstChild);
		for (i = 0; i < this._panes.length; i++) {
			var pane = this._panes[i];
			var tab = document.createElement('div');
			var d;
			var a;

			tab.className = 'our-tab-tab';
			tab._pane = pane;

			d = document.createElement('div');
			d.className = (i == 0) ? 'our-tab-tab-lcap-first' : 'our-tab-tab-lcap';
			tab.appendChild(d);

			a = document.createElement('a');
			a.className = 'our-tab-tab-content';
			a.href = '#';
			if (pane.id) {
				a.id = pane.id + '-link';
			}
			a.onclick = function() {return false;}
			a.innerHTML = pane.title;
			tab.appendChild(a);

			d = document.createElement('div');
			d.className = 'our-tab-tab-rcap';
			tab.appendChild(d);

			Event.observe(a, 'click', this.tabClicked.bindAsEventListener(this));

			tabBar.appendChild(tab);

			if ((selectedTab == null) || (Element.hasClassName(pane, 'our-tab-pane-default'))) {
				selectedTab = tab;
			}

			pane.title = '';
		}

		for (i = 0; i < customs.length; i++) {
			tabBar.appendChild(customs[i]);
		}

		this.selectTab(selectedTab);
	},

	clickTab: function(id) {
		this.selectTab($(id).up('.our-tab-tab'));
		$$('.our-status-bar-hidden').each(function(item, index) {
				item.removeClassName('our-status-bar-hidden')
		});
		if (this._tabSelectCallback != null)
		{
			this._tabSelectCallback($(id).innerHTML);
		}
	},

	tabClicked: function(evt) {
		this.selectTab(Event.element(evt).up('.our-tab-tab'));
		if(Event.element(evt).innerHTML == 'Dashboard'){
			$$('.our-status-bar-hidden').each(function(item, index) {
				item.removeClassName('our-status-bar-hidden')
			});
			$$('.our-status-bar').each(function(item, index) {
				item.addClassName('our-status-bar-hidden')
			});
		}else{
			$$('.our-status-bar-hidden').each(function(item, index) {
				item.removeClassName('our-status-bar-hidden')
			});
		}
		if (this._tabSelectCallback != null)
		{
			this._tabSelectCallback(Event.element(evt).innerHTML);
		}
	},

	selectTab: function(tab) {
		tab = $(tab);
		var tabs = tab.up().getElementsBySelector('.our-tab-tab');
		var selectedPane = tab._pane;

		tabs.invoke('removeClassName', 'our-tab-tab-selected');
		tab.addClassName('our-tab-tab-selected');

		var z = 100;
		var deltaZ = 1;
		for (var i = 0; i < tabs.length; i++) {
			tabs[i].style.zIndex = z;
			if (tabs[i] == tab) {deltaZ = -1;}
			z += deltaZ;
		}

		for (var i = 0; i < this._panes.length; i++) {
			var pane = this._panes[i]
			if (selectedPane == pane) {
				pane.show();
			} else {
				pane.hide();
			}
		}
	}
};

var OurSliderField = Class.create();
OurSliderField.prototype = {

	initialize: function(textField, options) {
		this._input = $(textField);
		this._oldValue = this.value();
		this._minimum = options.minimum;
		this._maximum = options.maximum;
		if (typeof this._minimum == 'undefined') {this._minimum = 0;}
		if (typeof this._maximum == 'undefined') {this._maximum = 100;}

		var minor = options.minor_divisions;
		var major = options.major_divisions;
		if (typeof minor == 'undefined') {minor = 10};
		if (typeof major == 'undefined') {major = 2};

		var parent = this._input.up();
		var slider = $(document.createElement('div'));
		var ticks = $(document.createElement('div'));
		var tt = $(document.createElement('table'));
		var tr, td;
		var i;

		this._track = $(document.createElement('div'));
		this._thumb = $(document.createElement('div'));

		var gutter = $(document.createElement('div'));
		var lcap = $(document.createElement('div'));
		var rcap = $(document.createElement('div'));

		slider.addClassName('our-slider');
		slider.appendChild(this._track);

		if (minor > 0) {
			ticks.appendChild(tt);

			tr = $(document.createElement('tr'));
			for (var i = 0; i < minor; i++) {
				td = $(document.createElement('td'));
				td.innerHTML = '<div>&nbsp;</div>';
				tr.appendChild(td);
			}
			tt.appendChild(tr);

			if (major > 0) {
				var majorSpan = Math.floor(minor / major);
				tr = $(document.createElement('tr'));
				for (var i = 0; i < major; i++) {
					td = $(document.createElement('td'));
					td.className = 'major-tick';
					td.colSpan = majorSpan;
					td.innerHTML = '<div>&nbsp;</div>';
					tr.appendChild(td);
				}
				tt.appendChild(tr);
			}

			ticks.addClassName('our-slider-ticks');
			slider.appendChild(ticks);
		}

		this._track.addClassName('our-slider-track');
		parent.insertBefore(slider, this._input);

		lcap.addClassName('our-slider-lcap');
		this._track.appendChild(lcap);
		gutter.addClassName('our-slider-gutter');
		this._track.appendChild(gutter);
		rcap.addClassName('our-slider-rcap');
		this._track.appendChild(rcap);

		this._thumb.addClassName('our-slider-thumb');
		this._track.appendChild(this._thumb);

		this._maxLeft = this._track.offsetWidth - this._thumb.offsetWidth;

		this._mouseDown    = this.mouseDown.bindAsEventListener(this);
		this._mouseMove    = this.mouseMove.bindAsEventListener(this);
		this._mouseUp      = this.mouseUp.bindAsEventListener(this);
		this._fieldChanged = this.fieldChanged.bindAsEventListener(this);
		this._dragging     = false;

		Event.observe(this._thumb, 'mousedown', this._mouseDown);
		Event.observe(document, 'mousemove', this._mouseMove);
		Event.observe(document, 'mouseup', this._mouseUp);
		new Form.Element.Observer(this._input, 0.25, this._fieldChanged);

		this.updateThumbPosition();
	},

	mouseDown: function(evt) {
		this._dragging = true;
		this._dragOrigin = Event.pointerX(evt);
		this._thumbOrigin = this._thumb.offsetLeft;
		Event.stop(evt);
	},

	mouseMove: function(evt) {
		if (!this._dragging) {return;}
		var offsetLeft = this._thumbOrigin + (Event.pointerX(evt) - this._dragOrigin);
		if (offsetLeft < 0) {offsetLeft = 0;}
		if (offsetLeft > this._maxLeft) {offsetLeft = this._maxLeft;}
		this._thumb.style.left = offsetLeft + 'px';
		this.updateValue();
		Event.stop(evt);
	},

	mouseUp: function(evt) {
		if (!this._dragging) {return;}
		this._dragging = false;
		Event.stop(evt);
	},

	fieldChanged: function(element) {
		var newValue = $F(this._input);
		if (newValue != this._oldValue) {
			this._oldValue = newValue;
			this.updateThumbPosition();
		}
	},

	updateValue: function() {
		var x = this._thumb.offsetLeft;

		this._value = Math.floor(this._minimum + ((x / this._maxLeft) * (this._maximum - this._minimum)));
		this._input.value = this._value;
	},

	updateThumbPosition: function() {
		var x = Math.floor(((this.value() - this._minimum) / (this._maximum - this._minimum)) * this._maxLeft);

		if (x < 0) {x = 0;}
		if (x > this._maxLeft) {x = this._maxLeft;}

		this._thumb.style.left = x + 'px';
	},

	value: function() {
		return parseInt($F(this._input), 10);
	}
};

var OurTokenField = Class.create();
OurTokenField.prototype = {

	initialize: function(selectElement) {
		var field    = document.createElement('div');
		var controls = document.createElement('div');
		var clr      = document.createElement('div');
		var newOption;

		this._tokens  = document.createElement('div');
		this._addMenu = document.createElement('select');
		this._name    = selectElement.getAttribute('name');
		this._id      = selectElement.id;

		field.className        = 'tokens-field';
		this._tokens.className = 'tokens';
		controls.className     = 'tokens-controls';
		clr.className          = 'our-clr';

		field.appendChild(controls);
		field.appendChild(this._tokens);
		field.appendChild(clr);
		controls.appendChild(this._addMenu);

		this._options = [];
		this._values = [];
		var options = selectElement.getElementsBySelector('option');
		for (var i = 0; i < options.length; i++) {
			var option = options[i];
			var selected = ((option.getAttribute('selected') == 'selected') || (option.getAttribute('selected') == true));

			this._values[this._values.length] = option.value;
			this._options[option.value] = {displayValue:option.innerHTML, selected:selected};
		}

		this.build();

		selectElement.up().insertBefore(field, selectElement);
		selectElement.up().removeChild(selectElement);

		Event.observe(this._addMenu, 'change', this.addMenuChanged.bindAsEventListener(this));
	},

	addMenuChanged: function() {
		if ($F(this._addMenu) == '') {return;}
		this._addedValue = $F(this._addMenu);
		var addedToken = this.selectValue(this._addedValue);
		this._addedValue = null;
		Effect.Appear(addedToken, {duration:0.5})
	},

	finishRemove: function(effect) {
		this.deselectValue(effect.element._value);
	},

	removeLinkClicked: function(evt) {
		var link = Event.findElement(evt, 'a');
		var token = $(link.rel);
		Effect.Fade(token, {duration:0.5, afterFinish:this.finishRemove.bindAsEventListener(this)})
	},

	selectValue: function(value) {
		this._options[value].selected = true;
		return this.build(value);
	},

	deselectValue: function(value) {
		this._options[value].selected = false;
		return this.build(value);
	},

	build: function(selectedValue) {
		var newToken = null;

		this._addMenu.blur();

		while (this._tokens.hasChildNodes()) {$(this._tokens.firstChild).remove();}
		while (this._addMenu.hasChildNodes()) {$(this._addMenu.firstChild).remove();}

		var newOption = document.createElement('option');
		newOption.value = '';
		newOption.innerHTML = 'Add...';
		this._addMenu.appendChild(newOption);
		this._addMenu.disabled = true;

		for (var i = 0; i < this._values.length; i++) {
			var value = this._values[i];
			var option = this._options[value];

			if (option.selected) {
				var addedToken = this.addToken(value);
				if (value == selectedValue) {newToken = addedToken;}
			} else {
				this.addOption(value);
			}
		}

		this._addMenu.value = '';

		return newToken;
	},

	addToken: function(value) {
		var newToken = document.createElement('div');
		var content = document.createElement('div');
		var leftCap = document.createElement('div');
		var rightCap = document.createElement('div');
		var input = document.createElement('input');
		var link = document.createElement('a');
		var string = document.createElement('span');

		newToken.className = 'token';
		newToken.id        = this._id + '_' + value;
		newToken._value    = value;

		if (value == this._addedValue) {
			newToken.style.display = 'none';
		}

		leftCap.className  = 'token-cap token-cap-left';
		leftCap.innerHTML  = '&nbsp;'
		rightCap.className = 'token-cap token-cap-right';
		rightCap.innerHTML = '&nbsp;'

		input.name  = this._name;
		input.type  = 'hidden';
		input.value = value;

		link.href      = "#";
		link.onclick   = function() {return false;};
		link.rel       = newToken.id;
		link.innerHTML = '<span>remove</span>';
		Event.observe(link, 'click', this.removeLinkClicked.bindAsEventListener(this), false);

		string.className = 'token-string';
		string.innerHTML = this._options[value].displayValue;

		content.className = 'token-content';
		content.appendChild(string);
		content.appendChild(link);
		content.appendChild(input);

		newToken.appendChild(leftCap);
		newToken.appendChild(content);
		newToken.appendChild(rightCap);
		this._tokens.appendChild(newToken);

		return newToken;
	},

	addOption: function(value) {
		var newOption = document.createElement('option');
		newOption.value = value;
		newOption.innerHTML = this._options[value].displayValue;
		this._addMenu.appendChild(newOption);
		this._addMenu.disabled = false;
	}

};

var OurExternalTokenField = Class.create(OurTokenField, {
	initialize: function($super, selectID) {
		$super($(selectID));
		this._checkBox = $(selectID + "_checkbox");
		if (this._checkBox != null) {
			this._checkBox._tokenField = this;
			this._checkBox.observe("click", this.allClick.bindAsEventListener(this));
		}
	},
	addMenuChanged: function($super) {
		$super();
		if (this._checkBox != null && this._addMenu.childNodes.length == 1) {
			this._checkBox.setValue(1);			
		}
	},
	addToken: function($super, value) {
		var container = $(value);
		if (!container.visible()) {
			var remover = container.select(".remover")[0];
			var input = document.createElement("input");
			input.name  = this._name;
			input.type  = "hidden";
			input.value = value;
			container.appendChild(input);
			remover.observe("click", this.removeClick.bindAsEventListener(this, value));
			container.show();
		}
		return container;
	},
	removeClick: function(evt, value) {
		var token = this.removeToken(value);
		Effect.Fade(token, {duration:0.5});		
	},
	removeToken: function(value) {
		var container = $(value);
		if (container.visible()) {
			var remover = container.select(".remover")[0];
			var input = container.select("input")[0];
			remover.stopObserving();
			container.removeChild(input);
			this.deselectValue(value);
			if (this._checkBox != null) {
				this._checkBox.setValue(null);				
			}
		}
		return container;
	},
	allClick: function(evt) {
		value = $F(this._checkBox);
		if (value) {
			while (this._addMenu.childElements().length > 1) {
				var value = this._addMenu.childElements()[1].value;
				var token = this.selectValue(value);
				token.show();
			}
		} else {
			for (var i = 0; i < this._values.length; i++) {
				var value = this._values[i];
				var token = this.removeToken(value);
				token.hide();
			}
		}
		this.build();
	}
});

var OurAjaxPagination = Class.create();

OurAjaxPagination.prototype = {

	initialize: function(containerID, pageURL, parameters) {
		this._container = $(containerID);
		this._container.ourAjaxPagination = this;
		this._pageURL = pageURL;
		this._parameters = $H(parameters);
		this.attachLinks(false);
	},

	attachLinks: function(scrollAfter) {
		links = this._container.getElementsBySelector(".pagination a");
		if (links && links.length > 0) {
			links.each(function(link) {
				this.ajaxifyLink(link, true);
			}.bind(this));
		}    
		if (scrollAfter) {
			this._container.scrollTo();
		}
	},

	ajaxifyLink: function(link) {
		var params = $H(link.href.toQueryParams());
		var page = params.get("page");
		if (typeof page == "undefined") {
			page = 1;
		}
		link.writeAttribute("href", "#");
		link.writeAttribute("rel", page);
		link.writeAttribute("onclick", "return false;");
		link.observe('click', this.gotoPage.bindAsEventListener(this));
	},

	gotoPage: function(evt) {
		var link = $(evt.element());
		var params = this._parameters.clone();
		var scrollAfter = link.up(".pagination").hasClassName("lower");
		params.set("page", link.rel);
		new Ajax.Updater(
			this._container,
			this._pageURL,
			{
				parameters:params,
				asynchronous:true,
				evalScripts:true,
				onComplete:this.afterPage.bindAsEventListener(this, scrollAfter)
			}
		);
	},

	afterPage: function(evt, scrollAfter) {
		this.attachLinks(scrollAfter);
		document.fire('ourstage:ajaxLoaded');
	}

};

tabberOptions = {tabCaps:true};

var OurCountdownTimer = Class.create();

OurCountdownTimer.prototype = {

	initialize: function(containerID, utcEndTime, hoverString) {
		this._TimerString = document.createElement('div');
		this._TimerString.className = 'countdown-timer-string';
		$(containerID).appendChild(this._TimerString);
		
		this._LabelString = document.createElement('div');
		this._LabelString.className = 'countdown-label-string';
    this._LabelString.innerHTML = hoverString;
		$(containerID).appendChild(this._LabelString);

		this._utcEndTime = Date.parse(utcEndTime);

    setTimeout(this.onTickDown.bind(this), 1000);
	},

	onTickDown: function() {
	  var now = new Date();
	  var diffInSecs = (this._utcEndTime - now) / 1000;
	  if (diffInSecs > 0) {
	    var sec = diffInSecs % 60;
	    var secLo = parseInt(sec % 10);
	    var secHi = parseInt(sec / 10);

      var min = (diffInSecs / 60) % 60;
	    var minLo = parseInt(min % 10);
	    var minHi = parseInt(min / 10);

      var hour = (diffInSecs / 60 / 60) % 24;
	    var hourLo = parseInt(hour % 10);
	    var hourHi = parseInt(hour / 10);

      var day = parseInt(diffInSecs / 60 / 60 / 24);

		  this._TimerString.innerHTML = "" + day + "d<span class='day-colon'>:</span>" + hourHi + hourLo + "h<span class='hour-colon'>:</span>" + minHi + minLo + "m<span class='minute-colon'>:</span>" + secHi + secLo + "s";
		  setTimeout(this.onTickDown.bind(this), 1000);
	  } else {
	    this._TimerString.innerHTML = "";
	    this._LabelString.innerHTML = "";
    }
	}

};
