
// created by: Geoff Pack, November 2009
// last modified: December 2009

// merges: common.js & index.js
// social_bookmarking.js


// -------------------------------------------------------------------------------
// utility functions

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

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

// comments, rules popups
function popUp(URL) {
	window.open(URL,'popUp','toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=520,height=450,left=390,top=312');
}
function popup(URL) {
	window.open(URL,'popUp','toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=560,height=500,left=390,top=312');
	return false;
}

// Show/Hide functions clean up later...
function show(id) {
	document.getElementById(id).style.display = 'block';
}

function hide(id) {
	document.getElementById(id).style.display = 'none';
}

function toggle(id) {
	if (document.getElementById(id).style.display == 'none') {
			document.getElementById(id).style.display = 'block';
	} else {
		document.getElementById(id).style.display = 'none';
	}
	return false;
}

function hasClass (element, theclass) {
	var reg = new RegExp('(^| )'+theclass+'( |$)', 'g');
	if (element.className.search(reg) == -1) {
		return false;
	} else {
		return true;
	}
}

function sendData(url) {
	// sends data to remote url
	var script = document.createElement('SCRIPT');
	script.setAttribute('src',url);
	document.getElementsByTagName('HEAD')[0].appendChild(script); 
}

function getData(url) {
	// retrieves data from remote url
	// callback function is fixCommentNumbers('id':n, ... 's0':0);
	var script = document.createElement('SCRIPT');
	script.setAttribute('src',url);
	document.getElementsByTagName('HEAD')[0].appendChild(script); 
}

function findCurrentPage() {
	// adds a class to the contributors A-Z nav corresponding to the current page
	// there are two lists to modify	
	var listWrappers = ['find','findMore'];
	var temp;
	
	for (var k=0; k<listWrappers.length; k++) {
		if (document.getElementById(listWrappers[k])) {
			var listitems = document.getElementById(listWrappers[k]).getElementsByTagName("UL")[0].getElementsByTagName("LI");	

			for (var i=0; i<listitems.length; i++) {
				// IE is dropping leading '/' from pathname
				if (listitems[i].firstChild.pathname.charAt(0) == "/") {
					temp = listitems[i].firstChild.pathname;
				} else {
					temp = "/" + listitems[i].firstChild.pathname;
				}

				if (location.pathname == temp) {
					listitems[i].firstChild.className = "active";
				}				
				listitems[i].firstChild.href += '#find';
			}
		}
	}
}

// -------------------------------------------------------------------------------
// story pages:

function countComments() {
	// story pages only
	// counts number of comments in a page

	var storyID = document.getElementsByTagName('BODY')[0].id;
	var comments = document.getElementById('comments');
	var commentCount = 0;
	var url;
	
	if (comments) {
		var commentsHeading = comments.firstChild; // heading of comments section
		if (commentsHeading.nodeType == 3) {
			// if it's a text node, we want the next sibling
			commentsHeading = commentsHeading.nextSibling;
		}
		// count comments: <p class="comment">	
		var paras = document.getElementsByTagName('P');
		
		for (var i in paras) {
			if (paras[i].className == 'comment') commentCount++;
		}

		if (!isNaN(commentCount)) {
			if (commentCount <= 0) {
				commentsHeading.innerHTML = "Be first to comment";
			} else if (commentCount == 1) {
				commentsHeading.innerHTML = '<span>1</span> comment';
			} else {
				commentsHeading.innerHTML = '<span>' + commentCount + '</span> comments';
			}
		}

		// Comments links at top of page
		var commLink = findCommentLinks();
		
		if (!isNaN(commentCount)) {
			if (commLink[0]) {
				if (commentCount <= 0) {
					commLink[0].innerHTML = 'Be first to comment';
				} else if (commentCount == 1) {
					commLink[0].innerHTML = '<span>1</span> comment';
				} else {
					commLink[0].innerHTML = '<span>' + commentCount + '</span> comments';
				}
			}
		}
		
		// send the count to a server so we can use it on the index pages...
		// ideally, we would send a delete message if the calculated total is the same as the TMB total
		if (storyID) {
			url = 'http://www.dhillon-pack.net/unleashed/store.php?storyID=' + storyID + '&comments=' + commentCount;
			sendData(url);
		}
	}
}


// -------------------------------------------------------------------------------
// index pages:

function findCommentLinks() {
	// finds all comments links on unleashed index pages
	// comment numbers are of the form <p class="comments"><a href="...">(0 comments)</a></p>
	
	var paras = document.getElementsByTagName('p');
	var commentLinks = [];
	var k=0;
	
	for (var i=0, j=paras.length; i<j; i++) {
		if (paras[i].className == "comments") {
			// copy firstchild (anchor) to commentLinks array
			commentLinks[k] = paras[i].firstChild;
			k++;
		}
	}
	return commentLinks;
}

function fixCommentNumbers(obj) {
	// updates comment numbers on index pages using data from a remote text file
	// and reformats existing comments text

	var commentLinks = findCommentLinks();
	
	for (var i=0, j=commentLinks.length; i<j; i++) {
		// for each comment link, extract the storyID from the href
		var numComments;
		var link = commentLinks[i];

		var storyID = link.href.split('stories/')[1].substring(0,8);
		
		// is there a matching storyID in the returned object?
		if (obj[storyID] != undefined) {
			numComments = parseInt(obj[storyID]);
		} else {
			numComments = link.innerHTML.trim().split(' comment')[0].substring(1);
			//alert(numComments);
		}
		
		// re-write comments text
		if (!isNaN(numComments)) {
			if (numComments <= 0) {
				link.innerHTML = 'Be first to comment';
			} else if (numComments == 1) {
				link.innerHTML = '<span>1</span> comment';
			} else {
				link.innerHTML = '<span>' + numComments + '</span> comments';
			}
		}
	}
}

function getCommentNumbers() {
	// index pages
	// for now get all results: in future, request specific story IDs
	getData('http://www.dhillon-pack.net/unleashed/retrieve.php');
}

function swapMissingImages() {
	// swap out missing images with dummy.gif
	// i.e. src = ??Multimedia4?? or empty or end in 'unleashed/'	
	var imgs = document.getElementsByTagName('img');
	
	for (var i=0, j=imgs.length; i<j; i++) {
		var currImg = imgs[i];		
		if ((currImg.src.indexOf('??Multimedia4??') != -1) || (currImg.src.match(/unleashed\/$/) != null) || (currImg.src == '')) {
			currImg.src = '/unleashed/images/dummy.gif';
			currImg.alt = '';
			currImg.title = '';
			//currImg.setAttribute('alt','x');
			//alert(currImg.alt);
		}
	}
}


// -------------------------------------------------------------------------------

function init() {
	var bodyObj = document.getElementsByTagName('body')[0];
	bodyID = bodyObj.id;	
	//alert(bodyID);
	
	if (hasClass(bodyObj,'story_page') || hasClass(bodyObj,'bio_page')) {
		// story page
		hide('social_bookmarking');
		// fix comment numbers
		countComments();

	} else if (hasClass(bodyObj,'home') || hasClass(bodyObj,'archive')){
		// home or archive page

		// add dummy images for missing Multimedia4 ?
		swapMissingImages();		

		// fix comment numbers
		getCommentNumbers();
		
	} else if (hasClass(bodyObj,'contributors')){
		// if a contributor index page, highlight current letter
		findCurrentPage();
	}	
}
addLoadEvent(init);


