/****************
*	Javascript Library for KPBS
*	version 1.0
*	Digitaria Inc
*	Created: 08.03.2006
*	Modified: 01.16.2007
****************/
var cDay = "";
// onload function written by Simon Willison - http://simon.incutio.com
// use this function instead of window.onload - usage addLoadEvent(functionName)
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
/*----------------------*/

function setOpacity(obj, opacity)
{
	
	opacity = (opacity == 100)?99.999:opacity;
	
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	
	// Safari < 1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
/*----------------------*/

function fadeIn(objId,opacity,speed)
{
	clearTimeout(fadeInTimer);
	if (document.getElementById)
	{
		obj = document.getElementById(objId);
		if (opacity <= 100)
		{
			setOpacity(obj, opacity);
			opacity += 10;
			var fadeInTimer = window.setTimeout("fadeIn('"+objId+"',"+opacity+","+speed+")", speed);
		}
	}
}
/*----------------------*/

function fadeOut(objId,opacity,speed)
{
	clearTimeout(fadeOutTimer);
	if (document.getElementById)
	{
		obj = document.getElementById(objId);
		if (opacity >= 0)
		{
			setOpacity(obj, opacity);
			opacity -= 10;
			var fadeOutTimer = window.setTimeout("fadeOut('"+objId+"',"+opacity+","+speed+")", speed);
		}
		else
		{
			obj.style.display = "none";
		}
	}
}
/*----------------------*/

// Drop down navigaition menu
// modified:
var timer = 100;		// delay before menu is cleared. set in milliseconds
var timerID = 0;
var menuID = null;
var oldID = 0;
var oldLink = null;
var dropDown = 	"";
var imgSel = "";
var realSel = "";
var isIE = 0;
function fixSelectBug()
{
	if(navigator.appVersion.indexOf("MSIE") != -1)
	{
		if(document.getElementById("programsSelect"))
		{
			dropDown = 	document.getElementById("programsSelect");
			imgSel = document.getElementById("selectImage");
			realSel = document.getElementById("realSelect");
			isIE = 1;
		}
		else if(document.getElementById("faqSelect"))
		{
			dropDown = 	document.getElementById("faqSelect");
			imgSel = document.getElementById("faqSelectImage");
			realSel = document.getElementById("faq_jump");
			isIE = 1;
		}
	}
}
function showItem(linkage,id)
{
	menuID = id;
	if(document.getElementById)
	{
		var target = document.getElementById(menuID);
		if(oldID)
		{
			document.getElementById(oldID).style.display = "none";
			oldLink.className = oldLink.className.replace("hover","");
			target.style.display = "block";			
			linkage.className += " hover";
		}
		else
		{
			target.style.display = "block";
			linkage.className += " hover";
		}
		clearTimer();
	}
	if(isIE)
	{
		imgSel.style.display = "block";
		realSel.style.display = "none";
	}
	oldID = menuID;
	oldLink = linkage;
}

function clearMenu()
{
	var target = document.getElementById(menuID);
	target.style.display = "none";
	oldLink.className = oldLink.className.replace("hover","");
	if(isIE)
	{
		imgSel.style.display = "none";
		realSel.style.display = "block";
	}
}

function startTimer()
{
	timerID  = setTimeout("clearMenu()", timer);
}

function clearTimer()
{
   if(timerID)
   {
	  clearTimeout(timerID);
	  timerID  = 0;
   }
}
/*----------------------*/

// SlideShow Object - used to rotate images automatically or manually
// modified 08.24.2006
// (path to images, id of div container, delay in milliseconds, the name of the object)
var Obj = "";
function SlideShow(id,duration,objName)
{
	this.el = document.getElementById(id);
	this.duration = duration;
	this.ObjName = objName;
	this.count = 0;
	Obj = this;
	this.noRotate = 1;
	this.newWindow = 0;
        this.altArray = new Array();
	this.imgArray = new Array();
	this.imgLinkArray = new Array();
	this.oldImage = new Array(null,null);	// used to track last image clicked in manual mode
	this.imgLoaded = 0;
	
	this.isset = function(varName)
	{
		return (typeof varName != "undefined");
	};
	
}
// loads the images into an array when page is loaded and starts the rotating madness
SlideShow.prototype.initImages = function(num, manual, manualID)
{
	this.preLoadImgs();
	this.numImage = num;
	this.el.innerHTML = this.createHTML();
	var preImage = new Image();
	var i = 0;
	var div = document.createElement("div");
	div.setAttribute("id","preLoad");
	var parentNode = this.el.parentNode;	
	/*do
	{
		div.innerHTML = "<img src="+this.imgArray[i]+" alt="+this.altArray[i]+" title="+this.altArray[i]+" />";
		i++;
	}while(i < num)*/
	if(manual == 1)
	{
		var numBar = document.getElementById(manualID);
		if(num > 1 && num < 5)
			numBar.style.backgroundImage = "url(/media/bg_slide_show_" + num + ".gif)";
		else if(num == 1)
			numBar.style.display = "none";
	}
	
	parentNode.appendChild(div);
	div.style.display = "none";
	if(num != 1/* && num == i*/)
	{
		this.startRotate();
	}
};

// cache images
SlideShow.prototype.preLoadImgs = function()
{
	this.imgObjArray = new Array(this.imgArray.length);
	for(var i = 0; i < this.imgArray.length; i++)
	{
		this.imgObjArray[i] = new Image();
		this.imgObjArray[i].src = this.imgArray[i];
	}
}

// creates HTML for images
SlideShow.prototype.createHTML = function()
{
	this.html = "";
	if(this.imgLinkArray[this.count] != "")
	{
		this.html = "<a ";
		if (this.newWindow) {
		  this.html += "target=\"_new\" ";
		}
		this.html += "href=\""+this.imgLinkArray[this.count]+"\">";
		this.html += "<img src="+this.imgObjArray[this.count].src+" alt=\""+this.altArray[this.count]+"\" title=\""+this.altArray[this.count]+"\" border=\"0\" />";
		this.html += "</a>";
	}
	else
	{
		this.html = "<img src="+this.imgObjArray[this.count].src+" alt=\""+this.altArray[this.count]+"\" title=\""+this.altArray[this.count]+"\" border=\"0\" />";
	}
	return this.html;
}
// fuction to...that's right you guessed right...rotate images
SlideShow.prototype.rotateImages = function(count)
{
	clearTimeout(this.timer);
	this.count++;
	if(this.count >= this.numImage)
		this.count = 0;	
	var getHTML = this.createHTML();
	this.writeHTML(getHTML);
	
}
SlideShow.prototype.writeHTML = function(HTML)
{
	fadeIn(this.el.id,50,50);
	this.el.innerHTML = HTML;
	this.imgLoaded = 0;
	this.timer = window.setTimeout(this.ObjName+".rotateImages("+this.count+")", this.duration);
	
}
// starts the rotate unless a link has been clicked to switch to an image manually
SlideShow.prototype.startRotate = function()
{
	if(this.noRotate == 1)
		this.timer = window.setTimeout(this.ObjName+".rotateImages("+this.count+")", this.duration);
}
// stops the images from rotating
SlideShow.prototype.stopRotate = function()
{
	clearTimeout(this.timer);
}

SlideShow.prototype.switchImage = function(num, id)
{
	clearTimeout(this.timer);
	var element = id;
	if(this.oldImage[0] != null)
	{
		//this.oldImage[0].style.backgroundImage = "url(/media/bg_num_"+this.oldImage[1]+".gif)";
		this.oldImage[0].className = this.oldImage[0].className.replace("on","");
	}
	else if(this.oldImage[1] == num)
	{
		alert(num);
		return false;
	}
	this.count = num-1
	//element.style.backgroundImage = "url(/media/bg_num_"+num+"_on.gif)";
	element.className += " on";
	this.el.innerHTML = this.createHTML();
	fadeIn(this.el.id,50,25);
	this.noRotate = 0;
	this.oldImage[0] = element;
	this.oldImage[1] = num;
}
/*----------------------*/
/* End SlideShow Object */

// Expand/Collapse Events Object
// modified: 08.24.2006
var eventsObj ="";
function Events(id, calendarID)
{
	this.element = document.getElementById(id);
	eventsObj = this;
	this.eventTop = "";		// the top part of the event details box
	this.eventBottom = "";	// the bottom part of the event details box
	this.oldDetails = ""	// the old event that needs to be closed
	this.cDay = ""			// holds the day selected on the calendar for the events calendar so when user selects a different category, the selected day doesn't change as well
	
	// initial function calls
	this.initLinks();	// set up click events
	this.monthDays(calendarID);
	this.eventTabs();	
}
// scan looking for links that need custom events
Events.prototype.initLinks = function()
{
	//alert("hello");
	this.links = document.getElementsByClassName("expandLink");
	for(i in this.links)
	{
		this.links[i].onclick = function()
		{
			if(this.getAttribute("rel"))
			{
				eventsObj.eventTop = document.getElementById(this.getAttribute("rel"));
				eventsObj.switchTop(this);
				return false;
			}
		}
	}
}
// switches the background of the top row which is the top of the details box
Events.prototype.switchTop = function(linkObj)
{
	var details = document.getElementById(this.eventTop.id + "Details");
	if(this.eventTop.className != "")
	{
		this.eventTop.className = this.eventTop.className.replace(this.eventTop.className, "");
		details.style.display = "none";
	}
	else
	{
		this.eventTop.className += " detailsTop";
		details.style.display = this.displayType(this.eventTop.id + "Details", true);		
	}
}
// make rowTrue if the element being show is is a table row
Events.prototype.displayType = function(id, rowTrue)
{
	var isRow = rowTrue;
	if((document.all) && (isRow))
		var displayType = "block";
	else if(isRow)
		var displayType = "table-row";
	else
		var displayType = "block";
	return displayType;
}
// this switchs the month calendar days on and off
Events.prototype.monthDays = function(id)
{
	this.monthDay = document.getElementById(id);
	if(this.monthDay != null)
	{	
		var dayLinks = this.monthDay.getElementsByTagName("a");
		for(var i = 0; i < dayLinks.length; i++)
		{
			dayLinks[i].onclick = function()
			{
				var oldToday = document.getElementsByClassName("today");
                if(oldToday[0])
				    oldToday[0].className = oldToday[0].className.replace("today", "");
				this.className = "today";
				cDay = this.id;
                var ajaxObj = new Ajax();
                var url = "/calendar/day?current_day=" + this.id;
                ajaxObj.open("get",url,true);
                ajaxObj.onreadystatechange=function()
                {
                    if (ajaxObj.readyState==4)
                    {
                        if(ajaxObj.status >= 200 && ajaxObj.status < 300)
                        {
                            var target = document.getElementById("calendarCont");
                            target.innerHTML = ajaxObj.responseText;
                            eventsObj.executeJS(ajaxObj.responseText);
                        }
                    }
                }
                ajaxObj.send("");

				return false;
			}
		}
	}
}
// switchs the tabs
Events.prototype.eventTabs = function()
{

	var tabsCont = document.getElementById("eventTabs");
	var tabLinks = tabsCont.getElementsByTagName("a");
	for(var i = 0; i < tabLinks.length; i++)
	{
		tabLinks[i].onclick = function()
		{
			var oldTab = document.getElementById("current");
			oldTab.id = "";
			this.parentNode.id = "current";
            var params = "";
            var params2 = "";
            var ddlCategoryFilter = document.getElementById("category_filter");
            var ddlMonthFilter = document.getElementById("month_filter");
            var cat = ddlCategoryFilter.value;
            if(cat != "0"){
                params = "?category_id=" + cat;
            }
            var month = ddlMonthFilter.value;
            if(month != "0"){
                params2 = "?month=" + month;
            }

			if(this.getAttribute("rel"))
			{
				var rel = this.getAttribute("rel");
				var relArray = rel.split(".");
				var ajaxObj = new Ajax();
				switch(relArray[0])
				{
				case "prev":
				  var url = "/calendar/prev_month" + params;
                  ddlCategoryFilter.style.display = "block";
                  ddlMonthFilter.style.display = "none";
				  break;
				case "this":
				  var url = "/calendar/this_month" + params;
                  ddlCategoryFilter.style.display = "block";
                  ddlMonthFilter.style.display = "none";
				  break;
				case "next":
				  var url = "/calendar/next_month" + params;
                  ddlCategoryFilter.style.display = "block";
                  ddlMonthFilter.style.display = "none";
				  break;
				case "all":
				  var url = "/calendar/all_events" + params2;
                  ddlCategoryFilter.style.display = "none";
                  ddlMonthFilter.style.display = "block"; 
				  break;
				}
				if(!url)
					return false;
				ajaxObj.open("get",url,true);
				ajaxObj.onreadystatechange=function()
				{
					if (ajaxObj.readyState==4)
					{
						if(ajaxObj.status >= 200 && ajaxObj.status < 300)
						{
							var target = document.getElementById("calendarCont");
							target.innerHTML = ajaxObj.responseText;
							eventsObj.executeJS(ajaxObj.responseText);		
						}
					}
				}
				ajaxObj.send("");
			}
			return false;
		}
	}
}
Events.prototype.executeJS = function(response)
{
	// RegExp from prototype.sonio.net
	var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
	
	var match    = new RegExp(ScriptFragment, 'img');
	var scripts  = response.match(match);
	
	if(scripts)
	{
		var js = '';
		for(var s = 0; s < scripts.length; s++)
		{
			var match = new RegExp(ScriptFragment, 'im');
			js += scripts[s].match(match)[1];
		}
		eval(js);
	}
}
/* End: Events Object */
/*----------------------*/

// xmlhttp object
function Ajax()
{
	// Create XMLHttpRequest object
	this.ajaxObj;
	this.ajaxObj = false;
	// native XMLHttpRequest object like firefox and safari
	if(window.XMLHttpRequest)
	{
		try
		{
			this.ajaxObj = new XMLHttpRequest();
		}
		catch(e)
		{
			this.ajaxObj = false;
		}
	// IE/Windows ActiveX version (why do people still use this browser?)
	}
	else if(window.ActiveXObject)
	{
		try
		{
			this.ajaxObj = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				this.ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				this.ajaxObj = false;
			}
		}
	}
	if(!this.ajaxObj)
		alert("Error loading XMLHTTP object");
	return this.ajaxObj;
}
/*----------------------*/

// function that allows getting elements by their class name. Returns the found elements in an array
document.getElementsByClassName = function(className)
{
	var children = document.getElementsByTagName('*') || document.all;
	var elements = [];
	for(i = 0; i < children.length; i++)
	{
		if(children[i].className == className)
			elements.push(children[i]);
	}
	return elements;
}

function clear_category_filter(){
    var ddlCategoryFilter = document.getElementById("category_filter");
    ddlCategoryFilter.value = 0;
}

    function update_calendar()
    {
            var currentTab = document.getElementById("current");
            if(document.getElementById("current").childNodes[0].getAttribute("rel"))
            {
                var rel = currentTab.childNodes[0].getAttribute("rel");
                var cat = document.getElementById("category_filter").value;
                var params = "";
                var relArray = rel.split(".");
                var ajaxObj = new Ajax();
		params = "?category_id=" + cat +"&current_day=" + cDay;
                switch(relArray[0])
                {
                case "prev":
                  var url = "/calendar/prev_month" + params;
                  break;
                case "this":
                  var url = "/calendar/this_month" + params;
                  break;
                case "next":
                  var url = "/calendar/next_month" + params;
                  break;
                case "all":
                  var url = "/calendar/all_events";
                  break;
                }
                if(!url)
                    return false;
		//alert(url);
                ajaxObj.open("get",url,true);
                ajaxObj.onreadystatechange=function()
                {
                    if (ajaxObj.readyState==4)
                    {
                        if(ajaxObj.status >= 200 && ajaxObj.status < 300)
                        {
                            var target = document.getElementById("calendarCont");
                            target.innerHTML = ajaxObj.responseText;
                            eventsObj.executeJS(ajaxObj.responseText);
                        }
                    }
                }
                ajaxObj.send("");
          }
    }

    function update_calendar_by_month()
    {
            var currentTab = document.getElementById("current");
            if(document.getElementById("current").childNodes[0].getAttribute("rel"))
            {
                var rel = currentTab.childNodes[0].getAttribute("rel");
                var month = document.getElementById("month_filter").value;
                var params = "";
                if(month != "0"){
                    params = "?month=" + month;
                }
                var relArray = rel.split(".");
                var ajaxObj = new Ajax();
                switch(relArray[0])
                {
                case "all":
                  var url = "/calendar/all_events" + params;
                  break;
                }
                if(!url)
                    return false;
                ajaxObj.open("get",url,true);
                ajaxObj.onreadystatechange=function()
                {
                    if (ajaxObj.readyState==4)
                    {
                        if(ajaxObj.status >= 200 && ajaxObj.status < 300)
                        {
                            var target = document.getElementById("calendarCont");
                            target.innerHTML = ajaxObj.responseText;
                            eventsObj.executeJS(ajaxObj.responseText);
                        }
                    }
                }
                ajaxObj.send("");
          }
    }
