//** Main navigation
 
function setupMenu(menuId) {			
	var mainmenu = $("#" + menuId); //reference main navigation ul			
	var liWithUL = mainmenu.find("ul").parent(); //find all sub ul's and get the parent, which should be a list item
	liWithUL.hover(
		function(e){			
			$(this).children('a:first').addClass('selected');
			$(this).children('ul:first').css({visibility: "visible",display: "none"}).animate({ height: 'show', opacity: 'show' }, 200);			
		},
		function(e){
			$(this).children('a:first').removeClass('selected');
			$(this).children('ul:first').css({visibility: "hidden"});
		}
	)
	mainmenu.find("ul").css({ display: 'none', visibility: 'visible' });
}



// Note: for postTabs index 0=default, 1=tag, 2=month, 3=author, 4=all, written to page server side, defined in theme sitemaster.cs	

// Assumes that the tab control is a div element with a unique id which is passed as a constructor parameter.
// Contained within the tab control we have tabs represented by a list of links followed by panels, each of which is a div.
// Tab links and corresponding panels should be id anchors, for example, if tab link href="#tab1" then matching div should have id="tab1"
// An optional zero based index number can be passed in to select an active tab, the default is random.
function setupTabs(containerId, tabIndex) {	
	if(document.getElementById(containerId) === null) { // Make sure a valid tab container exists		
		return;
	} else {
		containerId = "#" + containerId + " ";
	}
	var panels = $(containerId + '.tabPanel');		
	if (!(typeof(tabIndex) === "number" && tabIndex < panels.length)) { //Keep index if it's a number within range, else use random			
		tabIndex = Math.floor(Math.random() * panels.length);		
	}
	$(containerId + 'ul.tabs a').click(function() {
			panels.hide().filter(this.hash).show();			
			$(containerId + 'ul.tabs a').removeClass('active');
			$(this).addClass('active');										
			return false;
	}).filter(':eq(' + tabIndex + ')').click();
	//See if we are trying to open a tab from a link
	if(location.hash.length > 1) {
		var isTab = $('a[href=' + location.hash + ']');		
		if(isTab) {				
			$(isTab).click();									
		}
	}
}


//Open links in new window and center screen 
//Parameters are optional target element, new window width and height
function externalLinks (objConfig) {		
	var config = {		
		targetElement:null,
		winWidth:800,
		winHeight:600		
	};
	if(objConfig) {
		$.extend(config, objConfig);
	}	
		
	var left = (screen.width - config.winWidth)/2; 
	var top = (screen.height - config.winHeight)/2;	
		
	var ancs;
	var te = document.getElementById(config.targetElement);
	// If a value was given for targetElement make sure it can be found, otherwise default to all anc elements
	(te === null)? ancs = document.getElementsByTagName("a"): ancs = te.getElementsByTagName("a");		 
	for (var i = 0, j = ancs.length; i < j; i++)
	{
		var anc = ancs[i];
		if (anc.getAttribute("href") && anc.getAttribute("rel") === "external") {			
			$(anc).addClass("external");
			anc.title = anc.title? anc.title + " - link opens in new window" : "Link opens in new window";
			$(anc).click(function() {
				window.open(this.href, '', 'scrollbars=yes, resizable=yes, width='+config.winWidth+', height='+config.winHeight+', top='+top+', left='+left);		
				return false;			
			});						
		}
	}
}

//Triva stuff
$.ajaxSetup ({
		cache: false
	});

var Triviata = {
	
	theText: "",	
	embedID: "",	
	
	getTune: function(loadURL, playNow)
	{					
			//Check to see if the next button has been pressed without revealing the name of the last tune
			var ta = document.getElementById('tuneAnswer');
			if(playNow && ta !== null && ta.innerHTML != Triviata.theText) {
				ta.innerHTML = "";
				$('#' + Triviata.embedID).remove();
				alert("The last tune was " + Triviata.theText);
			}
			var tt = $("#themeTune"), tuneLink, playID, href;	
			
			$(tt).load(loadURL, function() {
					tuneLink = $("#themeTune a");
					Triviata.theText = tuneLink.html();									
					playID = tuneLink.attr("id") + "Play";
					Triviata.embedID = playID + "Embed";											
					href = tuneLink.attr("href");									
					tt.html('<a href="'+href+'" id="'+playID+'" title="Play"><img src="/themes/Default/images/play.gif" style="vertical-align:middle" /></a>&nbsp;<a href="javascript:Triviata.stopPlay();" disabled="disabled" title="Stop\\Answer"><img src="/themes/Default/images/stop.gif" style="vertical-align:middle" /></a>');
					$("#" + playID).bind('click',function(){																
							if(document.getElementById(Triviata.embedID) === null) {																			
								$(tt).append('<embed id='+Triviata.embedID+' src="'+this.href+'" type="audio/wav" autostart="true" height="1" width="1" style="position:absolute;left:-9999px;"></embed>');								
								if(document.getElementById("tuneAnswer") === null) {
									$(tt).append('&nbsp;&nbsp;<span id="tuneAnswer">Streaming ' + '<img src="/themes/Default/images/streaming.gif" style="vertical-align:middle;padding-bottom:1px" />' + '</span>');
								}								
							}																			
							return false;
					});
					if(playNow) {										
						$("#" + playID).click();						
					}
			});			
	},	
	
	stopPlay: function() {			
		$('#' + Triviata.embedID).remove();	
		if(document.getElementById("tuneAnswer") === null) {
			$("#themeTune").append('&nbsp;&nbsp;<span id="tuneAnswer">'+Triviata.theText+'</span>');
		} else {
			document.getElementById("tuneAnswer").innerHTML = Triviata.theText;
		}		
	}
};


//Directory can use either a DL or UL
var Directory =
{  
	init: function() {			
		var index = document.getElementById("index");		
		var indexTabs = index.getElementsByTagName("a");			
		var curTab, listing, children, entries, title, p, total = 0;				
		for (var i = 0, j = indexTabs.length; i < j; i++)
		{
			entries = 0;
			curTab = indexTabs[i];			
			listing = document.getElementById(curTab.hash.substring(1));								
			if (listing) {
							
				do{
					listing = listing.nextSibling;
				} while (listing && listing.nodeType !== 1); // Stop at what should be a dl or ul					
								
				if(listing.nodeName.toLowerCase() === "dl") {				
					children = listing.childNodes;
					for (var k = 0, l = children.length; k < l; k++)	{
						if(children[k].nodeName.toLowerCase() === "dt") {												
							++entries;
						}
					}
				} else { // It should be a list item					
					children = listing.childNodes;					
					for (var k = 0, l = children.length; k < l; k++)	{
						if(children[k].nodeName.toLowerCase() === "li") {													
							++entries;
						}						
					}					
				}				
				title = entries + ((entries === 1) ? " entry" : " entries");
				p = document.createElement("p");
				p.className = "meta";						
				p.appendChild(document.createTextNode(title));			
				listing.parentNode.insertBefore(p, listing); // Dom insert of this listing total at section head 
				total += entries;	
							
			}	else {			
				title = "0 entries";
				curTab.className = "inactive";		
			}
			curTab.setAttribute("title", title);
		}		
		var t = document.createTextNode(" The listing has " + total + ((total == 1) ? " entry in total." : " entries in total."));
		do{
				index = index.previousSibling;
			} while (index && index.nodeType !== 1);	
		index.appendChild(t);
  }  
};

/*** Accordion
This accordion is structured using a block level wrapper element such as a div or list with a unique id (used as a mandatory constructor parameter).
Its panels are represented by sub divs or list items, comprising a header link (header element containing a hyperlink) and a content div(fold).
Clicking on the header link expands or contracts the content div, all elements are styled using CSS.
Optional configuration is applied via an object literal in the constructor.
***/
Accordion = function(strAccordID, objConfig){	
	var config = {
		tExpand:300, //Fold expand duration (time in milliseconds)
		tCollapse:0 //Unless tCollapse specified, defaults to 0.8 tExpand time		
	};
	
	if(arguments.length > 1) { //Optional args supplied
		$.extend(config, objConfig);
	}
	
	var pic1= new Image(20,20); 
  pic1.src="/themes/Default/images/minus.gif";	//Cache image
	this.tExpand = config.tExpand;
	this.tCollapse = config.tCollapse || config.tExpand * 0.8;
	this.expandedFold = null; //Ref to currently expanded fold
	this.expandAfterFold = null; //Ref to fold to expand once currently expanded fold has been collapsed
	this.start(strAccordID);	
};
  	
Accordion.prototype.start = function(accord) {	
	var thisAccord = document.getElementById(accord);	
	//Set up panel components
	var children = thisAccord.childNodes;
	var panel, title, panelLinks, fold;
	for (var i = 0; children[i]; i++)
	{			
		if (children[i].nodeType === 1) { //If it's a panel			
			panel = children[i];						
			panelLinks = panel.getElementsByTagName("a");
			title = panelLinks[0]; //Get title element
			$(title).addClass("accPanTitle"); //Add title class
			fold = panel.getElementsByTagName("div")[0]; //Get fold			
			if (fold) {											
				panel._fold = fold; //Store a fold ref in each panel
				fold._thisAccord = this; //Store a ref to current accordion in each fold								
				$(fold).addClass("accPanFold hidden"); //Add fold classes, folds should appear closed on accordion load	
				fold._title = title; //Store title ref in each fold					
				fold._title._fold = fold; //Store a ref to each fold in title
				fold._title.onclick = this.clickListener;		
			}				
			for (var j = 1; panelLinks[j]; j++)
			{
				panelLinks[j].onfocus = this.focusListener; //Folds are hidden of screen, allow hidden links to receive	focus and open fold.			
			}			
		}			
	}		
	if (location.hash.length > 1) {	//If a named anchor is in a fold then expand to reveal		
		var selectedPanel = document.getElementById(location.hash.substring(1));		
		if (selectedPanel && selectedPanel.parentNode === thisAccord) { //If panel is found and is in this accordion			
			this.expand(selectedPanel._fold);
		}
	}		
};

Accordion.prototype.collapse = function(fold, expandAfterFold) {			
	clearTimeout(fold._timer); //Terminate any ongoing animation
	this.expandedFold = null;
	this.expandAfterFold = expandAfterFold;	
	this.collapseAnimate(fold);	
};
  
Accordion.prototype.collapseAnimate = function(fold) { 	    
	var foldHeight = parseInt(fold.style.height);	
	var duration = this.tCollapse;
  var freq = Math.PI / (2 * duration);
	var ratio =0;
	var startTime = new Date().getTime();
  fold._timer = setInterval(
    function() {
      var elapsedTime = new Date().getTime() - startTime;
      if (elapsedTime < duration) {
        ratio = Math.sin(elapsedTime * freq);
				var displacement = Math.round(ratio * foldHeight);
        fold.style.height = (foldHeight - displacement) + "px";				
				fold.style.opacity = 1 - ratio;				
      }
      else {
        clearInterval(fold._timer);
				fold.style.height = 0;
				$(fold._title).removeClass("selected");		
				$(fold).addClass("hidden");				
				if (fold._thisAccord.expandAfterFold) {
					fold._thisAccord.expand(fold._thisAccord.expandAfterFold);					
				}
      }
    }, 10
  );	
};

Accordion.prototype.expand = function(fold) {
	if(fold === this.expandedFold) {
		return; //Do nothing, fold is already open
	}
	if (this.expandedFold) { //Check if another fold is open		
		this.collapse(this.expandedFold, fold); //Collapse open fold first, the collapseAnimate method checks if a fold should be expanded thereafter			
	}		
	else { //No folds open, expand this fold now 		
		this.expandedFold = fold;
		clearTimeout(fold._timer); //Terminate any ongoing animation
		fold.style.height = 0;
		$(fold).removeClass("hidden");	
		$(fold._title).addClass("selected");			
		fold.style.opacity = 1;		
		this.expandAnimate(fold); 
	}
};
  
Accordion.prototype.expandAnimate = function(fold) {  
	var foldHeight = fold.scrollHeight;
	var duration = this.tExpand;
  var freq = Math.PI / (2 * duration);
	var ratio = 0;
	var startTime = new Date().getTime();	
  fold._timer = setInterval(
    function() {
      var elapsedTime = new Date().getTime() - startTime;
      if (elapsedTime < duration) {
        ratio = Math.sin(elapsedTime * freq);				
        fold.style.height = Math.round(ratio * foldHeight) + "px";
				fold.scrollTop = 0;
      }
      else {
        clearInterval(fold._timer);
        fold.style.height = foldHeight + "px";				
      }
    }, 10
  );	
};
  
Accordion.prototype.clickListener = function() {    
	var fold = this._fold;	
	if (fold === fold._thisAccord.expandedFold) { //Clicked on open panel
		fold._thisAccord.collapse(fold);						
	} else {
		fold._thisAccord.expand(fold);					
	}  
	return false;
};
  
Accordion.prototype.focusListener = function() { //Make links within folds respond to tabbing   
	var element = this;
	while (element.parentNode) {
		if (element._thisAccord) { //First element up with a thisAccord ref is a fold, expand method will check if fold is already open			
			element._thisAccord.expand(element);
			return;			
		}
		element = element.parentNode;
	}
};
