window.onload = init;

document.write('<style type="text/css">');
document.write("#exp img { display: none; }");
document.write('</style>');

function init () {
	showRandImg();
	if ($('yider') && $('searchForm')) {
		$('searchForm').onsubmit = checkSearch;
	}
	var forms = document.getElementsByTagName('form');
	for (var i = 0; i < forms.length; i++) {
		if (forms[i].id != 'yider' && window.location.toString().indexOf('search.asp') == -1) {
			clearInputs(forms[i])
		}
	}
	if ($('newsAlertForm')) {
		$('newsAlertForm').onsubmit = 'checkENews';
	}
	Jargon.init();
}

function checkENews() {
	var fields = ['Name', 'EmailAddress', 'Password'];
	var incompleteFields = [];
	for (var i = 0; i < fields.length; i++) {
		if ($(fields[i]).value.length == 0) {
			incompleteFields[incompleteFields.length] = $(fields[i]).name;
		}
	}
	if (incompleteFields.length == 0) {
		// validate email
		if (!/^([a-z0-9+_]|\-|\.)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/i.test($('EmailAddress').value)) {
			alert('The email address entered is invalid.');
			return false;
		}
		return true;
	}
	var msg = 'The following fields are required:\n';
	for (var i = 0; i < incompleteFields.length; i++) {
		msg += '\no) ' + incompleteFields[i];
	}
	alert(msg);
	return false;
}

function checkSearch () {
	var ok = true;
	var yider = $('yider');
	if (!yider || !$('searchForm')) {
		return false;
	}
	if (yider.value.length == 0) {
		alert('You must enter some text to search for!');
		yider.focus();
		ok = false;
	}
	else if (yider.value.search(/\*/) != -1 && yider.value.search(/\s/) != -1) {
		alert('If you are using the * to generalise your search, you can only search for one word at a time!');
		yider.focus();
		ok = false;
	}
	else if (yider.value.search(/^\S+\*\S+$/) != -1) {
		alert('You can only use the * at the beginning or end of your search term');
		yider.focus();
		ok = false;
	}
	else if (yider.value == '*') {
		alert('You cannot search for a general * character!');
		yider.focus();
		ok = false;
	}
	return ok;
}

var clearedInputs = new Array();
function inputClear (o) {
	var o = $(o);
	if (!o) {
		return;
	}
	o.value = '';
	for (var i = 0; i < clearedInputs.length; i++) {
		if (clearedInputs[i] == o) {
			return;
		}
	}
	clearedInputs[clearedInputs.length] = o;
}

function clearInputs(formObj) {
	var inputs = formObj.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == 'text') {
			inputClear(inputs[i]);
		}
	}
	var inputs = formObj.getElementsByTagName('textarea');
	for (var i = 0; i < inputs.length; i++) {
		inputClear(inputs[i]);
	}
}

function showRandImg () {
	var o = $('exp');
	if (!o) {
		return;
	}
	var baseImg = 'http://www.mwrlaw.com/wp-content/themes/mwrlaw/images/exps/exp';
	var noOfImages = 1;
	var img = document.createElement('img');
	img.alt = '';
	img.src = baseImg + (Math.floor(Math.random() * noOfImages) + 1) + '.jpg';
	img.style.display = 'block';
	while (o.childNodes.length > 0) {
		o.removeChild(o.childNodes[0]);
	}
	if (o) {
		o.appendChild(img);
	}
}

function $(element) {
	if (typeof element == 'string' && element.length > 0) {
		element = document.getElementById(element);
	}
	return element;
}

function $t(str) {
	return document.createTextNode(str);
}

Jargon = {
	xmlfile:	'http://www.mwrlaw.com/wp-content/themes/mwrlaw/jargon.xml',
	xml:		null,
	wordHolder:	'words',
	defHolder:	'definition',
	idprefix:	'jargon_',
	selected:	null,
	init:		function () {
	    var con = Jargon.xhcon();
		Jargon.wordHolder = $(Jargon.wordHolder);
		Jargon.defHolder = $(Jargon.defHolder);
	    if (!con || !Jargon.wordHolder || !Jargon.defHolder) {
			return;
		}

		function conComplete(oXML) {
			Jargon.xml = oXML.responseXML;
			//Jargon.showWords('a');
		}
		con.connect(Jargon.xmlfile, 'GET', Math.random(), conComplete);
	},
	showWords:	function (c) {
		if (Jargon.selected) {
			Jargon.selected.className = '';
		}
		var words = Jargon.getWords(c);
		while (Jargon.wordHolder.childNodes.length > 0) {
			Jargon.wordHolder.removeChild(Jargon.wordHolder.childNodes[0]);
		}
		while (Jargon.defHolder.childNodes.length > 0) {
			Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
		}
		for (var i = 0; i < words.length; i++) {
			var o = document.createElement('a');
			o.href = 'javascript:Jargon.showDef(\'' + words[i].id + '\');';
			o.id = Jargon.idprefix + words[i].id;
			//o.onclick = Jargon.showDef;
			o.appendChild($t(words[i].name));
			Jargon.wordHolder.appendChild(o);
			Jargon.wordHolder.appendChild(document.createElement('br'));
		}
		if (!words.length) {
			var o = document.createElement('p');
			var s = 'There are no words for the letter ' + c.toUpperCase();
			Jargon.wordHolder.appendChild(o.appendChild($t(s)));
		} 
	},
	showDef:	function (id) {
		var o = $(Jargon.idprefix + id);
		if (Jargon.selected) {
			Jargon.selected.className = '';
		}
		if (o) {
			o.className = 'selected';
			Jargon.selected = o;
		}
		var defobjs = Jargon.getDef(id);

		while (Jargon.defHolder.childNodes.length > 0) {
			Jargon.defHolder.removeChild(Jargon.defHolder.childNodes[0]);
		}
		for (var i = 0; i < defobjs.length; i++) {
			Jargon.defHolder.appendChild(Jargon.cloneNode(defobjs[i], true));
		}
		return;
		//return false;
	},
	getWords:	function(c) {
		var x = Jargon.xml;
		var letters = x.getElementsByTagName('letter');
		var oLetter = null;
		for (var i = 0; i < letters.length; i++) {
			if (letters[i].getAttribute('id') == c) {
				oLetter = letters[i];
				break;
			}
		}
		if (!oLetter) {
			return [];
		}

		var words = [];
		for (i = 0; i < oLetter.childNodes.length; i++) {
			var oJargon = oLetter.childNodes[i];
			if (oJargon.nodeName == 'jargon') {
				var s = Jargon.getName(oJargon);
				words[words.length] = {
					id: oLetter.childNodes[i].getAttribute('id'),
					name: s
				};
			}
		}
		return words;
	},
	getDef:		function (id) {
		var x = Jargon.xml;
		var j = null;
		var jargons = x.getElementsByTagName('jargon');
		for (var i = 0; i < jargons.length; i++) {
			if (jargons[i].getAttribute('id') == id) {
				j = jargons[i];
				break;
			}
		}
		if (!j) {
			return [];
		}
		for (i = 0; i < j.childNodes.length; i++) {
			if (j.childNodes[i].nodeName == 'desc') {
				return j.childNodes[i].childNodes;
			}
		}
		return [];
	},
	cloneNode:	function (oldNode, deep) {
		deep = (deep) ? true : false;
		// a replacement to the normal dom clone node
		// this will copy xml nodes to html nodes
		// which can then be inserted into the document
		// scope in all browsers
		// See for for the bug http://www.quirksmode.org/blog/archives/2005/12/xmlhttp_notes_c.html
		var newNode = null;
		if (oldNode.nodeType == '3') {
			// textnode
			newNode = $t(oldNode.nodeValue);
		}
		else if (oldNode.nodeType == '1') {
			// element node
			newNode = document.createElement(oldNode.nodeName);
			if (deep) {
				for (var i = 0; i < oldNode.childNodes.length; i++) {
					newNode.appendChild(Jargon.cloneNode(oldNode.childNodes[i], true));
				}
			}
		}
		return newNode;
	},
	getName:	function (oJargon) {
		for (var i = 0; i < oJargon.childNodes.length; i++) {
			if (oJargon.childNodes[i].nodeName == 'name') {
				var oName = oJargon.childNodes[i];
				var s = '';
				for (var j = 0; j < oName.childNodes.length; j++) {
					if (oName.childNodes[j].nodeType == 3) {
						// text node
						s += oName.childNodes[j].nodeValue;
					}
				}
				return s;
			}
		}
		return '';
	},
	xhcon:		function () {
		var xmlhttp, bComplete = false;
		try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) { try { xmlhttp = new XMLHttpRequest(); }
		catch (e) { xmlhttp = false; }}}
		if (!xmlhttp) {
			return null;
		}
		this.connect = function(sURL, sMethod, sVars, fnDone) {
			if (!xmlhttp) {
				return false;
			}
			bComplete = false;
			sMethod = sMethod.toUpperCase();
	
			try {
				if (sMethod == "GET") {
					xmlhttp.open(sMethod, sURL+"?"+sVars, true);
					sVars = "";
				}
				else {
					xmlhttp.open(sMethod, sURL, true);
					xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
					xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}
				xmlhttp.onreadystatechange = function() {
					if (xmlhttp.readyState == 4 && !bComplete) {
						bComplete = true;
						fnDone(xmlhttp);
					}
				};
				xmlhttp.send(sVars);
			}
			catch(z) { return false; }
			return true;
		};
		return this;
	}
}



/************************************************
*                                               *
*            Date object                        *
*                                               *
************************************************/

// format is used in a similar way to http://uk.php.net/date
// restricted chars must be escaped with a '\', however in javascript
// when writing the string the '\' itself must be escaped
// E.g. var str = new Date().format('\\Year: Y');  -> Year: 2005
//      var str = new Date().format('\Year: Y');   -> 2005ear: 2005
// note only the 1 '\' in the second example
Date.prototype.format = function (str) {
  this.procProps();
  var pos = 0;
  var buff = '';
  var esc = false;
  while (pos < str.length) {
    var c = str.charAt(pos);
    if (c == '\\' && !esc) {
      esc = true;
    }
    else if (this.isReservedChar(c) && !esc) {
      buff += eval('this.' + c);
    }
    else {
      buff += c;
      esc = false;
    }
    pos++;
  }
  return buff;
}
Date.prototype.isReservedChar = function (c) {
  for (var i = 0; i < this.reservedChars.length; i++) {
    if (this.reservedChars[i] == c) {
      return true;
    }
  }
  return false;
}
Date.prototype.strPad = function (strIn, padLength) {
  var strPad = '0';
  var strIn = new String(strIn);
  var j = strIn.length;
  for (var i = j; i < padLength; i++) {
    strIn = strPad + strIn;
  }
  return strIn;
}
Date.prototype.procProps = function () {
  // see http://uk.php.net/date for a list of the properties
  // D - A textual representation of a day, three letters (Sun through Sat)
  // l (lowercase 'L') - A full textual representation of the day of the week (Sunday through Saturday)
  // d - Day of the month, 2 digits with leading zeros (01 to 31)
  // j - Day of the month without leading zeros (1 to 31)
  // F - A full textual representation of a month, such as January or March (January through December)
  // m - Numeric representation of a month, with leading zeros (01 through 12)
  // M - A short textual representation of a month, three letters (	Jan through Dec)
  // Y - A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
  // y - A two digit representation of a year (Examples: 99 or 03)
  // H - 24-hour format of an hour with leading zeros (00 through 23)
  // i - Minutes with leading zeros (00 to 59)
  // s - Seconds, with leading zeros (00 through 59)
  // S - English ordinal suffix for the day of the month, 2 characters (st, nd, rd & th)
  this.reservedChars = ['D', 'l', 'd', 'j', 'F', 'm', 'M', 'Y', 'y', 'H', 'i', 's', 'S'];
  if (isNaN(this.getDate()) || isNaN(this.getMonth()) || isNaN(this.getFullYear())) { 
    this.setFullYear(1900, 0, 1);
  }
  var shortDays = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
  var longDays = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  var monthNames = new Array ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
  var shortMonthNames = new Array ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  this.D = shortDays[this.getDay()];
  this.l = longDays[this.getDay()];
  this.d = this.strPad(this.getDate(), 2);
  this.j = this.getDate();
  this.F = monthNames[this.getMonth()];
  this.m = this.strPad(this.getMonth() + 1, 2);
  this.M = shortMonthNames[this.getMonth()];
  this.Y = this.getFullYear();
  this.y = (this.getYear() > 100) ? this.strPad(this.getYear() - 100, 2) : this.strPad(this.getYear(), 2);
  this.i = this.strPad(this.getMinutes(), 2);
  this.H = this.strPad(this.getHours(), 2);
  this.s = this.strPad(this.getSeconds(), 2);
  switch (this.getDate()) {
    case 1:
      this.S = 'st';
      break;
    case 2:
      this.S = 'nd';
      break;
    case 3:
      this.S = 'rd';
      break;
    case 21:
      this.S = 'st';
      break;
    case 22:
      this.S = 'nd';
      break;
    case 23:
      this.S = 'rd';
      break;
    case 31:
      this.S = 'st';
      break;
    default:
      this.S = 'th';
      break;
  }
}
