//swfobject config
swfobject.switchOffAutoHideShow();

var playingID = null;

var playStarted = function() {
	if (playingID != null) {
		var viddlerVideo = document.getElementById(playingID);
		var playtime = viddlerVideo.getCurrentTime();
		if (playtime == 0) {
			//console.log('Playback started: ' + viddlerVideo.videoTitle);
			pageTracker._trackEvent('Viddler Videos', 'Play', viddlerVideo.videoTitle);
		} else {
			pageTracker._trackEvent('Viddler Videos', 'Play Resumed', viddlerVideo.videoTitle, playtime);
		}
	}
}

var playEnded = function() {
	if (playingID != null) {
		var viddlerVideo = document.getElementById(playingID);
		pageTracker._trackEvent('Viddler Videos', 'Completed', viddlerVideo.videoTitle);
	}
}

function playViddler(videoCode, replaceID, videoWidth) {
	var replaceID = (typeof replaceID != 'undefined' ? replaceID : $('#videoswitcher-target object:first').attr('id'));
	var videoWidth = (typeof videoWidth != 'undefined' ? videoWidth : 503);
	
	var flashvars = {
        useJavaScript: 't',
        enablecallbacks: 't',
        autoplay: 't'
    };
	var params = {
		allowscriptaccess: 'always',
		allowfullscreen: 'true',
		wmode: 'transparent'
	};
	var attributes = { id: 'video-' + videoCode };
	var parent = $('#' + replaceID).parent('div');
	if (!parent.hasClass('viddler')) parent.addClass('viddler');
	
	// Setup variables for event tracking
	playingID = 'video-' + videoCode;
	
	swfobject.embedSWF("http://www.viddler.com/simple/" + videoCode + "/", replaceID, videoWidth, "303", "9.0.0","/flash/expressInstall.swf", flashvars, params, attributes);
	
	$.getJSON('/utils/viddler/fetch_details.php?id=' + videoCode, function(data) {
		document.getElementById(playingID).videoTitle = data.video.title;
	});
}

function playMP3(file, replaceID) {
	var flashvars = {
        wimpyApp: '',
        wimpyReg: 'N1AlNUNVWWlmNSU3RSU4MHglMjQlM0MlODElM0I5bFRtJTgxNEclM0RiJTVDJTdCJTNEVi1HSCU=1RHB4',
        wimpySkin: '/rave/skins/skin_audio.xml',
        startPlayingOnload: 'yes',
        startOnTrack: 1,
        autoAdvance: 'no',
        theVolume: 75,
        popUpHelp: 'no',
        debugMode: 'no',
        playlist: file
    };
	var params = {
		allowscriptaccess: 'always',
		loop: false,
		menu: false,
		quality: 'high',
		salign: 'lt',
		scale: 'noscale',
		bgcolor: '#e6e6e6'
	};
	var attributes = { id: replaceID };
	
	swfobject.embedSWF("/rave/rave.swf" + "?cachebust=" + new Date().getTime(), replaceID, 333, 37, "9.0.0","/flash/expressInstall.swf", flashvars, params, attributes);
}

function initDefaultInputValues(parent) {
	var parent = (typeof(parent) != 'undefined' ? parent : 'body');
	$(parent).find('input[type=text], textarea').each(function() {
		// Go through all textboxes and swap their contents intelligently
		var input = $(this);
		var title = input.attr('title');
		if (title != '' && (input.val() == '' || input.val() == title)) {
			input.val(title).addClass('unchanged');
			input.focus(function() {
				if (input.val() == title) {
					input.val('').removeClass('unchanged');
				}
			});
			input.blur(function() {
				if (input.val() == '') {
					input.val(title).addClass('unchanged');
				}
			});
			input.parents("form:first").submit(function() {
				if (input.val() == title) {
					input.val('');
				}
			});
		}
	});
}

// Closes all open bubbles to prevent overlap
function closeBubbles() {
	$('.bubble').each(function() {
		if ($(this).is(":visible")) {
			$(this).fadeOut();
			$(this).prev('a').attr('data-targetopen', 'false');
		}
	});
}

// Function to setup the close buttons
function setupCloseButtons(target) {
	$(target).find('a.close').click(function() {
		$(target).fadeOut();
		$(target).prev('a').attr('data-targetopen', 'false');
		return false;
	});
}

// Function that initializes the actions for social action icons
function initSocialActions(parent) {
	var parent = (typeof(parent) != 'undefined' ? parent : 'body');
	$(parent).find('.social-actions li > a').each(function() {
		var link = $(this);
		link.attr('data-targetopen', 'false');
		var link_target = link.next('.bubble');
		switch (link.attr('class')) {
			case 'email':
				// Email requires an ajax call the first time, so it's a bit different
				link.click(function() {
					if (link.attr('data-targetopen') != 'false') {
						link_target.fadeOut();
						link.attr('data-targetopen', 'false');
					} else if (link_target.is(':empty')) {
						// Empty, so load in the contents via Ajax
						link_target.load($(this).attr('href') + 'inline/', function() {
							// Setup the form validation and submission
							link_target.find('form').validate({
								submitHandler: function(form) {
									if (link_target.find('.controls .success').length > 0) {
										link_target.find('.controls .success').remove();
									}
									$(form).ajaxSubmit({
										resetForm: true,
										beforeSubmit: function(form, object, options) {
											link_target.find('.controls').addClass('processing');
										},
										success: function(response, status, xhr, form) {
											link_target.find('.controls').removeClass('processing');
											link_target.find('.controls').append('<p class="success">Thank you for sharing!</p>');
										}
									});
								},
								rules: {
									'email': {
										required: true,
										email: true
									},
									'validate-comma-emails': {
										required: function(element) {
											return /^([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}(\s*,\s*)?)+$/i.test($(element).val());
										}
									}
								},
								messages: {
									'email': 'Valid email required',
									'validate-comma-emails': 'One or more valid emails required'
								},
								onfocusout: false,
								onkeyup: false,
								onclick: false
							});
							// Setup the close boxes
							setupCloseButtons(link_target);
							closeBubbles();
							link_target.fadeIn();
							link.attr('data-targetopen', 'true');
						});
					} else {
						closeBubbles();
						link_target.fadeIn();
						link.attr('data-targetopen', 'true');
					}
					return false;
				});
				break;
			
			case 'bookmark':
				// Select input field contents on focus
				link_target.find('input[type=text]').focus(function(){
				    this.select();
				});
				// Setup the close boxes
				setupCloseButtons(link_target);
				// Enable the toggling for the actual link click
				link.click(function(){
					if (link.attr('data-targetopen') != 'false') {
						link_target.fadeOut();
						link.attr('data-targetopen', 'false');
					} else {
						closeBubbles();
						link_target.fadeIn();
						link.attr('data-targetopen', 'true');
					}
					return false;
				});
				break;
		}
	});
}

// Init the social action links for Faceboxes
$(document).bind('reveal.facebox', function() {
	initSocialActions('#facebox');
});

// Handle pausing Flash videos and MP3s on Facebox close (since IE sucks at this)
$(document).bind('close.facebox', function() {
	var movie = $('#facebox object:first')[0];
	if (movie.js_wimpy_pause) {
		movie.js_wimpy_pause();
	} else if (movie.viddlerPause) {
		movie.viddlerPause();
	}
});

jQuery(document).ready(function($) {
	// Setup the special case resource library links
	$('.library a[rel*=facebox]').each(function() {
		if ($(this).parents('#footer').length > 0) {
			$(this).click(function() {
				var target = $(this).attr('href');
				$.facebox(function() {
					$.ajax({
						url: target,
						dataType: "html",
						complete: function( res, status ) {
							// If successful, inject the HTML into all the matched elements
							if ( status == "success" || status == "notmodified" ) {
								var rscript = /<script(.|\s)*?\/script>/gi;
								$.facebox(jQuery("<div />").append(res.responseText.replace(rscript, "")).find('#premium'));
							}
						}
					});
				});
				return false;
			});
			$(this).attr('rel', '');
		}
	});
	// Setup the special case Ajax links
	$('.ajax a[rel*=facebox]').each(function() {
		$(this).click(function() {
			var target = $(this).attr('href') + 'inline/';
			$.facebox({ ajax: target });
			return false;
		});
		$(this).attr('rel', '');
	});
	// Setup the rest of the Facebox links
	$('a[rel*=facebox]').each(function() {
		$(this).facebox();
	});
	$.facebox.settings.opacity = 0.1;
	initDefaultInputValues();
	
	$('#thumbnails li a').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).click(function() {
		$('#thumbnails li').each(function() { $(this).removeClass('active'); });
		$(this).parent('li:first').addClass('active');
		$('#detail').empty();
		$('#detail').load($(this).attr('href') + ' img');
		return false;
	});
	
	$('#trends li').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	$('#trends p, #trends h3').click(function(e) {
		e.stopPropagation();
		$(this).parents('li:first').find('a:first').trigger('click');
		return false;
	});
	
	$('.aggregate').change(function() {
		var result = '';
		$('.aggregate[name=' + $(this).attr('name') + ']').each(function(index, el) {
			if ($(this).val() !== '') {
				if (result === '') {
					result = $(el).val();
				} else {
					result += ('&' + $(this).val());
				}
			}
		});
		$('#aggregator-' + $(this).attr('name')).val(result);
	});
	
	if ($('.video-widget').length) {
		var total_vids = $('.video-widget li').length;
		var cur_vid = 1;
		
		$('#widget-right').click(function() {
			advance_video(1);
			return false;
		});
		$('#widget-left').click(function() {
			advance_video(-1);
			return false;
		});
	}
	
	function advance_video(increment) {
		var next = cur_vid + increment;
		if (next <= 0) {
			next = total_vids;
		} else if (next > total_vids) {
			next = 1;
		}
		$('#video-' + cur_vid).fadeOut();
		$('#video-' + next).fadeIn();
		cur_vid = next;
	}
	
	$('.videoswitcher').click(function() {
		playVideo($(this).attr('rel'));
		return false;
	});
	
	$('.viddlerswitcher').click(function() {
		playViddler($(this).attr('rel'));
		return false;
	});
	
	// For use with the homepage accordion; loads in images for img elements with blank src
	function load_delayed_images(element) {
		// Set up the images
		if (!element.hasClass('img-loaded')) {
			element.find('img').each(function() {
				$(this).attr('src', $(this).attr('data-endpoint'));
			});
			element.addClass('img-loaded');
		}
	}
	
	// Homepage non-Flash accordion setup
	if ($('.home #flash').length > 0 && !swfobject.hasFlashPlayerVersion('9.0.124')) {
		// Setup the basic tab actions
		$('#flash h2 a').each(function() {
			if (!$(this).hasClass('active')) {
				$('#' + $(this).url().attr('hash')).css({'width': 0});
			} else {
//				load_delayed_images($($(this).attr('href')));
			}
			$(this).click(function() {
				if (!$(this).hasClass('active')) {
					load_delayed_images($('#' + $(this).url().attr('hash')));
					// Toggle!
					var active = $('#flash h2 a.active');
					$('#' + active.url().attr('hash')).animate({'width': 0});
					active.removeClass('active');
					$(this).addClass('active');
					$('#' + $(this).url().attr('hash')).animate({'width': 677});
				}
				return false;
			})
		});
		$('#flash .hometab').css({'float': 'left'});
		
		// Setup the logic for the university and coaches tabs
		$('#flash .university .thumbs a, #flash #coaches .thumbs a').each(function() {
			if (!$(this).hasClass('active')) {
				$('#' + $(this).url().attr('hash')).hide();
			}
			$(this).click(function() {
				if (!$(this).hasClass('active')) {
					var active = $(this).parents('.thumbs').find('a.active:first');
					$('#' + active.url().attr('hash')).hide();
					active.removeClass('active');
					$(this).addClass('active');
					$('#' + $(this).url().attr('hash')).show();
				}
				return false;
			});
		});
		
		// Setup the logic for the rotating welcome images
		$('#flash #welcome').css({'overflow': 'hidden', 'position': 'relative'});
		$('#flash #welcome img').css({'position': 'absolute', 'top': '0px', 'left': '0px'}).hide();
		var imgs = $('#flash #welcome img');
		var activeindex = 0;
		$(imgs[0]).attr('src', $(imgs[0]).attr('data-endpoint')).show();
		function swap_welcome_image() {
			if ($('#welcome-toggle').hasClass('active')) {
				var targetindex = activeindex + 1;
				if (targetindex >= imgs.length)
					targetindex = 0;
				if ($(imgs[targetindex]).attr('src') == '') {
					// Load the image via ajax first
					$(imgs[targetindex]).load(function(){
						$(imgs[activeindex]).fadeOut();
						$(this).fadeIn();
					}).attr('src', $(imgs[targetindex]).attr('data-endpoint'));
				} else {
					// Just swap them
					$(imgs[activeindex]).fadeOut();
					$(imgs[targetindex]).fadeIn();
				}
				activeindex = targetindex;
			}
			setTimeout(function(){swap_welcome_image();}, $(imgs[activeindex]).attr('data-duration') * 1000);
		}
		setTimeout(function(){swap_welcome_image();}, $(imgs[activeindex]).attr('data-duration') * 1000);
	}
	
	// Setup for the tabbed widget on Undergrad and Adult pages
	$('.tabwidget .tabs li a').each(function(index) {
		if (index == 0) {
			$(this).addClass('active');
		} else {
			$('#' + $(this).url().attr('hash')).hide();
		}
		$(this).click(function() {
			var next_link = $(this);
			if (!next_link.hasClass('active')) {
				var active = $('.tabwidget .tabs li a.active:first');
				active.removeClass('active');
				next_link.addClass('active');
				$('#' + active.url().attr('hash')).fadeOut(100, function() {
					$('#' + next_link.url().attr('hash')).fadeIn(100);
				});
			}
			return false;
		});
	});
	
	// Setup the Ajax loading for various forms
	$('form#login-form, form.ajax-redirect-form').submit(function() {
		$(this).find('input[type=submit]').attr('disabled', true);
		$(this).addClass('processing');
		$.post($(this).attr('action'), $(this).serialize(), function(data, textStatus, request) {
			var temp = $('<div></div>').html(data);
			temp.find('p:contains("Return to Previous Page")').remove();
			if (data.indexOf('contained the following errors') < 0) {
				var metaRefresh = data.replace(/^[\s\S]*?<meta\s+http-equiv='refresh'\s+content='[0-9]+;\s*url=([^']+)'>[\s\S]*$/i, '$1');
				if (!metaRefresh) {
					metaRefresh = request.getResponseHeader('refresh');
				}
				if (metaRefresh) {
					// Make sure that the metaRefresh is the URL, not the whole refresh info
					metaRefresh = metaRefresh.replace(/([0-9]+;\s*url=)?(.+)/i, '$2');
					window.location = metaRefresh;
				}
				if ($(this)[0].reset) {
					$(this)[0].reset();
				}
			} else if ($('#formerrors').length == 0) {
				$.facebox(data);
			} else {
				$('#formerrors').html('<div class="error-content">' + temp.find('#content').html() + '</div>');
				temp.remove();
			}
		});
		$(this).removeClass('processing');
		$(this).find('input[type=submit]:disabled').removeAttr('disabled');
		return false;
	});
	
	// Setup for the lightbox sharing icons in case we're on a static page
	initSocialActions();
	
	$('.req-js').show();
});