//@author mcnamamj

$(document).ready(function() {

	$("#pullDown").css("background", "transparent url(/main/images/main_red_arrow_down.png) no-repeat scroll right 5px");
	//setupReputationPullDown();
	//setupReputationNavigation();
	setupAudience();
	
	//I give this a 1 second wait after DOM ready so as to give priority to requests that come from checkURL();
	//lazyLoad(7000);
	
	//check URL for hash
	//checkURL();
	
	$.nyroModalSettings({minWidth: 50,
	  minHeight: 50,
	  type: 'swf'
  }); 
	
	
});

function ajaxError (XMLHttpRequest, textStatus, errorThrown) {
  console.log(errorThrown);
  console.log(textStatus);
  console.log("End error report");
}


if(!Array.indexOf) {
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}


var busy = false;
var reputationPulledDown = false;

//finds hashes in the URL and sees if they correspond to something on the page
//uncalled - no more checking
function checkURL() {
	var hash = window.location.hash.replace(/#/, '');
	if(hash != '')
	{
		//reputationNavItemClickedByName(hash);
		//toggleAudienceChoice(hash);
		if(hash == 'about')
			$("#pullDown").click();
	}
}

//uncalled - no more reputation
//this is a one time run, adds the event listeners to the pullDown for reputation
function setupReputationPullDown() {
	$("#pullDown").click(function() {
		if(reputationPulledDown) {
			$("#reputation").animate({top: "-354"}, 1000, function() { $("#pullDown").html("MORE");
			$("#pullDown").css("background", "transparent url(/main/images/main_red_arrow_down.png) no-repeat scroll right 5px"); }); 
			reputationPulledDown = false;
			$("#pullDown").attr("href", "#");
			
			
		} else {
			$("#reputation").animate({top: "0"}, 1000, function() {$("#pullDown").html("LESS");
			$("#pullDown").css("background", "transparent url(/main/images/main_red_arrow.png) no-repeat scroll right 5px");
 }); 
			reputationPulledDown = true;
			$("#pullDown").attr("href", $("#contents #topThird #reputation ul.nav li a.active").attr("href"));
					}
	});
}


//this is a one time run, sets up the clicks on the audience listing
function setupAudience() {
	
	$("#bottomThird div.roles div.role div.audienceDetail").css('display', 'none');

	$("#bottomThird div.roles div.role h5").click(function(evt) { 
		if(!busy) {
			toggleAudienceChoice($($(this).parent().get(0)).attr("id"));

			return false;
		}
	});
}

//this is the function that is called when an audience item should be invoked
//  (can be called by things other than just clicking)
function toggleAudienceChoice(str) {
	var acceptableAudiences = ['aud_future', 'aud_parents', 'aud_alumni', 'aud_staff', 'aud_current'];
	if(acceptableAudiences.indexOf(str) === -1) {
		return;
	}
	var audienceSpeed = 1000;
	if(busy) return;
	var searchOnce = $("#bottomThird div.roles div#" + str + " div.audienceDetail");
	
	//does the content of the entity you're looking for exist?
	//* unused - this is not possible
	if($(searchOnce).size() <= 0) {
		//nope - lazy load it
		$("#bottomThird div.roles div#" + str).append("<div class='audienceLoading' class='active' style='display: none; text-align: center;'><br /><img src='/main/images/ajax-blue.gif'/><br/>Please wait while the content finishes loading.<br /><br /></div>");
		$(".audienceLoading").slideDown("fast");
		busy = false;
		return '';
	}
	//are you clicking on the audience entity that is already clicked?
	if($(searchOnce).hasClass("active")) {
		//remove the active class and slide up
		$.scrollTo(parseInt($("div#wrapper").height()) - parseInt($(window).height()) - parseInt($(searchOnce).height()), 750, {axis: 'y'});
		setTimeout(function() { $(searchOnce).removeClass("active");
		$(searchOnce).slideUp(audienceSpeed, function() { busy = false; } );
		}, 750);
		return '';
	}
	
	//this is not the existing active one, so close any existingly active ones
	var existing = $("#bottomThird div.roles div.active")
	if($(existing).size() > 0) {
		$(existing).removeClass("active");
		//animation chain: close active, THEN add active to what was clicked and slide it down THEN busy = false
		$(existing).slideUp(audienceSpeed, function() { } );
		$(searchOnce).addClass("active").slideDown(audienceSpeed, function() {busy = false;});
		return str;
	}
	else {
		//when you clicked, there were no other actives, so make this one active and slide it down
		$(searchOnce).addClass("active").slideDown(audienceSpeed, function() { busy = false });
		return str;
	}
}

//uncalled - got rid of reputation
//only called once: sets up the click event on the reputation navigation
function setupReputationNavigation() {
	$("#contents #topThird #reputation ul.nav li a").click(function() {
		var x = $(this).attr("href").replace(/#/,'');
		reputationNavItemClickedByName(x);
	});
}

//uncalled - got rid of reputation
//event response on clicking a reputation nav item, can also be called by passing a nav item id
function reputationNavItemClickedByName(strName) {

	if(!busy) {
		//if there exists a link that points to that id, then...
		//since this happens on page load, using ">" operator to speed up searching
		if($("#contents > #topThird > #reputation > ul.nav > li a[href='#" + strName + "']").size() > 0) {
			if(strName != $("#contents #topThird #reputation ul.nav li a.active").attr('href')) {
				$("#contents #topThird #reputation ul.nav li a.active").removeClass("active");
				$("#contents #topThird #reputation ul.nav li a[href='#" + strName + "']").addClass("active");
				showReputationPage(strName);
				if(!reputationPulledDown) {
					//the reputation wasn't pulled down when we decided to show this, so drop it
					$("#pullDown").click();
				}
				return;
			}
		} else {
			//there was no link to that id, so we pretend like nothing happened
			return;
		}
	}
}

var numRequests = 0;
var baseURL = '/main/content_components';
	
//should be uncalled - we no longer load these this way
function lazyLoad(waitTimeInMilliseconds) {
	setTimeout(function() {

		//llHelper(baseURL, "/reputation/about_ccomp.xhtml", "about_ccomp", ".reputationDetail");
		//llHelper(baseURL, "/reputation/living_learning_environment_ccomp.xhtml", "living_learning_environment_ccomp", ".reputationDetail");
		//llHelper(baseURL, "/reputation/community_outreach_ccomp.xhtml", "community_outreach_ccomp", ".reputationDetail");
		//llHelper(baseURL, "/reputation/awards_rankings_ccomp.xhtml", "awards_rankings_ccomp", ".reputationDetail");
		
		//llHelper(baseURL, "/reputation/history_ccomp.xhtml", "history_ccomp", ".reputationDetail");
		//llHelper(baseURL, "/reputation/marianists.xhtml", "marianists", ".reputationDetail");
		
		//llHelper(baseURL, "/audience/alumni_friends_ccomp.xhtml", "alumni_friends_ccomp", "#aud_alumni");
		//llHelper(baseURL, "/audience/current_students_ccomp.xhtml", "current_students_ccomp", "#aud_current");
		//llHelper(baseURL, "/audience/faculty_staff_ccomp.xhtml", "faculty_staff_ccomp", "#aud_staff");
		//llHelper(baseURL, "/audience/future_ud_students_ccomp.xhtml", "future_ud_students_ccomp", "#aud_future");
		//llHelper(baseURL, "/audience/parents_ccomp.xhtml", "parents_ccomp", "#aud_parents");
	
	}, waitTimeInMilliseconds);
}

//uncalled, no more lazy loading
function llHelper(baseURL, fileName, whatToCallIt, whereToPutIt) {
	++numRequests;
	$.get(baseURL + fileName, null, function(data) {
		if($(whereToPutIt + " > #" + whatToCallIt).size() <= 0) {
			$(whereToPutIt).append('<div class="loadedFromAJAX" id="' + whatToCallIt + '">' + data + '</div>');
		} else {
			var searchOnce = $(whereToPutIt + " > #" + whatToCallIt);
			searchOnce.addClass("loadedFromAJAX");
			//the item has already been loaded, that happens.  sorry.
		}
		checkDone();
	}, "html");
}

//uncalled - no more lazy loading
function checkDone() {
	--numRequests;
	if(numRequests == 0) {
		//$("#reputationLoading").fadeOut("slow", function() {
		//	showReputationPage($("#contents #topThird #reputation ul.nav li a.active").attr('href').replace(/#/,''));
		//});
		var parent = $(".audienceLoading").parent().get(0);
		$(".audienceLoading:not(:first)").slideUp("slow");
		$(".audienceLoading:first").slideUp("slow", function() {
			busy = false;
			toggleAudienceChoice($(parent).attr("id"));
		});
		
		removeSpotlightLLClass();

	}
}

function removeSpotlightLLClass(str) {
	var searchOnce = $("div#resultsNews div.active");
	$(searchOnce).fadeOut("fast");
	$(searchOnce).removeClass("active");

	var searchOnce = $("div#resultsNews div.loadedFromAJAX");
	$(searchOnce).fadeIn("fast");
	$(searchOnce).addClass("active");
	$(searchOnce).removeClass("loadedFromAJAX");
}

//uncalled - no more reputation
//just a little helper function to translate linkNames to ccomps
function translateReputationLinkToID(linkName) {
	
	if(linkName == 'about') {
		return 'about_ccomp';
	}
	else if(linkName == 'history') {
		return 'history_ccomp';
	}
	else if(linkName == 'marianists') {
		return 'marianists';
	}
	else if(linkName == 'lle') {
		return 'living_learning_environment_ccomp';
	}
	else if(linkName == 'communityOutreach') {
		return 'community_outreach_ccomp';
	}
	else if(linkName == 'awards') {
		return 'awards_rankings_ccomp';
	}
	return false;

}

//uncalled - no more reputation
//this actually loads the reputation item
function showReputationPage(page) {
	busy = true;
	var x = translateReputationLinkToID(page);
	if(x === false) {
		//default to about in event of a problem
		x = 'about_ccomp';
	}
	
	var searchOnce = $("#contents #topThird #reputation div.reputationDetail div.active");
	
	//are we already showing the page that you clicked on?
	if($(searchOnce).attr("id") == x) {
		//yep, so get out of here
		busy = false;
		return;
	}
	
	//check to see if this item doesn't exist
	if($("#contents #topThird #reputation div.reputationDetail div#" + x).size() == 0) {
		//it doesn exist, so see if there's an existing reputation page showing
		if($(searchOnce).size() >= 1) {
			//there is, so fade it out and replace with a loading screen, then llHelper the item we want
			$(searchOnce).fadeOut("fast", function() {
				$("#reputationLoading").fadeIn("slow", function() {
					llHelper(baseURL, "/reputation/" + x + ".xhtml", x, ".reputationDetail");
				});
			});
			return;
		} else {
			//there are no other reputation pages currently showing, so you don't have to fade them out
			$("#reputationLoading").fadeIn("slow", function() {
					llHelper(baseURL, "/reputation/" +  x + ".xhtml", x, ".reputationDetail");
			});
			return;
		}
	}
	
	//if there's an active page, fade it out
	if($(searchOnce).size() >= 1) {
		$(searchOnce).fadeOut("fast", function() {
			searchOnce.removeClass("active");
			fadeInReputationPage(x);
		});
	} else {
		//otherwise just fade in our dude
		fadeInReputationPage(x);
	}
}

//uncalled - no more reputation
//abstracted helper function since i call it in a few places
function fadeInReputationPage(x) {
	$("#contents #topThird #reputation div.reputationDetail div#" + x).addClass("active").fadeIn("fast", function() {busy = false; });
}


/***** McPlayVideos ********/

if($("a.udit.nyroModal").size() == 1) {
	$("a.udit.nyroModal img").css('border', 'none');
	$("a.udit.nyroModal").append("<div class='playButton'>&nbsp;</div>");
	setTimeout(function() {
		top = $("a.udit.nyroModal img").offset().top;
		left = $("a.udit.nyroModal img").offset().left;
		
		$("a.udit.nyroModal div").css("top", top + 15);
		$("a.udit.nyroModal div").css('left', left + 15);
	}, 5);
}



