/* Facebook Initialize */
window.fbAsyncInit = function() {
	FB.init({ xfbml: true });
};
if (typeof(stLight) != 'undefined') {
	stLight.options({
		publisher: '0cc8d0b8-009b-4b2f-89c0-c1411b906ec6'
	});
}
/* Variables */
var speakerTimer,
	fadeTimer,
	URL = window.location,
	fadeDuration = 3000,
	flashElements = [
		/* Homepage */
		{
			id: 'index-flash',
			path: 'home/shell',
			width: 950,
			height: 178,
			vars: $.extend({
				/* Included videos */
				video1: URI_SKIN + '/flash/video/home/appreciate.flv',
				handstandVid: URI_SKIN + '/flash/video/home/handstand.flv',
				/* Additional canvas-based links */
				teamworkLink: URI_ROOT + '/learn-with-resources-and-insights/books',
				iappreciateLink: URI_ROOT + '/learn-with-resources-and-insights/tools'
			}, flashCanvases),
			transparent: true
		},
		/* Blog */
		{
			id: 'blog-video',
			path: 'blog/iappreciate',
			width: 280,
			height: 162,
			vars: {
				iappreciateLink: URI_ROOT + '/learn-with-resources-and-insights/tools'
			},
			transparent: true
		},
		/* Headers */
		{
			id: 'learn-with-resources-and-insights-globalstudy-header',
			path: 'learn-with-resources-and-insights/globalstudy-header',
			width: 950,
			height: 178,
			transparent: true
		},
		{
			id: 'about-olympics-header',
			path: 'awards/olympics-header',
			width: 950,
			height: 178,
			transparent: false
		},
        {
			id: 'about-philanthropy-header',
			path: 'about/philanthropy',
			width: 950,
			height: 178,
			transparent: false
		},
		/* Sidebars */
		{
			id: 'about-green-sidebar',
			path: 'about/green-sidebar',
			width: 215,
			height: 411,
			transparent: true
		},
        {
			id: 'about-philanthropy-sidebar',
			path: 'about/green-sidebar',
			width: 215,
			height: 411,
			transparent: true
		},
		{
			id: 'about-olympics-sidebar',
			path: 'awards/olympics-sidebar',
			width: 230,
			height: 270,
			transparent: true
		},
		{
			id: 'learn-with-resources-and-insights-globalstudy-sidebar',
			path: 'learn-with-resources-and-insights/globalstudy-sidebar',
			width: 330,
			height: 345,
			transparent: true
		},
		{
			id: 'learn-with-resources-and-insights-exhibits-sidebar',
			path: 'learn-with-resources-and-insights/exhibits-sidebar',
			width: 280,
			height: 280,
			transparent: true,
			vars: {
				link1: 'http://www.exhibitoronline.com/exhibitormagazine/may10/design-awards-kinetic-energy.asp'
			}
		}
	],
	jsArray = [
		'//connect.facebook.net/en_US/all.js',
		'//platform.twitter.com/widgets.js',
		'//apis.google.com/js/plusone.js'/*,
		'//w.sharethis.com/button/buttons.js#publisher=0cc8d0b8-009b-4b2f-89c0-c1411b906ec6'*/
	];

/* Shadowbox */
if (typeof(Shadowbox) != 'undefined') {
	Shadowbox.init({
		displayCounter: false,
		displayNav: false,
		onFinish: function() {
			if (typeof(Cufon) != 'undefined') {
				Cufon('#sb-nav-close', { fontFamily: 'Gotham Bold', hover: true });
			}
		}
	});
}
/* Fader */
function setupFader(current, duration) {
	clearTimeout(fadeTimer);
	current.siblings('.fade').hide();
	fadeTimer = setTimeout(
		function() {
			runFader(current, duration);
			current = null; // IE GC
		},
		duration
	);
}
function runFader(current, duration) {
	var next = (current.prev('.fade').index() == -1) ? current.siblings('.fade:last') : current.prev('.fade');
	clearTimeout(fadeTimer);
	current.fadeOut(duration);
	next.fadeIn(
		duration,
		function() {
			setupFader($(this), duration);
		}
	);
}
/* Learn - Summit rotating speakers */
function setupSpeakers() {

	clearTimeout(speakerTimer);
	speakerTimer = setTimeout('rotateSpeakers()', 2000);
}
function rotateSpeakers() {
	/* old code for going in order, new code goes based on index from anchor rel attribute
	var next = $('#learn-summit-sidebar #speaker-images li:last a').hasClass('selected') ? $('#learn-summit-sidebar #speaker-images li:eq(0) a') : $('#learn-summit-sidebar #speaker-images li .selected').parents('li').next().find('a');
	*/
	var next = $('#learn-summit-sidebar #speaker-images li:eq(' + $('#learn-summit-sidebar #speaker-images li .selected').attr('rel') + ') a');
	$(next).trigger('swapSpeakers');
	setupSpeakers();
}
/* jQuery DOM-load */

$(function() {
	/* Social Media Plugins */

	$(jsArray).each(
		function(i, item) {

			var script = $('<script>').attr('async', true).attr('src', location.protocol + item),
				regex = new RegExp('facebook', 'gi');

			if (regex.test(jsArray[i])) {
				$('#fb-root').append(script);
			}
			else {
				$('script:first').before(script);
			}

		}
	);

	/* Blog Comments */
	$('#comments #respond').hide();
	$('#comments .add-comment').click(
		function() {
			$('#respond', $(this).closest('#comments')).show();
			$(this).remove();
			return false;
		}
	);
	/* Blog Tabs */
	$('.tab-container .tabs li:not(.active) a').click(
		function() {
			var container = $(this).closest('.tab-container');
			$('.active', container).removeClass('active');
			$(this).closest('li').addClass('active');
			$('.tab', container).hide();
			$($(this).attr('href'), container).show();
			return false;
		}
	);
	$('.tab-container').each(
		function() {
			var box = $('.box', this);
			$('.tab', this).each(
				function() {
					var currentHeight = box.innerHeight() - 10;
					if (currentHeight < $(this).outerHeight()) {
						box.css('height', $(this).outerHeight());
					}
					$(this).hide();
				}
			);
			$('.tabs li:first a', this).trigger('click');
		}
	);
	/* Rotate */
	$('#rotate div.slice').hover(
		function() {
			$(this).toggleClass('hover');
			$('#rotate').toggleClass('hover');
			$('#ring-full').toggle();
			$('#ring-partial').toggle().rotate($(this).index() * 60);
			$('p', this).toggle();
		}
	);
	/* Bubbles */
	$('#bubbles ul li').hover(
		function() {
			$('#bubbles div.info div').hide();
			$('#' + $(this).attr('class')).show();
			$(this).toggleClass('hover');
			$('#bubbles').toggleClass('hover');
			$('#bubbles div.info').toggle();
		}
	);
    /* Home Page Image Rotator */
    $('#image-rotator').slideShow();
	/* Flash Elements */
	$(flashElements).each(
		function(i, current) {
			if ($('#' + current.id).length > 0 && $.flash.available) {
				$('#' + current.id).empty().flash({
					id: current.id,
					name: current.id,
					swf: URI_SKIN + '/flash/' + current.path + '.swf',
					width: current.width,
					height: current.height,
					wmode: (current.transparent) ? 'transparent' : 'opaque',
					flashvars: current.vars
				});
			}
		}
	);
	/* Learn - Summit */
	/*if ($('#learn-summit-sidebar').length > 0) {

		$('#learn-summit-sidebar #speaker-images a').bind(
			'swapSpeakers',
			function() {

				var current = $(this);

				$($('.selected', $('#learn-summit-sidebar #speaker-images')).attr('href'), $('#learn-summit-sidebar #speaker-info')).hide(
					0,
					function() {

						$('#learn-summit-sidebar #speaker-images .selected').removeClass('selected');
						$(current).addClass('selected');
						$($(current).attr('href')).show(0);
						setupSpeakers();
					}
				);
			}
		).click(
			function() {
				return false;
			}
		);

		setupSpeakers();
	}*/
	/* Hovers for Summit	*/
	if ( $('.hoverDesc').length > 0 ) {
		$('.hoverDesc').each(function() {

			var link = $(' > a', $(this)),
				targetDiv = $('.longDesc', $(this)),
				top = $(targetDiv).outerHeight() + 5;
			$(link).hover(
				function() {
					$(targetDiv).css({'top':'-'+top+'px'}).fadeTo(150, 0.95);
				},
				function() {
					$(targetDiv).fadeOut(50);
				}
			);
		});
	}
	/* Font Replacement */
	if (typeof(Cufon) != 'undefined') {
		Cufon('#learn-with-resources-and-insights-tools #sub-header .marquee, #rotate .number, #rotate p, #rotate #you, #bubbles ul li p, #container.blog #sub-header, #image-rotator #intro p, #image-rotator #intro #to_work, #about-history #history-lecture h4, #awards-index #sub-header', { fontFamily: 'Gotham Medium', hover: true });
		Cufon('#primary-navigation a, #utility-navigation a, #buckets a .off, #customer-service-navigation a, #about-ourculture-sidebar a, #shadowbox-container:not(#shadowbox-container #content.shadowbox h1) h1, #shadowbox-container.people .name, #index-flash a, #learn-summit-sidebar h2, #container.blog #sub-header strong, #container.blog .format-quote .byline, #container.blog #content.list .format-link .we-love-title, #awards-grid #white-paper', { fontFamily: 'Gotham Bold', hover: true });
		Cufon('.landing h1, .greenawards h1, #services-quote p.quote, #bubbles div.info p', { fontFamily: 'Gotham Book', hover: true });
		Cufon('#container.blog .format-quote blockquote, #container.blog .date .day, .pull-quote', { fontFamily: 'CenturySchT Regular', hover: true });
        Cufon('#news-banner span', { fontFamily: 'New Century School Bold', hover: true });
	}
	/* Jumper */
	$('#jumper').change(
		function() {

			url = $(this).val();
			if ($(this).attr('selected') != 'selected') {

				if (typeof(pageTracker) != 'undefined') {
					pageTracker._link(url);
				}

				window.location = url;
			}

			return false;
		}
	);
	/* Customer Service - FAQs, Services - Training */
	$('.accordion li > a').click(
		function() {

			$('#training-books').children().hide();


			if ($(this).parent().hasClass('select')) {
				$('.accordion li.select').removeClass('select').parent().find('span').text('+');
			}
			else {
				$('#training-books').find(($(this).attr('href') != '#' ? $(this).attr('href') : '')).show();
				$('.accordion li.select').removeClass('select').parent().find('span').text('+');
				$('span', this).text(($('span', this).text() == '+' ? '-' : '+')).closest('li').addClass('select');
			}

			return false;
		}
	);
	/* Buckets */
	$('#buckets li:odd').addClass('even');
	$('#buckets li:even').addClass('odd');
	$('#buckets li a').hover(
		function() {
			$('.on, .off', $(this)).toggle();
		}
	);
	/* Off-site links */
	$('a[href^="http"]:not([href^="' + URL.protocol + '//' + URL.host + '"]):not([rel*="shadowbox"])').live(
		'click',
		function() {

			window.open($(this).attr('href'), $(this).text());
			return false;
		}
	);
	/* About Us - Shadowboxes */
	$('#shadowbox-container #navigation li a').click(
		function() {

			if ($(this).parents('li').hasClass('selected')) return false;

			var element = $(this);
			$('#items li.selected').fadeOut(
				125,
				function() {
					$(this).removeClass('selected');
					$($(element).attr('href')).fadeIn(
						125,
						function() {
							$(this).addClass('selected');
						}
					);
				}
			);

			$('#navigation li.selected img').fadeTo(
				250,
				1,
				function() {
					$(this).parents('li').removeClass('selected');
				}
			);

			$('img', this).fadeTo(
				250,
				.2,
				function() {
					$(this).parents('li').addClass('selected');
				}
			);
		}
	);
	/* Landing slider */
	$('input[name=request-type], #ppcform input[name=type]').change(
		function() {
			$('#more-info').slideToggle();
		}
	);
	/* Search results number per page */
	$('#r').change(
		function() {
			$('#per-page').submit();
		}
	);
	/* Image fading */
	if ($('.fader').length > 0) {
		setupFader($('.fader .fade:last'), 3000);
	}
	/* Marquee */
	if ($('.marquee').length > 0) {

		var marquee = $('.marquee'),
			slide = $('.slide', marquee),
			fade = $('span', slide),
			rightPosition = -(slide.outerWidth(true) + 230),
			slideDuration = 8000,
			fadeDuration = 500;

		slide.css({
			right: rightPosition,
			display: 'block'
		}).animate(
			{ right: 0 },
			slideDuration,
			function() {
				fade.fadeOut(fadeDuration);
			}
		);

	}
	/* Video player */
	$('.video-sb').click(
		function() {

			if (typeof(Shadowbox) != 'undefined') {
				Shadowbox.open({
					content: URI_SKIN + '/flash/player.swf',
					player: 'swf',
					width: 640,
					height: 360,
					options: {
						flashVars: {
							'v': $(this).attr('href'),
							'quality': 'high',
							'wmode': 'transparent'
						}
					}
				});

				return false;
			}
		}
	);
	/* Gallery video */
	if ($('.video').length > 0) {
		$('.video').each(
			function() {
				$(this).empty().flash({
					id: $(this).attr('id'),
					name: $(this).attr('id'),
					swf: URI_SKIN + '/flash/player.swf',
					width: 327,
					height: 184,
					wmode: 'transparent',
					flashvars: {
						v: URI_SKIN + '/flash/video/about/' + PARAM_VIEW + '/' + $(this).attr('id') + '.flv'
					}
				});
			}
		);
	}
});

/**
 * Summit TED Talks Hover
**/
;(function($, window, document, undefined) {
	$(function() {
		$('a.toolTipHover').hover(function () {
			$('img[data-roll]', $(this)).each(function() {
				$(this).attr('src', $(this).data('roll'));
			});
		}, function() {
			$('img[data-orig]', $(this)).each(function() {
				$(this).attr('src', $(this).data('orig'));
			});
		});
	});
})(jQuery, window, document);

/**
 * Form Validation
**/
;(function($, window, document, undefined) {
	$(function() {
		$('.validate-form').submit(function () {
			var _form = $(this);
			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			var errors = false;
			$('input.required, select.required, textarea.required', _form).each(function() {
				if ($(this).val() == "" || $(this).val() == null || $(this).val() == undefined) {
					$(this).css({
						borderColor: 'red'
					});
					errors = true;
				} else {
					if ($(this).hasClass('validate-email') && !re.test($(this).val())) {
						$(this).css({
							borderColor: 'red'
						});
						errors = true;
					} else {
						$(this).removeAttr('style');
					}
				}
			});

			if (errors == true) {
				if ($('.form-errors', _form).length <= 0) {
					_form.prepend('<span class="form-errors" style="color: red;">Please make sure to fill out the required fields.<span>');
				}
				return false;
			} else {
				$('.form-errors', _form).remove();
				return true;
			}
		});
	});
})(jQuery, window, document);

