//
//
// INITIALIZE PAGE
//
// 
var start = new Date().getTime();
function initializePage(){
	log("initializing...");
//	showToolbar();
	fixHomepage();
	initLeedsExplore();
	initLeedsFeedback();	
	initializeGoogleMap();
	populateLeftMenu(); // Combine with setMenuClickEvents ?
	setMenuClickEvents(); // Combine with populateLeftMenu ?
	initCalendar();
	initFeedbackPage();
	initSiteSearch();
	initIndex();
	fixEmails();
//	fixFootnotes();
	initTopicSorting();
	initSearchSorting();
	fixBlockMargins(); 
	initCol3Toggle();
	initKeyStrokeListener();
	initHashListener();
	fixPortal();
	log("done. it took " + (new Date().getTime() - start) + " milliseconds.");
}

//
// ORGANIZATION
//
//
// 1. Toolbar, Homepage & Feedback
// 2. Calendar & Google Maps
// 3. Search
// 4. Show
// 5. Index
// 6. Helper functions



// TO DO:
//   replace things like $(this).parent().parent() with $(this).parents('.someclass')
//   share code amongst three different sorting types
//   replace .find() methods with children() or parents()



//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############       Toolbar, Homepage, Feedback           ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//

function showToolbar(){
	if($("#main").hasClass("homepage_index")){
		$("#central").hide().delay(1000).fadeIn(2000);
		$("#central *:not(#searchresults)").show();		
	}
	else if($("#main").hasClass("homepage_welcome")){
		$("#central").show();
	}
	else{
		$("#central *:not(#searchresults)").show();
	}
}

// compatibility concerns with different browsers based on $(window).height()
function fixHomepage(){
	if($("#black").length) {
	
		//first, make feature gravitate to bottom of window
		var winheight = $(window).height();
		var adjustment = Math.max(0,winheight-570);
		adjustment = adjustment.toString() + "px";
		$("div#marquee").css("height",adjustment);
		
		/* resize doesn't work on trunk firefox and/or windows browsers
		//adjust on window resize
		$(window).resize(function() {
			var h = $(window).height();
			var adjustment = Math.max(0,h-723);
			adjustment = adjustment.toString() + "px";
			$("div#marquee").css("padding-bottom",adjustment); 
		});*/
	}
}


function initLeedsExplore(){
  var $explore = $('#toolbar h2.explore');
	var $nav = $('#nav');
	if($explore.length && $nav.length){
		
		$explore.toggle(function() {
		  if(typeof ClickTaleExec=='function')
        ClickTaleExec("initLeedsExplore()");
        _gaq.push(['_trackPageview', '/#explore']);        
			$explore.css("background-position", "0 -75px");
			$explore.css("margin-top", "-12px");
      $nav.show();			
			}, function() {
			$explore.css("background-position", "0 0");
			$explore.css("margin-top", "-12px");
      $nav.slideToggle(200);		
		});	
	
    $('html').click(function(e){ 
      if($nav.is(":visible") && !$(e.target).parents('#nav').length){
        $explore.click();
      }
    });
	}
}


function initLeedsFeedback(){
  var $fb = $('#feedback'), $fbButton = $('#toolbar h2.feedback');
  if($fb.length && $fbButton.length){
    var $ct = $('#commenttext'), $warning = $('#warning');
    
    var url = location.host + location.pathname + location.hash;
		
    $fbButton.toggle(function () {
		  if(typeof ClickTaleExec=='function')
        ClickTaleExec("initLeedsFeedback()");
		_gaq.push(['_trackPageview', '/#feedback']);        
      $("#response").hide();
      $fbButton.css("background-position", "0 -75px");
      $fbButton.css("margin-top", "-12px");       
      $("#feedback p.url").html(url);
      $fb.show();
      }, function () {
      $fbButton.css("background-position", "0 0");
      $fbButton.css("margin-top", "-12px");
      $fb.slideToggle(200);
    });
    
    
    $ct.keyup(function(){
      var text = $ct.val();
      var remaining = 140 - text.length;
      if(remaining > 0){
        $warning.removeClass("hazard");        
        $warning.html("-" + Math.abs(remaining));              
      }
      if(remaining == 0) {
        $warning.removeClass("hazard");      
        $warning.html(Math.abs(remaining));
      }
      if(remaining < 0) {
        $warning.addClass('hazard');     
        $warning.html("+" + Math.abs(remaining));      
      }     
    });
    
    $("#sitefeedback").submit(function() {
      var c = $ct.val();
      var a = $("#authortext").val();
      if((c.length > 10) && (c.length <= 140) && (a.length > 2) && (a.length <= 40)){
        $warning.html("");
        url = location.host + location.pathname + location.hash;
        $.ajax({
          url: "/comment/add",
          type: "post",
          dataType: "json",
          data: "comment=" + escape(c) + "&url=" + escape(url) + "&author=" + escape(a),
          complete: doneCommenting
        });
      }
      else{
        $warning.addClass('hazard');
        if(a.length < 2){
          $warning.html("Name is too short");
        }
        else if(a.length > 40){
          $warning.html("Name is too long");
        }
        else if(c.length < 10){
          $warning.html("Comment is too short");
        }         
        else{
          $warning.html("Error. Please email.");
        }
      }
      return false;
    });
  }
}

function doneCommenting(results){
  var r = eval('('+results.responseText+')');
  if(r == "success"){
	$("#feedback").css("height", "115px");
	$("form#sitefeedback").hide();
    $(".length").hide();    
    $("#response").fadeIn("100");
    $("#authortext").val("");
    $("#commenttext").val("");
  }
  else log("failed to submit comment. response: "+r);
}
function doneDeleting(results){
	var r = eval('('+results.responseText+')');
  if(r == "success"){
		reFresh();
	}
  else log("failed to submit comment. response: "+r);
}
function doneReplying(results){
	var r = eval('('+results.responseText+')');
  if(r == "success"){
		reFresh();
	}
  else log("failed to submit comment. response: "+r);
}

function refreshIfNotTyping(){
  if(!$('input:focus, textarea:focus').length)
    reFresh();
}

function initFeedbackPage(){
	if($("#main").hasClass('comment_index')){
		
    // window.setInterval("refreshIfNotTyping()",120000); //refresh every 2 minutes
    
		
	  if($(".comment_block a.reply").length){ //if admin
			
	    $(".comment_block a.reply, .response_block a.reply").click(function(){
	      var id = $(this).parents('.comment_block, .response_block').attr("id").substring(1);
				var replyform = $(this).parent().children("form.replyform");
				if ($(replyform).not(':visible').length) 
					$(replyform).slideDown();
				else 
					$(replyform).slideUp();
	      var text = $(replyform).children(".replytext");
	      text.val("");
	      text.keyup(function(){
					var remaining = 140 - text.val().length;
					var warning = text.parent().children(".warning");
					if(remaining > 0){
						warning.removeClass("hazard");				
						warning.html("-" + Math.abs(remaining));							
					}
					if(remaining == 0) {
						warning.removeClass("hazard");			
						warning.html(Math.abs(remaining));
					}
					if(remaining < 0) {
						warning.addClass('hazard');			
						warning.html("+" + Math.abs(remaining));			
					}
	      });
	      
	      $(replyform).submit(function(){
	      	var c = $(this).children(".replytext").val();
					if((c.length > 1) && (c.length <= 140)){
						$.ajax({
							url: "comment/reply",
							type: "post",
							dataType: "json",
							data: "comment=" + c + "&id=" + id,
							complete: doneReplying
						});
					}
					return false;
	      });
	    });
	  }
	  
	  if ($(".comment_block a.delete, .response_block a.delete").length) {
			$(".comment_block a.delete, .response_block a.delete").click(function(){
				var ans = confirm("Delete this comment?");
				if (ans) {
					var id = $(this).parents('.comment_block, .response_block').attr('id').substring(1);
					$.ajax({
						url: "/comment/delete",
						type: "post",
						dataType: "json",
						data: "id=" + id,
						complete: doneDeleting
					});
				}
			});
		}
  }
}























//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############            Calendar, Google Maps            ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//

function initCalendar(){
	if($("#calendar").length){
		setCalenderClickEvents();
		var hash = self.document.location.hash.substring(1);
		$.get(
		  '/events',
		  { date: hash, updatecalendar: true },
			function(data){
				var calindex = $(".col1 > .section").index($("#calendar").parent('.section'));
				$(".col1 > .section").eq(calindex).replaceWith(data);
				setCalenderClickEvents();
				if(hash.length){
					$('#calendar .date a[href$="'+hash+'"]').click();
					self.document.location.hash = hash;
				}
			}
		);
  }
}

function getCurrentDate()
{
	if($("#calendar").length)
	{
		if ($('#calendar .dates .selected').length) {
			return $("#calendar .dates .selected").children('a').attr("href").substring(1);
		}
		else {
			log('unable to find current date');
			return false;
		}
	}
}

function setCalenderClickEvents(){
	if ($("#calendar").length) {
		$("#calendar .date a").click(function(e){
			if (!$(this).hasClass('selected')) {
		  	var date = $(this).attr('href').substring(1);
		  	$("#calendar .date").removeClass("selected");
		  	$(this).parent('.date').addClass("selected");
		  	$.get('/events', {
		  		date: date
		  	}, handleSortResults);
		  }
		});
	
		$("#calendar .previous_month").click(function(){
			var currentIndex = $(".month").index($(this).parent().parent());
			if (currentIndex > 0) {
				$(this).parent().parent().hide();
				$("#calendar .month").eq(currentIndex - 1).show();
			}
		});
		$("#calendar .next_month").click(function(){
			var currentIndex = $(this).parent().parent().index();
			if (currentIndex < $("#calendar").find(".month").eq(-1).index()) {
				$(this).parent().parent().hide();
				$("#calendar").find(".month").eq(currentIndex + 1).show();
			}
		});
	}
}

//
// For Google Map
//
//   - The variables that follow are shared by the two functions 
//		 
//
var koelbel;
var directionsService;
var directionsDisplay;
var geocoder;

function initializeGoogleMap() {
	if($("#map_canvas").length && $("#directionsPanel").length){
		
		var center = new google.maps.LatLng(40.004974, -105.263481);
		koelbel = new google.maps.LatLng(40.005774, -105.263481);
	
	  var myOptions = {
	    zoom: 16,
	    center: center,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  };
	  var map = new google.maps.Map(document.getElementById("map_canvas"),
	                                myOptions);
	
	  var marker = new google.maps.Marker({
	  	position: koelbel,
	  	map: map,
	  	title: "Koelbel"
	  });
	  
		directionsService = new google.maps.DirectionsService();
	  directionsDisplay = new google.maps.DirectionsRenderer();
	  directionsDisplay.setMap(map);
	  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  }
  
  //alumni page
  //
  if($("#mymapform").length){
  
  	initMapForm();
  
	  geocoder = new google.maps.Geocoder();
	  
  	var options = {
	    zoom: 7,
	    center: new google.maps.LatLng(40.004974, -105.263481),
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  };
  	var map = new google.maps.Map(document.getElementById("map_canvas"), options);
			// Now that we have our map, lets layer some placemarks on top.
    var geoXml = new google.maps.KmlLayer('http://newleeds.colorado.edu/asset/dashboard/alumnimap.kml?c='+(new Date().getTime()));
    google.maps.event.addListenerOnce(geoXml, 'metadata_changed', function() {
      log("done loading kml layer after " + (new Date().getTime() - start) + " ms");
      $("p.loading").hide();
    });
    geoXml.setMap(map);
    
  }
}
  
function calcRoute() {
	if($("#start_directions").length){
	  var start = document.getElementById("start_directions").value;
	  var end = koelbel;
	  var request = {
	    origin:start, 
	    destination:end,
	    travelMode: google.maps.DirectionsTravelMode.DRIVING
	  };
	  directionsService.route(request, function(response, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
	      directionsDisplay.setDirections(response);
	      $("#mapsearch p").html("Address located. See below for directions. ");
	      $("#directionsPanel").show();
	    }
	    else{
	    	log("Google did not return an OK directions status: " + status);
	    	$("#mapsearch p").html("Address not found. Please enter a different address. ");
	    	$("#directionsPanel").hide();
	    }
	  });
  }
}

function mapMe(){
	if($("#mymapform").length){
		if($("#mmname").val().length && 
				$("#mmvalidator").val().length && 
				$("#mmaddress").val().length)
		{
			geocoder.geocode( { 'address': $("#mmaddress").val() }, function(results, status) {
				if(status == google.maps.GeocoderStatus.OK) {
					$("p.warning").hide();
					
					var coords = results[0].geometry.location.lng().toString();
					coords += ','+results[0].geometry.location.lat().toString()+',0';
					var n = $("#mmname").val();
					var d = $("#mmdegree").val();
					var w = $("#mmwebsite").val();
					var c = $("#mmcomment").val().substring(0,420);
					var v = $("#mmvalidator").val();
					insertPlacemark(coords, n, d, w, c, v);
				} else {
					$("#addresswarning").show();
				}
			});
		}
		else{
			if($("#mmname").val().length)
				$("#namewarning").hide();
			else
				$("#namewarning").show();
			if($("#mmaddress").val().length)
				$("#addresswarning").hide();
			else
				$("#addresswarning").show();
			if($("#mmvalidator").val().length)
				$("#validatorwarning").hide();
			else
				$("#validatorwarning").show();
		}
	}
}

function insertPlacemark(coords, name, degree, website, comment, validator){
	$.post('map/mapme', 
		{ coordinates: coords, name: name, degree: degree, 
			website: website, comment: comment, validator: validator },
		function(data, textStatus, XMLHttpRequest){
			if(textStatus == "success"){
		    $("#map_canvas").append(data);
		    $("input#post").hide();
			  $("p.success").show();
			}
			else
				$("#validatorwarning").show();
		}
	);
}

function initMapForm(){
	if($("#mymapform").length){
		$("#mmname").keydown(function(){
			limitInput(this, 40)
		});
		$("#mmdegree").keydown(function(){
			limitInput(this, 40)
		});
		$("#mmwebsite").keydown(function(){
			limitInput(this, 127)
		});
		$("#mmcomment").keydown(function(){
			limitInput(this, 420)
		});
	}
}




































































//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############                   Search                    ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//
function initSiteSearch(){
	if($("#sitesearch input#site").length){
		$("#sitesearch input#site").keyup(function(event){
			event.preventDefault();
			if(this.value.length > 2 && ((event.which > 59 && event.which < 91) || 
																		event.which == 8) || 
																	 (event.which > 47 && event.which < 58)){
				$.get(
					"/leeds_dev.php/search/instant",
					{ query: this.value },
					function(data){
						$("#searchresults").html("");
						if($("#searchresults").not(":visible")) $("#searchresults").fadeIn("fast");
						if(!data.trim().length){
							$("#searchresults").append('<div class="showallresults">' + 
								'<a href="JavaScript:void(0);"><p class="showall">No Results</p></a></div>');
						}
						else{
							$("#searchresults").append(data);
/*							$("#searchresults").append('<div class="showallresults">' + 
								'<a href="JavaScript:void(0);"><p class="showall">Show All Results</p></a></div>'); */
							if($("#sitesearch").length){
/*								$("#searchresults .showallresults").click(function(){
									$("#sitesearch form").submit();
								}); */
							}
							fixLiveResultsCss();
							fixEmails();
						}
					}
				);
			}
			else if(this.value.length < 3){
				$("#searchresults").fadeOut("fast");
				$("#searchresults > .searchresult").remove();
				$("#searchresults > hr").remove();
			}
			
			if($("#searchresults > div").length){
				var current = -1;
				if($("#searchresults .selected").length){
					var s = $("#searchresults .selected");
					current = $("#searchresults > div").index(s);
				}
				var numresults = $("#searchresults > div").size();
				if(event.which == 40){ //arrow down
					var nextindex = (current + 1) % numresults;
					$("#searchresults > div").removeClass("selected");
					$("#searchresults > div").eq(nextindex).addClass("selected");
				}
				else if(event.which == 38){ //arrow up
					var nextindex = (current - 1) % numresults;
					if(current < 0) nextindex = numresults-1;//if first move is up, go to show all
					$("#searchresults > div").removeClass("selected");
					$("#searchresults > div").eq(nextindex).addClass("selected");
				}
				else if(event.which == 13){ //enter
					if($("#searchresults .selected").length && !$("#searchresults .selected").hasClass("showallresults")){
						window.location = $("#searchresults .selected").children("a").attr("href");
					}
					else{
						$("#sitesearch form").submit();
					}
				}
				fixLiveResultsCss();
			}
		});
		$("#sitesearch input#site").blur(function(){
			if($("#searchresults").is(":visible"))
				$("#searchresults").fadeOut("fast");
		});
		$("#sitesearch input#site").focus(function(){
			if($("#searchresults").not(":visible") && $("#searchresults div").size() > 1)
				$("#searchresults").fadeIn("fast");
		});
	}
	if($("#searchresults").length && $("#sitesearch").length){
		$("#searchresults .showallresults").click(function(){ log('here');
			$("#sitesearch form").submit();
		});
	}
}




function fixLiveResultsCss(){ 
  var $results = $("#searchresults div.searchresult, #searchresults div.showallresults");
  if($results.length){ 
    $results.hover(function(){
      $(this).children("img").css("opacity","0.8");
      $(this).children("p").css("color", "rgb(73,169,66)");
      $results.removeClass("selected");
      $(this).addClass("selected");
    }, function(){ 
      $(this).children("img").css("opacity","1.0");
      $(this).children("p").css("color", "#fff");
      $results.removeClass("selected");
    });
		$results.each(function(){
		  $(this).click(function(){
				window.location.href = $(this).children("a").attr("href");
				//$(this).children("a").click();
			});
	  });
    $results.children("img").css("opacity","1.0");
    $results.children("p").css("color", "#fff");
    var $selected = $("#searchresults div.selected");
    $selected.children("img").css("opacity", "0.8");
    $selected.children("p").css("color", "rgb(0,121,193)");
		if($("#searchresults").length && $("#sitesearch").length){
		  $("#searchresults .showallresults").click(function(){ 
		    $("#sitesearch form").submit();
		  });
		}
  }
}


function initSearchSorting(){
	if($("ul#search_filter .sorting_item a").length && $("#title h1 em").length){
		$("ul#search_filter .sorting_item a").click(function(){
			if($(this).hasClass('selected')){
				$("#search_blocks").hide();
				$("#static_blocks").show();
				self.document.location.hash="";
				$(this).removeClass("selected");
			}
			else {
				var target = $(this);
				$("#search_filter a").removeClass("selected");
				$(this).addClass("selected");
				var a = $(this).html().trim().toLowerCase();
				var query = $("#title h1 em").html();
				$.get(
					'/search',
					{ s: query, filter: a },
					handleSortResults
				);
			}
		});
	}
}













































































//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############                 Sorting Show                ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//


//
// For pages like Person profiles where the menu is determined by the content.
//
function populateLeftMenu(){
	if($("#dynamic_submenu").length && $("#main .content").size() > 1){
		$("#dynamic_submenu").append('<ul class="menuItems first"></ul>');
		$(".content > h2").each(function(){
				var name = $(this).html();
				var anchor = "";
				if($("#main").hasClass("type_index"))
					anchor = $(this).attr("class");
			  else if((anchor = getCustomHash($(this))) && anchor.length){}
				else
					anchor = makeAnchor(name);
				$("#dynamic_submenu > ul.menuItems").append('<li class="toggle_section">' + 
						'<a href="#' + anchor + '">' + name + '</a> </li>');
		});
		
		// This will either show the section that corresponds with an
		// anchor in the URL, or it will just show the first section. 
		var section = getSection();
		if(!section || section.length < 1){
			var a = makeAnchor($("#dynamic_submenu").find("li.toggle_section").eq(0).children("a").html());
			if($("#main").hasClass("type_index"))
				a = "";
			self.document.location.hash = a;
		
		  $("#dynamic_submenu").find("li.toggle_section a").removeClass("selected");
		  $("#dynamic_submenu").find("li.toggle_section").eq(0).children("a").addClass("selected");
		  
			$(".content").hide();
		  $(".content").eq(0).show();
		}
		else{
			$(".content").each(function(){
		  	$(this).hide();
				if ($(this).children("h2").html() == section) {
					$(this).show();
					$("#dynamic_submenu").find("li.toggle_section").each(function(){
						if($(this).children("a").html() == section){
							$(this).children("a").addClass("selected");
						}
						else{
							$(this).children("a").removeClass("selected");
						}
					});
				}
			});
		}
		
		
	}
	
	function getCustomHash(h2){
	  var h = '';
		var c;
		if(c = h2.attr('class')){
			var classes = c.split(' ');
			for(var i in classes){
			  if(classes[i].indexOf('_') == 0){
				  h = classes[i].substr(1);
				  h2.attr('class', h);
					break;					
				}
			}
		}
		return h;
	}
}

//
// The one for profiles <div class="content"><h2>title</h2> ... </div>
//
function setMenuClickEvents(){
	$(".toggle_section").click(function(){
		if(!$("#main").hasClass('type_index')){
			$(".toggle_section").children("a").removeClass("selected");
			$(this).children("a").addClass("selected");
			var href = document.location.href;
			var anchor = href.substring(25);
			_gaq.push(['_trackPageview', anchor]);
			
			//create anchor and set section
			setSection(makeAnchor($(this).children("a").html()));
		}
	});
}

function setSection(anchor){
	var currentAnchor = self.document.location.hash;
	
	if(arguments.length == 0){ //if no anchor passed, use whats up on the url bar
		anchor = currentAnchor;
	}
	/*
	if(false && anchor != currentAnchor){ //if we haven't already updated the anchor, do it now
		if(anchor.charAt(0) != "#")
			self.document.location.hash = "#" + anchor;
		else
			self.document.location.hash = anchor;
	}
	*/
	if($(".content").children("h2").length && $("#dynamic_submenu").length && anchor.length > 1){
		var sectionName = getSection(anchor);
		$(".content").each(function(){
			var header = $(this).children("h2").html();
			
			// If we have a match, slide it in (as long as its currently closed)
			if(header == sectionName){
				if (!$(this).attr("style")) {log("no style yet!");}
			  else {
					//only toggle it if its closed (don't close an open one)
			  	if ($(this).attr("style").match("none")) 
			  		$(this).slideToggle(300);
			  }
			}
			else //close others if they are open
			{
				if (!$(this).attr("style")) {log("no style yet!!");}
				else {
					if ($(this).attr("style").match("block")) 
				  	$(this).hide();
				}
			}
		});
	}
}

// Returns the section name
//	2 options:
//		:: getSection(anchor)
//				- get the name of the section from an anchor you pass in
//		:: getSection()
//				- get the name of the section using the current anchor in the url
//
function getSection(anchor){
	if(arguments.length == 0 || anchor.length <= 1){ 
		anchor = self.document.location.hash;
	}

	if (anchor.length > 1 && $(".content").children("h2").length){
		var matchedAnchor = false;
		var section = anchorToSection(anchor); 
		return section;
	}
	else
		return "";
}

// Called from populateLeftMenu()
//
//  - remove spaces and periods
//  - Replace &'s with the word And
//
function makeAnchor(str){
	str = str.replace(/&amp;/g,"and");
	str = str.replace(/&/g,"and");
	str = str.replace(/ /g,"");
	str = str.replace(/,/g,"");	
  str = str.replace(/-/g,"");
	str = str.replace(/\./g,"");
	return str.toLowerCase();
}

// Inverse of the function above. 
//
//
function anchorToSection(anc){
	if($(".content").children("h2").length){
		if(arguments.length == 0){
			anc = self.document.location.hash;
		}
		var returnValue = "";
		if(anc.indexOf("#") == 0) //trim leading # if there is one
			anc = anc.substring(1);
		anc = anc.replace(/_/g," ");
		$(".content").each(function(){
			var header = $(this).children("h2").html();
			if(makeAnchor(header) == anc)
				returnValue = header;
		});
		return returnValue;
	}
	else
		return "";
}



function initTopicSorting(){
	if($("ul#dynamic_filter").length && $(".block .sortingtag").length){
		var anchors = new Array();
		$(".block .sortingtag").each(function(){
		  var tag = $(this).html().trim();
			if(!inArray(tag, anchors))
				anchors.push(tag);
		});
		anchors.sort();
		for(var i=0; i<anchors.length; i++){
			$("ul#dynamic_filter").append('<li class="sorting_item">' +
				'<a href="#' + anchors[i] + '">' + anchors[i].capitalize() + '</a></li>');
		}
		
		if($("#dynamic_filter a").length){ 
			var topicname = $("#title h1 span").html();
			$("#dynamic_filter a").click(function(){
				if($(this).hasClass('selected')){
					$("#search_blocks").hide();
					$("#static_blocks").show();
			    self.document.location.hash="";
					$(this).removeClass("selected");
				}
				else {
					var target = $(this);
					$("#dynamic_filter a").removeClass("selected");
					$(this).addClass("selected");
					var a = $(this).html().trim().toLowerCase();
					$.get(
		        '/search/sort',
		        { table: a, type: 'topic', sortby: topicname },
		        handleSortResults
					);
				}
			});
		}
	}
	if(!$("#dynamic_filter a").length)
		$("#dynamic_filter").parent().children('h2').hide();
}









































































































//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############                Index Functions              ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//


// For scrolling and ajax search on index pages. 
//
//
var lastBottomHit = new Date().getTime();
var notDone = true;
function initIndex(){
  
	var threshold = 500; //half second between scoll appends
	if($("#pagesearch, #pagesearchinput, #static_blocks").length){
		var searchClass = $("#pagesearch").attr("class") || ""; 
		var parts = searchClass.split("_");
		var table = parts.shift(); //like pop
		$("#pagesearchinput").keyup(function(){
			if(this.value.length >= 3){
				$.get(
					'/leeds_dev.php/'+table+'/search',
					{query: this.value },
					function(data){
						if($("#static_blocks").is(":visible"))
							$("#static_blocks").hide();
						$("#search_blocks").html(data);
						$("#search_blocks").show();
						fixBlockMargins();
						fixEmails();
					}
				);
			}
			else{
				$("#search_blocks").html("");
				$("#static_blocks").show();
			}
		});
	  
			
		if($("#scroll_loader").length){
			if($("#static_blocks").hasClass("decaf")){ //topic show
				if($("#static_blocks .block").length){
					var count = 0;
					$("#static_blocks .block").each(function(){
						count++;
						if(count > 8) $(this).hide();
					});
				}
				$(window).scroll(function(){
					if($(window).height() + $(window).scrollTop() == $(document).height() 
													&& (new Date().getTime() - lastBottomHit > threshold)
													&& notDone
													&& $("#static_blocks").is(":visible")){
						getMoreStaticBlocks(8);
					}
				});
			}
			else {
				$(window).scroll(function(){
					if($(window).height() + $(window).scrollTop() > ($(document).height() - 300)
													&& ((new Date().getTime()) - lastBottomHit > threshold)
													&& notDone
													&& $("#static_blocks").is(":visible")){
						getMoreBlocks(8,table+"/append");
					}
				});
			}
		}
		
		
    $("#pagesearch").submit(function(){
      return false;
    });
	}
	
	initFilters();
	
	anchor = self.document.location.hash;
	if(anchor.length > 1){
	  var a = anchor.substring(1); // remove #
	  if($(".filter a").length){
	    var matchedanchor = false;
	    $(".filter a").each(function(){
	      if(a == makeAnchor($(this).html().trim()) || a == $(this).attr("href").substring(1)){
	        matchedanchor = true;
	        $(this).click();
	      }
	    });
	    if(!matchedanchor)
	      self.document.location.hash="";
	  }
	}
}

function getMoreStaticBlocks(num){
	lastBottomHit = new Date().getTime();
	if($("#static_blocks .block:hidden").length){
		var count = 0;
		$("#static_blocks .block:hidden").each(function(){
			if(count < num){
				$(this).show();
				count++;
			}
			else return false;
		});
		fixBlockMargins();
	}
}

function handleSortResults(data, textStatus, XMLHttpRequest){
	//$('html').css('cursor','default !important');
	if(textStatus == "success"){
		$('a.selected').blur();
		if($("#static_blocks").is(":visible"))
			$("#static_blocks").hide();
		$("#search_blocks").html(data);
		if($("#search_blocks").not(":visible"))
			$("#search_blocks").show();
		fixBlockMargins();
		fixEmails();
	}
	else log("failed with status: " + textStatus);
}

function getMoreBlocks(numToFetch, url){
	lastBottomHit = new Date().getTime();
	$("#scroll_loader").show();
	var bl = getBlackList();
	$.get(
		"/leeds_dev.php/"+url,
		{ blacklist: bl },
		function(data){ 
			$("#scroll_loader").hide();
			if(data.length < 1) {
				notDone = false; 
			}
			else{
				if($("#main").hasClass('entity_index')){ //location
					$("#static_blocks > .content:visible").append(data);
					$("#scroll_loader").appendTo("#static_blocks > .content:visible");
				}
				else{
					$("#static_blocks").append('<div id="appending" style="display:none">'+data+'</div>');
					$('#appending').fadeIn(600, function(){
					  $('#appending').remove();
						$('#static_blocks').append(data);
		        fixBlockMargins();
		        fixEmails();
					});
					$("#scroll_loader").appendTo("#static_blocks");
				}
			  fixBlockMargins();
				fixEmails();
		  }
		}
	);
}
// This is probably unnecessary. look into doctrine's OFFSET
function getBlackList(){
	var blacklist = '';
	if($("#static_blocks").length){
		var targetclass="";
		if($(".block").length) targetclass="block";
		else if($(".directory_block").length) targetclass="directory_block";
		$("#static_blocks ." + targetclass).each(function(){
			var idparts = $(this).children().eq(0).attr("id").split("_");
			blacklist += idparts[1] + "bl"; //bl is our delimiter here. 
		});
		blacklist = blacklist.substring(0,blacklist.length-2); //get rid of last bl delim
	}
	return blacklist;
}



function initFilters(){	
	if($(".filter a").length){
		$(".filter a").click(function(e){ 
		  e.preventDefault();
			if($(this).hasClass("selected")){ // Clear the sort
				//e.preventDefault();
				$("#search_blocks").hide();
				$("#static_blocks").show();
		    self.document.location.hash="";
				$(this).removeClass("selected");
				$(this).blur();//remove focus
			} 
			else { 												// Do the sort
			  window.location.replace($(this).attr('href'));
	      $(".filter a").removeClass("selected");
	      $(this).addClass("selected");
	      if($(this).parents('.filter').length)
	      	var filter = $(this).parents('.filter').attr("id");
	      var parts = $("#"+filter).attr("class").split("_");
	      var table = parts[1];
				var dirblocks = (table == 'Person' || (parts.length == 3 && parts[2] == 'getdirblocks'));
	      var success = true;
	      switch(filter){
	      	case "sortbytype":
			      var sortby = $(this).html().trim();
			      break;
          case "sortbyissue":
            var sortby = $(this).html().trim().replace(" ","_");
            break;
	      	case "sortbyentity":
	      		var classes = $(this).attr("class").split(" ");
	      		if(classes[0].indexOf("_") == 1){
					    var idparts = classes[0].split("_");
					    var sortby = idparts[1];
				    }
				    break;
	      	case "sortbyperson":
	      		var classes = $(this).attr("class").split(" ");
	      		if(classes[0].indexOf("_") == 1){
					    var idparts = classes[0].split("_");
					    var sortby = idparts[1];
				    }
				  	break;
				  default:
				  	success = false;
				  	log("invalid filter type: " + filter);
	      }
	      if(success){
	      	var type = filter.slice(6); //text after sortby (eg. sortbytype => type)
					//$('html').css('cursor','progress');
          if (type == "type") { 
					  var getPath = (table == 'jobs') ? '/leeds_dev.php/jobs' : '/search/sort';
						if(table == "person"){
			  	    $.get(getPath, 
								{ limit: 12, table: table, sortby: sortby, type: type, 
								dirblocks: dirblocks, date: getCurrentDate()}, 
								function(data, textStatus, XMLHttpRequest){
								  if(textStatus == "success"){
								    $('a.selected').blur();
								    if($("#static_blocks").is(":visible"))
								      $("#static_blocks").hide();
								    $("#search_blocks").html(data);
								    if($("#search_blocks").not(":visible"))
								      $("#search_blocks").show();
								    fixBlockMargins();
								    fixEmails();
								  }
								  else log("failed with status: " + textStatus);
								}
					    ).success(function(){
			  		    $.get(getPath, 
								  { offset: 12, table: table, sortby: sortby,
			  			      type: type, dirblocks: dirblocks, date: getCurrentDate() }, 
		              function(data, textStatus, XMLHttpRequest){
		                if(textStatus == "success"){
		                  $('a.selected').blur();
		                  if($("#static_blocks").is(":visible"))
		                    $("#static_blocks").hide();
		                  $("#search_blocks").append(data);
		                  if($("#search_blocks").not(":visible"))
		                    $("#search_blocks").show();
		                  fixBlockMargins();
		                  fixEmails();
		                }
		                else log("failed with status: " + textStatus);
		              }
								);
			  	    });
						}
						else {
						  $.get(getPath, 
                { table: table, sortby: sortby, type: type, 
                dirblocks: dirblocks, date: getCurrentDate()}, 
                function(data, textStatus, XMLHttpRequest){
                  if(textStatus == "success"){
                    $('a.selected').blur();
                    if($("#static_blocks").is(":visible"))
                      $("#static_blocks").hide();
                    $("#search_blocks").html(data);
                    if($("#search_blocks").not(":visible"))
                      $("#search_blocks").show();
                    fixBlockMargins();
                    fixEmails();
                  }
                  else log("failed with status: " + textStatus);
                }
              )
						}
		      }
		      else {
            var getPath = (table == 'jobs') ? '/leeds_dev.php/jobs' : '/search/sort';
            if(table == 'portfolio') getPath = '/leeds_dev.php/portfolio';
            $.get(getPath, 
						  { table: table, sortby: sortby, type: type, 
							  dirblocks: dirblocks, date: getCurrentDate() }, 
							handleSortResults
						);
		      }
	      }
	    }
		});
	}
}


function initCol3Toggle(){
	if($("#main").hasClass("type_index") && $(".toggle_section > a").length && $(".col3 .swap").length){
		$(".toggle_section > a").click(function(){
			$(".toggle_section > a").removeClass("selected");
			$(this).addClass("selected");
			var col3target = $(this).attr("href").substring(1);
			if(col3target.length == 0)
				col3target = "section";
			var col2target = $(this).html().trim();
			$(".col2 .content").each(function(){
				if($(this).children('h2').html() == col2target && $(this).is(":hidden"))
					$(this).show();
				else if($(this).children('h2').html() != col2target && $(this).is(":visible"))
					$(this).hide();
			});
			$(".col3 .swap").each(function(){
				if($(this).hasClass(col3target) && $(this).is(":hidden")){
					$(this).show();
				}
				else if(!$(this).hasClass(col3target) && $(this).is(":visible")){
					$(this).hide();
				}
			});
		});
		
/* load section from anchor
		anchor = self.document.location.hash;
		if(anchor.length > 1){
		  var a = anchor.substring(1); // remove #
	    var matchedanchor = false;
	    $(".toggle_section > a").each(function(){
	      if(a == makeAnchor($(this).html().trim()) || a == $(this).attr("href").substring(1)){
	        matchedanchor = true;
	        $(this).click();
	        log('ya!');
	      }else log('nooo');
	    });
	    if(!matchedanchor)
	      self.document.location.hash="";
	  } 
*/
	}
}



function initHashListener(){
  if($('#dynamic_submenu').length){
	  var lastHash = '';
	  setInterval(function(){ 
	    var currentHash = window.location.hash;
	    if(currentHash != lastHash){
	      var target = $('a[href='+currentHash+']');
	      if(target.length && target.parent('.toggle_section').length){
	        target.click();
	      }
	      lastHash = currentHash;
	    }
	  }, 100);
	}
}































//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############               Pending Deletion              ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//

/*
function fixFootnotes(){
	if($('li[id^="footnote"] > a').length){ log('found ya');
		$('li[id^="footnote"] > a').click(function(e){
			var href = $(this).attr('href');
			var height = $(window).scrollTop();
			log(height);
			$(window).scrollTop(height+1000);
			log('done trying to fix footnotes');
		});
	} else log('no such thing');
}*/



/*
// doesn't work if a word is larger than the line length 
function numLines(phrase, lineLength){
  if(phrase.length <= lineLength){
    if(phrase.length < 1) return 0;
    else return 1;
  } 
  else{
    var linecount = 0;
    var lines = 1;
    var words = phrase.split(" ");
    for(var i in words){
      if(i>0 && linecount>0) linecount++; //add one for a space
      var l = words[i].length;
      if(l + linecount > lineLength){
        lines++;
        linecount = l;
      }
      else{
        linecount += l;
      }
    }
    return lines;
  }
}
*/


































//
//
//
// ######################################################################### 
// ######################################################################### 
// ##############                                             ############## 
// ##############               Helper Functions              ############## 
// ##############                                             ############## 
// ######################################################################### 
// ######################################################################### 
//
//
//


function fixEmails(){ 
  $('.directory_block dd.email a, .searchresult p.email, p.email a').each(function(){ 
		var height = $(this).height(); 
		if (height > 20) { 
			var parts = $(this).text().split("@");
			if(parts.length == 2){ 
				var newtext = parts[0]+"@\n"+parts[1];
				$(this).text(newtext);
			}
		}
	});
}


//
//
function fixPortal() {
//	fixBlockMargins("portalblock", 0, "right", 3)
}


//Parameters not required. See first if statement
//Fixes margins between blocks and directoryblocks
function fixBlockMargins(targetclass, margin, side, nth){
	if(arguments.length >= 0 && arguments.length <= 3){
		var blockclass;
		var margin;
		var side;
		var nth;
		if($(".block").length){
			blockclass = "block";
			margin = 20;
			side = "right";
			nth = 2;
		}
		else if ($(".directory_block").length){
			if($("#main").hasClass("entity_show")){
				margin = 20;
				nth = 3;  
				side = "right";
			}
			else{
				margin = 13;
				nth = 4;
				side = "right";
			}
			blockclass = "directory_block";
		}
		
		fixBlockMargins(blockclass, margin, side, nth);
	}
	else if(arguments.length == 4){
		if($("." + targetclass).length){
			if((side == "left" || side == "right") && (nth > 0)){ 
				var i = 1;
				var lastindex=-2; //so that the first if statement is true
				var selector = "."+targetclass+":visible";
				if($("."+targetclass).parents('.content').length)
					selector = "."+targetclass;
				$(selector).each(function(){
					if($(this).index() != lastindex + 1 && $(this).parent().hasClass("content")){
						i=1;
					}
					if(i%(nth) == 0){
						if(side == "left"){
							$(this).css("margin-left", "0px");
						}
						else if(side == "right"){ 
							$(this).css("margin-right", "0px");
						}
					}
					else{
						var marg = parseInt(margin) + "px";
						marg = marg.toString();
						if(side == "left"){
							$(this).css("margin-left", marg);
						}
						else if(side == "right"){ 
							$(this).css("margin-right", marg);
						}
					}
					i++;
					lastindex = $(this).index();
				});
			}
		}
	}
	else{
		log("Unable to handle "+arguments.length+" arguments in fixBlockMargins()");
	}
}

function reFresh() {
  location.reload(true)
}

// like php's ucwords; makes a string uppercase
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}



//checks if the needle is in the haystack
function inArray(needle, haystack)
{
	if(haystack.length < 1)
		return false;
	for(var i=0; i<haystack.length; i++){
		if(haystack[i] == needle){
			return true;
		}
	}
	return false;
}


// A function to get get parameters from the url or a string
//
// Slightly modified version of a function found here...
// http://www.netlobo.com/url_query_string_javascript.html
//
function gup(name, target)
{
	if(arguments.length < 2)
		target = window.location.href;
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( target );
  if( results == null )
    return "";
  else
    return results[1];
}


//
//Some functions for the search text box.
//
function clearSearch(target, prompt){
	if($(target).length){
		if($(target).attr("value") == prompt)
			$(target).attr("value","");
	}
}

function reprompt(target, prompt){
	if($(target).length){
		if($(target).attr("value") == "")
			$(target).attr("value",prompt);
	}
}


var i = 0;
var e = new Array();
e[0]=65;e[1]=76;e[2]=76;e[3]=73;e[4]=69;
e[5]=82;e[6]=69;e[7]=73;e[8]=68;
function initKeyStrokeListener(){
	if($("#nav").length){
		$(document).keyup(function(event){
			if(false){
			//if(event.which == 0 || event.which == 191){ // question mark
				if($("#nav").not(":visible").length){
					$('#central h2.central').css("background-position", "0 -30px");
					$('#central h2.central').css("margin-top", "-2px");	
					$("#nav").slideToggle(200);
				}
				else if($("#nav").is(":visible")){
					$('#central h2.central').css("background-position", "0 0");
					$('#central h2.central').css("margin-top", "-5px");	
					$("#nav").slideToggle(200);
				}
			}
			else{
				if(event.which==e[i]){
					i++;
					if(i > 8){
						alert('you typed alliereid!');
					}
				}
				else
					i=0;
			}
		});
	}
}


//makes sure the target doesn't have more characters than its limit
function limitInput(target, limit){
	if(target.value.length > limit)
		target.value = target.value.substring(0,limit);
}


// like php's trim; trim whitespace from beginning and end of string
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

jQuery.extend(jQuery.expr[':'], {
    focus: function(element) { 
        return element == document.activeElement; 
    }
});




// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};


