//Style Sheet Switcher version 1.1 Oct 10th, 2006
//Author: Dynamic Drive: http://www.dynamicdrive.com
//Usage terms: http://www.dynamicdrive.com/notice.htm

var manual_or_random="manual" //"manual" or "random"
var randomsetting="3 days" //"eachtime", "sessiononly", or "x days (replace x with desired integer)". Only applicable if mode is random.

//////No need to edit beyond here//////////////

function getCookie(Name) { 
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
}

function setCookie(name, value, days) {
var expireDate = new Date()
//set "expstring" to either future or past date, to set or delete cookie, respectively
var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5)
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}

function deleteCookie(name){
setCookie(name, "moot")
}


function setStylesheet(title, randomize){ //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled
var i, cacheobj, altsheets=[""]
for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) {
if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title
cacheobj.disabled = true
altsheets.push(cacheobj) //store reference to alt stylesheets inside array
if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter
cacheobj.disabled = false //enable chosen style sheet
}
}
if (typeof randomize!="undefined"){ //if second paramter is defined, randomly enable an alt style sheet (includes non)
var randomnumber=Math.floor(Math.random()*altsheets.length)
altsheets[randomnumber].disabled=false
}
return (typeof randomize!="undefined" && altsheets[randomnumber]!="")? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet
}

function chooseStyle(styletitle, days){ //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie
if (document.getElementById){
setStylesheet(styletitle)
setCookie("mysheet", styletitle, days)
}
}

function indicateSelected(element){ //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu
if (selectedtitle!=null && (element.type==undefined || element.type=="select-one")){ //if element is a radio button or select menu
var element=(element.type=="select-one") ? element.options : element
for (var i=0; i<element.length; i++){
if (element[i].value==selectedtitle){ //if match found between form element value and cookie value
if (element[i].tagName=="OPTION") //if this is a select menu
element[i].selected=true
else //else if it's a radio button
element[i].checked=true
break
}
}
}
}

if (manual_or_random=="manual"){ //IF MANUAL MODE
var selectedtitle=getCookie("mysheet")
if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored
setStylesheet(selectedtitle)
}
else if (manual_or_random=="random"){ //IF AUTO RANDOM MODE
if (randomsetting=="eachtime")
setStylesheet("", "random")
else if (randomsetting=="sessiononly"){ //if "sessiononly" setting
if (getCookie("mysheet_s")==null) //if "mysheet_s" session cookie is empty
document.cookie="mysheet_s="+setStylesheet("", "random")+"; path=/" //activate random alt stylesheet while remembering its "title" value
else
setStylesheet(getCookie("mysheet_s")) //just activate random alt stylesheet stored in cookie
}
else if (randomsetting.search(/^[1-9]+ days/i)!=-1){ //if "x days" setting
if (getCookie("mysheet_r")==null || parseInt(getCookie("mysheet_r_days"))!=parseInt(randomsetting)){ //if "mysheet_r" cookie is empty or admin has changed number of days to persist in "x days" variable
setCookie("mysheet_r", setStylesheet("", "random"), parseInt(randomsetting)) //activate random alt stylesheet while remembering its "title" value
setCookie("mysheet_r_days", randomsetting, parseInt(randomsetting)) //Also remember the number of days to persist per the "x days" variable
}
else
setStylesheet(getCookie("mysheet_r")) //just activate random alt stylesheet stored in cookie
} 
}


// rotating image change for homepage
function changeQuote()
{
var quotes = new Array(
'<p>&quot;OpenCourseWare is exactly the kind of thing that universities should be doing.&quot;</p><ul><li><strong>Larry Birenbaum</strong><br />MIT Class of 1969 and OCW supporter<br /> United States</li></ul>', 
'<p>&quot;Through OCW, I am part of a movement to help make education free and available to the world.&quot;</p><p><ul><li><strong>Clinton Blackburn</strong><br />MIT student<br />United States</li></ul>', 
'<p>&quot;I was amazed that a university such as MIT would freely give access to its educational information.&quot;</p><ul><li><b>Triatno Yudo Harjoko</b><br />Educator<br />Indonesia</li></ul>',
'<p>&quot;When I realized I could follow along with an MIT course... I thought, \'I can handle this!\'&quot;</p><ul><li><b>Ali Sheikh</b><br />Student<br />United States</li></ul>', 
'<p>&quot;OCW is definitely going to help me make decisions about what to study in the future.&quot;</p><ul><li><b>Benjamin Goff</b><br />Self learner<br />United States</li></ul>', 
'<p>&quot;I found lecture notes, handouts and slides from presentations, and some problem sets. It helped me a lot.&quot;</p><ul><li><b>Maria Karamitsou</b><br />Student<br />Greece</li></ul>',
'<p>&quot;OCW opens up knowledge across the world and allows universities to benchmark teaching.&quot;</p><ul><li><b>François Viruly</b><br />Educator<br />South Africa</li></ul>',
'<p>&quot;My life is in teaching. To have a chance to do that with a world audience is just wonderful.&quot;</p><ul><li><b>Gilbert Strang</b><br />MIT Mathematics professor<br />United States</li></ul>',
'<p>&quot;It\'s a great opportunity for students to become extraordinary engineers.&quot;</p><ul><li><b>Juan Lara</b><br />Student<br />Mexico</li></ul>',
'<p>&quot;It puts a previously untouchable subject within reach for anyone who is interested.&quot;</p><ul><li><b>Wendy Ermold</b><br />Self Learner<br />United States</li></ul>',
'<p>&quot;I strive to make as much as possible enjoyable and educational at the same time.&quot;</p><ul><li><b>Amy Santee</b><br />Educator<br />United States</li></ul>',
'<p>&quot;It\'s an important way to ensure the quality of my courses.&quot;</p><ul><li><b>Shirley Harrell</b><br />Educator<br />United States</li></ul>',
'<p>&quot;OCW will enable us to create better educational linkages.&quot;</p><ul><li><b>Karen Willcox</b><br />MIT Aeronautics and Astronautics professor<br />United States</li></ul>');

var images = new Array (
"/OcwWeb/images/wihomeimages/birenbaum.jpg", 
"/OcwWeb/images/wihomeimages/blackburn.jpg", 
"/OcwWeb/images/wihomeimages/harjoko.jpg",
"/OcwWeb/images/wihomeimages/sheikh.jpg",
"/OcwWeb/images/wihomeimages/goff.jpg",
"/OcwWeb/images/wihomeimages/karamitsou.jpg",
"/OcwWeb/images/wihomeimages/viruly.jpg",
"/OcwWeb/images/wihomeimages/gil3.jpg",
"/OcwWeb/images/wihomeimages/juan_banner.jpg",
"/OcwWeb/images/wihomeimages/wendy_banner.jpg",
"/OcwWeb/images/wihomeimages/santee_banner.jpg",
"/OcwWeb/images/wihomeimages/harrell_banner.jpg",
"/OcwWeb/images/wihomeimages/willcox_banner.jpg");

var links = new Array (
"/OcwWeb/web/about/stories/birenbaum/birenbaum.htm", 
"/OcwWeb/web/about/stories/blackburn/blackburn.htm", 
"/OcwWeb/web/about/stories/harjoko/harjoko.htm",
"/OcwWeb/web/about/stories/sheikh/sheikh.htm",
"/OcwWeb/web/about/stories/goff/goff.htm",
"/OcwWeb/web/about/stories/karamitsou/karamitsou.htm",
"/OcwWeb/web/about/stories/viruly/viruly.htm",
"/OcwWeb/web/about/stories/strang/strang.htm",
"/OcwWeb/web/about/stories/lara/lara.htm",
"/OcwWeb/web/about/stories/ermold/ermold.htm",
"/OcwWeb/web/about/stories/santee/santee.htm",
"/OcwWeb/web/about/stories/harrell/harrell.htm",
"/OcwWeb/web/about/stories/willcox/willcox.htm");

var rand = Math.floor(Math.random()*quotes.length);
var txt='';
txt+='<ul><li class="email"><a href="javascript:emailPopUp()">Email this page<\/a><\/li><\/ul>';
document.getElementById("switchbutton").innerHTML=txt;
document.getElementById("EWebEditProPlaceholder1").style.backgroundImage = "url("+images[rand]+")";
var mainQuotesPlaceHolder = document.getElementById("quote_main");
if(mainQuotesPlaceHolder){
	mainQuotesPlaceHolder.innerHTML = quotes[rand] + '<p><a href="' + links[rand] + '"  class="bullet">Read more<\/a><\/p>';
	}

}


// rotating image change ends here

window.onload=function(){
var txt='';
txt+='<ul><li class="email"><a href="javascript:emailPopUp()">Email this page<\/a><\/li><\/ul><div class="clear"><\/div>';
document.getElementById("switchbutton").innerHTML=txt;
showRandomSidebarQuote();
populateAPPagesRSI();
populateYoutubePlaceholders();
}

function showRandomSidebarQuote()
{
	var quotes = new Array(
	'<p>&quot;I donated because I want MIT to keep OCW going.&quot;<br /><br /> &mdash;Heath Novak<br />Student, USA</p>', 
	'<p>&quot;OCW inspires just as much as it enriches.&quot;<br /><br /> &mdash;Jeff Breidenbach<br /> MIT Alumnus, Class of 1996</p>',
	'<p>&quot;It\'s every person\'s responsibility to stand up and support the things he (or she) values.&quot;<br /><br /> &mdash;Assaf Tal<br /> Self Learner, Israel</p>',
	'<p>&quot;Supporting OCW was my way of saying \'thank you\' for having the courage and insight to take this bold step.&quot;<br /><br /> &mdash;Ted Inoue<br /> Self Learner, USA</p>',
	'<p>&quot;I gained so much by the educational materials from MIT faculty.&quot;<br /><br /> &mdash;Aditi Gupta<br /> Student, USA</p>',
	'<p>&quot;OCW has been instrumental in my professional development.&quot;<br /><br /> &mdash;Harry Crissy<br /> Self Learner, USA</p>') 
	
	var rand = Math.floor(Math.random() * quotes.length);
	var sidebarQuotesPlaceHolder = document.getElementById("quote_sidebar");
	if(sidebarQuotesPlaceHolder){
		sidebarQuotesPlaceHolder.innerHTML = quotes[rand];
	}
}

function emailPopUp()
{
	var pageTitle = document.title;
	var pageUrl   = document.location;
	var URL = "/OcwWeb/jsp/emailpage.jsp?title=" + pageTitle + "&referer=" + pageUrl;
	window.open(URL,null,"height=470,width=530,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");
}
function clearSearchBox()
{
	if(document.getElementById("terms").value == "Enter search keyword")
	{
		document.getElementById("terms").value = "";	
	}
	
}
function clearEmailBox()
{

	if(document.getElementById("txt_subscribe").value == "Enter email address")
	{
		document.getElementById("txt_subscribe").value = "";	
	}
	
}

function fillSearchBox()
{
	if(document.getElementById("terms").value == "")
	{
		document.getElementById("terms").value = "Enter search keyword";	
	}
}
function fillEmailBox()
{
	if(document.getElementById("txt_subscribe").value == "")
	{
		document.getElementById("txt_subscribe").value = "Enter email address";	
	}
}
function SearchOptionChanged()
{
	if (document.getElementById("searchSelection").selectedIndex!='0' && document.getElementById("searchSelection").selectedIndex!='1')
	{
		document.getElementById("searchInOcwSite").disabled = true;
		document.getElementById("siteSelectionIndex").value = document.getElementById("searchSelection").selectedIndex;
	}

	if (document.getElementById("searchSelection").selectedIndex=='1')
	{
		document.getElementById("searchInOcwSite").disabled = false;
		document.getElementById("searchInOcwSite").value = 'ocw';
		document.getElementById("siteSelectionIndex").value = document.getElementById("searchSelection").selectedIndex;
	}
	else
	if(document.getElementById("searchSelection").selectedIndex=='0')
	{
		document.getElementById("searchInOcwSite").disabled = false;
		document.getElementById("searchInOcwSite").value = 'ocwhs';
		document.getElementById("siteSelectionIndex").value = document.getElementById("searchSelection").selectedIndex;
	}

}
function setSiteSelection()
{
	// fetch the value of siteSelectionIndex from URL
	var selectionIndex=getParameter ("siteSelectionIndex");	
  	document.getElementById("searchSelection").selectedIndex = selectionIndex;
  	SearchOptionChanged();	
}

function getParameter (parameterName ) {
// Add "=" to the parameter name (i.e. parameterName=value)
var queryString = window.top.location.search.substring(1);

var parameterName = parameterName + "=";
if ( queryString.length > 0 ) {
// Find the beginning of the string
begin = queryString.indexOf ( parameterName );
// If the parameter name is not found, skip it, otherwise return the value
if ( begin != -1 ) {
// Add the length (integer) to the beginning
begin += parameterName.length;
// Multiple parameters are separated by the "&" sign
end = queryString.indexOf ( "&" , begin );
if ( end == -1 ) {
end = queryString.length
}
// Return the string
return unescape ( queryString.substring ( begin, end ) );
}
// Return "null" if no parameter has been found
return "null";
}
} 
function populateAPPagesRSI()
{
	var APPhysicsReferenceList = document.getElementById("APPhysicsRSI");
	var APCalculusReferenceList = document.getElementById("APCalculusRSI");
	var APBiologyReferenceList = document.getElementById("APBiologyRSI");

	if(APPhysicsReferenceList)
	{
		APPhysicsReferenceList.innerHTML = renderAPRSIHTML(APPhysicsCourseReferencesText,APPhysicsCourseReferencesLink);
	}
	if(APCalculusReferenceList)
	{
		APCalculusReferenceList.innerHTML = renderAPRSIHTML(APCalculusCourseReferencesText,APCalculusCourseReferencesLink);
	}
	if(APBiologyReferenceList)
	{
		APBiologyReferenceList.innerHTML = renderAPRSIHTML(APBiologyCourseReferencesText,APBiologyCourseReferencesLink);
	}
	
}
function renderAPRSIHTML(referenceNames,referenceLinks)
{
	var APRSIReferenceHTML = '';
	for(var referenceIndex = 0; referenceIndex < referenceLinks.length; referenceIndex++)
		{
			APRSIReferenceHTML += '<p class="course_ref bullet"><a title="Launch a new window to view this page." href=';
			APRSIReferenceHTML += referenceLinks[referenceIndex];
			APRSIReferenceHTML += ' target="_blank">';
			APRSIReferenceHTML += referenceNames[referenceIndex];
			APRSIReferenceHTML += '</a><img src="/OcwWeb/images/new_window.gif" /></p>'
		}
	return APRSIReferenceHTML;
}

// Start code for injecting tags for embedding YouTube videos
document.getElementsByClassName = function(cl) {
        var retnode = [];
        var myclass = new RegExp('\\b'+cl+'\\b');
        var elem = this.getElementsByTagName('*');
        for (var i = 0; i < elem.length; i++) {
                var classes = elem[i].className;
                if (myclass.test(classes)) retnode.push(elem[i]);
        }
        return retnode;
};

function populateYoutubePlaceholders(){
	
	if(CanCurrentTemplateExecuteYouTubeScript())
        {
		var stringToReplace = "ACTUAL_LINK_GOES_HERE";
		var videoinjectionstring = '<object type="application/x-shockwave-flash" style="width:425px; height:344px;" data="' + stringToReplace+ '">'
                + '<param name="movie" value="' + stringToReplace + '"></param>'
                + '<param name="allowFullScreen" value="true"></param></object>';
        var videoContainers = document.getElementsByClassName("youtubevideo");
		for(i = 0; i < videoContainers.length; i ++){
			var videoURL = videoContainers[i].getElementsByTagName("a")[0].getAttribute("href");
			var finalvideoinjectionstring = videoinjectionstring.replace(stringToReplace, videoURL).replace(stringToReplace, videoURL);
			videoContainers[i].innerHTML = finalvideoinjectionstring;
		}
        }
}

function CanCurrentTemplateExecuteYouTubeScript(){
	
	var templatesToDisable = new Array (
		"SiteHomePage.aspx", 
		"DepartmentHomePage.aspx", 
		"MasterCourseList.aspx",
		"ArchiveCourseList.aspx",
		"AFcourseList.aspx",
		"CourseList.aspx");
		
	//For all CMS pages (ONLY) __CMS_CurrentUrl contains the template name - this variable does not exist in orphaned pages
	if (typeof(__CMS_CurrentUrl) == "undefined")
	{
		return false;
	}
	else
	{
		for (templateCounter = 0; templateCounter < templatesToDisable.length; templateCounter++)
		{
			if (__CMS_CurrentUrl.match(templatesToDisable[templateCounter]) != null)
			{
				return false;
			}
		}
		//for all other templates and pages return true
		return true;
	}
}
// End code for injecting tags for embedding YouTube videos
