function crtOpt(jObject, elemSelectId) {	
	var jsonProperties = jObject.properties;	
	
	document.getElementById(elemSelectId).innerHTML = "";
	for ( var i = 0; i < jsonProperties.length; i++) {
		var parameter = jsonProperties[i];
		var optNew = document.createElement('option');
		
		optNew.text = parameter.text;
		optNew.value = parameter.value;	
		var elemSelec = document.getElementById(elemSelectId);
		try {
			elemSelec.add(optNew, null);
		}
		catch(ex) {
			elemSelec.add(optNew);
		}
	}
}

function nextPage() {
	if (pageNumber != maxPage) {
		var pageNo = parseInt(pageNumber) + 1;
		setSiteList(pageNo);
	}
}

function previousPaginationPage() {
	if (pageNumber != 1) {
		var pageNo = parseInt(pageNumber) - 1;
		setSiteList(pageNo);
	}
}

function lastPage() {
	if (pageNumber != maxPage) {
		setSiteList(maxPage);
	}
}

function firstPage() {
	if (pageNumber != 1) {
		setSiteList(1);
	}
}

function setPagination() {
	for (var ctr = 1; ctr <= maxPage; ctr++) {
		if ((ctr <= (pageNumber + 2) && ctr >= (pageNumber - 2)) || 
				((pageNumber == 1 || pageNumber == 2) && ctr <= 5) || 
				((pageNumber == maxPage || pageNumber == (maxPage - 1)) && ctr >= (maxPage - 4))) {
			document.getElementById("pg_" + ctr).style.display = "";
		} else {
			document.getElementById("pg_" + ctr).style.display = "none";
		}
		document.getElementById("pg_" + ctr).className = "";
	}
	document.getElementById("pg_" + pageNumber).className = "list_pagination_current";
	if (pageNumber == maxPage) {
		document.getElementById("pg_next").className = "list_pagination_innactive";
		document.getElementById("pg_last").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_next").className = "list_pagination_nav";
		document.getElementById("pg_last").className = "list_pagination_nav";
	}
	if (pageNumber == 1) {
		document.getElementById("pg_first").className = "list_pagination_innactive";
		document.getElementById("pg_prev").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_first").className = "list_pagination_nav";
		document.getElementById("pg_prev").className = "list_pagination_nav";
	}
}

function setAdminPagination() {
	for (var ctr = 1; ctr <= maxPage; ctr++) {
		if ((ctr <= (pageNumber + 2) && ctr >= (pageNumber - 2)) || 
				((pageNumber == 1 || pageNumber == 2) && ctr <= 5) || 
				((pageNumber == maxPage || pageNumber == (maxPage - 1)) && ctr >= (maxPage - 4))) {
			document.getElementById("pg_" + ctr).style.display = "";
			document.getElementById("pg_top_" + ctr).style.display = "";
		} else {
			document.getElementById("pg_" + ctr).style.display = "none";
			document.getElementById("pg_top_" + ctr).style.display = "none";
		}
		document.getElementById("pg_" + ctr).className = "";
		document.getElementById("pg_top_" + ctr).className = "";
	}
	
	document.getElementById("pg_" + pageNumber).className = "list_pagination_current";
	if (pageNumber == maxPage) {
		document.getElementById("pg_next").className = "list_pagination_innactive";
		document.getElementById("pg_last").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_next").className = "list_pagination_nav";
		document.getElementById("pg_last").className = "list_pagination_nav";
	}
	if (pageNumber == 1) {
		document.getElementById("pg_first").className = "list_pagination_innactive";
		document.getElementById("pg_prev").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_first").className = "list_pagination_nav";
		document.getElementById("pg_prev").className = "list_pagination_nav";
	}

	document.getElementById("pg_top_" + pageNumber).className = "list_pagination_current";
	if (pageNumber == maxPage) {
		document.getElementById("pg_top_next").className = "list_pagination_innactive";
		document.getElementById("pg_top_last").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_top_next").className = "list_pagination_nav";
		document.getElementById("pg_top_last").className = "list_pagination_nav";
	}
	if (pageNumber == 1) {
		document.getElementById("pg_top_first").className = "list_pagination_innactive";
		document.getElementById("pg_top_prev").className = "list_pagination_innactive";
	} else {
		document.getElementById("pg_top_first").className = "list_pagination_nav";
		document.getElementById("pg_top_prev").className = "list_pagination_nav";
	}
}

function onfocusBillingAdForm(elem) {
	if (elem.id == 'lotNumber' && elem.value == 'Unit Number') {
		elem.value = '';
	} else if (elem.id == 'streetNumber' && elem.value == 'Street Number') {
		elem.value = '';
	} else if (elem.id == 'streetName' && elem.value == 'Street Name') {
		elem.value = '';
	} else if (elem.id == 'suburb' && elem.value == 'Suburb') {
		elem.value = '';
	} else if (elem.id == 'state' && elem.value == 'State') {
		elem.value = '';
	} else if (elem.id == 'postcode' && elem.value == 'Postcode') {
		elem.value = '';
	} else if (elem.id == 'abn' && elem.value == 'ABN') {
		elem.value = '';
	}
}

function onblurBillingAdForm(elem) {
	if (elem.id == 'lotNumber' && elem.value == '') {
		elem.value = 'Unit Number';
	} else if (elem.id == 'streetNumber' && elem.value == '') {
		elem.value = 'Street Number';
	} else if (elem.id == 'streetName' && elem.value == '') {
		elem.value = 'Street Name';
	} else if (elem.id == 'suburb' && elem.value == '') {
		elem.value = 'Suburb';
	} else if (elem.id == 'state' && elem.value == '') {
		elem.value = 'State';
	} else if (elem.id == 'postcode' && elem.value == '') {
		elem.value = 'Postcode';
	} else if (elem.id == 'abn' && elem.value == '') {
		elem.value = 'ABN';
	}
}

function closeBrowserWarning() {
	var browserWarning = document.getElementById("browserWarning");
  	browserWarning.style.display = "none";
}

function populateExpiryYear() {
	if (document.getElementById("expirationYear") != null) {
		var today = new Date();
		var yearField = document.getElementById("expirationYear");
		
		var thisYear = today.getFullYear();
		for (var y = 0; y < 20; y++) {
			yearField.options[y] = new Option(thisYear, thisYear.toString());
			thisYear += 1;
		}
		yearField.options[0] = new Option(today.getFullYear(), today.getFullYear().toString(), true, true);
	}
}

function showCreditCardInfo() {
	var isNewCreditCard = document.getElementById("newCreditCard").checked;
	if (isNewCreditCard) {
		document.getElementById("creditCardTypeContainer").style.display = "block";
		document.getElementById("cardNumberContainer").style.display = "block";
		document.getElementById("cardNameContainer").style.display = "block";
		document.getElementById("securityCodeContainer").style.display = "block";
		document.getElementById("expirationDateContainer").style.display = "block";
		document.getElementById("isDefaultCardContainer").style.display = "block";
	} else {
		document.getElementById("creditCardTypeContainer").style.display = "none";
		document.getElementById("cardNumberContainer").style.display = "none";
		document.getElementById("cardNameContainer").style.display = "none";
		document.getElementById("securityCodeContainer").style.display = "none";
		document.getElementById("expirationDateContainer").style.display = "none";
		document.getElementById("isDefaultCardContainer").style.display = "none";
	}
}

function showMeSecurityCode() {
	var showMeSecurityCode = document.getElementById("showMeSecurityCode");
	if (showMeSecurityCode.style.display == "none") {
		showMeSecurityCode.style.display = "block";
	} else {
		showMeSecurityCode.style.display = "none";
	}
}

function redirectClaimPropertyForm() {
	var formPage = document.getElementById("claimPropertyFormPage").value;
	window.location.href = formPage;
}

function comparableSalesView(view) {
	var content = document.getElementById('comparableSalesContent');
	var viewAllButton = document.getElementById('viewAllButton');
	if (content != null && viewAllButton != null) {
		if (view == 'display') {
			content.style.display = 'block';
			viewAllButton.style.display = 'none';
		} else {
			content.style.display = 'none';
			viewAllButton.style.display = 'block';
		}
	}
}

function didWeMissSomethingView(view) {
	var message = document.getElementById('missSomethingMessage');
	var thankYou = document.getElementById('missSomethingThankYou');
	var fields = document.getElementById('missSomethingFields');
	if (message != null && thankYou != null && fields != null) {
		if (view == 'display') {
			message.style.display = 'none';
			thankYou.style.display = 'block';
			fields.style.display = 'block';
		} else {
			message.style.display = 'block';
			thankYou.style.display = 'none';
			fields.style.display = 'none';
		}
	}
}

function btnActive(val){	
	var index = val.split("_");	
	var elemId = index[0];
	var elemNum = index[1];
	var elemLength = index[2];	
	var cont = "active";
	
	if (document.getElementById(elemId + elemNum + 'liForSale')) {
		cont = (document.getElementById(elemId + elemNum + 'liForSale').className != "active") ? "no" : "active";
	} else {
		cont = (document.getElementById(elemId + elemNum + 'li').className != "active") ? "no" : "active";
	}
	
	if (cont != "active") {
		for(var x=0; x<=elemLength; x++){			
			if(document.getElementById(elemId + x + 'liForSale')) {
				document.getElementById(elemId + x + 'liForSale').className = "tabforSale";
			} else {
				document.getElementById(elemId + x + 'li').className = "menu";
			}	
			document.getElementById(elemId + x + 'span').className = 'spanI';
		}
		
		if(document.getElementById(elemId + elemNum + 'liForSale')) {
			document.getElementById(elemId + elemNum + 'liForSale').className = "active";
		} else {
			document.getElementById(elemId + elemNum + 'li').className = "active";
		}
		document.getElementById(elemId + elemNum + 'span').className = "spanA";		
	}
}

function onhover(val){
	val.className = "menu_headA";
}

function outhover(val){
	val.className = "menu_headI";
}

function previousPage() {
	history.go(-1);
}

function displayElement(elemId) {
	var elem = document.getElementById(elemId);
	if (elem == null)
		return false;
	
	elem.className = '';
	return true;
}

function onfocusFormLabel(elem) {
	if (elem.value == elem.defaultValue) {
		elem.value = '';
	}
}

function onblurFormLabel(elem) {
	if (elem.value == '') {
		elem.value = elem.defaultValue;
	}
}

function onfocusLoginForm(elem) {
	if (elem.id == 'userName' || elem.id == 'userNameLabel') {
		var userNameLabel = document.getElementById('userNameLabel');
		userNameLabel.style.display = 'none';
		if (elem.id == 'userNameLabel') {
			var userName = document.getElementById('userName');
			userName.focus();
		}
	} else if (elem.id == 'password' || elem.id == 'passwordLabel') {
		var passwordLabel = document.getElementById('passwordLabel');
		passwordLabel.style.display = 'none';
		if (elem.id == 'passwordLabel') {
			var password = document.getElementById('password');
			password.focus();
		}
	}
}

function onblurLoginForm(elem) {
	if (elem.id == 'userName') {
		if (elem.value == '') {
			var userNameLabel = document.getElementById('userNameLabel');
			userNameLabel.style.display = 'block';
		}
	} else if (elem.id == 'password') {
		if (elem.value == '') {
			var passwordLabel = document.getElementById('passwordLabel');
			passwordLabel.style.display = 'block';
		}
	}
}

function getParam(name) {
	hu = window.location.search.substring(1);
	params = hu.split("&");
	for (i = 0; i < params.length; i++) {
		prop = params[i].split("=");
		if (prop[0] == name) {
			return prop[1];
		}
	}
}

function createList(entity) {
	var ids = document.getElementById(entity + "Ids").value.split(",");
	var list = "";
	var item = "";
	if (ids != null && ids.length != 0) {
		list += "<table cellspacing='0' cellpadding='0' class='form form_text'>";
	}
	for (var ctr = 1; ctr < ids.length; ctr++) {
		document.getElementById(entity + "s").value = ids[ctr];
		var id = document.getElementById(entity + "s").selectedIndex
		item = document.getElementById(entity + "s").options[id].innerHTML;
		list += "<tr><td width='30px'>&nbsp;</td><td width='220px'><span>" + item + "</span></td><td><input type='button' onclick='deleteItem(\"" + entity + "\"," + ids[ctr] + ");' value='Delete'/></td></tr>";
	}
	if (ids != null && ids.length != 0) {
		list += "</table>";
	}
	document.getElementById(entity + "List").innerHTML = list;
	document.getElementById(entity + "s").selectedIndex = 0;
}

function addItem(entity) {
	var index = document.getElementById(entity + "s").selectedIndex;
	if (index != 0) {
		var id = document.getElementById(entity + "s").options[index].value;
		var ids = document.getElementById(entity + "Ids").value.split(",");
		var item = document.getElementById(entity + "s").options[index].innerHTML;
		var isExists = false;
		for (var ctr = 1; ctr < ids.length; ctr++) {
			if (ids[ctr] == id.toString()) {
				isExists = true;
				break;
			}
		}
		if (!isExists) {
			document.getElementById(entity + "Ids").value += "," + id;
		} else {
			alert(item + " already exists.");
		}
		createList(entity);
	}
}

function addAllItems(entity) {
	var index = document.getElementById(entity + "s").selectedIndex;
	var items = document.getElementById(entity + "s").options;
	if (items.length != 0) {
		if (index == 0) {
			for (var i = 1; i < items.length; i++) {
				var id = document.getElementById(entity + "s").options[i].value;
				var ids = document.getElementById(entity + "Ids").value.split(",");
				var isExists = false;
				for (var ctr = 1; ctr < ids.length; ctr++) {
					if (ids[ctr] == id.toString()) {
						isExists = true;
						break;
					}
				}
				if (!isExists) {
					document.getElementById(entity + "Ids").value += "," + id;
				}
			}
			createList(entity);
		} else {
			addItem(entity);
		}
	}
}

function deleteItem(entity, id) {
	var ids = document.getElementById(entity + "Ids").value.split(",");
	var idsValue = "";
	for (var ctr = 1; ctr < ids.length; ctr++) {
		if (ids[ctr] != id.toString()) {
			idsValue += "," + ids[ctr];
		}
	}
	document.getElementById(entity + "Ids").value = idsValue;
	createList(entity);
}

function viewProperty(propertyLink) {
	window.location.href = propertyLink;
}

function cancelForm() {
	history.go(-1);
	//window.location.href = window.location.href; ---- changes back to previous page
}

function cancelFormButtn(url) {
	window.location.href = url;
}

function reloadForm() {
	window.location.href = window.location.href;
}

function validateNumber(e, field, isDecimal) {
	var evt = e || window.event;
	var key = evt.keyCode || evt.which;
	if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 46)) {
		return false;
		if (theEvent.preventDefault) theEvent.preventDefault();
	}
	if (key == 46 && !isDecimal) {
		// don't allow dot
		return false;
	}
	if (key == 46) {
		if (field.value.indexOf(".") >= 0)
			// don't allow more than one dot
			return false;
    }
	return true;
}

function initializeTinyMCE(textareaId) {
	tinyMCE.init({
	    // General options
		mode : "exact",
		elements : textareaId,
	    theme : "advanced",
	    height : "300",
	    plugins : "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	
	    // Theme options
	    theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
	    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	    theme_advanced_buttons3 : "",
	    theme_advanced_buttons4 : "",
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_toolbar_align : "left",
	    theme_advanced_statusbar_location : "bottom",
	    theme_advanced_resizing : true,
	
	    // Skin options
	    skin : "o2k7",
	    skin_variant : "silver",
	
	    // Example content CSS (should be your site CSS)
	    content_css : "css/example.css",
	
	    // Drop lists for link/image/media/template dialogs
	    template_external_list_url : "js/template_list.js",
	    external_link_list_url : "js/link_list.js",
	    external_image_list_url : "js/image_list.js",
	    media_external_list_url : "js/media_list.js",
	
	    // Replace values for the template plugin
	    template_replace_values : {
	            username : "VSC",
	            staffid : "991234"
	    },
	
	    handle_event_callback : "handleTinyMceOnblurEvent"
	});
}

function handleTinyMceOnblurEvent(e) {
    if (e.type == 'keyup' || e.type == 'click') {
    	tinyMCE.activeEditor.save();
    }
    return true;
}

function setBillingAdFormError(formId, details) {
	if (details == null)
		return false;
	
	var form = document.getElementById(formId);
	clearBillingAdFormError(form);

	for (var loopCounter = 0; loopCounter < details.length; loopCounter++) {
		var fieldName = details[loopCounter].fieldName;
		var description = details[loopCounter].description;
	
		if (fieldName == null) {
			continue;
		}
		var parentElem = document.getElementById(fieldName).parentNode;
		if (parentElem != null && parentElem.nodeName == "SPAN") {
			var errorSpan = getErrorSpan(parentElem.parentNode);
			if (errorSpan != null && description != null) {
				errorSpan.innerHTML = description;
				displayFieldError(errorSpan.parentNode);
			}
			displayFieldError(parentElem);
		}
	}
	return true;
}

function clearBillingAdFormError(formElem) {
	if (formElem == null)
		return false;
	
	var childElem = formElem.getElementsByTagName("span");
	for (var loopIndex = 0; loopIndex < childElem.length; loopIndex++) {
		if (childElem[loopIndex].className.indexOf("form_error") >= 0) {
			var newClassName = childElem[loopIndex].className.replace("form_error", "");
			childElem[loopIndex].className = newClassName;
		}
	}
	return true;
}

function getErrorSpan(liElem) {
	if (liElem == null)
		return false;
	
	var childElem = liElem.getElementsByTagName("span");
	for (var loopIndex = 0; loopIndex < childElem.length; loopIndex++) {
		if (childElem[loopIndex].id == "errorMessage") {
			return childElem[loopIndex];
		}
	}
	return null;
}

function setFormError(formId, details) {
	if (details == null)
		return false;
	
	var form = document.getElementById(formId);
	clearFormError(form);
	
	for (var loopCounter = 0; loopCounter < details.length; loopCounter++) {
		var fieldName = details[loopCounter].fieldName;
		var description = details[loopCounter].description;
	
		if (fieldName == null)
			continue;
		var parentElem = document.getElementById(fieldName).parentNode;
		if (parentElem != null && parentElem.nodeName == "LI") {
			var errorDiv = getErrorDiv(parentElem);
			if (errorDiv != null && description != null) {
				errorDiv.innerHTML = description;
			}
			displayFieldError(parentElem);
		}
	}
	return true;
}

function displayFieldError(fieldElem) {
	if (fieldElem == null)
		return false;
	
	var className = fieldElem.className;
	if (className.indexOf("form_error") < 0) {
		if(className != "")
			className = className + " " + "form_error"
		else
			className = "form_error"
	}
	fieldElem.className = className;
	return true;
}

function clearFormError(formElem) {
	if (formElem == null)
		return false;
	
	var childElem = formElem.getElementsByTagName("li");
	for (var loopIndex = 0; loopIndex < childElem.length; loopIndex++) {
		if (childElem[loopIndex].className.indexOf("form_error") >= 0) {
			var newClassName = childElem[loopIndex].className.replace("form_error", "");
			childElem[loopIndex].className = newClassName;
		}
	}
	return true;
}

function getErrorDiv(liElem) {
	if (liElem == null)
		return false;
	
	var childElem = liElem.getElementsByTagName("div");
	for (var loopIndex = 0; loopIndex < childElem.length; loopIndex++) {
		if (childElem[loopIndex].id == "errorMessage") {
			return childElem[loopIndex];
		}
	}
	return null;
}

function enterKeySubmit(op, e) {
	var keycode;
	
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		return true;
	}
	
	if (keycode == 13) {
		if (op == 'loginHeader') {
			loginCustomer();
		} else if (op == 'loginPurchase') {
			loginPurchase();
		} else if (op == 'promotionCode') {
			validatePromotionCode();
		} else if (op == 'forgotPass') {
			validateForm();
		}
	   return false;
	} else {
	   return true;
	}
}

var autoCompleter = null;

function loadSearchValue() {
	var singleLineSearchValue = getCookie('singleLineSearchValue');
	if (singleLineSearchValue != null && singleLineSearchValue != "") {
		document.getElementById('singleLineSearch').value = singleLineSearchValue;
		document.getElementById("singleLineSearch").style.color = "#000000";
	}
}

function slas_onfocus(obj) {
	if (obj.value == obj.defaultValue) {
		obj.value = "";
		document.getElementById("singleLineSearch").style.color = "#000000";
	}
	document.getElementById("searchResults").style.display = "none";
	return true;
}

function slas_onblur(obj) {
	if (obj.value == "") {
		obj.value = obj.defaultValue;
		document.getElementById("singleLineSearch").style.color = "#A7A9AC";
	}
	return true;
}

function slas_keypress(evt) {
	var keyCode =
	    document.layers ? evt.which :
	    document.all ? event.keyCode :
	    document.getElementById ? evt.keyCode : 0;
	if (keyCode == 13) {
		return false;
	}
	return true;
}

function slas_onclick(li) {
	if (typeof checkValidation != "undefined") {
		checkValidation = 0;		
	}	
	getTargetSearch(li);
	return true;
}

function getTargetSearch(li) {	
	var returnVal = true;
	var searchStringId = li.id;
	var searchString = document.getElementById(searchStringId).innerHTML;
	document.getElementById("singleLineSearch").value = searchString;
	
	if (document.getElementById("hbiSuburbRules")) {
		returnVal = searchValidation("on");
	}
	
	if (returnVal == true) {
		setCookie('singleLineSearchValue', searchString, null);
		document.getElementById("selectedCategory").value = li.id.substring(li.id.length - 1);	
		document.getElementById("singleLineSearchForm").submit();
	}
}

function cmdHover(obj){
	var elem = obj.id;
	elem.onmouseover = function() {
		if (elem.className == ""){
			this.className += "hover";
		} else {
			this.className += " hover";
		}
	}
	elem.onmouseout = function() {
		this.className = this.className.replace("hover", "");
	}
}

//determine browser
function browserDetect() {
	var agent = navigator.userAgent.toLowerCase();
	
	if (agent.indexOf("opera") != -1) return 'Opera';
	if (agent.indexOf("staroffice") != -1) return 'Star Office';
	if (agent.indexOf("webtv") != -1) return 'WebTV';
	if (agent.indexOf("beonex") != -1) return 'Beonex';
	if (agent.indexOf("chimera") != -1) return 'Chimera';
	if (agent.indexOf("netpositive") != -1) return 'NetPositive';
	if (agent.indexOf("phoenix") != -1) return 'Phoenix';
	if (agent.indexOf("firefox") != -1) return 'Firefox';
	if (agent.indexOf("safari") != -1) return 'Safari';
	if (agent.indexOf("skipstone") != -1) return 'SkipStone';
	if (agent.indexOf("msie") != -1) return 'Internet Explorer';
	if (agent.indexOf("netscape") != -1) return 'Netscape';
	if (agent.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agent.indexOf('\/') != -1) {
		if (agent.substr(0,agent.indexOf('\/')) != 'mozilla')
			return navigator.userAgent.substr(0,agent.indexOf('\/'));
		else return 'Netscape';
	} else if (agent.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agent.indexOf(' '));
	else return navigator.userAgent;
}

//cookie utilities
function setCookie(name, value, expireDays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expireDays);
    var cookie = name + "=" + escape(value) + ((expireDays == null) ? "" : ";expires=" + exdate.toUTCString()) + ";path=/";
	document.cookie = cookie;
}

function getCookie(name) {
	if (document.cookie.length > 0) {
	    var start = document.cookie.indexOf(name + "=");
	    if (start != -1) {
		    start = start + name.length + 1;
	        var end = document.cookie.indexOf(";", start);
	        if (end == -1) end = document.cookie.length;
	        return unescape(document.cookie.substring(start, end));
	    }
	}
	return "";
}

function deleteCookie(name) {
	if (document.cookie.length > 0) {
		var exdate = new Date();
	    var start = document.cookie.indexOf(name + "=");
	    if (start != -1) {
		    exdate.setDate(exdate.getDate() - 1);
		    var cookie = name + "=;expires=" + exdate.toUTCString() + ";path=/";
		    document.cookie = cookie;
	    }
	}
}

function showMapCover(divId) {
	document.getElementById(divId).className = "expiredMapCover";
}

function hideMapCover(divId) {
	document.getElementById(divId).className = "disp_none";
}

//The following block implements the string.parseJSON method
(function (s) {
	// This prototype has been released into the Public Domain, 2007-03-20
	// Original Authorship: Douglas Crockford
	// Originating Website: http://www.JSON.org
	// Originating URL    : http://www.JSON.org/JSON.js

	// Augment String.prototype. We do this in an immediate anonymous function to
	// avoid defining global variables.

	// m is a table of character substitutions.

	var m = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\\"',
			'\\': '\\\\'
	};

	s.parseJSON = function (filter) {

		// Parsing happens in three stages. In the first stage, we run the text against
		// a regular expression which looks for non-JSON characters. We are especially
		// concerned with '()' and 'new' because they can cause invocation, and '='
		// because it can cause mutation. But just to be safe, we will reject all
		// unexpected characters.

		try {
			if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
					test(this)) {

				// In the second stage we use the eval function to compile the text into a
				// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
				// in JavaScript: it can begin a block or an object literal. We wrap the text
				// in parens to eliminate the ambiguity.
				var j = eval('(' + this + ')');

				// In the optional third stage, we recursively walk the new structure, passing
				// each name/value pair to a filter function for possible transformation.
				if (typeof filter === 'function') {
					function walk(k, v) {
						if (v && typeof v === 'object') {
							for (var i in v) {
								if (v.hasOwnProperty(i)) {
									v[i] = walk(i, v[i]);
								}
							}
						}
						return filter(k, v);
					}
					j = walk('', j);
				}
				return j;
			}
		} catch (e) { }
		throw new SyntaxError("parseJSON");
	};
}
) (String.prototype);

/* Tool tip functions */

var Opentip = {

	Version: '1.2.5',
	REQUIRED_PROTOTYPE_VERSION: '1.6.0',
	REQUIRED_SCRIPTACULOUS_VERSION: '1.8.0',
	cached: {},
	debugging: false,
	load: function() {
		function getComparableVersion(version) { var v = version.split('.'); return parseInt(v[0])*100000 + parseInt(v[1])*1000 + parseInt(v[2]); }
		if((typeof Prototype === 'undefined') || (typeof Element === 'undefined') || (typeof Element.Methods === 'undefined') || (getComparableVersion(Prototype.Version) < getComparableVersion(Opentip.REQUIRED_PROTOTYPE_VERSION))) { throw("Opentip requires the Prototype JavaScript framework >= " + Opentip.REQUIRED_PROTOTYPE_VERSION); }
		if((typeof Scriptaculous === 'undefined') || (typeof Effect === 'undefined') || (getComparableVersion(Scriptaculous.Version) < getComparableVersion(Opentip.REQUIRED_SCRIPTACULOUS_VERSION))) { throw("Opentip requires the Scriptaculous JavaScript framework >= " + Opentip.REQUIRED_SCRIPTACULOUS_VERSION); }
	},
	debug: function() { if (this.debugging && typeof console !== 'undefined' && typeof console.debug !== 'undefined') console.debug.apply(console, arguments); },
	IEVersion: function() {
		if (typeof Opentip.cached.IEVersion !== 'undefined') return Opentip.cached.IEVersion;
		if (Prototype.Browser.IE) {
			var version = navigator.userAgent.match('MSIE ([\\d.]+)');
			var IEVersion = version ? (parseFloat(version[1])) : false;
		}
		else IEVersion = false;
		Opentip.cached.IEVersion = IEVersion;
		return IEVersion;
	},
	objectIsEvent: function(obj) {
		return (typeof(obj) == 'object' && obj.type && obj.screenX);
	},
	useIFrame: function() { return Opentip.IEVersion() ? (Opentip.IEVersion() <= 6) : false; },
	lastTipId: 1,
	lastZIndex: 100,
	documentIsLoaded: false,
	postponeCreation: function(createFunction) {
		if (Opentip.documentIsLoaded || !Opentip.IEVersion) createFunction();
		else {
			Event.observe(window, 'load', createFunction); 
		}
	}
};
Opentip.load();

Event.observe(window, Opentip.IEVersion ? 'load' : 'dom:loaded', function() { Opentip.documentIsLoaded = true; });

Opentip.styles = {
	myrp: {
		className: 'myrp', // The class name to be used in the stylesheet
		stem: false, // false (no stem) || true (stem at tipJoint position)
						// || POSITION (for stems in other directions)
		delay: null, // float (in seconds - if null, the default is used: 0.2
						// for mouseover, 0 for click)
		hideDelay: 0.1, // --
		fixed: false, // If target is not null, elements are always fixed.
		showOn: 'mouseover', // string (the observe string of the trigger
								// element, eg: click, mouseover, etc..) ||
								// 'creation' (the tooltip will show when being
								// created) || null if you want to handle it
								// yourself.
		hideTrigger: 'trigger', // 'trigger' | 'tip' | 'target' | 'closeButton'
								// | ELEMENT | ELEMENT_ID
		hideOn: null, // string (event eg: click) || null (let Opentip decide)
		offset: [ 0, 0 ], // COORDINATE
		containInViewport: true, // Whether the targetJoint/tipJoint should
									// be changed if the tooltip is not in the
									// viewport anymore.
		autoOffset: true, // If set to true, offsets are calculated
							// automatically to position the tooltip. (pixels
							// are added if there are stems for example)
		showEffect: 'appear', // scriptaculous effect
		hideEffect: 'fade',
		showEffectDuration: 0.3,
		hideEffectDuration: 0.2,
		stemSize: 8, // integer
		tipJoint: [ 'left', 'top' ], // POSITION
		target: null, // null (no target, opentip uses mouse as target) ||
						// true (target is the triggerElement) ||
						// elementId|element (for another element)
		targetJoint: null, // POSITION (Ignored if target == null) || null
							// (targetJoint is the opposite of tipJoint)
		ajax: false, // Ajax options. eg: { url: 'yourUrl.html', options: {
						// ajaxOptions... } } or { options: { ajaxOptions } /*
						// This will use the href of the A element the tooltip
						// is attached to */ }
		group: null // You can group opentips together. So when a tooltip shows,
					// it looks if there are others in the same group, and hides
					// them.
	}
};
Opentip.defaultStyle = 'myrp'; // Change this to the style name you want
									// your tooltips to have.



var Tips = {
	list: [],
	append: function(tip) { this.list.push(tip); },
	remove: function(element) {
		if (!element.element) var tip = this.list.find(function(t) { return t.triggerElement === element });
		else var tip = this.list.find(function(t) { return t === element });
		if (tip) {
			tip.deactivate();
			tip.destroyAllElements();
			this.list = this.list.without(tip);
		}
	},
	add: function(element, evt) {
		if (element._opentipAddedTips) {
			/*
			 * TODO: Now it just returns the first found... try to find the
			 * correct one.
			 */
			var tip = this.list.find(function(t) { return (t.triggerElement === element); });
			if (tip.options.showOn == 'creation') tip.show();
			Opentip.debug('Using an existing opentip');
			return;
		} else setTimeout(function() { element._opentipAddedTips = true; }, 1); // I
																				// added
																				// a
																				// timeout,
																				// so
																				// that
																				// tooltips,
																				// defined
																				// in
																				// an
																				// onmouseover
																				// or
																				// onclick
																				// event,
																				// will
																				// show.

		Opentip.debug('Creating new opentip');

		var tipArguments = [];

		$A(arguments).each(function(arg, idx) {
			if (idx == 1 && !Opentip.objectIsEvent(arg)) tipArguments.push(null);
			tipArguments.push(arg);
		});

		var self = this;
		var createTip = function() { self.append(new TipClass(tipArguments[0], tipArguments[1], tipArguments[2], tipArguments[3], tipArguments[4])); }

		Opentip.postponeCreation(createTip);
		
		return;
	},
	hideGroup: function(groupName) {
	  this.list.findAll(function(t) { return (t.options.group == groupName); }).invoke('doHide');
	}
};

var Tip = function() { Tips.add.apply(Tips, arguments); return; };

Element.addMethods({
	addTip: function(element) {
		element = $(element);
		Tips.add.apply(Tips, arguments);
		return element;
	}
});


var TipClass = Class.create({
	initialize: function(element, evt) {
		this.id = Opentip.lastTipId ++;

		element = $(element);

		this.triggerElement = element;

		this.loaded  = false; 
		this.loading = false; 

		this.visible = false;
		this.waitingToShow = false;
		this.waitingToHide = false;

		this.lastPosition = { left: 0, top: 0 };
		this.dimensions   = [ 100, 50 ];

		var options = {};
		this.content = '';

		if      (typeof(arguments[2]) == 'object') { this.content = '';           options = arguments[2]; }
		else if (typeof(arguments[3]) == 'object') { this.content = arguments[2]; options = arguments[3]; }
		else if (typeof(arguments[4]) == 'object') { this.content = arguments[2]; options = arguments[4];  options.title = arguments[3]; }
		else {
			if (Object.isString(arguments[2]) || Object.isFunction(arguments[2])) this.content = arguments[2];
			if (Object.isString(arguments[3])) options.title = arguments[3];
		}

		if (!options.showOn && evt) options.showOn = evt.type;
		
		if (options.ajax && !options.ajax.url) {
			if (this.triggerElement.tagName.toLowerCase() == 'a') {
				if (typeof(options.ajax) != 'object') options.ajax = { };
				options.ajax.url = this.triggerElement.href;
			} else { options.ajax = false; }
		}
		if (options.showOn == 'click' && this.triggerElement.tagName.toLowerCase() == 'a') { if (evt) { evt.stop(); } this.triggerElement.observe('click', function(e) { e.stop(); }); }


		options.style || (options.style = Opentip.defaultStyle);

		var styleOptions = Object.extend({ }, Opentip.styles.standard); // Copy
																		// all
																		// standard
																		// options.
		if (options.style != 'standard') Object.extend(styleOptions, Opentip.styles[options.style]);

		options = Object.extend(styleOptions, options);


		options.target && (options.fixed = true);


		if (options.stem === true) options.stem = options.tipJoint;
		if (options.target === true) options.target = this.triggerElement;
		else if (options.target) options.target = $(options.target);


		this.currentStemPosition = options.stem;


		if (options.delay === null) {
			if (options.showOn == 'mouseover') options.delay = 0.2;
			else options.delay = 0
		}


		if (options.targetJoint == null) {
			options.targetJoint = [];
			options.targetJoint[0] = options.tipJoint[0] == 'left' ? 'right' : (options.tipJoint[0] == 'right' ? 'left' : 'center');
			options.targetJoint[1] = options.tipJoint[1] == 'top' ? 'bottom' : (options.tipJoint[1] == 'bottom' ? 'top' : 'middle');
		}

		this.options = options;

		this.buildContainer();


		this.options.showTriggerElementsWhenHidden = [];

    if (this.options.showOn && this.options.showOn != 'creation') {
      this.options.showTriggerElementsWhenHidden.push({ element: this.triggerElement, event: this.options.showOn });
    }

		this.options.showTriggerElementsWhenVisible = [];


		this.options.hideTriggerElements = [];

		if (this.options.hideTrigger) {
		  var hideOnEvent = null;
		  var hideTriggerElement = null;
			switch (this.options.hideTrigger) {
				case 'trigger':
				  hideOnEvent = this.options.hideOn ? this.options.hideOn : 'mouseout';
				  hideTriggerElement = this.triggerElement;
				  break;
				case 'tip':
				  hideOnEvent = this.options.hideOn ? this.options.hideOn : 'mouseover';
				  hideTriggerElement = this.container;
				  break;
				case 'target':
			    hideOnEvent = this.options.hideOn ? this.options.hideOn : 'mouseover';
				  hideTriggerElement = this.options.target;
				  break;
				case 'closeButton': break;
				default:
		      hideOnEvent = this.options.hideOn ? this.options.hideOn : 'mouseover';
				  hideTriggerElement = $(this.options.hideTrigger);
				  break;
			}
			if (hideTriggerElement) {
			  this.options.hideTriggerElements.push({ element: hideTriggerElement, event: hideOnEvent });
  			if (hideOnEvent == 'mouseout') {
          this.options.showTriggerElementsWhenVisible.push({ element: hideTriggerElement, event: 'mouseover' });
  			}
			}
		}

		this.activate();

		if (evt || this.options.showOn == 'creation') this.show(evt);
	},
	activate: function() {
		this.bound = {};
		this.bound.doShow   = this.doShow.bindAsEventListener(this);
		this.bound.show     = this.show.bindAsEventListener(this);
		this.bound.doHide   = this.doHide.bindAsEventListener(this);
		this.bound.hide     = this.hide.bindAsEventListener(this);
		this.bound.position = this.position.bindAsEventListener(this);

		if (this.options.showEffect || this.options.hideEffect) this.queue = { limit: 1, position: 'end', scope: this.container.identify() };

    this.setupObserversForReallyHiddenTip();
		this.setupObserversForHiddenTip();
	},
	deactivate: function() {
		this.doHide();
		this.setupObserversForReallyHiddenTip();
	},
	buildContainer: function() {
		this.container = $(Builder.node('div', { className: 'opentipContainer style-' + this.options.className + (this.options.ajax ? ' loading' : '') })).setStyle({ display: 'none', position: 'absolute' });
	},
	buildElements: function() {
		if (this.options.stem) {
			var stemOffset = '-' + this.options.stemSize + 'px';
			this.container.appendChild(Builder.node('div', { className: 'stemContainer ' + this.options.stem[0] + ' ' + this.options.stem[1] }, Builder.node('div', { className: 'stem' }, Builder.node('div', ''))));
		}
		var self = this;
		var content = [];
		var headerContent = [];
		if (this.options.title) headerContent.push(Builder.node('div', { className: 'tool_tip_title' }, this.options.title));

		content.push(Builder.node('div', { className: 'tool_tip_header' }, headerContent));
		content.push($(Builder.node('div', { className: 'tool_tip_content' })).update(this.content));
		if (this.options.ajax) { content.push($(Builder.node('div', { className: 'loadingIndication' }, Builder.node('span', 'Loading...')))); }
		this.tooltipElement = $(Builder.node('div', { className: 'opentip' }, content));

		this.container.appendChild(this.tooltipElement);

		var buttons = this.container.appendChild(Builder.node('div', { className: 'opentipButtons' }));
		if (this.options.hideTrigger == 'closeButton') buttons.appendChild(Builder.node('a', { href: 'javascript:undefined', className: 'close' }, Builder.node('span', 'x')));
		
		if (Opentip.useIFrame()) this.iFrameElement = this.container.appendChild($(Builder.node('iframe', { className: 'opentipIFrame', src: 'javascript:false;' })).setStyle({ display: 'none', zIndex: 100 }).setOpacity(0));

		document.body.appendChild(this.container);
		this.storeAndFixDimensions();
	},
	storeAndFixDimensions: function() {
		this.container.setStyle({ width: 'auto', left: '0px', top: '0px' });
		this.dimensions = this.container.getDimensions();
		this.container.setStyle({ width: this.dimensions.width + 'px', left: this.lastPosition.left + 'px', top: this.lastPosition.top + 'px' });
	},
	destroyAllElements: function() { if (this.container) this.container.remove(); },
	clearShowTimeout: function() { window.clearTimeout(this.timeoutId); },
	clearHideTimeout: function() { window.clearTimeout(this.hideTimeoutId); },
	clearTimeouts: function() { this.clearShowTimeout(); this.clearHideTimeout(); },
	setupObserversForReallyVisibleTip: function() {
		this.options.showTriggerElementsWhenVisible.each(function(pair) { $(pair.element).observe(pair.event, this.bound.show); }, this);
  },
 	setupObserversForVisibleTip: function() {
		this.options.hideTriggerElements.each(function(pair) { $(pair.element).observe(pair.event, this.bound.hide); }, this);
		this.options.showTriggerElementsWhenHidden.each(function(pair) { $(pair.element).stopObserving(pair.event, this.bound.show); }, this);
		Event.observe(document.onresize ? document : window, "resize", this.bound.position);
		Event.observe(window, "scroll", this.bound.position);
	},

	setupObserversForReallyHiddenTip: function() {
		this.options.showTriggerElementsWhenVisible.each(function(pair) { $(pair.element).stopObserving(pair.event, this.bound.show); }, this);
  },
	setupObserversForHiddenTip: function() {
		this.options.showTriggerElementsWhenHidden.each(function(pair) { $(pair.element).observe(pair.event, this.bound.show); }, this);
		this.options.hideTriggerElements.each(function(pair) { $(pair.element).stopObserving(pair.event, this.bound.hide); }, this);
		Event.stopObserving(document.onresize ? document : window, "resize", this.bound.position);
		Event.stopObserving(window, "scroll", this.bound.position);
	},
	show: function(evt) {
	  if (this.waitingToHide) {
  		this.clearTimeouts();
  		this.waitingToHide = false;
  		this.setupObserversForVisibleTip();
	  }
		if (this.visible) return;

		Opentip.debug('Show', this.id);

		this.waitingToShow = true;

 		this.setupObserversForVisibleTip();

		this.followMousePosition();
		this.position(evt);

		if (!this.options.delay) this.bound.doShow(evt);
		else this.timeoutId = this.bound.doShow.delay(this.options.delay);
	},
	doShow: function() {
	  this.clearTimeouts();
	  if (this.visible) return;

		Opentip.debug('DoShow', this.id);

    if (this.options.group) Tips.hideGroup(this.options.group);


		this.visible = true;
		this.waitingToShow = false;

		if (Object.isFunction(this.content)) { Opentip.debug('Executing content function...'); this.content = this.content(this);}

		if (!this.tooltipElement) this.buildElements();

		if (this.options.ajax && !this.loaded) { this.loadAjax(); }

		this.searchAndActivateHideButtons();

		this.ensureElement();
		this.container.setStyle({ zIndex: Opentip.lastZIndex += 1 });

		this.setupObserversForReallyVisibleTip();
		this.setupObserversForVisibleTip();

		if (this.options.showEffect || this.options.hideEffect) this.cancelEffects();

		if (!this.options.showEffect) this.container.show();
		else this.container[this.options.showEffect]({ duration: this.options.showEffectDuration, queue: this.queue, afterFinish: this.afterShowEffect.bind(this) });
		if (Opentip.useIFrame()) this.iFrameElement.show();

		this.activateFirstInput();

		this.position();
	},
	loadAjax: function() {
		if (this.loading) return;
		this.loading = true;
		this.container.addClassName('loading');
		var self = this;
		new Ajax.Request(this.options.ajax.url,
			Object.extend({ onSuccess: function(transport) {
				self.content = transport.responseText;
				var content = self.container.down('.content');
				if (content) {
					content.update(self.content);
					self.searchAndActivateHideButtons();
				}
				self.loaded = true;
				self.loading = false;
				self.container.removeClassName('loading');
				self.storeAndFixDimensions();
				self.position();
				this.activateFirstInput();
			} }, this.options.ajax.options || {}));
	},
	afterShowEffect: function() {
		this.activateFirstInput();
		this.position();
	},
	activateFirstInput: function() {
		var input = this.container.down('input');
		var textarea = this.container.down('textarea');
		if (input) { input.focus(); }
		else if (textarea) textarea.focus();
	},
	searchAndActivateHideButtons: function() {
		if (this.options.hideTrigger == 'closeButton' || !this.options.hideTrigger) {
			this.options.hideTriggerElements = [];
			this.container.select('.close').each(function(el) {
				this.options.hideTriggerElements.push({ element: el, event: 'click' });
			}, this);
			if (this.visible) this.setupObserversForVisibleTip();
		}
	},
	hide: function(afterFinish) {
	  if (this.waitingToShow) {
  		this.clearTimeouts();
			this.stopFollowingMousePosition();
  		this.waitingToShow = false;
  		this.setupObserversForHiddenTip();
	  }
	  if (!this.visible) return;

		Opentip.debug('Hide', this.id);

		this.waitingToHide = true;
 		this.setupObserversForHiddenTip();

		this.hideTimeoutId = this.bound.doHide.delay(this.options.hideDelay, afterFinish); 
	},
	doHide: function(afterFinish) {
	  this.clearTimeouts();
	  if (!this.visible) return;

		this.visible = false;
		this.waitingToHide = false;

		Opentip.debug('DoHide', this.id);

		this.deactivateElementEnsurance();

		this.setupObserversForReallyHiddenTip();
		this.setupObserversForHiddenTip();

		if (!this.options.fixed) this.stopFollowingMousePosition();

		if (this.options.showEffect || this.options.hideEffect) this.cancelEffects();

		if (!this.options.hideEffect) this.container.hide(); 
		else {
			var effectOptions = { duration: this.options.hideEffectDuration, queue: this.queue };
			if(afterFinish && Object.isFunction(afterFinish)) effectOptions.afterFinish = afterFinish;
			this.container[this.options.hideEffect](effectOptions);
		}
		if (Opentip.useIFrame()) this.iFrameElement.hide();
	},
	cancelEffects: function() { Effect.Queues.get(this.queue.scope).invoke('cancel'); },
	followMousePosition:        function() { if (!this.options.fixed) $(document.body).observe('mousemove', this.bound.position); },
	stopFollowingMousePosition: function() { if (!this.options.fixed) $(document.body).stopObserving('mousemove', this.bound.position); },
	positionsEqual: function(position1, position2) {
		return (position1.left == position2.left && position1.top == position2.top);	
	},
	position: function(evt) {
		var evt = evt || this.lastEvt;

		this.currentStemPosition = this.options.stem; 
		var position = this.ensureViewportContainment(evt, this.getPosition(evt));
		if (this.positionsEqual(position, this.lastPosition)) {
			this.positionStem();
			return;
		}

		this.lastPosition = position;
		if (position) {
			var style = { 'left': position.left + 'px', 'top': position.top + 'px' };
			this.container.setStyle(style);
			if (Opentip.useIFrame() && this.iFrameElement) {
				this.iFrameElement.setStyle({ width: this.container.getWidth() + 'px', height: this.container.getHeight() + 'px' });
			}

			var container = this.container;
			(function() {
				container.style.visibility = "hidden"; 
				var redrawFix = container.offsetHeight;
				container.style.visibility = "visible";
			}).defer();
		}
		this.positionStem();
	},
	getPosition: function(evt, tipJ, trgJ, stem) {
		var tipJ = tipJ || this.options.tipJoint;
		var trgJ = trgJ || this.options.targetJoint;

		var position = {};

		if (this.options.target) {
			var tmp = this.options.target.cumulativeOffset();
			position.left = tmp[0];
			position.top = tmp[1];
			if (trgJ[0] == 'right')  {
				if (typeof this.options.target.getBoundingClientRect != 'undefined') {
					position.left = this.options.target.getBoundingClientRect().right + $(document.viewport).getScrollOffsets().left;
				}
				else {
					position.left = position.left + this.options.target.getWidth();
				}
			}
			else if (trgJ[0] == 'center') { position.left += Math.round(this.options.target.getWidth() / 2); }
			if      (trgJ[1] == 'bottom') { position.top += this.options.target.getHeight(); }
			else if (trgJ[1] == 'middle') { position.top += Math.round(this.options.target.getHeight() / 2); }
		} else {
			if (!evt) return;
			this.lastEvt = evt;
			position.left = Event.pointerX(evt);
			position.top = Event.pointerY(evt);
		}

		if (this.options.autoOffset) {
			var stemSize = this.options.stem ? this.options.stemSize : 0;
			var offsetDistance = (stemSize && this.options.fixed) ? 2 : 10; 
			var additionalHorizontal = (tipJ[1] == 'middle' && !this.options.fixed) ? 15 : 0;
			var additionalVertical   = (tipJ[0] == 'center' && !this.options.fixed) ? 15 : 0;
			if      (tipJ[0] == 'right')  position.left -= offsetDistance + additionalHorizontal;
			else if (tipJ[0] == 'left')   position.left += offsetDistance + additionalHorizontal;
			if      (tipJ[1] == 'bottom') position.top -= offsetDistance + additionalVertical;
			else if (tipJ[1] == 'top')    position.top += offsetDistance + additionalVertical;

			if (stemSize) {
				var stem = stem || this.options.stem;
				if      (stem[0] == 'right')  position.left -= stemSize;
				else if (stem[0] == 'left')   position.left += stemSize;
				if      (stem[1] == 'bottom') position.top -= stemSize;
				else if (stem[1] == 'top')    position.top += stemSize;
			}
		}
		position.left += this.options.offset[0];
		position.top += this.options.offset[1];

		if (tipJ[0] == 'right')  { position.left -= this.container.getWidth(); }
		if (tipJ[0] == 'center') { position.left -= Math.round(this.container.getWidth()/2); }
		if (tipJ[1] == 'bottom') { position.top -= this.container.getHeight(); }
		if (tipJ[1] == 'middle') { position.top -= Math.round(this.container.getHeight()/2); }

		return position;
	},
	ensureViewportContainment: function(evt, position) {
		if (!this.visible) return position;

		var sticksOut = [ this.sticksOutX(position), this.sticksOutY(position) ];
		if (!sticksOut[0] && !sticksOut[1]) return position;

		var tipJ = this.options.tipJoint.clone();
		var trgJ = this.options.targetJoint.clone();		
		
		var viewportScrollOffset = $(document.viewport).getScrollOffsets();
		var dimensions = this.dimensions;
		var viewportOffset = { left: position.left - viewportScrollOffset.left, top: position.top - viewportScrollOffset.top };
		var viewportDimensions = document.viewport.getDimensions();
		var reposition = false;

		if (viewportDimensions.width >= dimensions.width) {
			if (viewportOffset.left < 0) {
				reposition = true;
				tipJ[0] = 'left';
				if (this.options.target && trgJ[0] == 'left') { trgJ[0] = 'right'; }
			}
			else if (viewportOffset.left + dimensions.width > viewportDimensions.width) {
				reposition = true;
				tipJ[0] = 'right';
				if (this.options.target && trgJ[0] == 'right') { trgJ[0] = 'left'; }
			}
		}

		if (viewportDimensions.height >= dimensions.height) {
			if (viewportOffset.top < 0) {
				reposition = true;
				tipJ[1] = 'top';
				if (this.options.target && trgJ[1] == 'top') { trgJ[1] = 'bottom'; }
			}
			else if (viewportOffset.top + dimensions.height > viewportDimensions.height) {
				reposition = true;
				tipJ[1] = 'bottom';
				if (this.options.target && trgJ[1] == 'bottom') { trgJ[1] = 'top'; }
			}
		}
		if (reposition) {
			var newPosition = this.getPosition(evt, tipJ, trgJ, tipJ);
			var newSticksOut = [ this.sticksOutX(newPosition), this.sticksOutY(newPosition) ];
			var revertedCount = 0;
			for (var i = 0; i <=1; i ++) {
				if (newSticksOut[i] && newSticksOut[i] != sticksOut[i]) {
					revertedCount ++;
					tipJ[i] = this.options.tipJoint[i];
					if (this.options.target) { trgJ[i] = this.options.targetJoint[i]; }
				}
			}
			if (revertedCount < 2) {
				this.currentStemPosition = tipJ;
				return this.getPosition(evt, tipJ, trgJ, tipJ);
			}
		}
		return position;
	},
	sticksOut: function(position) {
		return this.sticksOutX(position) || this.sticksOutY(position);
	},
	/**
	 * return 1 for left 2 for right
	 */
	sticksOutX: function(position) {
		var viewportScrollOffset = $(document.viewport).getScrollOffsets();
		var viewportOffset = { left: position.left - viewportScrollOffset.left, top: position.top - viewportScrollOffset.top };
		if (viewportOffset.left < 0) return 1;
		if (viewportOffset.left + this.dimensions.width > document.viewport.getDimensions().width) { return 2; }
	},
	/**
	 * return 1 for left 2 for right
	 */
	sticksOutY: function(position) {
		var viewportScrollOffset = $(document.viewport).getScrollOffsets();
		var viewportOffset = { left: position.left - viewportScrollOffset.left, top: position.top - viewportScrollOffset.top };
		if (viewportOffset.top < 0) return 1;
		if (viewportOffset.top + this.dimensions.height > document.viewport.getDimensions().height) return 2;
	},
	getStemElement: function() {
		return this.container.down('.stem');
	},
	stemPositionsEqual: function(position1, position2) {
		return (position1 && position2 && position1[0] == position2[0] && position1[1] == position2[1]);	
	},
	positionStem: function() {
		if (this.options.stem) {
			var stemElement = this.getStemElement();

			if (stemElement && !this.stemPositionsEqual(this.lastStemPosition, this.currentStemPosition)) {

				Opentip.debug('Setting stem style');

				this.lastStemPosition = this.currentStemPosition;

				var stem = this.currentStemPosition;
				var stemSize = this.options.stemSize;

				var stemsImageSize = [ 320, 160 ];

				var style = { width: stemSize + 'px', height: stemSize + 'px' };

				style.left = style.top = '0';

				switch (stem[0]) {
					case 'center': style.width = stemSize * 2 + 'px'; // no
																		// break
					case 'left':   style.left = '-' + stemSize + 'px'; break;
				}
				switch (stem[1]) {
					case 'middle':  style.height = stemSize * 2 + 'px'; // no
																		// break
					case 'top':     style.top = '-' + stemSize + 'px'; break;
				}

				if (stem[0] != 'center' && stem[1] != 'middle') style.width = style.height = stemSize * 2 + 'px'; // Corners.

				var imageStyle = { left: 0, top: 0 };

				switch (stem[0] + '-' + stem[1]) {
					case 'left-middle':
						imageStyle.left = '-' + Math.round(stemsImageSize[0] * (1/2)) + 'px';
						imageStyle.top  = '-' + Math.round(stemsImageSize[1] * (1/2) - stemSize) + 'px';
						break;
					case 'center-top':
						imageStyle.left = '-' + Math.round(stemsImageSize[0] * (3/4) - stemSize) + 'px';
						break;
					case 'center-bottom':
						imageStyle.left = '-' + Math.round(stemsImageSize[0] * (3/4) - stemSize) + 'px';
						imageStyle.top  = '-' + Math.round(stemsImageSize[1] - stemSize) + 'px';
						break;
					case 'right-middle':
						imageStyle.left = '-' + Math.round(stemsImageSize[0] - stemSize) + 'px';
						imageStyle.top  = '-' + Math.round(stemsImageSize[1] / 2 - stemSize) + 'px';
						break;
					case 'left-top': break;
					case 'right-top':
						imageStyle.left = '-'   + Math.round(stemsImageSize[0] * (1/2) - stemSize * 2) + 'px';
						style.top = '-' + stemSize + 'px';
						style.left = '-' + stemSize + 'px';
						break;
					case 'right-bottom':
						imageStyle.left = '-'   + Math.round(stemsImageSize[0] * (1/2) - stemSize * 2) + 'px';
						imageStyle.top  = '-' + Math.round(stemsImageSize[1] - stemSize*2) + 'px';
						style.left = '-' + stemSize + 'px';
						style.top = '-' + stemSize + 'px';
						break;
					case 'left-bottom':
						imageStyle.top = '-' + Math.round(stemsImageSize[1] - stemSize * 2) + 'px';
						style.left = '-' + stemSize + 'px';
						style.top = '-' + stemSize + 'px';
						break;
				}

				stemElement.down('div').setStyle(imageStyle);
				stemElement.setStyle(style);
				stemElement._appliedStyle = true;
				
				stemElement.up('.stemContainer').removeClassName('left').removeClassName('right').removeClassName('center').removeClassName('top').removeClassName('bottom').removeClassName('middle').addClassName(stem[0] + ' ' + stem[1]);
			}
		}
	},
	ensureElementInterval: 1000, 
	ensureElement: function() { 
		this.deactivateElementEnsurance();
		if (!this.triggerElement.parentNode || !this.triggerElement.visible() || !this.triggerElement.descendantOf(document.body)) { this.deactivate(); }
		this.ensureElementTimeoutId = setTimeout(this.ensureElement.bind(this), this.ensureElementInterval);
	},
	deactivateElementEnsurance: function() { clearTimeout(this.ensureElementTimeoutId); }
});

Ajax.Autocompleter.prototype._onComplete =
  Ajax.Autocompleter.prototype.onComplete;
Ajax.Autocompleter.prototype._onKeyPress =
  Ajax.Autocompleter.prototype.onKeyPress;
Object.extend(Ajax.Autocompleter.prototype, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous = true;
    this.options.onComplete = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url = url;
    this.cache = {};
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var t = this.getToken();
    if (this.cache[t]) {
      this.updateChoices(this.cache[t]);
    } else {
      entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(t);

      this.options.parameters = this.options.callback ?
        this.options.callback(this.element, entry) : entry;

      if(this.options.defaultParams)
        this.options.parameters += '&' + this.options.defaultParams;

      new Ajax.Request(this.url, this.options);
    }
  },

  onKeyPress: function(event) {
      var originallyActive = this.active;
      this._onKeyPress(event);

      // Catch <enter> keypresses
      if (event.keyCode == 13) {

          // Workaround for a bug in for Safari 2.0.3.  Already fixed in WebKit as of 2006-06-29.
          // This makes the selection go to the end.
          if(navigator.appVersion.indexOf('AppleWebKit/4') > -1) {
              var element = Event.element(event);
              element.setSelectionRange(element.value.length, element.value.length);
              return false;
          }

          // Don't submit the form when you click enter!
          Event.stop(event);

          if (!originallyActive && this.options.onEnter) {
              this.options.onEnter(this.element);
          }

          return false;
      }

      return true;
  },

  // Extend Ajax.Autocompleter to add a callback when the returned list is empty
  // See http://dev.rubyonrails.org/ticket/5120
  onComplete: function(request) {
    this._onComplete(request);
    if (this.entryCount == 0 && this.options.onEmpty) {
      this.options.onEmpty(this.element);
    } else if (this.options.onNotEmpty) {
      this.options.onNotEmpty(this.element);
    }

    // for caching
    this.updateChoices(this.cache[this.getToken()] = request.responseText);
  },

    // Page jump fix
    markPrevious: function() {
      if (this.index > 0) {
        this.index--;
      } else {
        this.index = this.entryCount-1;
        this.update.scrollTop = this.update.scrollHeight;
      }

      selection = this.getEntry(this.index);
      selection_top = selection.offsetTop;

      if (selection_top < this.update.scrollTop) {
        this.update.scrollTop = this.update.scrollTop - selection.offsetHeight;
      }
    },

    markNext: function() {
      if (this.index < this.entryCount-1) {
        this.index++;
      } else {
        this.index = 0;
        this.update.scrollTop = 0;
      }
      selection = this.getEntry(this.index);
      selection_bottom = selection.offsetTop+selection.offsetHeight;
      if (selection_bottom > this.update.scrollTop + this.update.offsetHeight) {
        this.update.scrollTop = this.update.scrollTop+selection.offsetHeight;
      }
    },

    updateChoices: function(choices) {
      if (!this.changed && this.hasFocus) {
        this.update.innerHTML = choices;
        Element.cleanWhitespace(this.update);
        Element.cleanWhitespace(this.update.down());

        if (this.update.firstChild && this.update.down().childNodes) {
          this.entryCount = this.update.down().childNodes.length;
          for (var i = 0; i < this.entryCount; i++) {
            var entry = this.getEntry(i);
            entry.autocompleteIndex = i;
            this.addObservers(entry);
          }
        } else {
          this.entryCount = 0;
        }

        this.stopIndicator();
        this.update.scrollTop = 0;
        this.index = 0;

        if (this.entryCount==1 && this.options.autoSelect) {
          this.selectEntry();
          this.hide();
        } else {
          this.render();
        }
      }
    }
});

function firstLetterOrdering(suburbLink, state, letter) {
	new Ajax.Request("myrp-1?op=myrp_widgets.suburbSitemap.suburbSitemap&suburbLink=" + suburbLink + "&state="+ state +"&letter=" + letter, {
		method:'post',
		onComplete: function (transport) {
			var htmlContent = transport.responseText;
			var elementId = "suburb_result_" + state;
			var element = document.getElementById(elementId).parentNode;
			if (element != null) {
				element.innerHTML = htmlContent;
			}
		},
		onFailure: function () {
			alert("We apologise that an error was encountered processing your request. Please refresh you page.");	       
		}
	});
	return false;
}
