/* TODO: required?
HTMLInputElement.prototype.base_focus = HTMLInputElement.prototype.focus;
HTMLInputElement.prototype.focus = function() {
	this.select();
	this.base_focus();
}
*/

function getEvent(e) {
	if(e) {
		return e;
	} else if(window.event) {
		return window.event;
	}
}

function getEventSource(e, o) {
	if(e.srcElement) {
		return e.srcElement;
	} else {
		return o;
	}
}

function cancelEvent(e) {
	if(e) {
		e.cancelBubble = true;
		if(e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
	}
}

function disableConfirmChangeButton(id)
{
	var objBtn = document.getElementById(id);
	objBtn.disabled = true;
}

function insertBackButton() {
	if(document.getElementById) {
		if(window.history.length > 1) {
			var oMain = document.getElementById("bc-main");
			if(oMain) {
				var oBreadcrumb = document.getElementById("breadcrumb");
				if(oBreadcrumb) {
					oMain.className = "m";
	
					var oD = _createNode("div");
					if(oD) {
						oD.className = "b";
		
						var oA = _createNode("a");
						if(oA) {
							oA.title = "Back to previous page";
							oA.href = "javascript:window.history.go(-1)";
							oD.appendChild(oA);
			
							var oImg = _createNode("img");
							if(oImg) {
								oImg.src = "/i/b/btnBack.gif";
								oImg.alt = "Back";
								oImg.style.display = "block";
								oA.appendChild(oImg);
			
								oBreadcrumb.insertBefore(oD, oMain);
							}
						}
					}
				}
			}
		}
	}
}

function insertPrintButton(id, buttonText) {
	if(window.print) {
		return insertButton(id, buttonText, _print, "/i/b/btnPrintPage.gif");
	}
}

function insertButton(id, buttonText, functionPointer, imgSrc) {
	if(document.getElementById && document.createTextNode) {
		var o = document.getElementById(id);
		if(o) {
			var oA = _createNode("a");
			oA.style.textDecoration = "none";
			oA.href = "#";
			oA.tabIndex = -1;
			oA.setAttribute("buttonId", id);
			attachEventHandler(oA, "click", functionPointer);
			o.appendChild(oA);
	
			if(imgSrc) {
				var oImg = _createNode("img");
				oImg.src = imgSrc;
				oImg.alt = buttonText;
				oA.appendChild(oImg);
			} else {
				var oButton = _createNode("input");
				oButton.type = "button";
				oButton.value = buttonText;
				oA.appendChild(oButton);
			}
		}
	}
	
	return false;
}

function _print(e) {
	cancelEvent(getEvent(e));

	window.print();
}

function _createNode(nodeName) {
	var oNode;
	if(nodeName) {
		if(document.createElementNS) {
			oNode = document.createElementNS("http://www.w3.org/1999/xhtml", nodeName);
		} else if(document.createElement) {
			oNode = document.createElement(nodeName);
		}
	}
	
	return oNode;
}

function attachEventHandler(o, e, f) {
	if(o) {
		if(o.addEventListener) {
			o.addEventListener(e, f, false);
		} else if(o.attachEvent) {
			o.attachEvent("on" + e, f);
		}
	}
}

function formatNumber(n, decimalPlaces) {
	if(n.toFixed) {
		return n.toFixed(2);
	} else {
		if(decimalPlaces == 0) {
			return Math.round(n);
		} else {
			var i = Math.pow(10, decimalPlaces);
			return Math.round(n * i) / i;
		}
	}
}


Number.prototype.decimalPlaces = function(decimalPlaces) {
	if(this.toFixed) {
		return this.toFixed(decimalPlaces);
	} else {
		if(decimalPlaces == 0) {
			return Math.round(this);
		} else {
			var i = Math.pow(10, decimalPlaces);
			var s = new String(Math.round(this * i) / i);
			for(var ii = 0; ii < decimalPlaces - (s.length - s.indexOf(".") - 1); ii++) {
				s += "0";
			}
			return s;
		}
	}
}

// String object extensions...
String.prototype.rtrim = function() {
	return this.replace(/\s*$/,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s*/,"");
}

String.prototype.trim = function() {
	return this.ltrim().rtrim();
}

String.prototype.capitaliseFirstWord = function() {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

String.prototype.capitaliseWords = function() {
	var astrAllWords = this.split(" ");
	
	for(var i = 0; i < astrAllWords.length; i++) {
		astrAllWords[i] = astrAllWords[i].toLowerCase();
		astrAllWords[i]=  astrAllWords[i].charAt(0).toUpperCase() + astrAllWords[i].substring(1);
	}
	
	return astrAllWords.join(" ");
}

String.prototype.capitaliseFirstWord = function() {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

// These two are not complete, but works fine for now
String.prototype.URLEncode = function() {
	var s = this.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	return s;
}

String.prototype.URLDecode = function() {
	var s = this.replace(/&lt;/g, "<");
	s = s.replace(/&gt;/g, ">");
	return s;
}

function openWindow(url, title, width, height, scrollbar, focus, returnWin) {
  	var iLeft = (screen.width - width) / 2;
	var iTop = (screen.height - height) / 2;
	
	if(typeof(returnWin)=="undefined") {
		returnWin=true;
	}

	if(typeof(focus)=="undefined") {
		focus=true;
	}
	if(!scrollbar) {
		scrollbar = "no";
	} else {
		scrollbar = "yes";
	}

	var oWin = window.open(url, title, "toolbar=no,menubar=no,hotkeys=no,location=no,scrollbars=" + scrollbar + ",width=" + width + ",height=" + height + ",top=" + iTop + ",left=" + iLeft);
	if(oWin && (focus)) {
		oWin.focus();
	}
	if(returnWin) {
		return oWin;
	}
}

function textLimit(field, maxlen) {
	if (field.value.length > maxlen + 1)
		alert('Please limit your message to ' + maxlen + ' characters.');
	if (field.value.length > maxlen)
		field.value = field.value.substring(0, maxlen);
}

function setNodeTextValue(node, textValue) {
	try {
		node.innerHTML = textValue;
	} catch(e) {
		try {
			node.textContent = textValue;
		} catch(e) {
			node.innerHTML = textValue;
		}
	}
}

function getNodeTextValue(node) {
	try {
		return node.textContent;
	} catch(e) {
		return node.innerHTML;
	}
}

tdcUtils = {
	event : _event = {
		get:function(e) {
			if(e) {
				return e;
			} else if(window.event) {
				return window.event;
			}
		},
		
		getSource:function(e, o) {
			if(e.srcElement) {
				return e.srcElement;
			} else {
				return o;
			}
		},
		
		cancel:function(e) {
			if(e) {
				e.cancelBubble = true;
				if(e.preventDefault) {
					e.preventDefault();
				} else {
					e.returnValue = false;
				}
			}
		},
		
		attach:function(o, e, f) {
			if(o) {
				if(o.addEventListener) {
					o.addEventListener(e, f, false);
				} else if(o.attachEvent) {
					o.attachEvent("on" + e, f);
				}
			}
		}
	},
	
	node : _node = {
		create:function(nodeName, textValue) {
			var oNode;
			if(nodeName) {
				if(document.createElementNS) {
					oNode = document.createElementNS("http://www.w3.org/1999/xhtml", nodeName);
				} else if(document.createElement) {
					oNode = document.createElement(nodeName);
				}
				if(textValue) {
					utils.node.setTextValue(oNode, textValue);
				}
			}
			
			return oNode;
		},
		
		setTextValue:function(node, textValue) {
			try {
				node.innerHTML = textValue;
			} catch(e) {
				try {
					node.textContent = textValue;
				} catch(e) {
					node.innerHTML = textValue;
				}
			}
		},
		
		getHtmlValue:function(node) {
			try {
				return node.textContent ? node.textContent : node.innerHTML;
			} catch(e) {
				return node.innerHTML;
			}
		},
	
		getTextValue:function(node) {
			try {
				return node.textContent ? node.textContent : node.innerText;
			} catch(e) {
				return node.innerText;
			}
		},

		getTextValueNS:function(prefix, local, parentElem, index) {
			var result = utils.node.getNS(prefix, local, parentElem, index);
			if(result) {
				if (result.childNodes.length > 1) {
					return result.childNodes[1].nodeValue;
				} else {
					return result.firstChild.nodeValue;    		
				}
			} else {
				return "";
			}
		},
		
		getNS:function(prefix, local, parentElem, index) {
			var result = null;
			if(prefix && window.ActiveXObject) {
				result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
			} else {
				result = parentElem.getElementsByTagName(local)[index];
			}
			return result;
		}
	},

	form : _form = {
		originalValueAttribute : "originalValue",

		changedIndicator : _changedIndicator = {
			initialize : function(objForm) {
				if (objForm && objForm.length > 0) {
					var els = objForm.elements;
					if (els) {
						var numEls = els.length;
						for (var i = 0; i < numEls; i++) {
							var el = els[i];
							if (el) {
								el.setAttribute(this.originalValueAttribute, tdcUtils.form.elements.getValue(el));
							}
						}
					}
				}
			},
			
			hasChanged : function(objForm) {
				if (objForm && objForm.length > 0) {
					var els = objForm.elements;
					if (els) {
						var numEls = els.length;
						for (var i = 0; i < numEls; i++) {
							var el = els[i];
							if (el) {
								if (tdcUtils.form.elements.getValue(el) != el.getAttribute(this.originalValueAttribute)) {
									return true;
								}
							}
						}
					}
					return false;
				}
				return true;
			}
		},

		elements : _elements = {
			getValue : function(el) {
				if (el) {
					switch(el.nodeName.toLowerCase()) {
						case 'select':
							return el.options[el.selectedIndex].value;
						case 'checkbox':
							if (el.checked) {
								return el.name;
							}
							break;
						case 'radio':
							if (el.checked) {
								return el.name;
							}
							break;
						case 'fieldset':
							return '';
						default:
							return el.value;
					}
				}
				return '';
			}
		}
	},

	cookie : function(name, value, days, path) {
		CookieUtils = function(name, value, days, path) {
			this.name = name;
			this.value = value;
			this.path = path ? path : "/";
			this.days = days;

			this.calculateExpiry = function() {
				if (this.days) {
					var date = new Date()
					date.setTime(date.getTime()+(this.days*24*60*60*1000));
					return date.toGMTString();
				}
				else {
					return "";
				}
			}

			this.getExpiry = function() {
				var s = this.calculateExpiry();
				if (s.length > 0) return "expires=" + s;
				return "";
			}

			this.set = function() {
				document.cookie = this.name + "=" + escape(this.value) + ";" + this.getExpiry() + ";path=" + this.path +";";
			}
			
			this.get = function() {
				var nameEquals = this.name + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i < ca.length; i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEquals) == 0) return c.substring(nameEquals.length, c.length);
				}
				return null;
			}
			
			this.remove = function() {
				this.days = -1;
				this.value = "";
				this.set();
			}
		}
		return new CookieUtils(name, value, days, path);
	}
}

var trk = {
	trkCookieName : "si-trk",
	trkCookieAttribute : "siTrk",

	record : function(el) {
		if (el) {
			var useId = (el && el.id);
			var valueToRecord = useId ? el.id : tdcUtils.node.getTextValue(el);
			var siTrk = el[this.trkCookieAttribute];
			if (siTrk && siTrk.node) {
				var containerId = siTrk.node.id;
				if (containerId) valueToRecord = containerId + "-" + valueToRecord;
			}
			(new tdcUtils.cookie(this.trkCookieName, valueToRecord)).set();
		}
	},
	
	handleRecordRequest : function(event) {
		var srcA = tdcUtils.event.getSource(tdcUtils.event.get(event), this);
		if (srcA) {
			trk.record(srcA);
		}
	},
	
	recordingObject : function(node) {
		RecordingObject = function(node) {
			this.node = node;
		}
		return new RecordingObject(node);
	},

	recordGroup : function(id) {
		if (id) {
			var node = document.getElementById(id);
			if (node) {
				if (node.hasChildNodes()) {
					var anchors = node.getElementsByTagName("a");
					if (anchors) {
						var numAnchors = anchors.length;
						for (var i = 0; i < numAnchors; i++) {
							var anchor = anchors[i];
							if (anchor) {
								anchor[this.trkCookieAttribute] = new this.recordingObject(node);
								tdcUtils.event.attach(anchor, "click", this.handleRecordRequest);
							}
						}
					}
				}
			}
		}
	}
}

