/* =================================================================================================
* NiceTitles
* January 5, 2004
* http://neo.dzygn.com/code/nicetitles
*
* NiceTitles turns your boring (X)HTML tags into a dynamic experience
*
* original code by Stuart Langridge Februari 2003 - http://www.kryogenix.org/code/browser/nicetitle/
*
* fixed by Paul McLanahan - http://paulmclanahan.com/
* A fix to stop titles remaining on the page when you open a link in a new window
*
* modified by Peter Janes 2003-03-25 - http://peterjanes.ca/blog/archives/2003/03/25/nicetitles-for-ins-and-del
* added in ins and del tags
*
* fix by Brad Choate - http://www.bradchoate.com/
* perfects positioning
*
* modified by Dunstan Orchard 2003-11-18 - http://www.1976design.com/blog/
* added in accesskey information
*
* final genius touch by by Ethan Marcotte 2003-11-18 - http://www.sidesh0w.com/
* worked out how to delay showing the popups to make them more like the browser's own
*
* rewritten by Mark Wubben 2003-12-14 - http://neo.dzygn.com/code/nicetitles
* rewritten code, added templating system, support for different styles, several bugfixes
*
* minor bugfix by Mark Wubben, invalid URI's messed up it's behaviour in Mozilla
*
* modified by Garoo - http://www.garoo.net/
* changed the display and position, removed code that wasn't needed anymore, and misc. changes
*
* Copyright (c) 2003 Stuart Langridge, Paul McLanahan, Peter Janes, Brad Choate, Dunstan Orchard, Ethan Marcotte, Mark Wubben, Garoo
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==================================================================================================*/

function NiceTitles(sTemplate, sContainerID, sClassName){
	//var oTimer;
	var isActive = false;
	var sNameSpaceURI = "http://www.w3.org/1999/xhtml";
	
	if(!sTemplate){ sTemplate = "attr(nicetitle)";}
	if(!sContainerID){ sContainerID = "nicetitlecontainer";}
	if(!sClassName){ sClassName = "nicetitle";}

	var oContainer = document.getElementById(sContainerID);
	if(!oContainer){
		oContainer = document.createElementNS ? document.createElementNS(sNameSpaceURI, "div") : document.createElement("div");
		oContainer.setAttribute("id", sContainerID);
		oContainer.className = sClassName;
		oContainer.style.display = "none";
		if(document.body){
			document.body.appendChild(oContainer);
		} else {
			document.getElementsByTagName("body").item(0).appendChild(oContainer);
		}
	}
	
	//=====================================================================
	// Method addElements (Public)
	//=====================================================================
	this.addElements = function addElements(collNodes, sAttribute, iForce){
		var currentNode, sTitle;
		
		for(var i = 0; i < collNodes.length; i++){
			currentNode = collNodes[i];
		
			//GAROO

			sTitle = currentNode.getAttribute(sAttribute);
			if(sTitle || iForce){
				if(!sTitle) sTitle = " ";
				if(hreflang = currentNode.getAttribute("hreflang")) sTitle = sTitle + " <span class='hreflang'>[" + hreflang.toLowerCase() + "]</span>";
				currentNode.setAttribute("nicetitle", sTitle);
				//currentNode.removeAttribute(sAttribute);
				currentNode.removeAttribute("title");
				addEvent(currentNode, 'mouseover', show);
				addEvent(currentNode, 'mouseout', hide);
				addEvent(currentNode, 'focus', show);
				addEvent(currentNode, 'blur', hide);
			}
		}

	}
	
	//=====================================================================
	// Other Methods (All Private)
	//=====================================================================
	function show(e){
		//if(isActive){ hide(); }
		
		var oNode = window.event ? window.event.srcElement : e.currentTarget;
		if(!oNode.getAttribute("nicetitle")){ 
			while(oNode.parentNode){
				oNode = oNode.parentNode; // immediately goes to the parent, thus we can only have element nodes
				if(oNode.getAttribute("nicetitle")){ break;	}
			}
		}

		var sOutput = parseTemplate(oNode);
		oContainer.innerHTML = sOutput;
		
		var oPosition = getPosition(e, oNode);
		oContainer.style.left = oPosition.x;
		oContainer.style.top = oPosition.y;
		oContainer.style.width = oPosition.w;
		//oContainer.style.height = oPosition.h;

		oContainer.style.display = "block";
		oContainer.style.visiblity = "visible";

		isActive = true;		
		// Lets put this event to a halt before it starts messing things up
		window.event ? window.event.cancelBubble = true : e.stopPropagation();
	}
	
	function hide(){
		oContainer.style.display = "none";
		oContainer.innerHTML = '';
		isActive = false;
	}

	function getPosition(e, oNode){

		var margin = 25, height = 55;

		var oCoords = { x: -500, y: 0, w: 0, h: 0 };
		/*
		var oViewport = getViewport();
		var oCoords = {
			x : oViewport.x + margin, 
			y : oViewport.y + oViewport.height - margin - height, 
			w : oViewport.width - 2 * margin, 
			h : height };
		*/

		if(!e) e = window.event;
		
		if(window.innerWidth)
		{
			oCoords.x = margin;
			if(window.pageXOffset) oCoords.x += window.pageXOffset;
			else if(window.scrollX) oCoords.x += window.scrollX;
			
			if(window.pageYOffset) scrollY = window.pageYOffset;
			else if(window.scrollY) scrollY = window.scrollY;
			else scrollY = 0;

			oCoords.y = scrollY + window.innerHeight - height - margin * 2;
			
			if(e.pageY && (e.pageY - scrollY > window.innerHeight - height - margin * 3)) oCoords.y -= height + margin * 3;
			
			oCoords.w = window.innerWidth - (margin * 2);
			oCoords.h = height;
		}
		else if(document.documentElement && document.documentElement.clientWidth) // MSIE standards
		{
			oCoords.x = document.documentElement.scrollLeft + margin;
			
			oCoords.y = document.documentElement.scrollTop + document.documentElement.clientHeight - height - margin * 2;
			
			if(document.documentElement.scrollTop && (e.clientY > document.documentElement.clientHeight - height - margin * 3)) oCoords.y -= height + margin * 3;
			
			oCoords.w = document.documentElement.clientWidth - (margin * 2);
			oCoords.h = height;
		}
		else if(document.body && document.body.clientWidth) // MSIE quirks
		{
			oCoords.x = document.body.scrollLeft + margin;
			
			oCoords.y = document.body.scrollTop + document.body.clientHeight - height - margin * 2;
			
			if(document.body.scrollTop && (e.clientY > document.body.clientHeight - height - margin * 3)) oCoords.y -= height + margin * 3;
			
			oCoords.w = document.body.clientWidth - (margin * 2);
			oCoords.h = height;
		}
		else 
		{
			oCoords.x = 10;
			oCoords.y = 10;
			oCoords.w = 50;
			oCoords.h = 50;
		}
		
		oCoords.x += "px";
		oCoords.y += "px";
		oCoords.w += "px";
		oCoords.h += "px";

		return oCoords;
	}

	function parseTemplate(oNode){
		var sAttribute, collOptionalAttributes;
		var oFound = {};
		var sResult = sTemplate;
		
		if(sResult.match(/content\(\)/)){
			sResult = sResult.replace(/content\(\)/g, getContentOfNode(oNode));
		}
		
		var collSearch = sResult.split(/attr\(/);
		for(var i = 1; i < collSearch.length; i++){
			sAttribute = collSearch[i].split(")")[0];
			oFound[sAttribute] = oNode.getAttribute(sAttribute);
		}
		
		var collOptional = sResult.split("?")
		for(var i = 1; i < collOptional.length; i += 2){
			collOptionalAttributes = collOptional[i].split("attr(");
			for(var j = 1; j < collOptionalAttributes.length; j++){
				sAttribute = collOptionalAttributes[j].split(")")[0];

				if(!oFound[sAttribute]){ sResult = sResult.replace(new RegExp("\\?[^\\?]*attr\\("+sAttribute+"\\)[^\\?]*\\?", "g"), "");	}
			}
		}
		sResult = sResult.replace(/\?/g, "");
		
		for(sAttribute in oFound){
			sResult = sResult.replace("attr\("+sAttribute+"\)", oFound[sAttribute]);
		}
		
		return sResult;
	}
		
	function getContentOfNode(oNode){
		var sContent = "";
		var oSearch = oNode.firstChild;

		do {
			if(oSearch.nodeType == 3){
				sContent += oSearch.nodeValue;
			} else if(oSearch.nodeType == 1 && oSearch.hasChildNodes){
				sContent += getContentOfNode(oSearch);
			}
		} while(oSearch.nextSibling && (oSearch = oSearch.nextSibling));

		return sContent;
	}
	
}
	
//=====================================================================
// Event Listener
// by Scott Andrew - http://scottandrew.com
// edited by Mark Wubben, <useCapture> is now set to false
//=====================================================================
function addEvent(obj, evType, fn){
	if(obj.addEventListener){
		obj.addEventListener(evType, fn, false); 
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	} else {
		return false;
	}
}

//=====================================================================
// Here the default nice titles are created
//=====================================================================
NiceTitles.autoCreation = function(){
	var anchors, inserts, deletions, acronyms, abbreviations, i;

	if(!document.getElementsByTagName){ return; }

	function rewriteDateTime(collNodes){
		var month, day, strDate, newDate, i;
		for(i = 0; i < collNodes.length; i++){
			if((strDate = collNodes[i].getAttribute("datetime"))){
				month = strDate.substring(5,7);
				day = strDate.substring(8,10);
				if(month[0] == '0'){ 	month = month[1];	}
				if(day[0] == '0'){ day = day[1]; 	}
				newDate = new Date(strDate.substring(0,4), month-1, day, strDate.substring(11,13), strDate.substring(14,16), strDate.substring(17,19));
				collNodes[i].setAttribute("customdatetime", newDate.toString());
			}
		}
	}

	NiceTitles.autoCreated = {};
	
	NiceTitles.autoCreated.anchors = new NiceTitles("<p class=\"titletext\">attr(nicetitle)? <span class=\"accesskey\">[attr(accesskey)]</span>?</p> <p class=\"destination\"><nobr><span class=\"prefix\">&raquo;</span>&nbsp;attr(href)</nobr></p>");
	if(!(anchors = document.links)){ anchors = document.getElementsByTagName("a");	}
	NiceTitles.autoCreated.anchors.addElements(anchors, "title", 0);
	
	NiceTitles.autoCreated.paragraphs = new NiceTitles("<p class=\"titletext\">attr(nicetitle)</p>");
	paragraphs = document.getElementsByTagName("p");
	NiceTitles.autoCreated.paragraphs.addElements(paragraphs, "title");
	
	/*
	NiceTitles.autoCreated.inserts = new NiceTitles("<p class=\"titletext\">Added on attr(nicetitle)</p>?<p class=\"destination\">Reason: attr(cite)</p>?");
	inserts = document.getElementsByTagName("ins");
	rewriteDateTime(inserts);
	NiceTitles.autoCreated.inserts.addElements(inserts, "customdatetime");
	
	NiceTitles.autoCreated.deletions = new NiceTitles("<p class=\"titletext\">Deleted on attr(nicetitle)</p>?<p class=\"destination\">Reason: attr(cite)</p>?");
	deletions = document.getElementsByTagName("del");
	rewriteDateTime(deletions);
	NiceTitles.autoCreated.deletions.addElements(deletions, "customdatetime");
	*/
	
	NiceTitles.autoCreated.acronyms = new NiceTitles("<p class=\"titletext\">content(): attr(nicetitle)</p>");	
	acronyms = document.getElementsByTagName("acronym");
	NiceTitles.autoCreated.acronyms.addElements(acronyms, "title");
	
	NiceTitles.autoCreated.abbreviations = new NiceTitles("<p class=\"titletext\">content(): attr(nicetitle)</p>");	
	abbreviations = document.getElementsByTagName("abbr");
	NiceTitles.autoCreated.acronyms.addElements(abbreviations, "title");	
}

addEvent(window, "load", NiceTitles.autoCreation);
