function delegate(obj, method)
{
	delegate.callerObject = this; // this var can be used in the closure to refer to the caller object
	
	var closure = function () 
	{
		method.apply(obj, arguments);
	}
	
	return closure;
}

// menu fixes for ie 6/7
function fixIe67Menu() {
	$('ul#topNav>li, #nav>ul>li').css('position', 'relative').each(function (index){
		this.style.left = (-(index - 3)) + 'px'; // get next separator within the previous item
		// var link = $('a div ul', this)[0];
		//this.style.zIndex = link.style.zIndex - 1000; // get separator under green bg

		// fix reduced hotspot area
		this.style.cursor = 'pointer'; 
		$(this).hover(
			function () { $($('a', this)[0]).trigger('mouseOver').addClass('hover') },
			function () { $($('a', this)[0]).trigger('mouseOut').removeClass('hover') }
		);
	});	
	
	$('#nav>ul>li').css('position', 'relative').each(function (index){
		var link = $('a div ul', this)[0];
		link.style.paddingRight = '19px'; // 18px in intended style, compensate for relative offset
	});	
}

// ---------------------------------------------------------------------------------------------------------------------
nms = {};
// rollOver ref.counter. Some events on rollout occur only of there are not rollovers in progress
// for menus, rollOut is counted when the menu has done animating the hide transition
nms.roCount = 0;
nms.DropMenu = function () {}

nms.DropMenu.show = function ()
{
	if (this.timerId) {
		clearInterval(this.timerId);
		nms.roCount--;
	}
	var context = $('div', this);	
	context.stop(true, true).slideDown($('a', context).length*10 + 100);
	$('a', this).addClass('hover');
	$('#nav li a.active, #topNav li a.active').removeClass('active').addClass('halfactive');
	$('#nav li a.fauxactive, #topNav li a.fauxactive').removeClass('fauxactive').addClass('fauxhalfactive');
	nms.roCount++;
}

nms.DropMenu.showNoMenu = function ()
{
	$('#nav li a.active, #topNav li a.active').removeClass('active').addClass('halfactive');
	$('#nav li a.fauxactive, #topNav li a.fauxactive').removeClass('fauxactive').addClass('fauxhalfactive');
	nms.roCount++;
}

nms.DropMenu.hide = function ()
{
	var that = this;
	clearInterval(this.timerId);
	this.timerId = setTimeout(function() { nms.DropMenu.realHide(that); }, 65);
}

nms.DropMenu.hideNoMenu = function ()
{
	nms.roCount--;
	if (nms.roCount == 0) {
		$('#nav li a.halfactive, #topNav li a.halfactive').removeClass('halfactive').addClass('active');
		$('#nav li a.fauxhalfactive, #topNav li a.fauxhalfactive').removeClass('fauxhalfactive').addClass('fauxactive');
	}
}

nms.DropMenu.realHide = function (that)
{
	that.timerId = null;
	var context = $('div', that);	
	context.stop(true, true).slideUp($('a', context).length*5 + 50, function () {
		nms.roCount--;
		$('a', that).removeClass('hover');
		if (nms.roCount == 0) {
			$('#nav li a.halfactive, #topNav li a.halfactive').removeClass('halfactive').addClass('active');
		}
	});
}

$(function () {
	$('#nav li:has(div), #topNav li:has(div)').hover(nms.DropMenu.show, nms.DropMenu.hide);
	$('#nav li:not(:has(div)), #topNav li:not(:has(div))').hover(nms.DropMenu.showNoMenu, nms.DropMenu.hideNoMenu);
});

// ---------------------------------------------------------------------------------------------------------------------

// designed as a singleton, works only for one instance

nms.SlideShow = function (hostEl, picUrls, widthPx, heightPx, pauseMs, slideMs, fadeMs) {
	nms.SlideShow.instance = this;
	
	this.hostEl = hostEl;
	this.picUrls = picUrls;
	this.fadeMs = fadeMs;
	this.slideMs = slideMs;
	this.pauseMs = pauseMs;
	this.widthPx = widthPx;
	this.heightPx = heightPx;
	this.loaded = 0;
	this.position = 0;
	this.sliding = false;
	
	
	var code = '';
	
	var that = this;
		
	function genPic(config) {
		return '<div class="slidePic" onclick="document.location.href=' + config.url + '" style="cursor:pointer; z-index: ' + (1000 - i) + '; width:'+that.widthPx+'px; height:'+that.heightPx+'px;"><img onload="nms.SlideShow.onLoadImg(this)" src="/_media/home/html/' + config.name + '.jpg" /></div>';
	}
	
	for (i=0, m = this.picUrls.length; i < m; i++) {
		code += genPic(this.picUrls[i]);
	}
	
	// dupe last to form a loop
	code += genPic(this.picUrls[0]);
		
	$(hostEl).html('<div class="slideFrame">' + code + '</div>').width(widthPx).height(heightPx);
	
	$('.slideFrame').hide();
}

nms.SlideShow.instance = null;

nms.SlideShow.onLoadImg = function(img) {
	var that = nms.SlideShow.instance;
	that.loaded ++;
	
	if (that.loaded > that.picUrls.length && !that.sliding) {
		$('.slideFrame').show();		
		setTimeout(nms.SlideShow.onSlide, that.pauseMs + that.slideMs);
		that.sliding = true;
	}
}

nms.SlideShow.onSlide = function () {
	var that = nms.SlideShow.instance;
	
	if (that.position >= that.picUrls.length) {
		that.position = 0;
		$('.slideFrame .slidePic', that.hostEl).css('opacity', 1).show();
	}
	
	var photo = $('.slideFrame .slidePic', that.hostEl).eq(that.position);
	photo.animate({opacity: 0}, that.slideMs, function () { photo.hide();});
	
	that.position++;
	
	setTimeout(nms.SlideShow.onSlide, that.pauseMs + that.slideMs);
}



// ---------------------------------------------------------------------------------------------------------------------


nms.Scroller = function (scrollHandle, scrollBase, scrollClient, scrollArea) 
{
	this.scrollHandle = scrollHandle;
	this.scrollBase = scrollBase;
	this.scrollClient = scrollClient;
	this.scrollArea = scrollArea;
		
	scrollHandle.draggable({
		containment: scrollBase,
		start: delegate(this, this.startHandleDrag),
		stop: delegate(this, this.stopHandleDrag)
	});
  
  	var me = this;
  	
  	scrollArea.hover(
  		function () { nms.WheelManager.hookWheel(delegate(me, me.onWheel)); },
  		function () { nms.WheelManager.unhookWheel(); }
  	);
  	
	this.initScroller();
	
	// handles some edge cases where the scroller ends up in bad state on startup or during transitions
	// soft initialization allows the proper reaction to the current state
	setInterval(function () {me.initScroller(true);}, 300);
}

nms.Scroller.prototype = 
{
	handleTimer: null,
	areaOffset: 0,
	offColorBase: null,
	
	scrollHandle:null, // the scrollbar handle
	scrollBase:null, // the scroller base containing the handle
	scrollClient:null, // div beig scrolled
	scrollArea:null, // div containing the scrolled area
	
	dragging:false, // whether the handle is being dragged in the moment
	
	// softInit won't reset the cursor position, default is hard init
	initScroller: function (softInit)
	{
		if (typeof softInit == 'undefined') {
			softInit = false;
		}
		
		if (!softInit) this.scrollHandle.css('top', '0px');
		var areaHeight = this.scrollArea.height();
		var clientHeight = this.scrollClient.height() - this.scrollClient.get(0).deadSpace;
		var handleHeight = areaHeight * areaHeight / clientHeight;
		
		if (!isNaN(handleHeight)) { // won't be defined while hidden in IE
			this.scrollHandle.css('height', (handleHeight < 20 ? 20 : Math.round(handleHeight)) + 'px');
			if (areaHeight + 1 >= clientHeight) { // the + 1 account for some Safari inaccuracy that occurs.
				this.scrollHandle.hide();
			} else {
				this.scrollHandle.show();
			}
		}
		
		this.hookHandler(); // update may be needed
	},
	
	hookHandler: function ()
	{
		if (this.handleTimer === null) {
			this.handleTimer = setInterval(delegate(this, this.handleDrag), 30);
			this.handleDrag(); // for faster response the first call is direct
		}
	},
	
	unhookHandler: function ()
	{
		if (this.handleTimer !== null) {
			clearInterval(this.handleTimer);
			this.handleTimer = null;
		}
		
		//window.status = '---';
	},
	
	onWheel: function (delta)
	{
		var handle = this.scrollHandle;
		var base = this.scrollBase;
		
		// we make each click move about 100 pixels in either direction in the client.
		var offset = Math.ceil(100 * (this.scrollHandle.height() - this.scrollBase.height()) / (this.scrollClient.height() - this.scrollArea.height()) );
		var target = handle.get(0).offsetTop + delta * offset;
		target = Math.max(0, Math.min(target, base.height() - handle.height()));
		handle.css('top', Math.round(target) + 'px');
		
		this.hookHandler();
	},
	
	
	startHandleDrag: function ()
	{
		if (!$.browser.msie) {
			offColorBase = this.scrollHandle.css('background');
			this.scrollHandle.css('background', 'black');
		}
		
		this.dragging = true;
		
		this.hookHandler();
	},
	
	stopHandleDrag: function ()
	{
		if (!$.browser.msie) {
			this.scrollHandle.css('background', offColorBase);
		}
		
		this.dragging = false;
	},
	
	handleDrag: function ()
	{		
		// deadSpace is bottom padding to subtract/ignore 
		var target = (this.scrollClient.height() - this.scrollClient.get(0).deadSpace - this.scrollArea.height()) * this.scrollHandle.get(0).offsetTop / (this.scrollBase.height() - this.scrollHandle.height());
		
		var softTarget = this.areaOffset * 0.8 + target * 0.2;
		
		//window.status = softTarget + ' '+ target;
			
		if (Math.abs(softTarget - target) >= 0.4) {
			this.scrollClient.css('top', '-' + Math.round(softTarget) + 'px');
			this.areaOffset = softTarget;
		} else {
			if (!this.dragging) {
				this.unhookHandler();
			}
		}
	}
}


// ---------------------------------------------------------------------------------------------------------------------

nms.CatFilter = function (slotHost, slotScroller) 
{
	this.slotHost = slotHost;	
	this.slotScroller = slotScroller;
}

nms.CatFilter.prototype = 
{
	slotHost:null,
	slotScroller: null,

	// hashmap of selected states
	catState: {},
	
	selectCategory: function (catName, catValue, catLink)
	{
		this.catState[catName] = catValue;
		$('li', $(catLink).get(0).parentNode).removeClass('selected');
		$(catLink).addClass('selected');
		
		areaOffset = 0;
		var slots = $('.slot', this.slotHost).get();
		
		var showSlots = [];
		var hideSlots = [];
		
		for (var i = 0; i < slots.length; i++) {
			var slot = slots[i];
			var slotEl = $(slot);
			var match = true;
			for (var j in this.catState) {
				if (this.catState[j] !== null && slot.cats[j] !== '' && slot.cats[j] != this.catState[j]) {
					match = false;
				}
			}
			
			// default is 100 px for the normal slots, custom height slots use the property
			var origHeight = slotEl.get(0).originalHeight;			
			if (!origHeight) origHeight = 100; 
			
			if (match) {
				if (slotEl.height() != origHeight) showSlots.push(slotEl);
			} else {
				if (slotEl.height() != 0) hideSlots.push(slotEl);
			}
		}
		
		var transTime = Math.round(300 + 300 *(showSlots.length + hideSlots.length) / slots.length); 
		
		for (var i = 0; i < showSlots.length; i++) {
			var slotEl = showSlots[i];
			
			if ($.browser.msie || $.browser.opera) {
				slotEl.animate({'height':origHeight}, transTime, null, delegate(this.slotScroller, this.slotScroller.initScroller));
			} else {
				slotEl.animate({'height':origHeight, opacity:1}, transTime, null, delegate(this.slotScroller, this.slotScroller.initScroller));
			}
		}
		
		for (var i = 0; i < hideSlots.length; i++) {
			var slotEl = hideSlots[i];
			
			if ($.browser.msie || $.browser.opera) {
				slotEl.animate({'height':0}, transTime, null, delegate(this.slotScroller, this.slotScroller.initScroller));
			} else {
				slotEl.animate({'height':0, opacity:0}, transTime, null, delegate(this.slotScroller, this.slotScroller.initScroller));
			}
		}
	}
}


// ---------------------------------------------------------------------------------------------------------------------

nms.ProfileSlotManager = function (slotHost, profileHost)
{ 
	$('.slot', slotHost).click(delegate(this, this.slotClick));	
	
	this.slotHost = slotHost;
	this.profileHost = profileHost;
}

nms.ProfileSlotManager.prototype = {
	profileHost:null,
	slotHost:null,	
	lastSelectedSlot: null,
	profileSwitcher: null, // instance of nms.SwitcherManager
	
	slotClick: function (e) {
		var targ;
		
		// element target 
		
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
		
		// find the slot element
		
		while (targ.className != 'slot') targ = targ.parentNode;
		
		// process profile host
		
		this.profileHost.get(0).innerHTML = 'Loading...';
		
		if (this.lastSelectedSlot) $('img', this.lastSelectedSlot).animate({opacity:1}, 200);
		this.lastSelectedSlot = $(targ);
		
		$('img', targ).animate({opacity:0.5}, 200);
		
		selectedSwitcher = null;
		
		$.post(
			document.location.href, 
			{action:'getProfile', profileId:this.lastSelectedSlot.get(0).profileId}, 
			delegate(this, callback)
		);
		
		function callback(data, status)
		{
			this.profileHost.get(0).innerHTML = data;
			
			this.profileSwitcher = new nms.SwitcherManager($('#bioBox'));
		}
	}
}

// ---------------------------------------------------------------------------------------------------------------------

nms.SwitcherManager = function (switcherHost, useSeparators /* = true */, useIds /* = false */, selectId /* = 0 */) 
{ 
	if (typeof useSeparators == 'undefined') {
		this.useSeparators = useSeparators = true;
	} else {
		this.useSeparators = useSeparators;
	}
	
	if (typeof useIds == 'undefined') {
		this.useIds = useIds = false;
	} else {
		this.useIds = useIds;
	}
	
	if (typeof selectId == 'undefined') {
		selectId = 0;
	}
	
	this.switcherHost = switcherHost;
	
	var hostEl = switcherHost.get(0);
	var childNodes = hostEl.childNodes;
	
	var headings = [];
	var segs = [];
	var segId = -1;
	
	var compositeHeading = '<h2 class="switchTitles">';
	
	var childNodesCopy = [];
	
	for (var i = 0, m = childNodes.length; i < m; i++) {
		childNodesCopy.push(childNodes[i]);
	}
				
	for (var i = 0, m = childNodesCopy.length; i < m ; i++) {
		hostEl.removeChild(childNodesCopy[i]);
	}	
	
	for (var i = 0, m = childNodesCopy.length; i < m; i++) {

		if (childNodesCopy[i].nodeType != 3 && childNodesCopy[i].nodeName.toLowerCase() == 'h2') {
			segId ++;
			headings[segId] = childNodesCopy[i];			
			childNodesCopy[i].style.display = 'none';
			if (useIds) {
				var idStr = ' id="switchTitle'+segId+'"';
			} else {
				var idStr = '';
			}
			compositeHeading += (segId && useSeparators ? ' / ' : '') + '<span class="switchTitle"'+idStr+'>' + childNodesCopy[i].innerHTML + '</span>';
			
		} else {
			
			if (segId > -1) {
				if (!segs[segId]) {
					segs[segId] = document.createElement('div');
					segs[segId].style.display = 'none';
					segs[segId].className = 'switchSegment';
					if (useIds) {
						segs[segId].id = 'switchSegment'+segId;
					}
				}
				
				var node = childNodesCopy[i];
				segs[segId].appendChild(node);
			}
		}
	}
	
	compositeHeading += '</h2>';
	
	compositeHeading = $(compositeHeading);
	
	var spans = $('>span', compositeHeading)
					.click(delegate(this, this.switcherClickHandler))
					.hover(delegate(this, this.switcherOver), delegate(this, this.switcherOut)).get();
	
	for (var i in spans) {
		spans[i].switchIndex = i;
	}
	
	hostEl.appendChild(compositeHeading.get(0));
	
	for (var i in segs) {
		hostEl.appendChild(segs[i]);
	}
	
	this.switcherSegs = segs;
		
	if (selectId !== null && spans[selectId]) {
		this.switcherClickHandler({target:spans[selectId]});
	}
}

nms.SwitcherManager.prototype = {
	useSeparators: null,
	useIds:null,
	
	switcherHost: null,
	
	switcherSegs: null,
	
	selectedSwitcher: null,
	
	getSwitchTitle: function (e)
	{
		// element target 
		
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
		
		// find the slot element
		
		while (targ.className.indexOf('switchTitle') == -1) {
			targ = targ.parentNode;
		}
		
		return targ;
	},
	
	switcherClickHandler: function (e)
	{
		this.switcherClick(this.getSwitchTitle(e));
	},
	
	switcherClick: function (sender)
	{
		this.selectedSwitcher = sender;
		
		$('h2.switchTitles span', this.switcherHost).removeClass('active');
		$(sender).addClass('active');
		
		var segs = this.switcherSegs;
		
		if (this.useIds) {
			var seg = $('#switchSegment'+sender.switchIndex);
		} else {
			var seg = $(segs[sender.switchIndex]);
		}
					
		if ($.browser.msie) {
			$(segs).hide();
			seg.show();
		} else {
			$(segs).hide();			
			seg.fadeIn(200);
		}
	},
	
	switcherOver: function (e)
	{	
		$(this.getSwitchTitle(e)).addClass('active');
	},
	
	switcherOut: function (e)
	{
		var targ = this.getSwitchTitle(e);
		if (targ !== this.selectedSwitcher) $(targ).removeClass('active');
	}
}

// ---------------------------------------------------------------------------------------------------------------------

nms.WheelManager = {
	handler: null,
	
	hookWheel: function (handler)
	{
		nms.WheelManager.handler = handler;
		
		// gecko
		if (window.addEventListener) {
			window.addEventListener('DOMMouseScroll', nms.WheelManager.onWheel, false);
		}
		
		// ie/opera
		window.onmousewheel = document.onmousewheel = nms.WheelManager.onWheel;		
	},
	
	unhookWheel: function ()
	{
		nms.WheelManager.handler = null;
		
		// gecko
		if (window.addEventListener) {
			window.removeEventListener('DOMMouseScroll', nms.WheelManager.onWheel, false);
		}
		
		// ie/opera
		window.onmousewheel = document.onmousewheel = null;	
	},
	 
	onWheel: function (event) 
	{
		if (!nms.WheelManager.handler) return;
		
		var delta = 0;
		if (!event) event = window.event; // IE
			
		if (event.wheelDelta) { // Opera / IE
			delta = event.wheelDelta == 0 ? 0 : event.wheelDelta > 0 ? 1 : -1;
		} else if (event.detail) { // Mozilla			
			// has flipped delta signs
			delta = event.detail == 0 ? 0 : event.detail > 0 ? -1 : 1;
		}
		
		if (delta) {
			nms.WheelManager.handler(delta);
		}
	
		if (event.preventDefault) event.preventDefault();
		event.returnValue = false;		
		return false;
	}
}


/**
 * Events Slideshow Overlay
 */
function Overlay(overlayData, overlayHost)
{
	this.data = overlayData;
	this.hostEl = overlayHost;
	
	var doc = $(document);
	var win = $(window);
	var that = this;
	
	if (Overlay.instance !== null) {
		Overlay.instance.destruct();
	}
	
	Overlay.instance = this;

	$(this.hostEl).append(
		$('<div id="overlayFade"></div>').css('opacity', 0)
	);
	
	$('#overlayFade').height(doc.height()).animate({'opacity': 0.82}, 240, part2);
		
	function part2()
	{
		var fade = $('#overlayFade');
		var startLeftMargin = Math.floor(win.width()/2) - 2/2;
		var startTopMargin = Math.floor(win.height()/2) - 435/2 + $(document).scrollTop();
		var endLeftMargin = Math.floor(win.width()/2) - 705/2;
		
		$(that.hostEl).append('<div id="overlayPlate" style="margin-left:' + startLeftMargin + 'px; margin-top:' + startTopMargin + 'px"></div>');
		
		var plate = $('#overlayPlate');
		
		var animate = { 
			'width': '704px', 
			'marginLeft': endLeftMargin + 'px'
		};
		
		if (!$.browser.msie) {
			plate.css('opacity', 0);
			animate.opacity = 1;
		} else {
			plate.css('background-color', '#070706');
			animate.backgroundColor = '#fbfbfb';
		}
	
		$('#overlayPlate').animate(animate, 320, part3);
	}
		
	
	function part3()
	{
		var html = '';
		
		html += '<div id="overlayClient">';
		html += '<div class="controlsLeft">';
			html += '<p class="newsDate" style="margin-top:-2px;">' + that.data.event.date + '</p>';
			html += '<h2 class="newsTitle">' + that.data.event.title + '</h2>';
			html += '<p class="newsPartners">' + that.data.event.partners.split('<br>').join(', ') + '</p>';
		html += '</div>';
		html += '<div class="controlsRight"><a href="" class="close-link">Close</a></div><br clear="all">';
		html += '<div class="colLeft">&nbsp;</div>';
		html += '<div class="colRight">';
			var x = 40;
			var y = 0;
			for (var i = 0; i < that.data.slides.length; i++) {
				html += '<div class="icon" onclick="Overlay.instance.showSlide(' + that.data.slides[i] + '); return false" style="top:' + y + 'px; left:' + x + 'px; background-image:url(/_media/generated/slide-thumb-' + that.data.slides[i] + '.jpg)">&nbsp;</div>';
				y += 60;
				if (y >= 300) {
					x += 60;
					y = 0;
				}
			}
		html += '</div>';
		html += '<div id="overlayClientReveal"></div>';
		
		$('#overlayPlate').append($(html));
		
		// close link
		$('#overlayClient .controlsRight a').click(function () { that.destruct(); return false; });
		
		// show first slide auto
		that.showSlide(that.data.slides[0]);
		
		$('#overlayClientReveal').css('opacity', 1).animate({opacity: 0}, 120, part4);
	}
	
	function part4()
	{
		$('#overlayClientReveal').hide();
	}
}

Overlay.instance = null;
Overlay.linkOffColor = '#999';
Overlay.linkOnColor = '#292929';

Overlay.prototype = {
	data: null,
	hostEl: null,
	
	destruct: function ()
	{
		$('#overlayPlate').hide();
		$('#overlayFade').animate({opacity: 0}, 240, part1);
		
		var that = this;
		
		function part1()
		{
			$(that.hostEl).html('');
			Overlay.instance = null;
		}
	},
	
	showSlide: function(id)
	{
		var img = $('<img src="/_media/generated/slide-big-' + id + '.jpg">').css('opacity', 0).load(function () { $(this).animate({'opacity' : 1}, 300) });
		$('#overlayClient .colLeft').html('').append(img);		
	}
}


nms.EventScroller = function(count, containerId) {
	this.count = count;
	this.containerId = containerId;
	this.containerEl = $('#eventsWidget' + containerId);
	nms.EventScroller.instances[containerId] = this;
	// this.startTimer();
	var that = this;
	setInterval(function () { that.updateScrollBar() }, 20);
	
	$('.eventScrollSubcontainer', this.containerEl).css('top', 100);
	this.selectBox(0);
}

nms.EventScroller.instances = {};

nms.EventScroller.prototype = {
	containerId:null,
	containerEl:null,
	count:null,
	current:0,
	timer:null,
	currentBox:-1, // used for scroll display only
	
	startTimer: function ()
	{
		if (this.timer) clearInterval(this.timer);
		var that = this;
		this.timer = setInterval(function () { that.selectNextBox() }, 5000);
	},
	
	stopTimer: function ()
	{
		if (this.timer) clearInterval(this.timer);
	},
	
	updateScrollBar: function ()
	{
		var count = this.count;
		var that = this;
		function findCurrentPos(y, offs) {
			var i = 0; 
			while (i < count) {
				var pos = $('#eventScrollBox' + i, that.containerEl).position();
				if (y + offs >= -pos.top) return i;
				i++;
			}
			
			return i;
		}
		
		var currentBox = findCurrentPos(parseInt($('.eventScrollSubcontainer', this.containerEl).css('top')), 50);
		if (currentBox != this.currentBox) {
			$($('.eventScroller a', this.containerEl).removeClass('active').addClass('inactive')[currentBox]).removeClass('inactive').addClass('active');
			this.currentBox = currentBox;
		}
	},
	
	selectNextBox: function ()
	{
		if (this.current == this.count) {
			this.stopTimer();
		} else {
			this.selectBox(this.current + 1);
		}
	},
	
	selectBox: function (i, skipAnimation)
	{
		var scrollBox = $('#eventScrollBox' + i, this.containerEl);
		var pos = scrollBox.position();
		var containerHeight = scrollBox.height(); // Math.max(scrollBox.height(), 300);
		var subcontainerTop = -pos.top;
		
		if (skipAnimation) {
			$('.eventScrollSubcontainer', this.containerEl).css('top', subcontainerTop);
			$('.eventScrollContainer', this.containerEl).css('height', containerHeight);
		} else {
			var speed = Math.abs(this.current - i) * 200 + 500;
			$('.eventScrollSubcontainer', this.containerEl).animate({'top': subcontainerTop}, speed, 'easeInOutQuad');
			$('.eventScrollContainer', this.containerEl).animate({'height': containerHeight}, speed, 'easeInOutQuad');
		}
		
		this.current = i;
	},
	
	selectBoxByButton: function (i)
	{
		this.stopTimer();
		this.selectBox(i);
	}
}

// FlashManager v.1.01 (c) 2006-2009 Stan Vassilev

function FlashManager(params) {
	var checkList = {}; // the supported params are copies here and unknown params are detected and cause an error
	
	var enlistParam = function (param,def) {
		if (params[param] === undefined) params[param] = def;
		checkList[param] = params[param];
	}
	// list of supported params and their defaults
	enlistParam('movie','flash.swf');
	enlistParam('bgcolor',''); // expected format: "#XXXXXX"
	enlistParam('width','100%'); // accepts pixels (no unit) or %
	enlistParam('height','100%');	// accepts pixels (no unit) or %
	enlistParam('version','4,0,0,0'); // player version required for the content, in format A,B,C,D
	enlistParam('altContent','This content requires a new version of Flash Player. Please update your player <a href="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">here</a>.'); // shown when flash player isn't installed or too old
	enlistParam('flashVars',''); // pass data to Flash from a query string
	enlistParam('wmode','window'); // draw/control mode:  window (default), opaque, transparent
	enlistParam('allowFullScreen', false); // true / false
	enlistParam('name',''); // applies as "name" for <embed> and "id" for <object> and used for JS<->Flash communication
	enlistParam('swLiveConnect', false); // false (default), true: applies to <embed> to allow JS<->Flash communication
	enlistParam('expressInstall', false); // false (default), true: will pass special data via FlashVars required for Express Install
	
	// check for phantom params and dump on the object
	for (var i in params) {
		if (checkList[i] === undefined) alert("FlashManager: Unknown parameter \""+i+"\" passed to the constructor.");		
		this[i] = params[i];
	}
}

// encodes strings in form suitable for passing via GET and FlashVars to Flash
FlashManager.qscape = function(str) {
	str = String(str).split(' ');
	for (var i=0; i<str.length; i++) str[i] = escape(str[i]);
	return str.join('+');
}

// encodes a hashmap of values to a flashvars query string
FlashManager.objectToFlashVars = function (object) {
	var out = [];
	
	for (var i in object) {
		out.push(FlashManager.qscape(i) + '=' + FlashManager.qscape(object[i])); 
	}
	
	return out.join('&');
}

// just writes the code to the document
// altBehaviour same as "getCode"
FlashManager.prototype.writeCode = function (altBehaviour) {
	document.write(this.getCode(altBehaviour));
}
// replaces the inner content of the element (if string is passed it's assumed an id) with the code
// altBehaviour same as "getCode"
FlashManager.prototype.replaceCodeIn = function (element,altBehaviour) {
	var reqVer = this.version.split(',');
	if (altBehaviour == "cancel" && !FlashManager.availFlash(reqVer[0],reqVer[1],reqVer[2])) return;
	
	if (typeof(element)=="string") element = document.getElementById(element);
	element.innerHTML = this.getCode(altBehaviour);
}

// returns code to embed flash content
// altBehaviour (when Flash is not available) is one of: 
//   "altContent" (default) shows altContent
//   "force" returns Flash code
//   "cancel" cancels the action and/or returns nothing
FlashManager.prototype.getCode = function (altBehaviour) {	
	FlashManager.detectFlash();
	var reqVer = this.version.split(',');
	if (altBehaviour=="force" || FlashManager.availFlash(reqVer[0],reqVer[1],reqVer[2])) {
		if (this.expressInstall) {
			if (document.title.indexOf("Flash Player Installation") == -1) { // to ensure the document is not without a title
				document.title = document.title.slice(0, 47) + (document.title.length?" - ":"") + "Flash Player Installation";
			}
		}
		
		var cont = '';
		
		if (typeof this.flashVars == 'object') this.flashVars = FlashManager.objectToFlashVars(this.flashVars);
		
		if (FlashManager.isWinIE) { // IE
			cont +=                           '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
			if (this.name) cont +=            'id="'+this.name+'" ';
			cont +=                           'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.version+'" ';
			cont +=                           'width="'+this.width+'" height="'+this.height+'">';
			cont +=                           '<param name="movie" value="'+this.movie+(this.expressInstall?('?MMredirectURL='+FlashManager.qscape(window.location)+"&MMplayerType=ActiveX&MMdoctitle="+FlashManager.qscape(document.title)):"")+'" />';
			if (this.bgcolor) cont +=         '<param name="bgcolor" value="'+this.bgcolor+'" />';
			if (this.flashVars) cont +=       '<param name="flashVars" value="'+this.flashVars+'" />';
			if (this.allowFullScreen) cont += '<param name="allowFullScreen" value="true" />';
			if (this.wmode!="window") cont += '<param name="wmode" value="'+this.wmode+'" />';
			cont +=                           '<\/object>';
		} else {			
			cont +=                           '<embed src="'+this.movie+(this.expressInstall?('?MMredirectURL='+FlashManager.qscape(window.location)+"&MMplayerType=PlugIn&MMdoctitle="+FlashManager.qscape(document.title)):"")+'" ';
			if (this.name) cont +=            'name="'+this.name+'" ';		
			if (this.bgcolor) cont +=         'bgcolor="'+this.bgcolor+'" ';
			if (this.swLiveConnect) cont +=   'swLiveConnect="true" ';	
			if (this.allowFullScreen) cont += 'allowFullScreen="true" ';		
			if (this.flashVars) cont +=       'flashvars="'+this.flashVars+'" ';
			if (this.wmode!="window") cont += 'wmode="'+this.wmode+'" ';
			cont +=                           'width="'+this.width+'" height="'+this.height+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
		}
		
	} else if (altBehaviour=="cancel") {
		var cont = '';
	} else {
		var cont = this.altContent;
	}
	
	return cont;
}

//FlashManager.isWinIE = ((navigator.appVersion.indexOf("MSIE") != -1) ? true : false) && ((navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false) && !((navigator.userAgent.indexOf("Opera") != -1) ? true : false);
FlashManager.isWinIE = navigator.appName.indexOf("Microsoft") > -1;

FlashManager.detected = false; // to avoid detection running multiple times

FlashManager.detectFlash = function () { // returns array with major version, minor version and version revision (no flash = 0,0,0)
	if (!FlashManager.detected) {
		FlashManager.detected = true;
		
		// loop backwards until we find newest version
		if (FlashManager.isWinIE) {
			for (var i = 16; i > 0; i--) {
				var versionArray = FlashManager_detectFlashVB(i).split(" ")[1].split(",");
				if (versionArray[0]>0) break;
			}
		} else {
			var versionArray = FlashManager.detectFlashJS().split(".");
		}
		FlashManager.verMajor = parseInt(versionArray[0]);
		FlashManager.verMinor = parseInt(versionArray[1]);
		FlashManager.verRevision = parseInt(versionArray[2]);		
	}	
	
	return [FlashManager.verMajor, FlashManager.verMinor, FlashManager.verRevision];
}

// return true if equal or greater version detected
FlashManager.availFlash = function (reqMajorVer, reqMinorVer, reqRevision) {
	FlashManager.detectFlash();	
	var reqVector = reqMajorVer*1000000 + reqMinorVer*1000 + parseInt(reqRevision);
	var availVector = FlashManager.verMajor*1000000 + FlashManager.verMinor*1000 + FlashManager.verRevision;
	return availVector >= reqVector;
}


// helper functions that do the actual detection

if (FlashManager.isWinIE) {
	var s = '';
	s += '<script language="VBScript" type="text/vbscript">\n';
	s += 'Function FlashManager_detectFlashVB(i)\n';
		s += 'on error resume next\n';
		s += 'Dim swControl, swVersion\n';
		s += 'swVersion = "NA 0,0,0,0"\n';
		s += 'set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))\n';
		s += 'if (IsObject(swControl)) then\n';
			s += 'swVersion = swControl.GetVariable("$version")\n';
		s += 'end if\n';
		s += 'FlashManager_detectFlashVB = swVersion\n';
	s += 'End Function\n';
	s += '<\/script>\n';
	document.write(s);
}

FlashManager.detectFlashJS = function () {
	// Gecko/Chrome/Safari/Opera check for Flash plugin in plugin array
	// TRICKY: Opera doesn't support plugins.length, but for..in works
	if (navigator.plugins != null) { // && navigator.plugins.length > 0) {
		var plugRefr = navigator.plugins["Shockwave Flash"];
		if (!plugRefr) plugRefr = navigator.plugins["Shockwave Flash 2.0"];
		 
		if (plugRefr) {
			var descArray = plugRefr.description.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];

			if ( descArray[3] != "" ) {
				var tempArrayMinor = descArray[3].split("r");
			} else {
				var tempArrayMinor = descArray[4].split("r");
			}
      var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		} else {
			var flashVer = "0.0.0";
		}
	}
	
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = "4.0.0";
	
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = "3.0.0";
	
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = "2.0.0";
	
	// can't detect in all other cases
	else flashVer = "0.0.0";
	
	return flashVer;
} 