// Reorder plugin
$.fn.reorder = function() {
 
  // random array sort from
  // http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children(".event");
    var childCount = $children.length;
 	
    if (childCount > 1) {
      $children.remove();
 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { $this.append($children.eq(k)); });
 
    }
	if (childCount==0) {$(this).append("<p style=\"margin: .5em 0 1em\">There are currently no scheduled events.</p>");}
  }));
}


var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

// implementing a trim function for strings in javascript
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var masks=new Array();
//specify random images below. You can have as many as you wish
masks[0]="mask1.png";
masks[1]="mask2.png";
masks[2]="mask3.png";
masks[3]="mask4.png";

//put the images in randowm order
masks.sort(randOrd);

function randOrd(){
	return (Math.round(Math.random())-0.5); 
}

// ajax calls for sidebar calendar
function calendarAjax() {
	$("#calendar a.link_prev_month, #calendar a.link_next_month").click( function() {
		var link = $(this).attr("href");
		$.ajax({
			url: link,
			cache: false,
			success: function(html){
				$("#calendar").html(html);
				calendarAjax();
			}
		});
		return false;
	});
}

$().ready( function() {
	$("body.home #mainNav li").hover(function(){
		$(this).children("span").stop(true, true).animate({width: '249px'},200);
	}, function(){
		$(this).children("span").stop(true, true).animate({width: '45px'},200);
	});
	
	// Randomly display one of the three lectures/events pulled from the calendar API
	$("body.home #extras .column .calendar").reorder();
	$("body.home #extras .column .calendar").each( function() {
		$(this).children(".event").eq(0).show()
	});
	
	// Prepend list items in the main body and the news archive with ">>" as a bullet
	$("#newsArchive li, #main #extras li").prepend('<span class="bullet">&gt;&gt;</span>');
	
	// parse homepage feature title and create <h2>
	var featuretxt = $("body.home #extras h3.feature a").text();
	featuretxt = featuretxt.split(": ");
	$("body.home #extras h3.feature a").text(featuretxt[1]);
	$("body.home #extras h3.feature").before('<h2 class="feature"></h2>');
	$("body.home #extras h3.feature a").clone().appendTo($("body.home #extras h2.feature"));
	$("body.home #extras h2.feature a").text(featuretxt[0]);
	
	$("body.home #extras img").each( function() {
		var link = $(this).prev("h3").children("a").attr("href");
		$(this).wrap('<a></a>');
		$(this).parent("a").attr("href",link);
	});
	
	//Hide the footer link to home when on homepage
	$("body.home #footerNav li").eq(0).hide();
	
	// Prepend list items in the related links with a "#" as a bullet
	$("#relatedLinks li").prepend('<span class="bullet">#</span>');
	
	// Prepend list items in the section nav with a "_" as a bullet
	$("#sectionNav ul li").prepend('<span class="bullet">_</span>');
	
	// Make sure that the appended "_" changes color on hover
	$("#sectionNav a").hover(function(){
		$(this).parent("li").addClass("hover");
	},function(){
		$(this).parent("li").removeClass("hover");
	});
	
	// Set state-saving nav class
	$('#sectionNav a').each(function() {
		var navlink = $(this).attr("href");
		if (navlink.toLowerCase()==location.href.toLowerCase()) {
			$(this).parent("li").addClass("selected");
		}
	});
	
	// Add the randomly ordered masks to the slides in the homepage feature
	$("div.slide").each( function(i) {
		$(this).prepend('<img src="/assets/images/'+masks[i]+'" class="mask" />');
		$(this).children("p.more").children("a").empty();
		$(this).children("img.mask").wrap($(this).children("p.more").children("a"));
		$(this).children("p.more").remove();
	});
	
	// Append the links for the slides around the masks
	
	// Animation for BFA homepage
	$("#main ul.departments li").hover(function(){
		$(this).children("span.slider").stop(true, true).animate({width: '289px'},200);
	}, function(){
		$(this).children("span.slider").stop(true, true).animate({width: '30px'},200);
	});
	
	calendarAjax();
	
	// show/hide for job post blogs
	$("#main .archive ul li").eq(0).children("ul").show();
	$("#main .archive ul li").click(function() {
		$(this).children("ul").toggle();
	})
	
	// use the search form's label to fade in/out on click
	if ($("#q").val()=="") {
		$("#search label").css("visibility","visible");
	}
	$("#q").focus( function() {
		$("#search label").fadeOut("fast");
	});
	$("#q").blur( function() {
		if ($("#q").val()=="") {
			$("#search label").fadeIn("fast");
		}
	});
	
	// Capture click on footer newsletter subscribe link and display subscribe form
	$("#footer p.newsletter a").click( function() {
		$("#footer p.newsletter").css("display","none");
		$("#footer #subscribeForm").css("display","block");
		return false;
	});
	
	// use the footer subscribe form's label to fade in/out on click
	if ($("#mb-nulki-nulki").val()=="") {
		$("#subscribeForm label").css("visibility","visible");
	}
	$("#mb-nulki-nulki").focus( function() {
		$("#subscribeForm label").fadeOut("fast");
	});
	$("#mb-nulki-nulki").blur( function() {
		if ($("#mb-nulki-nulki").val()=="") {
			$("#subscribeForm label").fadeIn("fast");
		}
	});
	
	// Create interactive footer navigation
	$("#footerNav li ul").parent("li").children("a").click(function(){
		if ($(this).parent("li").attr("class")=="active") {
			$(this).parent("li").removeClass("active");
			$(this).parent("li").children("ul").hide();
		} else {
			$("#footerNav li ul").hide();
			$("#footerNav li").removeClass("active");
			$(this).parent("li").addClass("active");
			$(this).parent("li").children("ul").show();
			$(this).parent("li").children("ul").css("min-height",(this.offsetTop+16)+"px");
			//alert(this.offsetTop+"px");
			
		}
		return false;
	});
	
	// If IE6 just display the first slide, and don't try to animate the homepage slideshow
	if(IE6) {
		$('#slideshow .slide:first-child').css("display","block");
	} else {
		$('#slideshow').cycle({
			fx:     'fade', 
			speed:  'slow', 
		    timeout: 7000, 
		    pager:  '#slideNav',
			pause:  1,
			cleartype: 0
		});
	}
	
	// create elements and set styles needed for 3-D ".extruded" class
	$(".extruded").each(function(){
		var x = $(this).width(); 
		var xpl = $(this).css("padding-left");
		var xpr = $(this).css("padding-right");
		xpl = xpl.substr(0,xpl.length-2);
		xpr = xpr.substr(0,xpr.length-2);
		x = parseInt(x) + parseInt(xpl) + parseInt(xpr);
		var y = $(this).height();
		var ypt = $(this).css("padding-top");
		var ypb = $(this).css("padding-bottom");
		ypt = ypt.substr(0,ypt.length-2);
		ypb = ypb.substr(0,ypb.length-2);
		y = parseInt(y) + parseInt(ypt) + parseInt(ypb);
		$(this).append('<div class="shadow1"></div><div class="shadow2"></div>');
		$(this).children(".shadow1").css("top",y+"px");
		$(this).children(".shadow2").css("left",x+"px");
	});
	
	// Sort category archives into two columns
		$("body.mt-category-archive #main .twoCol").prev("h1").after('<div id="extras"><div class="column"></div><div class="column" style="width:300px;padding-right:0;"></div></div>');
		var entryCount = $("body.mt-category-archive #main .entry-asset").length;
		col1count = Math.round(entryCount/2);
		$("body.mt-category-archive #main .entry-asset").each( function(i) {
			if(i<col1count){
				$(this).appendTo($("div.column:eq(0)"));
			} else {
				$(this).appendTo($("div.column:eq(1)"));
			}
		});
	
	// Add a title attribute for links to certain filetypes (PDF, etc)
	$("#main a").each( function() {
		
		if ($(this).attr("href")) {
			fileExt = $(this).attr("href").trim();
			fileExt = fileExt.substring(fileExt.lastIndexOf(".")+1,fileExt.length);
			fileExt = fileExt.toUpperCase();
			if (fileExt=="PDF") {
				$(this).attr("title",fileExt);
			}
			if (fileExt=="WMV") {
				$(this).attr("title","Windows Media Video");
			}
		}
	});
	
	// Add filetype icons after links with corresponding title attributes
	$('a[@title^=PDF]').after('<img src="http://roski.usc.edu/assets/images/pdf_icon.gif" class="icon" alt="(PDF)" />');
	$('a[@title^=Word]').after('<img src="http://roski.usc.edu/assets/images/word_icon.gif" class="icon" alt="(Word)" />');
	$('a[@title^=Excel]').after('<img src="http://roski.usc.edu/assets/images/excel_icon.gif" class="icon" alt="(Excel)" />');
	$('a[@title^=PowerPoint], a[@title^=Powerpoint]').after('<img src="http://roski.usc.edu/assets/images/ppt_icon.gif" class="icon" alt="(PowerPoint)" />');
	$('a[@title^="Windows Media Video"]').after('<img src="http://roski.usc.edu/assets/images/wmv_icon.gif" class="icon" alt="(Windows Media Video)" />');
	$('a[@title^=Quicktime]').after('<img src="http://roski.usc.edu/assets/images/mov_icon.gif" class="icon" alt="(Quicktime movie)" />');
	
	// move the related links from #main into #navigation
	$("#main #relatedLinks").clone().appendTo("#navigation");
	$("#main #relatedLinks").remove();
});
