/*
*	Javascript Functions for the epsilon homepage
*/	
	// create a Tab class that can be turned on and off
	function Tab(i){
		this.elem = $($('tab_swapper_left').getElementsBySelector('a')[i]);
	}

	function do_lookup(e,v){
		// get the ul to update with people data
		var old_value = ""
		
		var ustProtocol = "http://"

		if ("https:" == document.location.protocol) {
			ustProtocol = "https://"
		}
			
		var ul = $('drawer').getElementsBySelector('ul')[2];
  		if (v.length <= 2){
			$(ul).update("<li>Enter at least 3 characters</li>");
			return;
		}
		else{
			$(ul).update("<li><img id='search_img' src=\"" + ustProtocol + "www.stthomas.edu/common/images/loading.gif\"></li>");
		}
		if (old_value == v){
			return;
		}
		else{
			var people_tab_link = $($('tab_swapper_left').getElementsBySelector('a')[0])
			// if people has been selected
			if (people_tab_link.hasClassName('tab_on')){
					HomepageUtils.attach_script(ustProtocol + Homepage.host + '/homepage/directories/lookupPerson.js?callback=write_directory&full_name=' + escape(v), 'lookup_script');
			}
			else{
				HomepageUtils.attach_script(ustProtocol + Homepage.host + '/homepage/directories/lookupDepartment.js?callback=write_departments&dept_name=' + escape(v), 'lookup_script');
			}
		}
	}
	/*
		write the directories from JSON data
	*/
	function write_directory (people) {

		// html output
		if ($('search_img')){$('search_img').remove()}
		
		if (people.length > 0){
			
			$A(people).each(function(person){
				var li = document.createElement('li');
				var a = document.createElement('a');
				var div = document.createElement('div');
				
				li.id = person.username;
				a.href = '#'
				$(a).update(person.full_name.gsub(/,/, ', '))
				div.style['display'] = 'none'
				
				li.appendChild(a)
				li.appendChild(div)
				
				Event.observe(a, 'click', get_more_info.bindAsEventListener(a));
				$('directory_output').appendChild(li)
			})
			
		}
		
		// code for outputting no users found
		if ($('lookup_script') && people.length == 0){
						
			// extract full_name from the search string in our script tag
			var full_name = $('lookup_script').src.toQueryParams().full_name
		
			if (full_name && full_name.length >= 3){
				$('directory_output').update("<li>No users found. Try looking for <a href='#' id='no_users'>departments</a></li>");
				Event.observe($('no_users') , 'click', function(){
					LookupTabs.internal_toggle(LookupTabs.directories.elem)
				})
			}
		}
		
	
	}
	
	// attach script to get more json info on a user
	function get_more_info(e){
		var ustProtocol = "http://"

		if ("https:" == document.location.protocol) {
			ustProtocol = "https://"
		}
		
		var username = Event.element(e).parentNode.id
		var more_info_div = Event.element(e).nextSibling
	
		// toggle the username
		Effect.toggle(more_info_div);
		if ($(more_info_div).empty()) { $(more_info_div).update('searching...');}
		// attach the json script with callback to write_more_info
		HomepageUtils.attach_script(ustProtocol + Homepage.host + '/homepage/directories/moreInformation.js?callback=write_more_info&username=' + username ,'more_information');
		
	}
	
	function toggle_dept_info(e){
		var a = Event.element(e);
		var dept_name_li = "<li>" + a.parentNode.innerHTML + "</li>"
		var dept_info_li = "<li>" + $(a.parentNode).next().innerHTML + "</a>"
		
		$('directory_output').update(dept_name_li + dept_info_li)
	
	
	}
	
	// write depts to the DOM
	function write_departments (depts) {
		// clear previous entries
		$('directory_output').update('')
		
		if (depts.length == 0){
			$('directory_output').update('<li>No departments found. Try looking for <a href="#" id="no_depts">people</a></li>')
			Event.observe($('no_depts') , 'click', function(){
				LookupTabs.internal_toggle(LookupTabs.people.elem)
			})
		}
		
		// for each dept returned
		$A(depts).each(function(dept){
			// create new DOM elements
			var li = document.createElement('li');
			var dept_info_li = document.createElement('li');
			var a = document.createElement('a');

			
			// add onclick event and set id
		
			a.id = 'dept_name_' + i
			a.innerHTML = dept.name;
			
			// attach onclick event
			Event.observe(a, 'click', toggle_dept_info.bindAsEventListener(a))
			
			// create a div with an id associated with it
			dept_info_li.id = 'dept_info_' + i;
			dept_info_li.style['display'] = 'none'
			$(dept_info_li).update('')
			
			// fill in the dept detail info
			if (dept.url) { dept_info_li.innerHTML += "<a href=\"" + dept.url + "\" >" + dept.url + "</a><br />" }
			if (dept.phone){ dept_info_li.innerHTML += "Phone: " + dept.phone + "<br />" }
			if (dept.email){dept_info_li.innerHTML+="<a style='display:inline' href='mailto:" + dept.email + "'>" + dept.email + "</a>" + '<br />';}
			if (dept.fax){ dept_info_li.innerHTML += "Fax: " + dept.fax + "<br />" }
			if (dept.building && dept.office ){dept_info_li.innerHTML += "<br />" + dept.building + " " + dept.office + "<br />"}
			if (dept.campus){
				if (dept.campus == "STP") {
					dept_info_li.innerHTML += "2115 Summit Ave.<br>St. Paul, MN 55105"
				}
				else if (dept.campus == "MPL") {
					dept_info_li.innerHTML += "1000 LaSalle Ave.<br>Minneapolis, MN 55403"
				}
			}
		
			if (dept_info_li.innerHTML == ''){
				$(dept_info_li).update('No more information found')
			}
			
			// attach elements to DOM
			li.appendChild(a)
			$('directory_output').appendChild(li)
			$('directory_output').appendChild(dept_info_li)
			
		});
	}
	
	/*
		write out information for a person to the page
	*/
	function write_more_info(person_info){
		// get username from the script src
		var username = $('more_information').src.toQueryParams().username;
		var user_li = $(username).cloneNode(true)
		if (Object.keys(person_info).length == 0){
			
			$(user_li).getElementsBySelector('div')[0].update('No more information found.');
			$(user_li).getElementsBySelector('div')[0].style['filter'] = 'alpha(opacity=100)'
			$(user_li).getElementsBySelector('div')[0].style['opacity'] = '1'
			$('directory_output').update('').appendChild(user_li)
			return;
		}
		var email = person_info.username.toLowerCase() + "@stthomas.edu";
		// write new phone number
		var phone_num = person_info.phone_number;
		if (phone_num){ // phone number might not exist.
			phone_num = person_info.phone_number.gsub(/(\d{3})(\d{3})(\d{4})/, function(match){
			return match[1] + "-" + match[2] + "-" + match[3];
			});
		}
		var html_out = "";
		if (phone_num){ html_out += phone_num + "<br/>"; }
		if (email){html_out += "<a style='display:inline' href='mailto:" + email + "'>" + email + "</a>" + '<br />'; }
		if (person_info.dept_desc){ html_out += "<i>Department: </i>" + person_info.dept_desc + '<br />'}
		if (person_info.mail_stop){html_out += person_info.mail_stop }
	
		// update the user's div
			
		$($(user_li).getElementsBySelector('div')[0]).update(html_out)
		
		$(user_li).getElementsBySelector('div')[0].style['display'] = 'block'
		$(user_li).getElementsBySelector('div')[0].style['filter'] = 'alpha(opacity=100)'
		$(user_li).getElementsBySelector('div')[0].style['opacity'] = '1'
		// remove all other users
		$('directory_output').update('') 
		$('directory_output').appendChild(user_li);
			
	}
	/*
		write news to the dom
	*/
	function write_news(news_items){ 
	
		write_feed(news_items, 0);
	}
	/*
		write events to the dom
	*/
	function write_events(events_items){ 
		for(i = 0; i < events_items.length; i++){
			if (events_items[i].description){
				events_items[i].description = "";
			}
		}
		write_feed(events_items, 1);
	}
	
	/*
		Write a feed from a list of json elements with link, title, and description
		
		items - array of javascript objects
		ul_index - the ul to use starting at 0
			0 = news
			1 = events
	*/
	function write_feed (items, ul_index) {
		var feed_items = $('drawer').getElementsBySelector('ul')[ul_index];
		// clear current feed items
		$(feed_items).update('');
	
		var html = '';
		// create the feed html
		for (i = 0; i < items.size(); i++){
			html += "<li>"
			html += "<a href='" + items[i].link + "'><h4>";
			html += items[i].title + "</h4>"
			html += items[i].description
			html += "</a></li>"
		}
		// attach newly created html
		feed_items.update(html);
	}
	
	/*
	*	Turn the scroll bars on for the news/events sections
	*
	*/

	function toggle_news_scrollbars () {
		$A($('drawer').getElementsBySelector('ul')).each(
			function(ul){
				ul.toggle_scrollbar();
			}
		)
	}
	
	/*
		Jump scrollbars down for a-z index
	*/
	function az_jump(anchor){
		// scrollTop
		// get the letter anchor span (e.g. letterJ)
		var letter_span = $(anchor)
		// find offset from top of element - offset from top of page
		var offset = letter_span.offsetTop - $(letter_span).parentNode.offsetTop;
		$(letter_span).parentNode.scrollTop = offset;
	}
	
		function write_a_to_z (atozJson) {
			
			var anchor_links_html = "";
			var html = "";
			var curr_letter = "";
			for(var i = 0; i < atozJson.length; i++){
			
				// add anchor for each letter
				
				if ( curr_letter != atozJson[i].title.substring(0,1)){
					curr_letter = atozJson[i].title.substring(0,1); 
					anchor_links_html += "<a href=\"#\" onclick=\"az_jump('letter" + curr_letter + "')\""  + " />" + curr_letter +"</a> " 
					html += "<span id=\"letter" + curr_letter + "\" >" + curr_letter +"</span>"
				}
				
				html += "<li><a href=\"http://" + atozJson[i].link + "\">" + atozJson[i].title + "</a></li>"
			}
		
			$('anchor_links').update(anchor_links_html);
			$($('output_azindex').getElementsBySelector('ul')[0]).update(html);
			
		}
		
 var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-9187134-6']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();