/*
 * JavaScript Functions
 * Author: Paul Caselton (Century Media)
 * Date: 13/06/2010
 * Revision: 0.1
 */

try {
	// Attemp to create AJAX connection
	var bs = new AjaxConnection('ajaxActions.php');

	// Connection ok, set the connected variable
	connected = true;

} catch (e) {
	alert("Cannot connect to the server!");
}


// Display a hidden DOM object
function popObj(targetId, objId) {
	if (checkObj(targetId) && checkObj(objId)) {
		var loc = objLoc(targetId);
		var obj = document.getElementById(objId);
		obj.style.top = loc[1]+'px';
		obj.style.left = loc[0]+'px';
		obj.style.display = 'block';
	}
}


// Function to create new DOM node
function createNode(targetId, type, attributes) {
	// For non-text elements/nodes...
	if (type != 'text') {
		var node = document.createElement(type);
		// Check for array
		if (attributes.length > 0) {
			// Loop through attributes list
			for (i = 0; i < attributes.length; i++) {
				eval('node.setAttribute(' + attributes[i] + ')');
			}
		}

	// ...else, for text nodes.
	} else if (type == 'text') {
		var node = document.createTextNode(attributes);
	}
	// Append new node to the DOM
	document.getElementById(targetId).appendChild(node);
}


// Function to remove DOM node
function removeNode(childId) {
	var parentId = document.getElementById(childId).parentNode.id;
	var pNode = document.getElementById(parentId);
	var node = document.getElementById(childId);
	pNode.removeChild(node);
}


// Work our coords for the given object
function objLoc(theId) {
	var obj = document.getElementById(theId);
	var cLeft = 0;
	var cTop = 0;
	// Only work with modern DOM compliant browsers
	if (document.getElementById) {
		// Loop until we reach the top of the tree
		while (obj.offsetParent) {
			cLeft += obj.offsetLeft;
			cTop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	var pos = new Array(cLeft, cTop);
	return pos;
}


// Function to generate external links
function extLinks(targetName) {
	// Check the browser can cope...
	if (document.getElementsByTagName) {
		// Init anchors var(s)
		var anchors = document.getElementsByTagName("a");
		var anchor = new Array();
		// Loop through all anchors in the doc
		for (var i = 0; i < anchors.length; i++) {
			anchor = anchors[i];
			// Check for proper link and rel attribute
			if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "nofollow") {
				anchor.target = targetName;
			}
		}
	}
}


// Handle for onLoad events
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
