// TODO: add cookie saving of open/close, add hide quicker onload functionality
if (document.getElementById && document.createElement && document.getElementsByTagName) {
	createStyleRule("#quick_access", "display:none;");
	Event.observe(window, 'load', function() { new QuickAccess(); });
	Event.observe(window, 'load', function() { new photoNav(); });
	Event.observe(window, 'load', function() {
		var aud_pro = $('aud_pro_sub');
		if (aud_pro) {
			$('aud_pro_sub').hide();
			$('prosp_students_choice_link').observe('click', toggleProspStudents, false);
		}
		Event.observe('suggest_form', 'submit', sendForm);
	});
}

function toggleProspStudents(e) {
	Event.stop(e);
	new Effect.toggle('aud_pro_sub', 'blind', { duration:0.5 });
}

/**
 * Logging class which ignores logging unless we set a level to output
 */
var Log = {
	levels: $A(['off', 'info', 'debug', 'error']),
	_level: 'off',
	_levelNotFoundValue: -1,
	
	// writes to the log if the level is appropriate and we have our Firebug console
	write: function(level, msg) {
		if (Log.getLevel() == 'off') return;
		var cur_level = Log.getLevelIndex(Log.getLevel());
		var req_level = Log.getLevelIndex(level);
		// only log if level exists and it is greater than or equal the the current level
		if (req_level != Log._levelNotFoundValue && cur_level <= req_level) {
			try {
				console.log(level + ': ' + msg);
			} catch(e) {
				// fail silently
			}
		}
	},
	
	// creates functions to write to the log at the various levels
	info: 	function(msg) { Log.write('info', msg); },
	debug: 	function(msg) { Log.write('debug', msg); },
	error: 	function(msg) { Log.write('error', msg); },
	
	// gets the levels array index of a level
	getLevelIndex: function(level) { return (Log.levels.include(level) ? Log.levels.indexOf(level) : Log._levelNotFoundValue); },
	
	// returns the current level string value
	getLevel: function() { return Log._level; },
	
	// sets the level of logging to output
	level: function(level) { 
		Log._level = Log.levels.include(level) ? level : null;
		if (Log._level == null) { throw('Log level does not exist'); }
	}
}
Log.level('info');

var QuickAccess     = Class.create();
QuickAccess.version = '0.1';
QuickAccess.prototype = {
	initialize: function() {
		this.qa = $("quick_access"); if (!this.qa) return;
		
		this.swapQuickAccessDivs();
		this.qa.setStyle({marginBottom:'1px'});
		
		// To keep track of whether or not the quick access div is currently animating. If it is then I don't
		// allow other animations to take place. Keeps scriptaculous from freaking out on double clicks and such.
		this.animating      = false;
		this.effectDuration = 0.5;
		this.helpLink       = $("quick_access_help_link");
		this.popularLink    = $("quick_access_popular_link");
		this.help           = $("help");
		this.popular        = $("popular");

		this.helpLink.observe('click', this.showHelp.bindAsEventListener(this));
		this.popularLink.observe('click', this.showPopular.bindAsEventListener(this));
	},
	
	swapQuickAccessDivs: function() {
		var div = Builder.node('div');
		var qa_js = Builder.node('div', {id:'quick_access_js', style:'display:none'});
		div.appendChild(qa_js);
		var qa_js_html = div.innerHTML;
		var qa_html = this.qa.innerHTML;
		new Insertion.Before(this.qa, qa_js_html);
		this.qa.remove();
		this.qa = $('quick_access_js');
		this.qa.hide();
		this.qa.update(qa_html);
	},
	
	showHelp: 		function(event) { Event.stop(event); this.showSection('help'); },
	showPopular: 	function(event) { Event.stop(event); this.showSection('popular'); },
	
	showSection: function(section) {
		if (this.animating) return;		
		this.animating     = true;
		var qaShowing      = this.qa.getStyle('display') == 'block' ? true : false;
		var helpShowing    = this.help.getStyle('display') == 'block' ? true : false;
		var popularShowing = this.popular.getStyle('display') == 'block' ? true : false;
		
		switch(section) {
			case 'help':
				if (qaShowing) {
					if (popularShowing) {
						this.slideUpAndShowHelp();
					} else {
						this.slideUp();
					}
				} else {
					this.slideDownAndShowHelp();
				}
				break;
			
			case 'popular':
				if (qaShowing) {
					if (helpShowing) {
						this.slideUpAndShowPopular();
					} else {
						this.slideUp();
					}
				} else {
					this.slideDownAndShowPopular();
				}
				break;
		}
	},
	
	slideDownAndShowPopular: function() {
		Log.info('Sliding QA Down and Showing Popular');
		this.help.hide();
		this.popular.show();
		new Effect.SlideDown(this.qa, {
			duration: this.effectDuration,
			afterFinish:  function() {
				this.helpLink.removeClassName('open');
				this.popularLink.addClassName('open');
				this.noLongerAnimating();
			}.bind(this)
		});
	},
	
	slideDownAndShowHelp: function() {
		Log.info('Sliding QA Down and Showing Help');
		this.popular.hide();
		this.help.show();
		new Effect.SlideDown(this.qa, {
			duration: this.effectDuration,
			afterFinish: function() {
				this.popularLink.removeClassName('open');
				this.helpLink.addClassName('open');
				this.noLongerAnimating();
			}.bind(this)
		});
	},
	
	slideUpAndShowPopular: function() {
		Log.info('Sliding QA Up and calling slideDownAndShowPopular()');
		new Effect.SlideUp(this.qa, {
			duration: this.effectDuration,
			afterFinish: this.slideDownAndShowPopular.bind(this)
		});
	},
	
	slideUpAndShowHelp: function() {
		Log.info('Sliding QA Up and Calling slideDownAndShowHelp()');
		new Effect.SlideUp(this.qa, {
			duration: this.effectDuration,
			afterFinish: this.slideDownAndShowHelp.bind(this)
		});
	},
	
	slideUp: function() {
		Log.info('Sliding QA Up');		
		this.popularLink.removeClassName('open');
		this.helpLink.removeClassName('open');
		new Effect.SlideUp(this.qa, {
			duration: this.effectDuration,
			afterFinish: this.noLongerAnimating.bind(this)
		});
	},
	
	noLongerAnimating: function() { Log.info('No longer animating'); this.animating = false; }
}

/*	dynamicCSS.js v1.0 <http://www.bobbyvandersluis.com/articles/dynamicCSS.php>
	Copyright 2005 Bobby van der Sluis
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/
function createStyleRule(selector, declaration) {
	if (!document.getElementsByTagName || !(document.createElement || document.createElementNS)) return;
	var agt = navigator.userAgent.toLowerCase();
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_iewin = (is_ie && (agt.indexOf("win") != -1));
	var is_iemac = (is_ie && (agt.indexOf("mac") != -1));
	if (is_iemac) return; // script doesn't work properly in IE/Mac
	var head = document.getElementsByTagName("head")[0]; 
	var style = (typeof document.createElementNS != "undefined") ?  document.createElementNS("http://www.w3.org/1999/xhtml", "style") : document.createElement("style");
	if (!is_iewin) {
		var styleRule = document.createTextNode(selector + " {" + declaration + "}");
		style.appendChild(styleRule); // bugs in IE/Win
	}
	style.setAttribute("type", "text/css");
	style.setAttribute("media", "screen"); 
	head.appendChild(style);
	if (is_iewin && document.styleSheets && document.styleSheets.length > 0) {
		var lastStyle = document.styleSheets[document.styleSheets.length - 1];
		if (typeof lastStyle.addRule == "object") { // bugs in IE/Mac and Safari
			lastStyle.addRule(selector, declaration);
		}
	}
}

function photoNav() {
	var href = '';
	current_page = get_path(document.URL);
	thedivs		 = $$('.photo-row');
	if (thedivs.length == 0) return;
	for(i=0; i < thedivs.length; i++) {
		thediv = thedivs[i];
		navas		= thediv.getElementsByTagName('a');
		if (navas.length == 0) return;
		// loop through nav a's
		for(j=0; j < navas.length; j++) {
			nava 	= navas[j];
			// if direct decendent of #nav ul
			if (nava.parentNode == thediv) {
				if (get_path(nava.href) == current_page) {
					if (nava.className != '') {
						nava.className += ' current';
					} else {
						nava.className = 'current';
					}
				}
			}
		}
	}
}


function get_path(url) {
	d 			     = document;
	site 		     = d.domain;
	sp 			     = url.indexOf(site) + site.length;
	path 		     = url.substring(sp);
	path 		     = path.replace(/([^/]+).(php)/, '');
	var splitter = path.split('#')
	path    		 = splitter[0];	
	return path;
}

function statTrack() {
	var dimensions 	= document.viewport.getDimensions();
	var os					= navigator.platform;
	var swidth      = screen.width;
	var sheight     = screen.height;
	var vwidth			= dimensions.width;
	var vheight			= dimensions.height;
	var flash     	= GetSwfVer();
	
	url = '/includes/stats.php';
	
	new Ajax.Request(url, {
		method: 'get',
		parameters: {os:os,swidth:swidth,sheight:sheight,vwidth:vwidth,vheight:vheight,flash:flash}
	});
}

if (document.observe) {
	document.observe('dom:loaded', function() { 
		statTrack();
		current_nav();
	});
}

function current_nav() {
	var href = '';
	current_page = get_path(document.URL);
	
	navul = document.getElementById("nav_secondary");
	if (!navul) return;
	//navul = navul[0];
	
	// get nav li's
	navlis = navul.getElementsByTagName('li');
	if (navlis.length == 0) return;
	
	// loop through nav li's
	for(i=0; i < navlis.length; i++) {
		navli = navlis[i];
		
		if(get_path(navli.firstChild.href) == current_page) navli.className += ' current';
		
		// if direct decendent of #nav ul
		if (navli.parentNode == navul) {
			subul = navli.getElementsByTagName('ul');
			
			// if not a sub ul, then continue
			if (subul.length == 0) continue;
			//if on subul's parent page, need to show ul as well
			if(get_path(subul[0].parentNode.firstChild.href) == current_page){
				subul[0].style.display = 'block';
			}

			subas = subul[0].getElementsByTagName('a');
			for(j=0; j < subas.length; j++) {
				curr_a = subas[j];
				if (get_path(curr_a.href) == current_page) {
					curr_a.parentNode.className = 'current';
					curr_a.parentNode.parentNode.style.display = 'block';
				}
			}
		}
	}
}

function cleanLastSlash(someurl){
	lastchar = someurl.length-1;
	if (someurl!="") {
		if (someurl.charAt(lastchar)=="/"){someurl = someurl.substring(0,(someurl.length-1))}
	}
	return someurl;
}

function get_path(url) {
	site 		= 'nd.edu';
	sp 			= url.indexOf('nd.edu') + site.length;
	path 		= url.substring(sp);
	path 		= path.replace(/index.(shtml|cfm)/, '');
	return path;
}


function sendForm(event){  
	// we stop the default submit behaviour
	Event.stop(event);
	var theform = $('suggest_form');
	
	if(theform['suggestion'].getValue() == '') {
		alert('Please enter a suggestion.');
	} else {
		
		url = '/includes/suggest.php';
		
		var form = theform['form'].getValue();
		var suggestion = theform['suggestion'].getValue();
		
		$('suggestion').addClassName('active')
		$('submitButton').disable();
		
		new Ajax.Request(url, {
			method: 'get',
			parameters: {form:form,suggestion:suggestion},
			onSuccess: function(transport) {
				$('suggest_form').update('<p id="suggest_thank_you">Thank you for your suggestion.');
			}
		});
	}
}