// THIS IS WHY WEBSITES SHOULD'T BE SIMULTANEOUSLY DESIGNED AND CODED WITH NO STRATEGY ... ICKY BAD JS :(
$.extend($.easing, {easeInQuad:function (e, a, b, c, d) { return c * (a /= d) * a + b }, easeInExpo: function (x, t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b}, easeOutQuad:function (e, a, b, c, d) { return-c * (a /= d) * (a - 2) + b }, easeInOutQuad:function (e, a, b, c, d) { if((a /= d / 2) < 1) { return c / 2 * a * a + b }return-c / 2 * (--a * (a - 2) - 1) + b }, easeInQuint:function (e, a, b, c, d) { return c * (a /= d) * a * a * a * a + b }, easeOutBack:function (e, a, b, c, d, f) { if(f == undefined) { f = 1.70158 }return c * ((a = a / d - 1) * a * ((f + 1) * a + f) + 1) + b }, easeOutExpo: function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t/d) + 1) + b}}); 

// http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
var IE_VERSION = (function () {
    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');
 
    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );
    return v > 4 ? v : undef;
}());




/** 
 * @author Kennedy Krieger Institute
 * Copyright: 2010
 * @version 0.10.0 TODO: finish documenting 
 * @fileoverview note, this is why you shouldn't attempt to do every aspect of 
 * front end site development, including design, css, html, and js, 
 * simultaneously while also installing, configuring, and customizing the CMS. 
 * Especially if you only have 2 weeks for the project. Sorry about the mess 
 * @requires jQuery
 */




var KKI = {}

/* Utilities */
/**
* gets the next in a sequence from x, when x is last, return to the beginning
* @name gNext
* @function
* @param x {int} current position in in a list of a known length
* @param len {int} total length of list
*/ 
KKI.gNext = function(x, len) { 
    return x %= len;
}

/**
 * use with event delegation to simplify target node testing for delegated events
 * @name isNode
 * @function
 * @param {object} node a dom node for comparision
 * @parm {string} test lowercase name of desired node
*/

KKI.isNode = function(node, test) {
	return (node.nodeName.toLowerCase() === test);
};

/*
// for in page links
KKI.getTarget = function (link) {
	return (link.match(/^#/)) ? link.substring(link.indexOf('#') + 1) : '';
}
*/

/**
* Remove the filter attribute from elements, called
* on completion of opacity animations in IE < 9
* @name IEaaFix
* @function
* @param {object} that dom node to style
*/
KKI.IEaaFix = function (that) {
		that.style.removeAttribute('filter');
}

KKI.viewport = {};
KKI.viewport.h = $(window).height();
KKI.viewport.w = $(window).width();
KKI.isActive = false;

// Handy cross-browser show/hide fade transition
KKI.showHide = function(toHide, toShow, clss, spd1, spd2) {
	var ease = jQuery.easing.easeInOutQuad ? 'easeInOutQuad' : 'swing',
		spd1 = spd1 ? spd1 : 660,
		spd2 = spd2 ? spd2 : spd1,
		hide, 
		show;
		
	if (KKI.isActive) {
		return;
	}
	hide = function(toHide, clss) {
		if (toHide.css('opacity') == 1) {
			KKI.isActive = true;
			toHide.animate({ opacity: 0 }, spd1, ease, function () {
				$(this).removeClass(clss).css({ display: 'none'});
			KKI.isActive = false;
			});
		}
	}

	show = function(toShow, clss) {
		KKI.isActive = true;
		toShow.css({ display: 'block', opacity: 0 }).animate({ opacity: 1 }, spd2, ease, function () {
			if (!$.support.opacity) {
				this.style.removeAttribute('filter');
			}
			KKI.isActive = false;
		}).addClass(clss);
	}

	if (toShow) {
		show(toShow, clss);
	}
	if (toHide) {
		hide(toHide, clss);
	}
}

if ($('#features').length > 0) {
(function () {
	var f = $('#featurewrapper > section'),
		i = len = f.length,
		newWidth = 1 / len;

	newWidth = Math.ceil((newWidth * ($('#pager').width() - len))); 

	$('head').append('<style id="featureshow">#pager > li { width: ' + newWidth + 'px }</style>');

	if (IE_VERSION && IE_VERSION <= 7) {
		while (i--) {
			$('#pager > li').eq(i).css({ width: newWidth });
		}
	}
	

	if (newWidth * len > f.width()) {
		$('#pager > li').eq(0).css({width: newWidth - 1});
	}

	f.eq(0).addClass('current');
}());


KKI.feature = function (e) {
    var gal = $('#featurewrapper'),
		item = gal.children('section'),
		gLen = item.length,
		pager = $('#pager'),
		pause = false,
		count = 0,
		autoAdv,
		adv;

// advance by one slide
	adv = function(e) {
		
		var targEl = KKI.isNode(e.target, 'li') ? $(e.target) : $(e.target).parents('li'),
			nSlide = targEl.data('id') % gLen;

    
		KKI.feature.auto = function(e) {
		if (!pause) {
				pager.children('li').eq(nSlide).click();
			} 
		} 

		if (KKI.isActive) {
			return false;
		} else {
		if (!targEl.hasClass('current')) {
			pager.children('.current').removeClass('current').children('h2').children('span').html('');
			targEl.addClass('current').children('h2').children('span').html('Current Slide: ');
			
			KKI.showHide(gal.children('.current'), item.eq(nSlide - 1), 'current', 500, 660);
		}
			if (!pause) {
				autoAdv = setTimeout(KKI.feature.auto, 4000); 
			}
		}
		if (count === gLen) {
			pause = true;
		}
		count++;
	}

	pager.bind('click', adv);

    
    // initialize slideshow

    (function () {
        var i = gLen,
            p = pager.children('li'),
            j;
        while (i--) {
            j = i + 1;
            item.eq(i).data('id', j).css({ zIndex: gLen - i, opacity: i > 0 ? 0 : 1, display: i > 0 ? 'none' : 'block' });
            p.eq(i)
			 .children('h2').prepend('<span class="visuallyhidden"></span>') // add a hidden span to update with "current slide" for screen readers
			 .attr('tabindex', 0)
			 .end() // return to original object
			 .data('id', j);
        }
		item.eq(0).addClass('current');
       pager.children('li').eq(0).click();
    }());
}
KKI.feature();
};



(function ($) {
var body = $('body'),
	sponsors = $('#sponsors > div > ul'),
	logoscroll = new Ticker(sponsors, 2),
	tick = setInterval(function () {
            logoscroll.tick();
        }, 30);

sponsors.bind('mouseenter mouseleave', function () {
	logoscroll.ani = !logoscroll.ani
});

$('#sponsors > div').prepend('<div class="left-gradient-mask"></div>');

function Ticker(list, spd) {
	this.ticker = list;
	this.spd = spd;
	this.lnkl = list.children('li').length;
	this.wol = 0;
	this.ml = 0;
	this.ani = true;

	this.tick = function () {
		if (this.ani) {
			this.ml > -this.wol ? this.ml -= this.spd : this.ml = 0;
			this.ticker.css('marginLeft', this.ml);
		}
	};

	while (this.lnkl--) {
		this.wol += this.ticker.children('li').eq(this.lnkl).width();
	}

	this.ticker.css({
		width: this.wol * 2,
		visibility: 'visible',
		marginLeft: 0
	});
	this.ticker.children('li').clone().appendTo(this.ticker);
}

KKI.clientWidth = document.documentElement.clientWidth;

KKI.currDate = new Date();
KKI.freeRideEnds = new Date(2010, 10, 23, 12, 00, 00);



// initialize other slideshow
$('#slideshow > div').scrollable({
	circular: true, 
	speed: 1000, 
	onBeforeSeek: function () {
		var idx = this.getIndex(), items = this.getItems();
		items.eq(idx).next().children('h4').css({opacity: .2}).end().children('h4').animate({ opacity: .5}, 200); 
	},
	onSeek: function () {
		var idx = this.getIndex(), items = this.getItems();
		items.eq(idx).children('h4').animate({ opacity: 1}, 500, function () {
			if (IE_VERSION && IE_VERSION < 9) {
				KKI.IEaaFix(this);
			}
		});
	}

}).autoscroll({ autoplay: true, interval: 3500});


// EXCLUDE FROM MOBILE
if (KKI.clientWidth > 500 && KKI.viewport.w > 500) {

// if (KKI.freeRideEnds > KKI.currDate) {
	body.prepend('<div id="support"><a title="learn more" href="/free-tickets.html"><img src="/assets/site/images/curldown.png" alt="learn more" /></a><div></div></div>');
// }
	$('header').append('<div id="sleigh"><div></div><div></div></div>');

	// non essential fixes for differences in widths across platforms caused by variations in type rendering
	(function () {
		var mainNav = $('header > nav > ul'), mainNavItems = mainNav.children('li'), i = mainNavItems.length, j = 0;
		while (i--) {
			j += mainNavItems.eq(i).outerWidth();
		}
		mainNav.width(j+2);
	}());

	$('#support').bind('mouseenter mouseleave', function (e) {
		var curl = $(this).children().children('img'), msg = $(this).children('div');
		if (e.type === 'mouseenter') {
			curl.stop().animate({height: 215, width: 200}, 200);
			msg.stop().animate({height: 195, width: 195}, 220);
		} else {
			curl.stop().animate({height: 100, width: 95}, 100);
			msg.stop().animate({height: 90, width: 90}, 90);
		}
	});

	if (body[0].id === 'index') {
		$('#sleigh').animate({ left: 320, top: 40 }, 3000, 'easeOutExpo');
	}
}




// MISC
$('a[rel=external], a[href$=pdf]').attr('target', '_blank'); // beloved of marketers everywhere
}(jQuery));

// get rid of trees
KKI.checkSize = function () {
	var a = $('header > img[src$=tree.png]'), b = function () {
		if (KKI.viewport.w < 805) {
			a.addClass('hidden');
			if (KKI.viewport.w > 481)
				$('body').css('overflowX', 'auto');
		} else if (KKI.viewport.w > 805) {
			a.removeClass('hidden');
			if (KKI.viewport.w > 481)
				$('body').css('overflowX', 'hidden');
		}
	};
	return b;
};

// CSS is used to position labels atop text inputs
// depending on the event and content of the adjacent
// text input, show or hide the label
KKI.labels = function (label, length, e) {
	var ev = typeof e === 'string' ? e : e.type;
	if (length > 0 || ev === 'focus') {
		label.css({display: 'none'});
	} else if (length === 0 && ev === 'blur') {
		label.css({display: 'block'});
	}
}

// This applies KKI.labels on the focus and blur events
$('input[type=text]').bind('focus blur', function(e) {
	KKI.labels($(this).next().is('label') ? $(this).next() : $(this).prev(), $(this).val().length, e);
});

// check the state of all fields and labels and apply KKI.labels where needed
KKI.checkLabels = function(e) {
    var labelIs = function (obj) {
        var label = obj.next().is('label') ? obj.next() : obj.prev();
        return label;
    },
    lengthIs = function (obj) {
        var length = obj.val().length;
        return length;
    },
    txtInput = $('input[type=text]'),
    i = txtInput.length;

    while (i--) {
        KKI.labels(labelIs(txtInput.eq(i)), lengthIs(txtInput.eq(i)), e);
    }
}

// also check for labels on DOM ready, which should catch refresh and back in the majority of browsers
$(function () {
    KKI.checkLabels('load');
});

$(window).load(KKI.checkSize()); 
$(window).bind('resize', KKI.checkSize()); 

// countdown
if (document.getElementById('countdown')) {
(function () {
	var ctFrom = new Date(),
		endsAt = new Date(2011, 10, 25, 10, 00, 00), 
		diff = endsAt - ctFrom,
		ctDown = function (ms) {
		var formatsMS = {
			milliseconds: 1,
			seconds: 1E3, 
			minutes: 6E4, 
			hours: 36E5, 
			days: 864E5
		},
		units = ['seconds', 'minutes', 'hours', 'days'],
		f = units.length,
		result = {};

		while (f-- && units[0]) {
			var res = Math.floor(ms / formatsMS[units[f]]);
			if (ms > 0) {
				result[units[f]] = (result[units[f]] >= 0) ? result[units[f]] += res : res;
			} else {
				result[units[f]] = 0;
			}
			ms -= res * formatsMS[units[f]];
		}
		return result;
	}, // end ctDown function

	days = document.getElementById('days'),
	hours = document.getElementById('hours'),
	minutes = document.getElementById('minutes'),
	seconds = document.getElementById('seconds'),
	result, counting;

	if (diff > 0) {
		counting = setInterval(function () {
			result = ctDown(diff -= 500);
			days.innerHTML = result.days;
			hours.innerHTML = result.hours;
			minutes.innerHTML = result.minutes > 9 ? result.minutes : '0' + result.minutes;
			seconds.innerHTML = result.seconds > 9 ? result.seconds : '0' + result.seconds;
		}, 500); // 500 because updating once per second won't do the trick
	} else {
		days.innerHTML = '0';
		hours.innerHTML = '00';
		minutes.innerHTML = '00';
		seconds.innerHTML = '00';
	}
}());
}

// IE STUFF
if (IE_VERSION && IE_VERSION < 9) {
	$('section').addClass('section');
	$('#entertainment table tr:nth-child(2n-1)').addClass('ieOdd').css('backgroundColor', '#eee');
}

// GA STUFF
function _recOut(b, c, d) {
    try {
        _gat._getTracker('UA-10349907-1')._trackEvent(c, d);
        setTimeout('top.location = "' + b.href + '"', 100)
    } catch (a) {}
}

	$('a[href$="pdf"]').attr('target', '_blank').bind('click', function (e) {
        e.preventDefault();
        a = $(this).attr('href');
        _recOut(this, 'Downloads', a);
    });
	
	

