// Capita HR & Payroll - JavaScript Functions

function addLoadEvent(func) {
	var oldonload = window.onload
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function addClass(element, value) {
	if (!element.className) {
		element.className = value;
	} else {
		newClassName = element.className;
		newClassName+= ' ' + value;
		element.className = newClassName;
	}
}

function stripeTables() {
	if (!document.getElementsByTagName) return false;
	var tables = document.getElementsByTagName('table');
	for (var i=0; i<tables.length; i++) {
		if (tables[i].className.indexOf('stripe') == -1) continue;
		var odd = false;
		var rows = tables[i].getElementsByTagName('tr');
		for (var j=1; j<rows.length; j++) {
			if (odd == true) {
				addClass(rows[j],'stripe');
				odd= false;
			} else {
				odd = true;
			}
		}
	}
}

function initialiseFields(whichform) {
	for (var i=0; i<whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if (element.type == 'submit') continue;
		if (element.type == 'password') continue;
		if (element.getAttribute('id') == 'txtUsername') continue; // don't add the title to the txtUsername field on the User Group login
		element.value = element.title;
		element.onfocus = function() {
			if (this.value == this.title) {
				this.value = '';
			}
		}
		element.onblur = function() {
			if (this.value == '') {
				this.value = this.title;
			}
		}
	}
}

function removeDefaults(whichform) {
	for (var i=0; i<whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if (element.type == 'submit') continue;
		if (element.type == 'text' && element.value == element.title) {
			element.value = '';
		}
	}
}
	
function initialiseForms() {
	for (var i=0; i<document.forms.length; i++) {
		var thisform = document.forms[i]
		initialiseFields(thisform);
		thisform.onsubmit = function() {
			removeDefaults(this);
		}
	}
}

function openWindow(href, name, width, height, top, left) {
	var windowDetails = 'width=' + width;
	windowDetails+= ', height=' + height;
	windowDetails+= ', top=' + top;
	windowDetails+= ', left=' + left;
	windowDetails+= ', scrollbars';
	var newWindow = window.open(href, name, windowDetails);
	return false
}

function mapLink() {
	if (!document.getElementById) return false;
	if (!document.getElementById('map-link')) return false;
	var mapLink = document.getElementById('map-link');
	mapLink.onclick = function() {
		return openWindow(this.href, 'maps', 470, 400, 100, 100);
	}
}

addLoadEvent(stripeTables);
addLoadEvent(initialiseForms);
addLoadEvent(mapLink);