
var w = '';
var target;
var actualWidth;
var actualHeight;
var inputHighlightColor = "#fafad2";
var myTabs;

function DrawCalendarPicker(sContainer,sFieldName,sMonth,sDay,sYear,sLabel){

	var Event = YAHOO.util.Event,
		Dom = YAHOO.util.Dom;	

	Event.onContentReady(sContainer, function () {

		var oCalendarMenu;

		if (sLabel === undefined) {
			sLabel = "Choose a Date";
		}

		var onButtonClick = function () {

			// Create a Calendar instance and render it into the body 
			// element of the Overlay.
            var oDateMin = new Date();
            var oDateMax = new Date();
            oDateMin.setFullYear(oDateMin.getFullYear()-1);
            oDateMax.setFullYear(oDateMax.getFullYear()+2);
			var oCalendar = new YAHOO.widget.Calendar(sFieldName, oCalendarMenu.body.id,
															{ mindate: oDateMin, 
	                                                          maxdate: oDateMax });

			oCalendar.render();


			// Subscribe to the Calendar instance's "select" event to 
			// update the Button instance's label when the user
			// selects a date.

			oCalendar.selectEvent.subscribe(function (p_sType, p_aArgs) {

				var aDate,
					nMonth,
					nDay,
					nYear;

				if (p_aArgs) {
					
					aDate = p_aArgs[0][0];

					nMonth = aDate[1];
					nDay = aDate[2];
					nYear = aDate[0];

					oButton.set("label", (nMonth + "/" + nDay + "/" + nYear));


					// Sync the Calendar instance's selected date with the date form fields

					Dom.get(sMonth).selectedIndex = nMonth;
					Dom.get(sDay).selectedIndex = nDay;
					Dom.get(sYear).value = nYear;

				}
				
				oCalendarMenu.hide();
			
			});


			// Pressing the Esc key will hide the Calendar Menu and send focus back to 
			// its parent Button

			Event.on(oCalendarMenu.element, "keydown", function (p_oEvent) {
			
				if (Event.getCharCode(p_oEvent) === 27) {
					oCalendarMenu.hide();
					this.focus();
				}
			
			}, null, this);
			
			
			var focusDay = function () {

				var oCalendarTBody = Dom.get(sFieldName).tBodies[0],
					aElements = oCalendarTBody.getElementsByTagName("a"),
					oAnchor;

				
				if (aElements.length > 0) {
				
					Dom.batch(aElements, function (element) {
					
						if (Dom.hasClass(element.parentNode, "today")) {
							oAnchor = element;
						}
					
					});
					
					
					if (!oAnchor) {
						oAnchor = aElements[0];
					}


					// Focus the anchor element using a timer since Calendar will try 
					// to set focus to its next button by default
					
					YAHOO.lang.later(0, oAnchor, function () {
						try {
							oAnchor.focus();
						}
						catch(e) {}
					});
				
				}
				
			};


			// Set focus to either the current day, or first day of the month in 
			// the Calendar	when it is made visible or the month changes

			oCalendarMenu.subscribe("show", focusDay);
			oCalendar.renderEvent.subscribe(focusDay, oCalendar, true);


			// Give the Calendar an initial focus
			
			focusDay.call(oCalendar);


			// Re-align the CalendarMenu to the Button to ensure that it is in the correct
			// position when it is initial made visible
			
			oCalendarMenu.align();


			// Unsubscribe from the "click" event so that this code is 
			// only executed once

			this.unsubscribe("click", onButtonClick);
		
		};


		var oDateFields = Dom.get(sContainer),
			oMonthField = Dom.get(sMonth),
			oDayField = Dom.get(sDay),
			oYearField = Dom.get(sYear);


		// Hide the form fields used for the date so that they can be replaced by the 
		// calendar button.

		oMonthField.style.display = "none";
		oDayField.style.display = "none";
		oYearField.style.display = "none";


		// Create a Overlay instance to house the Calendar instance

		oCalendarMenu = new YAHOO.widget.Overlay("calm-"+sFieldName, { visible: false });

		
		// Create a Button instance of type "menu"
		if(oMonthField.selectedIndex && oDayField.selectedIndex && oYearField.value)
		{
			var sMonthValue = oMonthField[oMonthField.selectedIndex].value;
			var sDayValue = oDayField[oDayField.selectedIndex].value;
			sLabel = (sMonthValue + '/' + sDayValue + '/' + oYearField.value);
		}

		var oButton = new YAHOO.widget.Button({ 
										type: "menu", 
										id: "calp-"+sFieldName, 
										label: sLabel, 
										menu: oCalendarMenu, 
										container: sContainer });


		oButton.on("appendTo", function () {
		
			// Create an empty body element for the Overlay instance in order 
			// to reserve space to render the Calendar instance into.
	
			oCalendarMenu.setBody("&#32;");
	
			oCalendarMenu.body.id = "calc-"+sFieldName;
			
		
		});


		// Add a listener for the "click" event.  This listener will be
		// used to defer the creation the Calendar instance until the 
		// first time the Button's Overlay instance is requested to be displayed
		// by the user.

		oButton.on("click", onButtonClick);
	
	});

};


function popupWindowPre(optimalWidth,optimalHeight)
{
	actualWidth = (optimalWidth < screen.availWidth) ? optimalWidth : screen.availWidth - 20;
	actualHeight = optimalHeight;
}

function popupWindowPost()
	{
	if (!w.closed && w.location)
	{
		w.close();
	}
	w = window.open(target,'WINDOW','scrollbars=yes,status=yes,width='+actualWidth+',outerWidth='+actualWidth+',height='+actualHeight+',outerHeight='+actualHeight+',resizable');
	w.focus();
}

function popupNote (term,crn,subj,crse,loc)
{
	if (loc == null)
	{
		loc = "lcom";
	}
	popupWindowPre(700,500);
	target = 'crn.php/note/' + term + '/' + crn + '/' + subj + '/' + crse + '/' + loc;
	popupWindowPost();
}

function popupAddress (bldg_code)
{
	popupWindowPre(500,500);
	target = 'location.php/addr/' + bldg_code;
	popupWindowPost();
}

function popupRegister (term,crn)
{
	popupWindowPre(780,700);
	target = 'register-ce.php?term=' + term + '&crn=' + crn;
	popupWindowPost();
}

function popupSkillLevel (term,crn,subj,crse)
{
	popupWindowPre(500,500);
	target = 'skill.php/levels/' + term + '/' + crn + '/' + subj + '/' + crse;
	popupWindowPost();
}

function popupSubjectNote(subject)
{
	popupWindowPre(500,500);
	target = 'http://www.jccc.edu/home/course_schedules/subjects/' + subject;
	popupWindowPost();
}

function validateKeyword (keywordvalue)
{
	if (keywordvalue == "")
	{
		alert("Please enter a keyword or phrase and try again.");
		document.getElementById('keyword').style.background = inputHighlightColor;
		document.getElementById('keyword').focus();
		return false;
	}
	else
	{
		document.getElementById('submitkeyword').value = "Searching...";
	}
}

function validateCRN (crnvalue)
{
	if (isNaN(crnvalue) || crnvalue.length != 5)
	{
		alert("Please enter a five-digit CRN and try again.");
		document.getElementById('crn').style.background = inputHighlightColor;
		document.getElementById('crn').focus();
		return false;
	}
	else
	{
		document.getElementById('submitcrn').value = "Searching...";
	}
}

function doKeywordSubmit (evt)
{
	if (evt.keyCode == 13)
	{
		document.getElementById('submitkeyword').click();
		return false;
	}
}

function doKeywordLateSubmit (evt)
{
	if (evt.keyCode == 13)
	{
		document.getElementById('submitlate').click();
		return false;
	}
}


function doCRNSubmit (evt)
{
	if (evt.keyCode == 13)
	{
		document.getElementById('submitcrn').click();
		return false;
	}
}

function clearSubmit()
{
	document.getElementById('submitkeyword').value = "";
	document.getElementById('submitinst').value = "";
	document.getElementById('submitcrn').value = "";
	document.getElementById('submitlate').value = "";
	document.getElementById('submit').value = "";
}

if (window.attachEvent) // IE
{
	window.attachEvent("onload",setAttachListeners);
}
else if (window.addEventListener) // Mozilla
{
	window.addEventListener("load",setAddListeners,false);
}

function setAttachListeners()
{
	inputList = document.getElementsByTagName("INPUT");
	for(i=0;i<inputList.length;i++)
	{
		inputList[i].attachEvent("onfocus",highlightOnAttach);
		inputList[i].attachEvent("onblur",highlightOffAttach);
	}
	selectList = document.getElementsByTagName("SELECT");
	for(i=0;i<selectList.length;i++)
	{
		selectList[i].attachEvent("onfocus",highlightOnAttach);
		selectList[i].attachEvent("onblur",highlightOffAttach);
	}
}

function setAddListeners()
{
	inputList = document.getElementsByTagName("INPUT");
	for(i=0;i<inputList.length;i++)
	{
		inputList[i].addEventListener("focus",highlightOnAdd,false);
		inputList[i].addEventListener("blur",highlightOffAdd,false);
	}
	selectList = document.getElementsByTagName("SELECT");
	for(i=0;i<selectList.length;i++)
	{
		selectList[i].addEventListener("focus",highlightOnAdd,false);
		selectList[i].addEventListener("blur",highlightOffAdd,false);
	}
}

function highlightOnAttach()
{
	event.srcElement.style.backgroundColor = inputHighlightColor;
}

function highlightOnAdd()
{
	this.style.backgroundColor = inputHighlightColor;
}

function highlightOffAttach()
{
	event.srcElement.style.backgroundColor = "";
}

function highlightOffAdd()
{
	this.style.backgroundColor = "";
}

function filterSubjects(subjectsSelect)
{
	var emptyArray = new Array();
	var subjectOptionsTerm = new Array();
	subjectOptionsTerm = subjectOptionsMaster.concat(emptyArray);
	var currentTermValue = parseInt(document.getElementById('term').options[document.getElementById('term').selectedIndex].value);
		for (var i=0; i<subjectOptionsTerm.length; i++)
	{
		if (parseInt(subjectOptionsTerm[i].optId.substr(0,6)) > currentTermValue)
		{
			subjectOptionsTerm.splice(i,1);
			i--;
		}
		else if (parseInt(subjectOptionsTerm[i].optId.substr(6,6)) < currentTermValue)
		{
			subjectOptionsTerm.splice(i,1);
			i--;
		}
	}
    subjectsSelect.options.length = 0;
    for (var loop=0; loop<subjectOptionsTerm.length; loop++)
    {
        var optObj = document.createElement('option');
        optObj.text = subjectOptionsTerm[loop].optText;
        optObj.value = subjectOptionsTerm[loop].optValue;
        optObj.id = subjectOptionsTerm[loop].optId;
        subjectsSelect.options.add(optObj);
    }
    subjectsSelect.selectedIndex = 0;
}


function filtery(pattern, list){
  pattern = new RegExp(pattern,"i");
  /*
  if the dropdown list passed in hasn't
  already been backed up, we'll do that now
  */
  if (!list.bak){
    /*
    We're going to attach an array to the select object
    where we'll keep a backup of the original dropdown list
    */
    list.bak = new Array();
    for (n=0;n<list.length;n++){
      list.bak[list.bak.length] = new Array(list[n].value, list[n].text);
    }
  }

  /*
  We're going to iterate through the backed up dropdown
  list. If an item matches, it is added to the list of
  matches. If not, then it is added to the list of non matches.
  */
  match = new Array();
  nomatch = new Array();
  
  for (n=0;n<list.bak.length;n++){
    if(pattern.test(list.bak[n][0])){
      match[match.length] = new Array(list.bak[n][0], list.bak[n][1]);
    }else{
      nomatch[nomatch.length] = new Array(list.bak[n][0], list.bak[n][1]);
    }
  }

  /*
  Now we completely rewrite the dropdown list.
  First we write in the matches, then we write
  in the non matches
  */
  list.options.length = 0;
  list.options.length = match.length;
  
  for (n=0;n<match.length;n++){
    list[n].value = match[n][0];
    list[n].text = match[n][1];
  }
  

  /*
  Finally, we make the 1st item selected - this
  makes sure that the matching options are
  immediately apparent
  */
  list.selectedIndex=0;
}

