var LOGGINGIN = false;

/** @author Alexander Farkas * v. 1.21 * Background animation */ (function($) { if(!document.defaultView || !document.defaultView.getComputedStyle){ var oldCurCSS = jQuery.curCSS; jQuery.curCSS = function(elem, name, force){ if(name === 'background-position'){ name = 'backgroundPosition'; } if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){ return oldCurCSS.apply(this, arguments); }	var style = elem.style;if ( !force && style && style[ name ] ){ return style[ name ];}return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);};}var oldAnim = $.fn.animate;$.fn.animate = function(prop){if('background-position' in prop){prop.backgroundPosition = prop['background-position'];delete prop['background-position'];}if('backgroundPosition' in prop){prop.backgroundPosition = '('+ prop.backgroundPosition;}return oldAnim.apply(this, arguments);};function toArray(strg){ strg = strg.replace(/left|top/g,'0px');strg = strg.replace(/right|bottom/g,'100%');strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];}$.fx.step. backgroundPosition = function(fx) {if (!fx.bgPosReady) {var start = $.curCSS(fx.elem,'backgroundPosition');if(!start){start = '0px 0px';}start = toArray(start);fx.start = [start[0],start[2]];var end = toArray(fx.options.curAnim.backgroundPosition);fx.end = [end[0],end[2]];fx.unit = [end[1],end[3]];fx.bgPosReady = true;}var nowPosX = [];nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];};})(jQuery);
function debug(msg) { if (window.console && window.console.log) window.console.log(msg); }
function getElementsByName(name){ var temp = document.all; var matches = []; for(var i=0;i<temp.length;i++){ if(temp[i].name == name) matches.push(temp[i]); } return matches; }

function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}
	return false;
}

function removeEvent(obj, evType, fn){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, false);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	}
	return false;
}

function getClientWidth() {
	var bWidth;
	if (window.innerWidth)  return (window.innerWidth);
	else if (document.documentElement && document.documentElement.clientWidth != 0) return (document.documentElement.clientWidth);
	else if (document.body) return (document.body.clientWidth);
	else { 
		var tk = java.awt.Toolkit;
		var size = new java.awt.Dimension(tk.getDefaultToolkit().getScreenSize());
		return (size.width);
	}
}

function getClientHeight() {
	var bHeight;
	if (window.innerHeight) return (window.innerHeight);
	else if (document.documentElement && document.documentElement.clientWidth != 0) return (document.documentElement.clientHeight);
	else if (document.body) return (document.body.clientHeight);
	else {
		var tk = java.awt.Toolkit;
		var size = new java.awt.Dimension(tk.getDefaultToolkit().getScreenSize());
		return (size.height);
	}
}

function POST(parent, command, action){
	var request = getAjaxHandle();
	var root 	= getObj(parent);
	var vals	= root.getElementsByTagName("input");
	var urlstr 	= "";
	var url 	= command;
	for(var i=0; i<vals.length; i++){
		if(vals[i].type == "radio"){
			if(vals[i].checked) urlstr += vals[i].name + "=" + vals[i].value + "&";
		}else if(vals[i].type == "checkbox"){
			if(vals[i].checked) urlstr += vals[i].name + "=" + vals[i].value + "&";
			else urlstr += vals[i].name + "=0&";
		}else if(vals[i].type != "button"){
			urlstr += vals[i].name + "=" + vals[i].value + "&";
		}
	}
	var vals = root.getElementsByTagName("textarea");
	for(var i=0; i<vals.length; i++){
		urlstr += vals[i].name + "=" + vals[i].value + "&";
	}
	var vals = root.getElementsByTagName("select");
	for(var i=0; i<vals.length; i++){
		urlstr += vals[i].name + "=" + vals[i].value + "&";
	}
	request.onreadystatechange = function(){
		var a = action;
		if(request.readyState == 4){
			if(request.responseXML != null && !request.responseText.match("S_OK") && !request.responseText.match("E_FAIL")){
				a(request.responseXML);
			}else{
				a(request.responseText);
			}
		}
	};
	request.open("POST", url , true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", urlstr.length);
    request.setRequestHeader("Connection", "close");
	request.send(urlstr);
}

function e_POST(parent, command, action){
	var request = getAjaxHandle();
	var root 	= parent;
	var vals	= root.getElementsByTagName("input");
	var urlstr 	= "";
	var url 	= command;
	for(var i=0; i<vals.length; i++){
		if(vals[i].type == "radio"){
			if(vals[i].checked) urlstr += vals[i].name + "=" + vals[i].value + "&";
		}else if(vals[i].type == "checkbox"){
			if(vals[i].checked) urlstr += vals[i].name + "=" + vals[i].value + "&";
			else urlstr += vals[i].name + "=0&";
		}else if(vals[i].type != "button"){
			urlstr += vals[i].name + "=" + vals[i].value + "&";
		}
	}
	var vals = root.getElementsByTagName("textarea");
	for(var i=0; i<vals.length; i++){
		urlstr += vals[i].name + "=" + vals[i].value + "&";
	}
	var vals = root.getElementsByTagName("select");
	for(var i=0; i<vals.length; i++){
		urlstr += vals[i].name + "=" + vals[i].value + "&";
	}
	request.onreadystatechange = function(){
		var a = action;
		if(request.readyState == 4){
			if(request.responseXML != null && !request.responseText.match("S_OK") && !request.responseText.match("E_FAIL")){
				a(request.responseXML);
			}else{
				a(request.responseText);
			}
			//if(request.responseText != "") a(request.responseText);
			//else a(request.responseXML);
		}
	};
	request.open("POST", url , true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", urlstr.length);
    request.setRequestHeader("Connection", "close");
	request.send(urlstr);
}

function s_POST(params, command, action){
	var request = getAjaxHandle();
	request.onreadystatechange = function(){
		var a = action;
		if(request.readyState == 4){
			if(request.responseXML != null && !request.responseText.match("S_OK") && !request.responseText.match("E_FAIL")){
				a(request.responseXML);
			}else{
				if (a) a(request.responseText);
			}
		}
	};
	request.open("POST", command , true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
	request.send(params);
}

function h_POST(params, command, action){
	var request = getAjaxHandle();
	request.onreadystatechange = function(){
		var a = action;
		if(request.readyState == 4){
			a(request.responseText);
		}
	};
	request.open("POST", command , true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
	request.send(params);
}

function trim(str){
	s = str.replace(/^(\s)*/, '');
	s = s.replace(/(\s)*$/, '');
	return s;
}

function setSelectSelected(select, value, default_val){
	var s;
	if (typeof select == "string") s = getObj(select);
	else if (select.nodeName == "SELECT") s = select;
	else return;
	var opts = s.options;
	var f = false;
	if(opts == null) return;
	
	var x = 0;
	for(x=0; x<opts.length && opts[x].value!=value; x++){}
	if(x<opts.length) s.selectedIndex = x; f = true;
	if(!f && default_val) setSelectSelected(select, default_val);
}

// Taken from quirksmode.org
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

// Implementation of getElementById that can be called on an element to get a
// child node
function getElementById(root, id){
	if(root){
		var y = root.childNodes.length;
		for(var x=0; x<y; x++){
			// If I'm the node return me.
			if(root.childNodes[x].id == id){
				return root.childNodes[x];
			}
			if(root.childNodes[x].hasChildNodes){
				var found = getElementById(root.childNodes[x], id);
				if(found != false){
					return found;
				}
			}
		}
	}
	return false;
}

function nodeListToArray(inc){
	var n_array = new Array();
	var y = inc.length;
	for(var x=0; x<y; x++){
		n_array[x] = inc.item(x);
	}
	return n_array;
}

function attach_script(inc, action){
	var s	= createObj("script");
	s.type	= "text/javascript";
	s.src	= inc;
	var h	= document.getElementsByTagName("head")[0];
	h.appendChild(s);
}

function clean_up_script(inc){
	var s = document.getElementById(inc);
	s.parentNode.removeChild(s);
}

// [0] = return code.
// [1] = message (if there is one empty otherwise)
function parse_return_code(inc){
	var tokens = "";
	var code = 0;
	var return_message = null;
	var error_message = null;
	if(inc.length){// A string response
		tokens = inc.split(":");
		if(tokens[1]) code = parseInt(tokens[1]);
		else code = -1;
		
		if(tokens[2]) return_message = tokens[2];
	}else{
		var info = inc.getElementsByTagName("info");
		info = info[0];
		code = parseInt(info.getAttribute("return_code"));
		if(info.getAttribute("return_message")) return_message = info.getAttribute("return_message");
		error_message = info.textContent;
	}
	return new Array(code,return_message, error_message);
}

function booleanShift(incoming, offset, length) {
	return ((Math.pow(2, length) - 1) & (incoming >> offset));
}

function displayPO(incoming, headerContent, content) {
	var root 	= document.getElementsByTagName("body")[0];
		root.style.overflow = "hidden";
	var po_div		= createObj("div");
		if (incoming) { po_div.id = incoming + "_po"; }
		else { po_div.id = "disp_po"; }

	var po_header	= createObj("div");
		if (incoming) { po_header.id = incoming + "_po_header"; }
		else { po_header.id = "disp_po_header"; }

		var close	= "<a href='#' class= 'close' onclick=\"close_pm()\">Close</a>";
		var reply	= "<a href='#' class= 'reply' onclick=\"reply_pm(this)\" pm_id='" + pm.getAttribute("pm_id") + "'>Reply</a>";

		var header	= createObj("h1");
			header.innerHTML += close;
			header.innerHTML += reply;
			if (headerContent) { header.innerHTML 	+= headerContent; }
		
		po_header.appendChild(header);
		po_div.appendChild(pm_header);

	var pm_msg		= createObj("div");
		pm_msg.id	= "disp_msg";
		var from	= createObj("p");
		var subject	= createObj("p");
		subject.className = "text";
		var subjectLabel = createObj("label");
		var content	= createObj("p");
		content.className = "text";
		var contentLabel = createObj("label");
		
		from.innerHTML 		= "Sent by " + sender.getAttribute("user_name") + " -- " + pm.getAttribute("pm_timestamp");
		subject.innerHTML	= pm.getAttribute("pm_title");
		subjectLabel.innerHTML = "Subject:";
		content.innerHTML	= pm.getAttribute("pm_content");
		contentLabel.innerHTML = "Content:";

		pm_msg.appendChild(subjectLabel);
		pm_msg.appendChild(subject);
		pm_msg.appendChild(contentLabel);
		pm_msg.appendChild(content);
		pm_msg.appendChild(from);
		po_div.appendChild(pm_msg);
	
	po_div.style.width = (getClientWidth() / 2) + "px";
	po_div.style.left 		= (getClientWidth() / 4) + "px";
	po_div.style.top 		= (getClientHeight() / 4) + "px";

	var po_background = createObj("div");
	po_background.id = "po_background";
	po_background.innerHTML = "&nbsp;";

	root.appendChild(pm_background);
	if(document.getElementById("disp_po")){ root.removeChild(document.getElementById("disp_po")); }		
	root.appendChild(po_div);
}

function getObj(inc) { return document.getElementById(inc); }
function createObj(inc) { return document.createElement(inc); }

function toggleDiv(incoming, outgoing) {
	if (outgoing !=null) {
		if (typeof outgoing === 'object' && outgoing instanceof Array) {
			for (var x=0;x<outgoing.length;x++) { getObj(outgoing[x]).style.display = "none"; }
		} else { getObj(outgoing).style.display = "none"; }
	}
	if (incoming!=null) {
		if (typeof incoming === 'object' && incoming instanceof Array) {
			for (var x=0;x<incoming.length;x++) { getObj(incoming[x]).style.display = "block"; }
		} else { getObj(incoming).style.display = "block"; }
	}
}

function toggleMenu(inc){
	var li = inc.parentNode;
	if(li.className.match(/open/i)) li.className = "closed";
	else li.className = "open";
}

function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}
function getDOMText(incoming) {
	if (incoming.text) { return incoming.text; }
	else if (incoming.textContent) { return incoming.textContent; } 
	else { return ""; }
}

function openModal(inc, x, y, position) {
	showOverlayBG();
	var overlay = $("#" + inc);
	$(overlay).css({"visibility": "visible", "display": "block"});
	if (x != null) $(overlay).width(x + "px");
	if (y != null) {
		$(overlay).height(y + "px");
		$("div.guts").height(y - 79);
	}
	$(overlay).center();
}

function getModal(inc, x, y, position, callback) {
	var div = $("#" + inc + "_overlay");
	if (div.length == 0) div = $("<div id='" + inc + "_overlay' class='overlay ui-radius-large'></div>").appendTo("body");
	showOverlayBG();
	$(div).empty().css({"visibility": "visible", "width": "100px", "height": "50px", "opacity": 0, "display": "block"}).center().animate({"opacity": 1}, 250);
	$.get('/modals.php?' + inc, function(data) {
		var temp = $("<div class='overlay ui-radius-large'></div>").appendTo("body");
		if (x) $(temp).css({"width": x + "px"});
		if (y) $(temp).css({"height": y + "px"});
		var dataobj = $("<div>" + data + "</div>").appendTo(temp);
		$(div).animate({
				"width": $(temp).width(),
				"left": (($(window).width() - $(temp).width()) / 2),
				"height": $(temp).height(), 
				"top": (($(window).height() - $(temp).height()) / 2)
			}, 
			500,
			function(){
				$(dataobj).detach().css({"display": "none", "opacity": 1}).appendTo(div).fadeIn();
				$(div).find("a.close").click(function(){
					closeModal(inc+"_overlay");
					positionMHMessages(null, 250);
				});
				$(temp).remove();
			}
		);
		if(callback !=null) callback();
	});
}

function defaultModal(inc) {
	$("#" + inc + " input").each(function(){$(this).removeClass("error"); $(this).val("");});
	$("#" + inc + " textarea").each(function(){$(this).removeClass("error"); $(this).val("");});
	$("#" + inc + " div.error").each(function(){ $(this).html(""); $(this).hide(); });
}

function closeModal(inc) {
	$("#" + inc).fadeOut();
	hideOverlayBG();
	defaultModal(inc);
}

function hideModals() { $(".overlay").hide(); }

function clearInputs(inputs) {
	for (var x = 0; x < inputs.length; x++) {
		switch (inputs[x].getAttribute("type")) {
		case "checkbox":
			inputs[x].checked = false;
			break;
		case "radio":
			if (inputs[x].value == 0) inputs[x].checked = true;
			else inputs[x].checked = false;
			break;
		case "text":
		case "password":
			inputs[x].value = "";
			break;
		default: break;
		}
	}
}

function clearSelects(selects) { for (var x = 0; x < selects.length; x++) { setSelectSelected(selects[x], 0); }}
function removeChildren(inc){ if (!inc) return; if (inc.hasChildNodes()) { while (inc.childNodes.length >= 1){ inc.removeChild(inc.firstChild ); }}}


/*
function not_lost_pass(){
	var urlstr="/leftbar/leftbar.php?m=not_lost&";


	var request = getAjaxHandle();
	request.open("GET", urlstr , true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var returnAble = request.responseText;
			document.getElementById("leftmenu_User").innerHTML = returnAble;
		}
	};
	request.send(null);
}

function lost_pass(){
	var urlstr="/leftbar/leftbar.php?m=lost&";
	
	
	var request = getAjaxHandle();
	request.open("GET", urlstr , true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var returnAble = request.responseText;
			document.getElementById("leftmenu_User").innerHTML = returnAble;
		}
	};
	request.send(null);
}

function retrieve_pass(){
	var url="/leftbar/leftbar.php?m=retrieve&";
	var urlstr = "e=" + document.getElementById("leftbar_user_loginEmail").value + "&l=" + document.getElementById("leftbar_user_loginID").value;
	
	var request = getAjaxHandle();
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var returnAble = request.responseText;
			document.getElementById("leftmenu_User").innerHTML = returnAble;
		}
	};
	request.open("POST", url , true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", urlstr.length);
 	request.setRequestHeader("Connection", "close");
	request.send(urlstr);

}*/

function login(){ if (!LOGGINGIN) { LOGGINGIN = true; POST("loginform", "/user/user.php?a=login", process_login_response); }}
function logout(){ s_POST("", "/user/user.php?a=logout", process_logout_response); }
function createAccount(){ POST("newaccForm", "/user/user.php?a=create-account", process_account_creation_response); }
function ftl_createAccount(){ POST("ftl_form", "/user/user.php?a=ftl-create-account", process_ftl_account_creation_response); }
function mhmredraw() { h_POST("", "/draw.php?draw=mh", redrawMastheadmenu); }
function redrawMastheadmenu(inc) { var masthead = getObj("mastheadmenu"); masthead.innerHTML = inc; }
function goHome() { window.location="/index.php?m=properties&g=" + document.mhForm.g.value; }

function positionMHMessages(inc, time) {
	if (!inc) {
		$(".mhmessage").each(function() { hideMHMessage($(this).attr("id"), time); });
		$("#imageblockmini").hide();
		$("#imageblockfull").hide();
		$("#closeGalleryBtn").empty().remove();
		hideOverlayBG();
	} else {
		showOverlayBG();
		$(".mhmessage").each(function() { if ($(this).attr("id") != inc) { hideMHMessage($(this).attr("id"), time); } });
		showMHMessage(inc, time);
	}
}
function showMHMessage(inc, time) {
	if (!time) time = 250;
	$("#"+inc).animate({top: "32px"}, time);
}
function hideMHMessage(inc, time){
	var div = $("#" + inc);
	if (div) {
		if (!time) $(div).css({top: "-" + $(div).height() + 100 +"px"});
		else $(div).animate({top: "-" + $(div).height()+ 100 + "px"}, time);
	}
	defaultModal(inc);
}

function showOverlayBG() { if (!$("#overlayBG").css("display","block").length) $("<div id='overlayBG' class='overlayBG'></div>").appendTo($("body")).css("display","block").bind("click", function() { positionMHMessages(null, 250); hideModals(); }); }
function hideOverlayBG() { if (!$("#overlayBG").css("display","none")) $("<div id='overlayBG' class='overlayBG'></div>").css("display","none").appendTo($("body")).bind("click", function() { positionMHMessages(null, 250); hideModals(); }); }
function removeMHMessage(inc) { var temp = $("#" + inc).remove(); }

var timer = null;
function process_login_response(inc){
	var string = new String(inc);
	tokens  = string.split(":");
	switch(tokens[1]){
	case "0":
		alert(tokens[2]);
		window.location.assign("/index.php");
		break;
	case "1":
		LOGGINGIN = false;
		positionMHMessages(null, 250);
		mhmredraw();
		var h = "Logged in!";
		var b = "You've been successfully logged in and we're forwarding you to your property panel!";
		var i = "gears";
		var linkarray = new Array();
		linkarray.push(["closethismessage", "Close this message", "", "clearTimeout(timer); positionMHMessages(null, 250);"]);
		linkarray.push(["gototheproperties","Go to the Property Panel","/index.php?m=properties","clearTimeout(timer); window.location.assign(\"/index.php?m=properties\")"]); 
		//linkarray.push(["gotothelistings","Go to My Listings","/index.php?m=listings","clearTimeout(timer); window.location.assign(\"/index.php?m=listings\")"]);
		var message = new MHMessage(h, b, i, linkarray);
		setTimer("gototheproperties", 10);
		break;
	case "2":
	case "3":
		LOGGINGIN = false;
		alert(tokens[2]);
		break;
	}
}

function setTimer(link, time) {
	if (link == null) return;
	linkobj = getObj(link);
	var span = linkobj.getElementsByTagName("span");
	if(span.length > 0) span = span[0];
	else {
		span = document.createElement("span");
		linkobj.appendChild(span);
	}
	if (time <= 0) {
		eval(linkobj.getAttribute("onclick"));
		return;
	}
	span.innerHTML = " (" + time + ")";
	timer = setTimeout("setTimer('" + link + "', " + (time-1) + ")", 1000);
}

function process_logout_response(inc){
	var string = new String(inc);
	tokens  = string.split(":");
	alert(tokens[2]);
	window.location.assign("/index.php");
}

function process_account_creation_response(inc){
	$("#naError").fadeOut().empty();
	$("#newaccForm input").each(function(){ $(this).removeClass("error");});
	var string = new String(inc);
	tokens  = string.split(":");
	switch(tokens[1]){
		case "5": break;
		case "20"://email bad
			alert(tokens[2]);
			$("#naError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> " + tokens[2] + "</p>").css({height: "auto"}).fadeIn();
			$("#email1").addClass("error");
			$("#email2").addClass("error");
			break;
		case "21"://pass bad
			$("#naError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> " + tokens[2] + "</p>").css({height: "auto"}).fadeIn();
			$("#password1").addClass("error");
			$("#password2").addClass("error");
			break;
		case "22"://pass and email bad
			$("#naError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> " + tokens[2] + "</p>").css({height: "auto"}).fadeIn();
			$("#email1").addClass("error");
			$("#email2").addClass("error");
			$("#password1").addClass("error");
			$("#password2").addClass("error");
			break;
		case "23"://Bad User/Group Name
			$("#naError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> That account name has already been taken.</p>").css({height: "auto"}).fadeIn();
			$("#username").addClass("error");
			break;
		case "25":
			$("#naError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> The email address you have supplied has already been used to create a newDigs account.</p>").css({height: "auto"}).fadeIn();
			$("#email1").addClass("error");
			$("#email2").addClass("error");
			break;
		case "24"://Other
			alert(tokens[2]);
			$("#naError").empty().fadeOut();
		default:
			alert(tokens[2]);
			window.location.assign("/index.php");
			break;
	}
}

function process_ftl_account_creation_response(inc){
	$("#ftlError").fadeOut().empty();
	var string = new String(inc);
	tokens  = string.split(":");
	switch(tokens[1]){
		case "5": break;
		case "20"://email bad
			$("#ftlError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> The email address you have supplied is not in the correct format.  Please try again or contact beta@newdigs.com for support.</p>").css({height: "auto"}).fadeIn();
			break;
		case "21"://pass bad
			$("#ftlError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> The passwords you have supplied do not match.  Please try again.</p>").css({height: "auto"}).fadeIn();
			break;
		case "22"://pass and email bad
			$("#ftlError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> The email address you have supplied is not in the correct format and your passwords do not match.  Please try again.</p>").css({height: "auto"}).fadeIn();
			break;
		case "23"://Bad User/Group Name
			$("#ftlError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> That account name has already been taken.</p>").css({height: "auto"}).fadeIn();
			break;
		case "25":
			$("#ftlError").html("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> The email address you have supplied has already been used to create a newDigs account.</p>").css({height: "auto"}).fadeIn();
			break;
		case "24"://Other
			alert(tokens[2]);
			$("#ftlError").empty().fadeOut();
		default:
			alert(tokens[2]);
			window.location.assign("/index.php");
			break;
	}
}

function MHMessage (heading, msg, imgclass, linkArray) {
	var messagebody = $("#mhmessage");
	if ($(messagebody).length) {
		$(messagebody).css({top:"-500px"});
		$(messagebody).html("");
	} else $("<div id=\"mhmessage\" class=\"mhmessage\"></div>").css({top: "-500px"}).appendTo('body');

	var contents = "<h2><span class=\"l icon-48 "+imgclass+"\"></span>"+heading+"</h2><p>" + msg + "</p>";
	if(linkArray!=null && linkArray.length > 0) { 
		contents += "<ul>";
		for (var x = 0; x < linkArray.length; x++) { 
		 	var link = "<li><a";
			if (linkArray[x][0] != null && linkArray[x][0] != "") link += " id='" + linkArray[x][0] + "'";
			if (linkArray[x][2] != null && linkArray[x][2] != "") link += " href='" + linkArray[x][2] + "'";
			if (linkArray[x][3] != null && linkArray[x][3] != "") link += " onclick='" + linkArray[x][3] + "'";
			if (linkArray[x][4] != null && linkArray[x][4] != "") link += " title='" + linkArray[x][4] + "'";
			else link += " title='" + linkArray[x][1] + "'";
			link +=">" + linkArray[x][1] + "</a></li>";
			contents += link;
		}
	}
	contents += "</ul>";
	$("<div class=\"content\">" + contents + "</div>").appendTo($("#mhmessage"));
	positionMHMessages('mhmessage',250);
}

function feedbackSubmit() {
	var fbError = $("#fbError");
	$("#fbForm input").each(function(){$(this).removeClass("error");});
	$("#fbForm textarea").each(function(){$(this).removeClass("error");});
	fbError.fadeOut();
	var vars = {
		"fb_name": $("#fb_name").val(),
		"fb_email": $("#fb_email").val(),
		"fb_message": $("#fb_message").val(),
		"fb_contact": $("#fb_contact:checked").val()
	};
	$.getJSON('/user/user_feedback.php?contact', vars, function(response) {
		fbError.html("");
		var messages = response['messages'];
		var errors = response['errors'];
		var success = response['success'];
		if (success) {
			alert(messages[0]);
			closeModal("fb_overlay");
		} else {
			for (var error in errors) {
				switch(errors[error]["type"]){
					case "highlight":
						if (errors[error]["id"]) $(errors[error]["id"]).addClass("error");
						break;
					case "fatal":
						debug("fatal error");
						break;
					default:
						debug("unhandled error case");
						break;
				}
			}
			for (var message in messages) {
				var error = createObj("p");
				$("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"></span><strong>Alert:</strong> "+ messages[message] +"</p>").appendTo(fbError);
			}
			$(fbError).css({height: "auto"}).fadeIn();
		}
	});
}

function ndls_search(inc) {
	if (inc.nodeName != "FORM") {
		while(inc.nodeName != "FORM") {
			if (inc.nodeName == "BODY") return;
			inc = inc.parentNode;
		}
	}
	input = $(inc).find("[name=ndlsno]");
	if ($(input).val() != null)
		if ($(input).val() != "" & $(input).val() != "Listing #") {
			debug($(input));
			debug($(input).val());
			s_POST("fetch=" + $(input).val(), "/listing/getListing.php?a=fetch", ndls_response);
		}
}


function ndls_response(inc) {
	var tokens = "";
	var val, code = 0;
	var return_message = null;
	if(inc.length){
		tokens = inc.split(":");
		if(tokens[1]) code = parseInt(tokens[1]);
		else code = -1;
		if(tokens[2]) return_message = tokens[2];
	}
	else return;
	alert(return_message);
	var input = $("form").find("[name=ndlsno]");
	if (input.length == 0) return;
	if (input.length == 1) val = $(input).val();
	else input.each(function(){ if ($(this).val() != "" && $(this).val() != "Listing #") val = $(this).val(); });
	val = val.substring(1);
	
	switch(code) {
		case 80: window.location.assign('/listing/listing.php?u=' + val,'unit'+val); break; 
		case 82: alert("Property listings are coming soon!"); break; 
		default: break;
	}
}

function showGroupList() {
	debug($("#stbGroupLinks").length);
	if ($("#stbGroupLinks").css("visibility") == "visible") $("#stbGroupLinks").css({"visibility":"hidden", "left": "-1000px;"});
	else {
		var position = findPos(getObj("stbGroupBtn"));
		debug (position);
		$("#stbGroupLinks").css({"visibility":"visible", "left": position[0] - $("#stbGroupLinks").width() + "px", "top": position[1] + 20 + "px"});
	}
}

function getArticles(){ $("div.article").each(function(i){ var header = $(this).find("h2").html(); var that = this; $("<li><a>" + header + "</a></li>").appendTo("#articleList").bind("click", function(){ var pos = findPos(that)[1] - 70; $(window).scrollTop(pos); }); }); }
function getAjaxHandle(){var xmlHttp = false;if(navigator.appName.match("Microsoft")){ try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ try{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ }}}else{try{xmlHttp = new XMLHttpRequest();}catch(e){}}return xmlHttp;}
jQuery.fn.center = function(){ this.css({"top": (($(window).height() - $(this).height()) / 2), "left": (($(window).width() - $(this).outerWidth()) / 2) }); return this; }
jQuery.fn.centerHorizontal = function(callback){ this.css({"left": parseInt(($(window).width() - $(this).outerWidth(true)) / 2)}); if(typeof callback == 'function') callback.call(this); return this; }
jQuery.fn.centerVertical = function(){ this.css({"top": (($(window).height() - $(this).outerHeight()) / 2)}); return this; }

$(document).ready(function(){
	positionMHMessages();
	$(".mhmessage a.close").each( function() { $(this).bind("click", function(){ positionMHMessages(null, 250); }); });
	$(".overlay a.close").each(function() { $(this).bind("click", function(){ closeModal($(this).parent().attr("id")); positionMHMessages(null, 250); }); });
	$("#loginBtn").bind("click", function(){login();});
	$("#newAccBtn").bind("click", function(){createAccount();});
	$(window).bind("resize", function() { $(".overlay").each(function(){$(this).center(); }); });
});
