JQ = jQuery.noConflict();

var homeNewsInterval = null;
var newsSliderThumbs = null;

// Figure out what browser is being used
var userAgent = navigator.userAgent.toLowerCase();
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
// Define constants for use in all .js files
var ISIE = jQuery.browser.msie;
var ISIE6 = jQuery.browser.msie && jQuery.browser.version == 6.0 ? true : false;
var ISCHROME = jQuery.browser.chrome ? true : false;



jQuery(window).load(function()
{
	initHomeNewsCarousel();
	initEventCarousel();
	initGallerySlideshows();
});

jQuery(document).ready(function($)
{
	var temp = new Object();

	// equal heights
	/*
		? Didn't work as separate plugin
		Modifications from original implementation: http://www.filamentgroup.com/lab/setting_equal_heights_with_jquery/
		some custom filters and properties
		Mostly applies to main columns in the main content area
	*/
	var toMakeEqualHeight = $("#the_content > .inner");

	toMakeEqualHeight.each(function()
	{
		var currentTallest = 0;
		var myFilter = "div[class*='col_'][class!='col_banner']";
			// expandable
		var myFilterChild = "div[class*='c_accordion']";
			// expandable
		var myPadding = -45;
			// ? should be in css

		if (ISIE6)
			myPadding = 15;

		else if (ISIE)
			myPadding = -90;

		$(this).children().filter(myFilter).each(function()
		{ // each container
			if ($(this))
			{
				if ($(this).height() > currentTallest)
				{
					currentTallest = $(this).height() - $(this).contents(myFilterChild).height();
				} // each child

				//alert('Tallest: ' + currentTallest + '\nOverflow: ' + $(this).css('overflow') + '\nHeight: ' + $(this).css('height') + '\nMin-Height: ' + $(this).css('min-height') + '\nMax-Height: ' + $(this).css('max-height'));
			}
		});

		if (ISIE6)
			$(this).children().filter(myFilter).css({'height': currentTallest + myPadding});
			// for ie6, set height since min-height isn't supported

		$(this).children().filter(myFilter).css({'min-height': currentTallest + myPadding});
	});


	// accordion
	/*
		Each item must have exactly two elements - the first one for the header, and the second one for the content.
		Modifications from original implementation
			tooltips
			smart height
			scrollTo plugin integration
			show_all button
	*/

	if ($.ui && $.isFunction($.ui.accordion)) {

		var myAccordion = $(".c_accordion .blades");

		myAccordion.find(".header").attr("title", "expand");
		myAccordion.find(".blade_opened .header").attr("title", "collapse");

		var maxHeight = 0;
		myAccordion.find(".content").each(function() {
			maxHeight = maxHeight < $(this).height() ? $(this).height() : maxHeight;
		});
		//myAccordion.height(myAccordion.find(".blade").height() + maxHeight);

		myAccordion.accordion({

			event: "click",
			autoHeight: false,
			alwaysOpen: false,
			selectedClass: "blade_opened",
			header: ".header",
			content: ".content"

			// active: ".current", (first child)
			// animated: "bounceslide", (requires easing)
			// fillSpace: true,
			// clearStyle: true,
			// navigation: true,

			/* navigationFilter: function() {
				return this.href.toLowerCase() == location.href.toLowerCase();
			   } (add to it) */

		}).bind("accordionchange", function (event, ui) {
			/*
				ui.options, ui.newHeader, ui.oldHeader, ui.newContent, ui.oldContent
			*/

			ui.oldHeader.attr("title", "expand");
			ui.newHeader.attr("title", "collapse");

			/*
			var scrollDestination = ui.oldHeader.attr("class") == ui.newHeader.attr("class") ? $(".c_accordion") : ui.newHeader;
			$.scrollTo( scrollDestination, 500, {
				easing: "linear",
				offset: { top: -18 }
				// axis: x,
				// margin: true,
				// over: [1/n of width or height],
				// queue: yx,
				// onAfterFirst: [function],
				// onAfter: [function],
			});*/
		});

		$(".c_accordion .title a.show_all").toggle(function(){

			$('.c_accordion .content:hidden').slideDown(500, function(){
				$(this).prev().attr("title", "collapse");
				$(this).parent().addClass("blade_opened");
			});
			$(this).text("hide all");

		}, function(){

			$('.c_accordion .content:visible').slideUp(500, function(){
				$(this).prev().attr("title", "expand");
				$(this).parent().removeClass("blade_opened");
			});
			$(this).text("show all");
		});

		// myAccordion.accordion("enable");
		// myAccordion.accordion("disable");
		// myAccordion.accordion("destroy");
		/*
		manual toggling
			myAccordion.accordion("activate", 0);			// 1st content
			myAccordion.accordion("activate", false);	 	// close all contents
			myAccordion.accordion("activate", "a:first"); 	// select descendants
		*/

	}


/*
	other
*/
	// dynamic text

	$("#search_input").focus(function() {
		if ($(this).attr("value").toLowerCase() == 'search usc dornsife')
		{
			$(this).attr("value", "");
		}
	});
	$("#search_input").blur(function() {
		if ($(this).attr("value").toLowerCase() == '')
		{
			$(this).attr("value", 'Search USC Dornsife');
		}
	});

/*
	css shortcomings
*/

	// consistent cursors

	$("ul[id*='nav'] li").css("cursor", "default");

	// smart heights with widget column

	equalizeCols([$("#the_content"), $("#the_sidebar")]);

	function equalizeCols (arrCols)
	{
		var maxColHeight;
		var i = 0
		for (var i = 0; i < arrCols.length; i++) {
			maxColHeight = Math.max(arrCols[i].height(), arrCols[i].height());
		}
		for (var i = 0; i < arrCols.length; i++) {
			arrCols[i].css({'min-height': maxColHeight});
		}
	}

	// tiger-striping

	$("ul.c_main_stripes > li:even").addClass("gray");

	// hovering

	$("input[type='image']").hover(
		function() {
			var url = $(this).attr("src");
			$(this).attr("src", url.replace(/.gif/, "_over.gif"));
		}, function() {
			var url = $(this).attr("src");
			$(this).attr("src", url.replace(/_over.gif/, ".gif"));
		}
	);

	$(".media_archive li").hover(
		function() {
			$(this).children("a").css("border-color", "#878787");
			$(this).next().children("a").css("border-color", "#878787");
		}, function() {
			$(this).children("a").css("border-color", "#767676");
			$(this).next().children("a").css("border-color", "#767676");
		}
	);
	$(".media_archive li:last-child").hover(
		function() {
			$(this).children("a").css("border-color", "#878787");
			$(".media_archive > ul").css("border-color", "#878787");
		}, function() {
			$(this).children("a").css("border-color", "#767676");
			$(".media_archive > ul").css("border-color", "#767676");
		}
	);

	// video slider effect
	if(document.getElementById('slider')){$("#slider").easySlider();}
});

function initGallerySlideshows()
{
	if (JQ('#gallery_slider').length > 0)
	{
		JQ('#gallery_slider').easySlider();


		// Remove any preexisting click functions.
		JQ('#gallery_slider ul li a').unbind('click');

		// Setup the click function to load the new image
		JQ('#gallery_slider ul li a').click(function(e)
		{
			var tempLink = JQ(this);

			JQ('#gallery_preloader').show();

			curImg = JQ('<img />');
			curImg.attr('src', tempLink.find('img').attr('src').replace('/thumb/', '/full/')).load(updateGalleryImage);

			e.stopPropagation();
			return false;
		});
	}
}

function updateGalleryImage()
{
	JQ(this).hide();
	JQ('#gallery_image img').replaceWith(JQ(this));
	JQ(this).fadeIn('slow');
	JQ('#gallery_preloader').hide();
}

function initEventCarousel()
{
	var maxHeight = 0;
	var items = JQ('.content_slider li');

	if (items.length > 1)
	{
		// Get the height of the tallest box

		items.each(function(i)
		{
			if (JQ(this).height() > maxHeight)
			{
				maxHeight = JQ(this).height();
			}

			if (i > 0)
			{
				JQ(this).hide();
			}

			JQ(this).css({position:'absolute', top:0, left:0 });
		});

		// Set the container height to the max item height
		items.parent().parent().height(maxHeight + 30);

		setInterval('crossFadeSideEvents()', 6500);
	}
}

function crossFadeSideEvents()
{
	var items = JQ('.content_slider li');
	var numBoxes = 0;
	var fadeOutBox = 0;
	var fadeInBox = 0;

	if (items.length > 1)
	{
		items.each(function(i)
		{
			numBoxes++;

			if (JQ(this).is(':visible'))
			{
				fadeOutBox = i;
			}
		});

		if (fadeOutBox == numBoxes - 1)
		{
			fadeInBox = 0;
		}

		else
		{
			fadeInBox = fadeOutBox + 1;
		}

		items.each(function(i)
		{
			if (i == fadeOutBox)
			{
				JQ(this).fadeOut(1000);
			}

			if (i == fadeInBox)
			{
				JQ(this).fadeIn(1000);
			}
		});
	}
}



function initHomeNewsCarousel()
{
	var items = JQ('ul#home_news_items > li');

	var maxHeight = 0;
	var modules = JQ('#home_modules .module_btm');

	modules.each(function(i){
		if (JQ(this).height() > maxHeight)
		{
			maxHeight = JQ(this).height();
		}
	});

	modules.height(maxHeight + 'px');


	if (items.length > 0)
	{
		var maxHeight = JQ('.home_news_thumbs').height();

		items.each(function(i){
			JQ(this).show();

			if (JQ(this).height() > maxHeight)
			{
				maxHeight = JQ(this).height();
			}

			JQ(this).css({'position':'absolute'});

			if (i > 0)
			{
				JQ(this).hide();
			}
		});

		JQ('ul#home_news_items').height((maxHeight) + 'px');

		JQ('.home_news_thumbs ul li a').eq(0).addClass('current');

		JQ('.home_news_thumbs ul li a').unbind('click').click(function(e)
		{
			e.stopPropagation();

			clearInterval(homeNewsInterval);

			var links = JQ('.home_news_thumbs ul li a');
			var index = links.index(JQ(this));

			links.removeClass('current');
			JQ(this).addClass('current');

			JQ('ul#home_news_items li:visible').fadeOut(1000);
			JQ('ul#home_news_items li#news_story_' + JQ(this).attr('rel')).fadeIn(1000);

			return false;
		});

		newsSliderThumbs = JQ('.home_news_thumbs .scrollable > ul').bxSlider(
		{
			mode:'vertical',
			infiniteLoop:false,
			moveSlideQty: 3,
			displaySlideQty: 3,
			infiniteLoop: true
		});

		if (items.length > 1)
		{
			homeNewsInterval = setInterval('crossFadeHomeNews()', 6500);
		}
	}
}

function crossFadeHomeNews()
{
	var items = JQ('ul#home_news_items li');
	var numBoxes = 0;
	var fadeOutBox = 0;
	var fadeInBox = 0;

	if (items.length > 1)
	{
		items.each(function(i)
		{
			numBoxes++;

			if (JQ(this).is(':visible'))
			{
				fadeOutBox = i;
			}
		});

		if (fadeOutBox == numBoxes - 1)
		{
			fadeInBox = 0;
		}

		else
		{
			fadeInBox = fadeOutBox + 1;
		}

		items.eq(fadeOutBox).fadeOut(1000);
		items.eq(fadeInBox).fadeIn(1000);

		var id = items.eq(fadeInBox).attr('id');
		id = id.replace('news_story_', '');

		JQ('.home_news_thumbs ul li a').removeClass('current');
		JQ('.home_news_thumbs ul li a[rel="' + id + '"]').addClass('current');

		if (fadeInBox == 0)
		{
			newsSliderThumbs.goToFirstSlide();
		}

		else if (fadeInBox % 3 == 0)
		{
			newsSliderThumbs.goToNextSlide();
		}
	}
}
