var xml;
var newTop;
var newLeft; 

// Set up the base directory to work from
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();
var baseDir = jQuery.url.attr("protocol") + '://' + jQuery.url.attr("host") + '/';


function loadXML(myURL){
	$.ajax({
		type: "GET",
		url: myURL,
		dataType: ($.browser.msie) ? "text" : "xml",
		error: function(){
			return;
		},
		success: function(data){
		     if (typeof data == "string") {
		       xml = new ActiveXObject("Microsoft.XMLDOM");
		       xml.async = false;
		       xml.loadXML(data);
		     	} else {
		       xml = data;
		     }
		}
	});
};

function searchInput(){
	$("input.searchInput").focus(function(){if(this.value=='SEARCH')this.value='';});
	$("input.searchInput").blur(function(){if(this.value=='')this.value='SEARCH';});
}
function cleanList(){
	$("#leftNav li ul li:first a").css("background", "none");
}
function showOverlay(){
	$("body").append("<div id='overlay'></div>");
	$("#overlay").css("width", $(document).width())
	$("#overlay").css("height", $(document).height()+20)
}
function hideOverlay(){
	$("#overlay").remove();
}
function showPopLayer(obj){
	$(".popLayer").css("display", "none");
	var popBox = "#"+$(obj).attr("name");
	var offsetObj = ($(obj).parent().hasClass("menuBox"))?$(obj).parent():$(obj)
	var offset = offsetObj.offset();
	$(popBox).css("display", "block");
	var newWidth = ($(popBox).width())-offsetObj.width();
	$(popBox).css("left", offset.left-newWidth+10);
	$(popBox).css("top", offset.top+offsetObj.height()+5);
}
function hidePopLayer(closeBtn){
	hideOverlay();
	$(closeBtn).parent().css("display", "none");
}
function showPopDr(){
	$(".author img").click(function(){$(this).toggleClass("highlight");return false;});
	$(".author img").hover(function(){showPopLayer(this);}, function(){return;});
}
function showPopSubscribe(){
	$(".subscribe").click(function(e) {
		$(".popLayer").css("display", "none");
		$("#sub").load(baseDir+"common/subscribe.html", function(){
			positionPopLayer(".subscribePop");
			$(".cancel").click(function(){hidePopLayer(".subscribePop #content"); return false;});
			$('.selectAll').click(function(){$("form").find("input[@type$='checkbox']").each(function() {this.checked = "checked";});return false;});
		});
		showOverlay();
		return false;
	});
}

function positionPopLayer(obj){
	newTop = Math.round(($(window).height()/2)-($(obj).height()/2));
	newTop = (newTop > 10) ? newTop : 10;		
	newLeft = Math.round((($(window).width())/2)-($(obj).width()/2));		
	newLeft = (newLeft > 10) ? newLeft : 10;		
	$("#sub").css("left", newLeft);
	$("#sub").css("top", newTop);
}
function positionPopLayerRelative(moveObj, refObj){
	var offset = $(refObj).offset();
	newTop = offset.top+($(refObj).height()+5);	
	newLeft = ((offset.left-($(moveObj).parent().offset().left))-($(moveObj).width()-$(refObj).width()));	
	$(moveObj).css("left", newLeft);
	$(moveObj).css("top", newTop);	
}

function showPullDown(){
	$(".menuBox a").click(function(){showPopLayer(this);return false;});
}
function showPopEmail(){
	$(".email").click(function(){
		var offset = $(this).offset();
		$(".popLayer").css("display", "none");
		$("#sub").load(baseDir+"common/email.html", function(){
			positionPopLayer(".emailPop");
			$(".cancel").click(function(){hidePopLayer(".emailPop #content"); return false;});
		});
		$("#sub").css("left", (($(window).width())/2)-220);
		$("#sub").css("top", offset.top+25);
		showOverlay();
		return false;
	});
}

function showPopInterstitial(){
	$(".window").click(function(){
		var targetURL = $(this).attr("href");
		$(".popLayer").css("display", "none");
		$("#sub").load(baseDir+"assets/html/interstitial.html", function(){
			$(".accept").click(function(){
				window.open(targetURL);
				hidePopLayer(".interPop #content");
				return false;
			});
			positionPopLayer(".interPop");
			$(".cancel").click(function(){hidePopLayer(".interPop #content"); return false;});
		});
		showOverlay();
		return false;
	});
}

function showGloss(x){
	var word = ($(x).text() == "Glossary") ?  $(xml).find('term').attr("name") : $(x).text();
	$(".popLayer").css("display", "none");
	$("#sub").load(baseDir+"common/glossary.html", function(){	
		$(xml).find('term').each(function(){glossaryDefinition(this, word)});
		$(".glossaryLink").click(function(){glossaryLinks(this);return false;});
		positionPopLayer(".glossaryPop");
	});

	showOverlay();	
	return false;
}

function showPopGlossary(){
	$(".glossary").click(function(){showGloss(this);return false;});
}

function glossaryLinks(link){
	$("#wordlist a").removeClass("selected");
	var newWord = $(link).text();
	$(link).addClass("selected");
	toggleGlossaryTerms(xml, newWord);
	return false;
}

function showPopDefinition(x){
	$(".glosstip").click(function(e) {
		var myWord = $(this).text();
		$(".popLayer").css("display", "none");
		$("#sub").load(baseDir+"common/tooltip.html", function(){	
			$(xml).find('term').filter(function(index){return $(this).attr("name") == myWord;}).each(function(){tooltipDefinition(this, myWord)});
			$(".glosslink .glossary").click(function(){showGloss($(".popLayer #content h5"));return false;});
			$(".definition-related .glossaryLink").click(function(){showGloss(this);return false;});
		});		
		var offset = $(this).offset();
		$("#sub").css("left", e.pageX+28);
		$("#sub").css("top", e.pageY-50);
		return false;
	});
}

function getDefinitionArray(xmlObj, word){	
	var i=0;
	var related_list = new Array();
	var item_name = $(xmlObj).attr('name')
	var item_definition = $(xmlObj).find('definition').text()
	var relatedtest = $(xmlObj).find('related').each(function(){
		related_list[i] = '<a class="glossaryLink">'+$(this).attr('name')+'</a>';
		i++;
	});
	var item_related = (related_list.length>0) ? '<div class="definition-related"><b>Related Terms:</b> ' + related_list.join(", ") + '</div>' : '';	
	var definitionArray = new Array();
	definitionArray["item_name"] = item_name
	definitionArray["item_definition"] = item_definition
	definitionArray["item_related"] = item_related	
	return definitionArray;
}

function tooltipDefinition(xmlObj, word){
	var definitionArray = getDefinitionArray(xmlObj, word);
	var newcontent = '<h5>' + definitionArray["item_name"] + '</h5><div class="definition-wrapper">' + definitionArray["item_definition"] + '</div>' + definitionArray["item_related"] + '<div class="glosslink"><a class="glossary">Full glossary</a></div>';
	$('<div id="content"></div>').html(newcontent).appendTo('#popContainer');
}
function glossaryDefinition(xmlObj, word){
	var definitionArray = getDefinitionArray(xmlObj, word);
	if (definitionArray["item_name"] == word) {
		$('<a class="glossaryLink selected"></a>').html(definitionArray["item_name"]).appendTo('#wordlist span');	
		$('<dt id="'+definitionArray["item_name"]+'"></dt>').html(definitionArray["item_name"]).appendTo('#definitions dl');
		$('<dd></dd>').html('<p>'+definitionArray["item_definition"]+'</p>'+definitionArray["item_related"]).appendTo('#definitions dl');
	} else {
		$('<a class="glossaryLink"></a>').html(definitionArray["item_name"]).appendTo('#wordlist span');	
	}
}
function toggleGlossaryTerms(xmlObj, word){	
	$(xml).find('term')
		.filter(function(index){return $(this).attr("name") == word;})
		.each(function(){
			var definitionArray = getDefinitionArray(this, word)
			var content = '<dt id="'+definitionArray["item_name"]+'">'+definitionArray["item_name"]+'</dt><dd><p>'+definitionArray["item_definition"]+'</p>'+definitionArray["item_related"]+'</dd>'
			$('#definitions').html(content)
		});
		$(".definition-related .glossaryLink").click(function(){
			var thisLinkText = $(this).text();
			var mainListLink = $("#wordlist a").filter(function(index){
				return $(this).text() == thisLinkText;
                });	
			glossaryLinks(mainListLink);
			return false;
		});
	return
}

//unconditionally popup the interstitial popup.
//if user clicks yes, go to targetURL in a new window.
function showInterstitial(targetURL){
			targetHTML = "assets/html/interstitial.html";
			return showInterstitial(targetURL, targetHTML);
}

//unconditionally popup the interstitial popup. 
//if user clicks yes, go to targetURL in a new window.
//the popup html is found in targetHTML
function showInterstitial(targetURL, targetHTML){
			$(".popLayer").css("display", "none");
			$("#sub").load(baseDir+targetHTML, function(){
				$(".accept").click(function(){
					window.open(targetURL);
					hidePopLayer(".interPop #content");
					return false;
				});
				positionPopLayer(".interPop");
				$(".cancel").click(function(){hidePopLayer(".interPop #content"); return false;});
			});
			showOverlay();
			return false;
}
//to make a popup, the link id should be 'popup' 
//optionally you can provide the popup dimensions in the name attribute, eg:
//if you dont provide the dimensions/name attr, the popup will open in a full window
//<a href=".." id="popup" name="800x600">..</a>
function enablePopups(){
	$('a.popup').click(function(){
			var targetURL = $(this).attr("href");
			// If this item also has class "offiste" then the interstitial
			// will need to be shown to notify the user that they are leaving the site
			if ($(this).is('.offsite')) 
			{ 
				targetHTML = "assets/html/interstitial.html";
				showInterstitial(targetURL, targetHTML);
				return false;
			}
			
			
			n = $(this).attr('name');
			t = $(this).attr('opts');
			fix = "";
			option = '';
		if(t != 'none'){
				option = "location=1,scrollbars=1,menubar=1,toolbar=1,top=0,left=0";//default stuff new windows get
		} 			
			
		windowName = "window"+new Date().getTime();

		if (n != null) {
			re='(\\d+)x(\\d+)';	
			width = 600;
			height = 600;
			p = new RegExp(re,["i"]);
			m = p.exec(n);
		if(m != null && m.length == 3){
				width=m[1];
				height=m[2];
		}
		
		if(option != '') fix = ","; //kludge
				window.open(this.href, windowName, option+fix+"width="+width+", height="+height).focus();
			} else {
				window.open(this.href, windowName, option).focus();
			}
			

		
		
			return false;
	});
}
//if url contains /sel/value/ and the page has element with id="value" then 
//it will get a class of "selected"
function setSelection(){
	p = new RegExp('.*?sel\\/((?:[a-zA-Z0-9_-]+))\\/',["i"]);
	var m = p.exec($.jqURL.url());
	if (m != null && m.length>0){
		$("#"+m[1]).addClass("selected");
	}
}

$(document).ready(function() {
    enablePopups();
});


