/* -- global variables -- */
/* maintains the visibility state of the flash cue card */
var flashVisible = false;

$(document).ready(function() {

	window.onresize = function() {
		if (flashVisible) updateFlashContainerHeight('expanded');
	}
	window.onscroll = function() {
		if (flashVisible) updateFlashContainerHeight('expanded');
	}
	
	/* Drop Down Menu functionality */
	function toggleMenu() {
		if ($('#sortMenu').hasClass('sortMenuAlt')) {
			//sliding up - delay to make the header graphic change smooth
			setTimeout("$('#sortMenu').removeClass('sortMenuAlt'); $('#sortMenu').addClass('sortMenuInitial')", 200);
		} else {
			if ($('#sortMenu').hasClass('sortMenuInitial')) {
				$('#sortMenu').removeClass('sortMenuInitial');
				$('#sortMenu').addClass('sortMenuAlt');
			}
		}
	}
	function toggleCourseMenu() {
		if ($('#courseMenu').hasClass('courseMenuAlt')) {
			//sliding up - delay to make the header graphic change smooth
			setTimeout("$('#courseMenu').removeClass('courseMenuAlt'); $('#courseMenu').addClass('courseMenuInitial')", 200);
		} else {
			if ($('#courseMenu').hasClass('courseMenuInitial')) {
				$('#courseMenu').removeClass('courseMenuInitial');
				$('#courseMenu').addClass('courseMenuAlt');
			}
		}
	}
														 
	//assign styles/class based on position in drop down list												 
	$('#viewSortSelector li:first').addClass('topItem');
	$('#viewSortSelector li:last').addClass('sortMenuListCap');
	$('#viewSortSelector li:not(li:last)').css({cursor: "pointer"});
	
	$('#courseSelector li:first').addClass('topItem');
	$('#courseSelector li:last').addClass('courseMenuListCap');
	$('#courseSelector li:not(li:last)').css({cursor: "pointer"});
	
	//event handlers
	$('#sortMenu').click(function() {
		$('.sortMenuDropDownList').slideToggle(200);
		
		toggleMenu();		
	});
	$('#courseMenu').click(function() {
		$('.courseMenuDropDownList').slideToggle(200);
		
		toggleCourseMenu();		
	});


	$('.sortMenuDropDownList').click(function(){
		$('.sortMenuDropDownList').slideUp(200);
		
		toggleMenu();
	});
	
	$('.courseMenuDropDownList').click(function(){
		$('.courseMenuDropDownList').slideUp(200);
		
		toggleCourseMenu();
	});
	

$('.sortMenuDropDownList li:not(li:last)').hover(
		function() {
			$(this).addClass("selected");
		}, 
		function() {
			$(this).removeClass("selected");
		}
	)
$('.courseMenuDropDownList li:not(li:last)').hover(
		function() {
			$(this).addClass("selected");
		}, 
		function() {
			$(this).removeClass("selected");
		}
	)
	
	//change 'header' text upon list item selection
	$('.sortMenuDropDownList li:not(li:last)').click(function() {
			var text = $(this).text();
			$('#selectedCategory').text(text);
	});

	$('.courseMenuDropDownList li:not(li:last)').click(function() {
			var text = $(this).text();
			$('#selectedCourse').text(text);
	});


	/* Header Drop Down Functionality */												 
	
	function updateHeaderState() {
		$(".dropDownContent").slideToggle(200);
		
		if($(".searchDropDown").hasClass("selected")) {
			$(".searchDropDown").removeClass("selected");
		} else {
			$(".searchDropDown").addClass("selected");
		}
	}
	
	$(".searchDropDown, .cueCard, .people").click(function () {
		updateHeaderState();
	});
		
	$(".cueCard").hover(
		function () {
			$(this).addClass("selected");
		}, 
		function () {
			$(this).removeClass("selected");
		}
	);
		
	$(".people").hover(
		function () {
			$(this).addClass("selected");
		}, 
		function () {
			$(this).removeClass("selected");
		}
	);
	
	$("#goButton").hover(
		function(){
			$(this).addClass("over");
		},
		function(){
			$(this).removeClass("over");
			$(this).addClass("up");
		}
	);
	
	$("#goButton").click(function(){
		$(this).addClass("down");
	});
	
});
/* end of document.ready */

window.onload = function() {
	iCueInitialize();
}
	
function iCueActivateTab(theTabIndex)
{
	// switch z-index and swap selected image state
	for (i = 0; i < 5; i++)
	{
		evalPrefix = 'document.getElementById("mainTab' + i + '")';
		if (i == theTabIndex) {
			eval(evalPrefix + '.style.zIndex = "99"');
			eval(evalPrefix + '.className = "selectedTab"'); /* this is for a test only */
		} else {
			eval(evalPrefix + '.style.zIndex = "' + (94 - i) + '"');
			eval(evalPrefix + '.className = "unselectedTab"'); /* this is for a test only */
		}
	}
}

/* triggered at page load */
function iCueInitialize()
{
	/* prevents dotted outline around clicked elements in firefox */
	window.onclick = function(theEvent)
	{
		theTagName = theEvent.target.tagName;
		doBlur = true;
		if (theTagName == "INPUT") doBlur = false;
		if (theTagName == "SELECT") doBlur = false;
		if (theTagName == "TEXTAREA") doBlur = false;
		if (theTagName == "OPTION") doBlur = false;
		if (theTagName == "EMBED") doBlur = false;
		
		if (doBlur) {
			theEvent.target.focus = theEvent.target.blur();
		}
	}
}

/* thumbnail rollover with mask */
var timeOut; 
function courseInfo(showStatus, theCourse, theCourseImage)
{
	courseImg = document.getElementById(theCourseImage);
	if (showStatus == "in")
	{	
		courseImg.style.position = "absolute";
		courseImg.style.zIndex = "202";
		timeOut = setTimeout("$('#" + theCourse + "').fadeIn(300)", 500);
	} else {
		clearTimeout(timeOut);
		courseImg.style.position = "static";
		$('#'+theCourse).fadeOut(300);
		courseImg.style.zIndex = "0";
	}
}

/* swaps an image based on the passed target node */
function imgSwap(theTarget, theImage)
{
	theTarget.src = theImage;
}

/* opens the clicked course in floating layer */
function openCourse(courseID)
{
	alert('Placeholder div would be here.');
}

/* removes a course from the presentation layer when the close button is clicked */
function removeCourse(theDeleteIcon)
{
	containerRef = theDeleteIcon.offsetParent.offsetParent;
	while (containerRef.rows.length > 0)
	{
		containerRef.removeChild(containerRef.firstChild);
	}
	containerRef.style.display = "none";
}

function getSelectedRadioButtonValue(elems) {
	for(var i = 0; i < elems.length; i++) {
		if(elems[i].checked)
			return elems[i].value;
	}
	return undefined;
}

function getSelectedRadioButtonIndex(elems) {
	for(var i = 0; i < elems.length; i++) {
		if(elems[i].checked)
			return i;
	}
	return undefined;
}

function submitViaEnter(evt)
{
	evt = (evt) ? evt : event;
	var target = (evt.target) ? evt.target : evt.srcElement;
	var form = target.form;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
	if (charCode == 13 || charCode == 3) {
		form.submit();
		return false;
	}
	return true;
}

/* selects checkboxes in a specified parent element using a base name for inclusion */
function selectCheckboxs(checkboxsParentId, baseName, selectAll)
{
	theParent = document.getElementById(checkboxsParentId);
	
	// check to see if fleXcroll scrollbar is applied since parent ID will be different
	if(theParent.fleXcroll) {
		theParent = document.getElementById(checkboxsParentId + "_contentwrapper");
	}
	
	for (i = 0; i < theParent.childNodes.length; i++)
	{
		thisChild = theParent.childNodes[i];
		if (thisChild.tagName == "INPUT" && thisChild.id.indexOf(baseName) > -1)
		{
			thisChild.checked = selectAll;
		}
	}
}

/* in the registration section, hides the my info portion from user control */
function hideMyInfo(hide)
{
	if (navigator.userAgent.indexOf('MSIE 6.0') > -1) {
		hideFormElements(hide, "registrationForm", ["country","state","education"]);
	}
	document.getElementById('hideMyInfo').style.display = hide ? "block" : "none";
	document.getElementById('myAgeButtonArea').style.visibility = hide ? "visible" : "hidden";
}

function hideStateZip(hide, form)
{
	toggleFormElemDisable(hide,'state','stateLabel');
	toggleFormElemDisable(hide,'zipCode','zipLabel');
}

function hideLogin(hide, form)
{
	if (document.getElementById('hideLogin'))
		document.getElementById('hideLogin').style.display = hide ? "block" : "none";
	
	//Handle form fields (to prevent/allow access)
	if (hide) {
		$('#confirmEmail, #password, #confirmPassword').val('');
		$('#confirmEmail, #password, #confirmPassword').attr("disabled", "disabled");
	} else {
		$('#confirmEmail, #password, #confirmPassword').removeAttr("disabled");
	}
}

/* fixes IE6 bleed through of selectors when content is draw above it on the z-index */
function hideFormElements(hide, formName, selectorArray)
{
	/* selectorArray is an array of selector ID's to hide */
	for (i = 0; i < selectorArray.length; i++)
	{
		showState = hide ? "hidden" : "visible" ;
		eval('document.forms["' + formName + '"].' + selectorArray[i] + '.style.visibility = "' + showState + '"');
	}
}

/* shows/hides state and zip areas based on drop down selection */

function checkCountry(form)
{
	var hide = false;
	var selection = document.getElementById('country');
	if(selection.options[selection.selectedIndex].value != 'US')
		hide = true;
	
	hideStateZip(hide, form);
	/* if(!hide) { document.getElementById("state").focus(); } */
	/* hideLogin(hide, form); */
}

/* fixes IE6 bleed through of selectors when content is draw above it on the z-index */
function disableFormElements(disable, formName, selectorArray)
{
	/* selectorArray is an array of selector ID's to hide */
	for (i = 0; i < selectorArray.length; i++)
	{
		eval('document.forms["' + formName + '"].' + selectorArray[i] + '.disabled = "' + disable + '"');
	}
}


/* hides all plugins on the page */
function hidePlugins()
{
	for (i = 0; i < document.embeds.length; i++)
	{
		document.embeds[i].style.visibility = "hidden";
	}
}

/* shows all plugins on the page */
function showPlugins()
{
	for (i = 0; i < document.embeds.length; i++)
	{
		document.embeds[i].style.visibility = "visible";
	}
}

/* hides or shows an elemtn based on it's ID */
function showToggle(theID,theVisibility)
{
	switch(theVisibility)
	{
		case "show" :
			document.getElementById(theID).style.display = "block";
		break;
		case "hide" :
			document.getElementById(theID).style.display = "none";
	}
}


/*
********** form handling for advanced search
*/
var fleXcrollAdvSearchTriggered = false;
function switchSearchSource(theSource)
{
	switch(theSource)
	{
		case "cueCardsInput":
			document.getElementById("asCueCards").style.display = "block";
			document.getElementById("asPeople").style.display = "none";
			/* must trigger flexcroll this way because initial state is hidden */
			/* when initially hidden, flexcroll areas will not work */
			if (!fleXcrollAdvSearchTriggered) CSBfleXcroll('sourceCheckBoxs'); 
			fleXcrollAdvSearchTriggered = true;
			break;
			
		case "peopleInput":
			document.getElementById("asCueCards").style.display = "none";
			document.getElementById("asPeople").style.display = "block";
			break;
	}
}

function advSearchCheckState(formElem)
{
	var hide = false;
	switch(formElem.options[formElem.selectedIndex].value)
	{
		case "US":
		case "United States":
			hide = false;
			break;
			
		default:
			hide = true;
			break;
	}
	toggleFormElemDisable(hide,'stateSelector','stateLabel');
}

function toggleFormElemDisable(hide,formElemID,labelID)
{
	labelID = "#" + labelID;
	formElemID = "#" + formElemID;
	if (hide) {
		$(labelID).addClass('disabled');
		$(formElemID).attr("disabled", "disabled");
	} else {
		$(labelID).removeClass('disabled');
		$(formElemID).removeAttr("disabled");
	}
}


/* checks the status of and assigns values to the MIT reqs checkbox */
function MITCheckBoxStatus(bool) 
{
	var oldEnough = ageCheck();
	document.getElementById('requirementsMIT').checked = bool;
	
	if (!bool) { 
		$('#parentGuardianEmail,#parentGuardianEmailConfirm').val('');
		$('#parentGuardianInfo').hide();
	} else {
		
		if (!oldEnough) {
			$('#parentGuardianInfo').show();
		} else {
			$('#parentGuardianEmail,#parentGuardianEmailConfirm').val('');
			$('#parentGuardianInfo').hide();
		}
	}
}

/* assigns values to the MIT reqs radio group */
function MITRadioGroupStatus(bool) 
{
	if (bool) {
		document.getElementById('requirementsMIT').checked = true;
	}
	else {
		document.getElementById('rejectRequirementsMIT').checked = true;
	}
}

/* determines action when parental consent form is submitted */
function parentalConsentValidate()
{
	var oldEnough = ageCheck(); // returns true if 18 or over
	
	if (oldEnough == true) {
		$('#headerText').text("THANK YOU!");
		// Check for participation and set text accordingly
		if ($("#requirementsMIT").attr("checked") == true) {
			$('#smallContent').text("Thank you for your response! We appreciate your child's participation in this important MIT study.");
		} else {
			$('#smallContent').text("Thank you for your response! Your child will not participate in the MIT study, but can still enjoy all of the features of iCue.");
		}
	} else {
		$('#headerText').text("SORRY");
		$('#smallContent').text("In order to approve a minor you need to be 18 or over.");
	}
	$('#alertDialog').jqmShow();
}

/* hides the parentGuardian emails fields when the checkbox isn't checked */
function hideParentEmails() 
{
	if ($("#requirementsMIT").attr("checked") == false)
	{
		$('#parentGuardianEmail,#parentGuardianEmailConfirm').val('');
		$('#parentGuardianInfo').hide();
	}
}

/*
********** handling for modals containing custom scroller
*/
var privacyPolicyModalTriggered = false;
var sysReqsModalTriggered = false;
var termsOfServiceModalTriggered = false;
var MITModalTriggered = false;
var modalTriggered = false;

function modalFleXcrollCheck(modalId, contentId, modal) {
	//format id for jQuery use...
	var id = "#" + modalId;
	// ...then show the modal

	$(id).jqmShow();
	
	switch (modal) {
		case 'TOS':
		{
			if (!termsOfServiceModalTriggered) 
				termsOfServiceModalTriggered = true;
			break;
		}	
		case 'sysReq' : 
		{
			if (!sysReqsModalTriggered) 
				sysReqsModalTriggered = true;
			break;
		}
		case 'privacy': 
		{
			if (!privacyPolicyModalTriggered) 
				privacyPolicyModalTriggered = true;
			break;
		}
		case 'MIT': 
		{
			if (!MITModalTriggered) 
				MITModalTriggered = true;
			break;
		}
		default:
		{
			if (!modalTriggered) 
				modalTriggered = true;
			break;
		}
	}
	CSBfleXcroll(contentId); 
}

/*
********** handler for MIT checkbox state w/ modal display
********** bool = desired value of the MIT reqs checkbox on click
*/
function MITReqsCheckbox(checkboxObj) {
	
	if (checkboxObj.checked == true) {
		modalFleXcrollCheck('MITDialog', 'MITContent', 'MIT');
	}
	$('#parentGuardianEmail,#parentGuardianEmailConfirm').val('');
	$('#parentGuardianInfo').hide();
}

/* Launches MIT Requirements modal regardless of checkbox state */
function MITReqs() {
	modalFleXcrollCheck('MITDialog', 'MITContent', 'MIT');
}

/* Displays the MIT modal depending on the state of the acceptance radio group */

function MITRadioReqs(radioObj) {

	if (radioObj.checked == false )
		modalFleXcrollCheck('MITDialog', 'MITContent', 'MIT');

}

/* Dynamically adjust # of days in regards to entered month/year */
function daysInMonth(select) {
	var monthObj = document.getElementById('month');
	var yearObj = document.getElementById('year');
	
	var month = parseInt(monthObj.options[monthObj.selectedIndex].value);
	var year = parseInt(yearObj.options[yearObj.selectedIndex].value);

	if (month > 0) {
		$('#day').removeAttr("disabled");
		
		if (year <= 0 || isNaN(year)) {
			year = 1990;
		}
		
		/* date wraps to the next month if days are too many for currently
		 * selected month and year. 32 - excess days = number of days in
		 * selected month and year.
		 */
		var days = 32 - new Date(year, month-1, 32).getDate();
			
		// -1 length for correction (top empty option) 
		var dayChange = days - (select.length - 1);
		
		if (dayChange < 0) {
			dayChange = Math.abs(dayChange);
			for (var i=0; i<dayChange; i++)
			{
				// delete the last option 
				select.options[select.length - 1] = null;
			}
		} else {
			//latest day in the month
			var latestDate = parseInt(select.options[select.length - 1].value);
			for (var i=1; i<=dayChange; i++)
			{
			  var day = i + latestDate;
			  var option = new Option(day, day);
			  select.options[select.length] = option;
			}	
		}
	} else {
		$('#day').attr("disabled", "disabled");
	}
}

/*
********** Checks the entered age of the user 
*/

function ageCheck() {
	var playerAge = new Date();
	var now = new Date();
			
	var dayObj = document.getElementById('day');
	var monthObj = document.getElementById('month');
	var yearObj = document.getElementById('year');
	
	var day = parseInt(dayObj.options[dayObj.selectedIndex].value);
	var month = parseInt(monthObj.options[monthObj.selectedIndex].value);
	var year = parseInt(yearObj.options[yearObj.selectedIndex].value);

	if (isNaN(month) || isNaN(day) || isNaN(year) || month < 0 || day < 0 || year < 0) {
		document.getElementById('alertText').innerHTML = "Please enter your Date of Birth";
		return null;
	}

	//Check for player age of 13
	playerAge.setFullYear(year+13, month-1, day);
	var ageDiffThirteen = now.getTime() - playerAge.getTime();
	
	//Check for player age of 18
	playerAge.setFullYear(year+18, month-1, day);
	var ageDiffEighteen = now.getTime() - playerAge.getTime();

	// determine if user is old enough
	if (ageDiffThirteen < 0) {
		document.getElementById('alertText').innerHTML = "You must be at least 13 years of age to use iCue at this time. Feel free to visit <a href='http://www.msnbc.com'>msnbc.com </a> for the latest news, sports, and entertainment.";
		return null;
	} else {
		if (ageDiffThirteen >= 0 && ageDiffEighteen < 0) {
			$('#minor').attr("value", "true");
			return false;
		} else {
			if (ageDiffEighteen >= 0)
				$('#minor').attr("value", "false");
				return true;
		}
	}
}

/* Uses ageCheck() to determine what to do */
function ageValidation() {
	
	var oldEnough = ageCheck();
	
	if (oldEnough == null) {
		$('#alertDialog').jqmShow();
	} else {
		hideMyInfo(false);
		
		//Re-enable all input fields
		$("input").removeAttr("disabled");
		
		$("#country, #education").removeAttr("disabled");
		checkCountry('registrationForm');
		$("#month, #day, #year").attr("disabled", "disabled");
	}
}

/* updates the state of the JS scrollbar */
function updateScroller(delay) {
	
	if (delay == null) 
		delay = 200;
	
	setTimeout("document.getElementById('treeContainer').scrollUpdate()", delay);
}

/*
	Scroll by defining relative or absolute values:

		scrollerObject.contentScroll(x,y,relative);
	
	-positions of content and can be set to false if we don't
		require scrolling in that direction:
		
		scrollerObject.contentScroll("false", "300px", true);
		
	-x and y should be sent as string, between quotation marks.
	-x and y can take three different units: px, s, p
		px = pixels
		s = scroll step
		p = a scroll page
	-If 'relative' is set to true, x and y positions are relative
		to the scrollObj position.
*/
function fleXcrollTo(scrollObj, resetPosition) {
	
	if (scrollObj == null)
		return;
	
	var selectedId = "#" + scrollObj.id;
	
	if (resetPosition) {
		// 510px = default/original height of scrollable content
		var newHeight = 510;
		$(selectedId).height(newHeight);
	} else {
		var scrollHeight = $(selectedId).height() + "px";
		scrollObj.contentScroll('0px', scrollHeight, true);
	}
	// update the scrollbar object
	updateScroller();
}

/* sets a delay when updating the scrolling position to account for the tree animation */
function fleXcrollToDelay(delay) {
	if (delay == null) 
		delay = 100;
	
	setTimeout("fleXcrollTo(document.getElementById('treeContainer'), false)", delay);
}

/* opens a new window via javascript */
function goWindow(windowname, page, width, height) {
	var url = "" + page;

	var newWindow = window.open(url, windowname, "width=" + width +",height=" + height +",resizable=0, scrollbars=0, status=0, top=0, left=" + (screen.width-(width+10)));
	if ((document.window != null) && (!newWindow.opener))
		newWindow.opener = document.window;
}


function updateFlashContainerHeight(state)
{
	if (state == "expanded")
	{
		var scrollOffset = 0;
		if (document.body && typeof document.body.scrollTop != "undefined")
		{
			scrollOffset += document.body.scrollTop;
			if (document.body.parentNode && typeof document.body.parentNode.scrollTop != "undefined") { 
				scrollOffset += document.body.parentNode.scrollTop;
			}
		} else if (typeof window.pageYOffset != "undefined") { 
			scrollOffset +=  window.pageYOffset;
		}
		$("#flashContainer").css( { height : $(window).height() + scrollOffset + "px" } );
		flashPlayer_mc.height = $(window).height() + scrollOffset;
	} else {
		$("#flashContainer").css( { height : "2px" } );
		flashPlayer_mc.height = "2";
	}
}
