/* The generic javascript library for the main physics website.
 * 
 * Any script routines are to go here.
 * 
 * - Simon Harvey
*/

/* *** Utility functions. *** */
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};


var $jq = jQuery.noConflict();

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}


/* Format the page headers with a special style. */
function Typeset_PageHeaderFormat() {
	var titles = $jq("#center h2");
	var count = titles.size();
	
	if(count > 1) {
		/* We make the assumption that the first title will be the page title. */
		var title = titles.get(0);
		$jq(title).addClass("pageTitle");
	}
}

/* Format the Featured News and Events. */
function Typeset_FeaturedNewsAndEventsFormat() {
	var featured = $jq("#featured-content > div.main");
        var count = featured.size();
	
	if(count < 1) return;
	
	for(i = 0; i < count; i++) {
		f = featured[i];
		
		$jq(f).attr("style", "");
		
		if(i == 0) $jq(f).addClass("featuredContentItemFirst");
		if((i + 1) == count) $jq(f).addClass("featuredContentItemLast");
		
		$jq(f).addClass("featuredContentItem");
		
		if((i % 2) == 0) $jq(f).addClass("featuredContentItemEven");
		else $jq(f).addClass("featuredContentItemOdd");
	}
}

function Typeset_NewsPageFormat() {
	var h2 = $('h2.tplvar-content-title');
	var sections = null;
	var kids = null;
	var entry = null;
	
	if(h2.length < 1) return;
	
	if($(h2[0]).text().trim() == "News") {
		//alert("News site");
		$('div#center').addClass("newsPage");
		
		/* Locate the last entries at the end of the list. */
		//sections = $("div#center > div.tplblock-list");
		sections = $("#center div.tplblock-list");
		if(sections.length > 0) {
			for(i = 0; i < sections.length; i++) {
				section = $(sections[i]);
				
				kids = section.children("div.BlockContent").children("div.tplrepeat-parent").children("div.listRow"); //> div.tplrepeat-parent > div.listRow");
				//alert("sections.length: " + sections.length);
				
				if(kids.length > 0) {
					for(j = 0; j < kids.length; j++) {
						if((j + 1) == kids.length) break;
						entry = $(kids[j]);
						entry.addClass("newsPage-border-bottom");
					}	
				}
			}
		}
		
		/* *** Reorganise the sidebar. *** */
		if($("div#right").text().trim() != "") {
			var html = $("div#right").html();
			var new_html = "<div id='rightbar-ne-list' class='rightBarNEList'>\n" + html + "</div>\n";
			$("div#right").html(new_html);
		}
	}
}

/* Format the Right Sidebar List. */
function Typeset_RightSidebarListFormat() {
	var featured = $jq("#rightbar-ne-list > div.main");
        var count = featured.size();

        if(count < 1) return;

        for(i = 0; i < count; i++) {
                f = featured[i];

                if(i == 0) $jq(f).addClass("neContentItemFirst");
                if((i + 1) == count) $jq(f).addClass("neContentItemLast");

                $jq(f).addClass("neContentItem");

                if((i % 2) == 0) $jq(f).addClass("neContentItemEven");
                else $jq(f).addClass("neContentItemOdd");
        }
}

/* Set up the Staff/Student directory. */
function Directory_Setup() {
	var top_anc = $('#site_top');	
	if(top_anc.length < 1) return;
	
	var student_scrolldiv = $('#student-topofpage');
	if(student_scrolldiv.length < 1) return;

	/* Display it. */
	student_scrolldiv.show();

	$('#scrollto-top').click(function() {
		$.scrollTo(0, 0, { queue:true, duration: 1000 });
	});
}

/** Hide the right bar if there is nothing there. */
function Layout_HideRightbar() {
	var right = $('#right');
	var text = '';

	if(right.length < 1) return;

	text = right.text().trim();
	if(text == "") right.hide();
}

var g_advsearch_settings = false;

function Search_ToggleAdvancedSettings() {
	
	/* Determine what the current state of the settings are. */
	var adv = $("#advanced-search-option-table");
	var state = null;
	
	if(adv.length < 1) return;
	
	state = adv.css("display");
	if(state == "none") {
		g_advsearch_settings = false;
	}
	else {
		g_advsearch_settings = true;
	}
	
	if(g_advsearch_settings == false) {
		$('.tplflag-searchAdvancedOption').show('fast');
		$('#advancedSearchForm_searchadvanced').val(1);
		g_advsearch_settings = true;
	}
	else {
		$('.tplflag-searchAdvancedOption').hide('fast');
		$('#advancedSearchForm_searchadvanced').val(0);
		g_advsearch_settings = false;
	}	
}


// Pinched from search.js?v=5012
function Search_ToggleSearchForm(action){
	
	//alert("Action: " + action);
	
	if(action == 'show'){
		$('.tplflag-searchAdvancedOption').show('fast');
		
		//$('#toggleSearchOptionsLinkShow').hide();
		//$('#toggleSearchOptionsLinkHide').show();
		$('#toggleSearchOptionsLinkShow').css("display", "none");
                $('#toggleSearchOptionsLinkHide').css("display", "inline");
		
		$('#advancedSearchForm_searchadvanced').val(1);
	}else if(action == 'hide'){
		$('.tplflag-searchAdvancedOption').hide('fast');
		
		//$('#toggleSearchOptionsLinkShow').show();
		//$('#toggleSearchOptionsLinkHide').hide();
		$('#toggleSearchOptionsLinkShow').css("display", "inline");
		$('#toggleSearchOptionsLinkHide').css("display", "none");
		
		$('#advancedSearchForm_searchadvanced').val(0);
	}
} 

function Search_SetupTextArea() {
	var area = $("#search-toggle-options-row");
	if(area.length < 1) return;
	
	area.show();

	search_title = $('.tpllang-SearchResultTitle');
	if(search_title.length > 0) {
		num_title = search_title.text();
		num_title = num_title.toLowerCase();
		
		if(num_title.indexOf("search result") != -1) {
			var parts = num_title.split(" ");
			if(IsNumeric(parts[0]) == true) {
				var count = 0;
				var items = " items";
				
				count =  (parts[0]);
				if(count == "1") items = " item";
				$('#search-page-title').html("Search results &mdash; " + parts[0] + items);
			}
		}
	}
}

var g_smallsearch_message = "Search this site...";
var g_color = "#000000";
var g_ss_color = "rgb(160,160,160)";

/* Add an interactive section to the left sidebar. */
function Search_SetupSmallSearch() {
	var ss = $("#smallSearch_Query");

        if(ss.length < 1) return;
	
	var ssf = $("#smallSearchForm");
	g_color = $('body').css('color');
		
	/* Set the default text. */
	ss.val(g_smallsearch_message);
	ss.css("color", g_ss_color);
	
	ss.keydown(function() {
		ss.css("color", g_color);
	});
	
	ss.blur(function () {
		var txt = ss.val();
		if(txt.trim() == "") {
			ss.css("color", g_ss_color);
			ss.val(g_smallsearch_message);
		}
	});
	ss.focus(function () {
		var txt = ss.val();
		if(txt == g_smallsearch_message) {
			ss.val("");
		}
		
		ss.css("color", g_color);
        });
	
	ssf.submit(function () {
		var txt = ss.val();
		if(txt == g_smallsearch_message) ss.val("");
	});
}


function Search_HighlightText(term_text, text) {
	
	var terms = term_text.toLowerCase().split();
	var stxt = null;
	var updated_text = '';
	var regex = null;
	var term_length = 0;
	
	if(terms.length < 1) return text;
	
	stxt = text.toLowerCase();
	
	match = new Array();
	for(i = 0; i < stxt.length; i++) {
		match[i] = 0;
	}
	
	/* See if a given term exists in the text. */
	for(i = 0; i < terms.length; i++) {
		var term = terms[i];
		var ind = 0;
		term_length = term.length;
		
		/* We do not count any negative terms. */
		if(term.indexOf("-") == 0) continue;
		
		
		while(true) {
			ind = stxt.indexOf(term, ind);
			if(ind == -1) break;
				
			for(j = ind; j < (ind + term_length); j++) {
				match[j] = 1;
			}
			
			ind++;
		}
	}
	
	/* Add the bold. */
	for(j = 0; j < match.length; j++) {
		c = text.charAt(j);
		if(match[j] == 0) updated_text += c;
		else updated_text += "<b>" + c  + "</b>";
	}
	
	return updated_text;
}

function Search_HighlightResults() {
	var sres = $('#search_results');
	var res = null;
	
	if(sres.length < 1) return;
	
	var terms = $("#search_Query").val().trim();
	if(terms == "") return;
	
	res = $('#search_results div.listRow h3 a');
	if(res.length < 1) return;

	$(res).each(function(i) {
		var entry = $(this);
		text_res = Search_HighlightText(terms, entry.text());
		entry.html(text_res);
		
		return true;
	});

        res = $('#search_results div.listRow div.listSummary');
        if(res.length < 1) return;

        $(res).each(function(i) {
                var entry = $(this);
                text_res = Search_HighlightText(terms, entry.text());
                entry.html(text_res);

                return true;
        });

}

function Form_CleanOptions() {
	var opts = $("option");
	if(opts.length < 1) return;

	for(i = 0; i < opts.length; i++) {
		opt = $(opts[i]);
		opt.text(opt.text().trim());
	}
}

/* The scripts 'main' function */
$jq(document).ready(function() {
	
	Layout_HideRightbar();
	
	Typeset_PageHeaderFormat();
	Typeset_FeaturedNewsAndEventsFormat();
	Typeset_RightSidebarListFormat();
	Typeset_NewsPageFormat();
	
	Search_SetupTextArea();
	Search_SetupSmallSearch();
	Search_HighlightResults();
	Directory_Setup();
});

