
/* === TEST JAVASCRIPT SUPPORT === */
var DOM = !!(document.getElementById && document.getElementsByTagName); /* Basic W3C DOM Support */
var advDOM = !!(DOM && document.createElement); /* More Advanced W3C DOM Support */


/* === DEBUGING HELPERS === */
var debug = (getURLVars()['debug'] != null);
function dalert(msg) {
	if (debug) alert(msg);
}

/* === SETTINGS AND GLOBAL VARIABLES === */
var popups = { 		// commonly used popup window settings
		full		:	"width=760,height=500,scrollbars,resizable,menubar,toolbar,location,status,directories",
		normal		:	"width=760,height=500,scrollbars,resizable,menubar",
		form		:	"width=760,height=500,scrollbars,resizable",
		notice		:	"width=240,height=200",
		movie		:	"width=450,height=400,status"
};
var re = {			// commonly used regex
		protocol	:	new RegExp("(ftp|https?)://"),
		index		:	new RegExp("(/|((default|index)\\.(htm|html|cfm|php)))$"),
		email		:	new RegExp("^(mailto:)?\\w+([+\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,})+$"),  	// bob@gmail.com or mailto:bob@gmail.com
		pccemail	:	new RegExp("^(mailto:)?\\w+([\\.-]?\\w+)*@pcc\\.edu$"),  								// webteam@pcc.edu or mailto:webteam@pcc.edu
		cfvar		:	new RegExp("^[A-z]\\w*$")  // compliant coldfusion var name, used in form inspection
};

var fns = {}; 		// folder alias' used in addDirNav()
fns["/business"]				=	'Center for Business and Industry';
fns["/resources/culture"]		=	'Multicultural Center';
fns["/about/events/ease"]		=	'EASE';
fns["/resources/academic/eac"]	=	'Educational Advisory Council';
fns["/prepare/esl"]				=	'English as a Second Language';
fns["/resources/first-term"]	=	'Panther Tracks: First Term Guide';
fns["/resources/testing/ged"]	=	'GED';
fns["/resources/guia"]			=	'Gu\u00eda en Espa\u00F1ol';											// must use unicode for special chars 
fns["/resource/media"]			=	'Media Services';
fns["/programs"]				=	'Academic Programs';
fns["/resources/rcesc"]			=	'Rock Creek Environmental Studies Center';
fns["/resources/tlc"]			=	'Teaching Learning Center';
fns["/resources/css"]			=	'Curriculum Support Services';
fns["/hr"]						=	'Human Resources';
fns["/resources/tss"]			=	'Technology Solutions Services';
fns["/programs/think-big"]		=	'ThinkBIG';
fns["/resources/aspcc"]			=	'ASPCC';
fns["/prepare/esol"]			=	'ESOL';
fns["/business/ihp"]			=	'Institute for Health Professionals';
fns["/community"]				=	'Community Education';
fns["/programs/mri"]			=	'MRI';

/* === INITIALIZE === */
// Use .ready to run functions prior to image load
$(document).ready(function() {
	var i, j, o, c;
	//activateGnav(); // turn on correct tab
	designTime();					// Presentational Scripting
	linkSetup(); 					// setup links (to self, popup, etc.)
	addFeeds();						// Add Feed autofinds site-wide
	addDirNav(); 					// create breadcrumb style directory path links
	addFormValidation(); 			// add validation to forms
	setAnalytics();					// add google analytics
});
// Use addEvent to run functions that require loaded images
addEvent(window, "load", fixColumns); // extend main to match sidebar


/* === ADD ANALYTICS TO THE PAGE === */
function setAnalytics() {	
	var gaTrackCode = "UA-1329150-1";
  	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

  	jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
    	var pageTracker = _gat._getTracker(gaTrackCode);
    	pageTracker._setDomainName("pcc.edu");
		pageTracker._initData();
    	pageTracker._trackPageview();
  	});
	
}

/* === ADD FEED AUTOFIND SITE-WIDE === */
function addFeeds() {	
	$("head").append('<link rel="alternate" type="application/rss+xml" title="News Releases | Portland Community College" href="http://www.pcc.edu/about/feeds/news/" />');
	$("head").append('<link rel="alternate" type="application/rss+xml" title="Profiles | Portland Community College" href="http://www.pcc.edu/about/feeds/profiles/" />');
	$("head").append('<link rel="alternate" type="application/rss+xml" title="Videos | Portland Community College" href="http://www.pcc.edu/about/feeds/videos/" />');
}
 
/* === PRESENTATIONAL SCRIPTING, FIXES AND HACKS === */
function designTime() {
	// remove design time styles to avoid breaking dw/contribute design view - lame I know 
	$('body').removeClass('design-time');
	
	// add corner to forms with class advanced
	$('form.advanced').css({position:"relative"}).append('<div id="foldcorner" class="corner"/>');
	
	// add ! to alert
	$('#alert').prepend('<span id="alert-icon">!</span>');
	
	// update copyright
	var currentYear = (new Date()).getFullYear();
	$('#copyright').text( $('#copyright').text().replace("2000","2000-"+currentYear) );
	
	// collapse and animate dl.collapse
	$("dl.faq dd").hide();
	$("dl.faq dt").click(function() {
		$(this).toggleClass("open");
		$(this).nextUntil("dt").slideToggle("normal",fixColumns); // make sure that the column length is correct after change
    }).hover(function () {
      	$(this).addClass("hover");
    	}, function () {
      	$(this).removeClass("hover");
    });
	
}

// make sure #snav is not longer than #main
function fixColumns() {
	try { // wrapping in empty try/catch block for silent failure
		var main = document.getElementById('main'), snav = document.getElementById('snav');
		if (!main || !snav) return;
		// store default padding in global variable, needed for runtime changes (show/hide)
		if (window.defaultMainPaddingBottom == null) {
			if (main.currentStyle)
				window.defaultMainPaddingBottom = main.currentStyle.paddingBottom;
			else if (document.defaultView && document.defaultView.getComputedStyle)
				window.defaultMainPaddingBottom = document.defaultView.getComputedStyle(main,'').getPropertyValue('padding-bottom');
		}
		// restore default padding before calculating column heights
		main.style.paddingBottom = window.defaultMainPaddingBottom;
		// add bottom padding to #main to make it at least as tall as snav if shorter
		if (main.offsetHeight < snav.offsetHeight)
			main.style.paddingBottom = parseInt(window.defaultMainPaddingBottom)+snav.offsetHeight-main.offsetHeight+'px';
	} catch(e) { }
}


/* === CLASSNAME FUNCTIONS === */
String.prototype.hasClass = function(cls) {
	return new RegExp('(^| )'+cls+'( |$)').test(this);
};
String.prototype.addClass = function(cls) {
	if (this == '') return cls;
	if (this.hasClass(cls)) return this;
	return this+" "+cls;
};
String.prototype.removeClass = function(cls) {
	return this.replace(new RegExp('(^| )'+cls+'( |$)'), '');
};
function getElementsByClassName(node, cls, tag) {
	if (!DOM) return [];
	var i, elem, elems = node.getElementsByTagName( (tag != null ? tag : '*') ), results = [];
	for (i=0; elem = elems[i]; i++) if (elem.className.hasClass(cls)) results.push(elem);
	return results;
}


/* === URL/PATH/HISTORY INFORMATION/MANIPULATION === */
function getDirs(path) { // returns an array of directory hierarchy
	var folders = path.split('/');
	if (folders[0] == "") folders.shift(); // remove empty first element
	if (re.index.test(folders[folders.length-1])) folders[folders.length-1] = '';
	return folders;
}
function getReferringPage() {
	if (document.referrer) return document.referrer;
	else if (window.opener) return window.opener.location;
	else return '';
}
function getURLVars() {
	var url = document.URL; //used document.URL instead of location because URL is returned as a string, location as an object
	if (!url || url.indexOf('?') < 0) return {};
	var pairs, i, v, vars = {};
	pairs = url.replace(/&(amp;)?/, '&amp;').substring(url.lastIndexOf('?')+1).split('&amp;'); //account for & and &amp; delimeters
	for (i=0; i<pairs.length; i++) {
		v = pairs[i].split('=');
		vars[v[0]] = unescape(v[1]);
	}
	return vars;
}
function populateFormFromGets() {
	if (!DOM) return;
	var id, vars = getURLVars();
	for (id in vars)
		if(document.getElementById(id) && document.getElementById(id).value != null)
			document.getElementById(id).value = unescape(vars[id]);
}

/* === COOKIE MANAGEMENT (via http://www.quirksmode.org/js/cookies.html) === */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name){
	createCookie(name,"",-1);
}

/* === LINKS SETUP === */
function filterPath(string) {  // used in current link below. could be moved to var re
  return string
	.replace(/^\//,'')
	.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
	.replace(/\/$/,'');
 }

function linkSetup() {
	// current link (link to self + account for index files)
	var locationPath = filterPath(location.pathname);
	$("a[href]").each( function () {	
		var thisPath = filterPath(this.pathname);
		if (  locationPath == thisPath && (location.hostname == this.hostname) && !this.href.match(/(\?|#)/) ) { // ? eliminates cfm pages like schedule.cfm?var=3
			$(this).addClass('current');
		}
	});	
		
	// links to documents [not blank or image links! :parent:not(:has(img))]
	$("a[href$=.pdf]:parent:not(:has(img))").append(' <em class="link-type" title="Portable Document Format - www.pcc.edu/help/">[pdf]</em>');
	$("a[href$=.doc]:parent:not(:has(img))").append(' <em class="link-type" title="Microsoft Word Document - www.pcc.edu/help/">[doc]</em>');
	$("a[href$=.xls]:parent:not(:has(img))").append(' <em class="link-type" title="Microsoft Excel Document - www.pcc.edu/help/">[xls]</em>');
	
	// links to intranet
	$("a[@href^=http://intranet.pcc.edu]:parent:not(:has(img))").append(' <em class="link-type" title="Only Available on PCC Campus - www.pcc.edu/help/">[intranet]</em>');
				
	// redirect @pcc.edu mailto: to email form 
	$("a[href^=mailto:][href$=@pcc.edu]:not([onclick])").each( function () {								// find all a href="mailto:.*pcc.edu"		
		var address = $(this).attr("href").replace('mailto:','');											// get address
		var linkHtml = $(this).html();																		// need to grab due to ie bug http://groups.google.com/group/jquery-dev/browse_thread/thread/22029e221fe635c6?pli=1
		if ($(this).attr("title").length) { address += "&subject="+ $(this).attr("title"); }				// if title add subject														
		else{$(this).attr("title","Send mail to "+address);}												// or update title
		$(this).attr("href","http://www.pcc.edu/resources/web/forms/email/?to="+address).html(linkHtml).addClass('popup'); // alter link and add popup
	});	
	
	// popup links
	$("a[class^=popup]:not([onclick])").click( function () {		// all class=popup where an onClick is not set
					var s = /popup-(\w+)/.exec(this.className);		// Which kind of popup?
					s = s ? s[1] : 'default';						// add code
					return popup(this.href, s);						// and call genteral popup function
	});		
}
function popup(url, s) {
	if (!url) return true;
	if (window.opener) window.location = url; // if already in a popup just change location
	else window.open(url,'popup'+(new Date().getSeconds()), (s && popups[s]) ? popups[s] : popups.normal);
	return false;
}
	
/* === ACTIVATE SECTION TABS === 
var reGnav = {			// regex for global nav
		about	:	new RegExp("^/about/(^calendars/)"),
		temp	:	new RegExp("^/temp/(^gabes)")
};
function activateGnav() {
	if (!advDOM) return;
	var currpath = window.location.pathname;
	
	if( reGnav.temp.test(currpath) ){
		tabLink= document.getElementById('gnav-temp').firstChild;
		tabLink.className = tabLink.className.addClass('current');
		
	}

}*/
	
/* === ADD BREADCRUMB TRAIL / DIRECTORY TREE TO PAGE === */
function addDirNav() {
	if (!advDOM) return;
	var stitle = document.getElementById('stitle');
	if (!stitle // no #stitle
		|| document.getElementById('dirnav') // dirnav was created manually
		|| document.getElementById('page').className.hasClass('popup') // no dirnav in popup template
		) return;
	var folders = getDirs(window.location.pathname);
	// only insert when atleast two levels deep (2 folders or one folder + non-index page)
	if (folders.length < 2 || (folders.length == 2 && folders[folders.length-1] == '')) return;
	// remove last element since it represents current page
	if (folders.pop() == '') folders[folders.length-1] = '';
	// insert PCC first
	folders.unshift('PCC');
	// build
	var p, i, j, f, a, href, c = '';
	p = document.createElement('p');
	p.setAttribute('id', 'dirnav');
	for (i=0; i<folders.length; i++) {
		f = unescape(folders[i]);
		if (f == '') continue;
		if (i>0) c += '/'+f;
		f = (fns[c]) ? fns[c] : f.replace(/-/, ' ');
		a = document.createElement('a');
		href = '';
		j = folders.length-i;
		if (j==1) href += "./";
		else while(--j) href += "../";
		a.setAttribute('href', href);
		a.appendChild(document.createTextNode(f));
		p.appendChild(a);
		p.appendChild(document.createTextNode(' \u002f '));
	}
	// insert
	stitle.insertBefore(p, stitle.firstChild);
}

/* === FORM VALIDATION === */
function addFormValidation() {
	if (!DOM) return;
	var i, form, forms = document.getElementsByTagName('form');

	for (i=0; frm=forms[i]; i++) {
		if (frm.onsubmit == null){ 
			frm.onsubmit = function() { return validateForm(this); };
		}
		if (frm.onreset == null){ 
			frm.onreset = function() { return resetWarning(this); };
		}
	}
}

function resetWarning(frm, s) {  // warn on reset
	return confirm("Are you sure you want to clear the form?\nYou will have to start over..."); 
}
	
var valid = validateForm; // backwards compatiable until I can update all pages
function validateForm(frm, s) {
	if (!DOM || !frm) return;
	var silent = (s || s == 'silent') ? true : frm.className.hasClass('fail-silent') ? true : false;
	var i, j, ok, field, errors = [], devErrors = [];
	for (i in frm.elements) {
		field = frm.elements[i];
		if (field && field.type){										// Inspect form for dev errors
			if (field.name && !re.cfvar.test(field.name)){ 				// Test for invalid name
				devErrors.push( "Invalid field name: \""+field.name+"\"");
			}
			if (field.id && !re.cfvar.test(field.id)){ 					// Test for invalid id
				devErrors.push( "Invalid field id: \""+field.id+"\"");
			}
		}
		if (field && field.className && field.className.hasClass('required')) {
			switch (field.type) {
				case 'text':
				case 'textarea':
				case 'password':
					if (!(/\w+/).test(field.value)) errors.push(field);
					else if (field.className.hasClass('pccemail')) { if (!re.pccemail.test(field.value)) {errors.push(field);} }
					else if (field.className.hasClass('email')) {
						if (field.value.toLowerCase() == 'none') { field.value = 'webadmin@pcc.edu'; }
						else if (!re.email.test(field.value)) { errors.push(field);}
					}
					break;
				case 'select-one':
				case 'select-multiple':
					if (field.selectedIndex < 0 || field.options[field.selectedIndex].value == "null") errors.push(field);
					break;
				case 'radio':
					for (j=0, ok=false; j<frm[field.name].length; j++) {
						if (frm[field.name][j].checked) {
							ok = true;
							break;
						}
					}
					if (!ok) {
						for (j=0, ok=false; j<errors.length; j++) {
							if (errors[j].name == field.name) {
								ok = true;
								break;
							}
						}
						if (!ok) errors.push(field);
					}
					break;
				case 'checkbox':
					if (!field.checked) errors.push(field);
					break;
			}
		}
	}
	if (devErrors.length > 0) {
		var mess = "Warning - this form contains errors...\n\n";
		for (i in devErrors) {mess += "     "+devErrors[i]+"\n";}
		mess += "\nPlease contact webteam@pcc.edu\n";
		alert(mess);
		return false;
	}
	else if (errors.length > 0) {
		if (!silent) {
			var mess = "The form appears to be incomplete, please include...\n\n";
			for (i in errors) {
				// If element has a title
				if( errors[i].title ){ j = errors[i].title; }
				// Or, if the label has a title
				else if( (errors[i].parentNode.nodeName == "LABEL") && (errors[i].parentNode.title) ){ j = errors[i].parentNode.title; }
				// Otherwise, use the element name
				else{ j =  errors[i].name; }
				mess += "    * "+j+'\n';
			}
			alert(mess);
		}
		errors[0].focus();
		return false;
	}
	return true;
}
function getLabel(field) {
	var i, labels = document.getElementsByTagName("label");
	for (i=0; i<labels.length; i++) {
		if (labels[i].htmlFor == field.id) return labels[i];
	}
	return null;
}


/* =====================================================================
 *	DEPRECATED FUNCTIONS - AVOID THESE SO THAT WE CAN REMOVE 
 * ===================================================================== */

/* === EVENT HANDLING (via http://www.scottandrew.com/weblog/articles/cbs-events) === */
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent) {
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

function removeEvent(elm, evType, fn, useCapture) {
	if (elm.removeEventListener) {
		elm.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.detachEvent) {
		var r = elm.detachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

function addCorner(elem, cornerId) {
	var o = (typeof elem == 'string') ? document.getElementById(elem) : elem;
	if (!elem) return false;
	var corner = document.createElement('div');
	if (cornerId) corner.id = cornerId;
	corner.className = 'corner';
	elem.appendChild(corner);
	return true;
}























