var LOGGINGIN = false;

function debug(msg) { if (window.console && window.console.log) window.console.log(msg); }
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 = $(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);
}

// 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;
}

// [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 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 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 login(refresh){
	if(!refresh) refresh = false;
	if (!LOGGINGIN) {
		$("#btn-login").addClass("disabled").unbind("click").prepend("<img src='/images/loading_btn_bl2.gif'/>");
		LOGGINGIN = true;
		$.post("/user/user.php?a=login", $("#loginform").serialize(), function(data){
			if(!refresh) $("#loginform").hide();
			process_login_response(data, refresh);
		});
	}
}
function logout(){ $.post("/user/user.php?a=logout", function(data){process_logout_response(data); }); }
function process_logout_response(inc){
	$("#mast ul").find("ul").remove();
	$("#mast ul").animate({"margin-top":"-80px"}, 800, function(){ window.location.assign("/"); });
}
function showCreateAccount(email){
	if($("#loginform")) $("#loginform").hide();
	if($("#tt")) $("#tt").hide();
	var ca = $("#camodal"); 
	ca.empty().remove();
	ca = $("<div id='camodal'></div>").appendTo("body"); 
	ca.load("/home/modals.php?create_account", function() {
		$(".errorMessage").empty().remove();
		$(this).dialog({
			width: 540,
			title:"Create <i>an</i> <b>account!</b>",
			resizeable: false,
			dialogClass: "full",
			modal: true,
			dragStart: function(){$(".errorMessage").fadeTo('fast', .2);},
			dragStop: function(){redrawErrors();redrawErrors(); $(".errorMessage").fadeTo('fast', 1);},
			close: function(){$(".errorMessage").empty().remove();$("#btn-signup").attr('onClick', 'showCreateAccount()');},
			resizeStart: function(){$(".errorMessage").fadeTo('fast', .2);},
			resizeStop: function(){redrawErrors(); redrawErrors();$(".errorMessage").fadeTo('fast', 1);}
		});
		configCreateAccount();
		$("#newAccBtn").bind("click", function(){
				createAccount();
			});
		$("#camodal").bind("keypress", function(e){
				if(e.keyCode==13){ 
					createAccount();
				}
			});
		if($("#loading"))	$("#loading").remove();
		if(email){
		$("#email1").val(email);
		$("#email2").val(email);
		}
	});
	$("#btn-signup").attr('onClick', '');
}

function createAccount(){
	if ($("#newaccForm").valid()) {
		var btn = $("#newAccBtn");
		$("<img id='loading' src='/images/loading_btn_g.gif'/>").prependTo(btn);
		btn.addClass("disabled").unbind("click").css({"cursor": "default"});
		var email = $("#email1").val();
		var post = $("#newaccForm").serialize();
		$.post(
			"/user/user?create", 
			post, 
			function(data){
				$("#camodal").empty();
				$(".errorMessage").empty().remove();
				$("#camodal").html("<div style='float: left; height: 80%; width: 100%; '>"+data+"</div>");
				$("#tryAgain").bind("click", function(){showCreateAccount(email);});
				$("#getStarted").bind("click", function(){$("#camodal").empty().remove();});
				$("#btn-signup").attr('onClick', 'showCreateAccount()');
		});
	}

}
function configCreateAccount() {
	if (jQuery().validate) {
		$("#newaccForm").validate({ 
			rules: { 
				email1: { 
					required: true, 
					email: true,
					remote: {
					url: "/user/user?validate",
					type: "post"
					}
				},
				email2: {
					required: true,
					equalTo: "#email1",
					email: true 
				},
				username: {
					required: false,
					remote: {
						url: "/user/user?validate",
						type: "post"
					}
				},
				password1: {
					required: true,
					minlength: 6 
				},
				password2: {
					required: true,
					equalTo: "#password1"					
				}
				
			},
			messages: {
				email1:  {
					email: "Must be in the form of an email address (i.e.  example@newdigs.com).",
					remote: "<p>This email address is already in our system.</p><a class='forgot nd-btn xsm r' onclick='modalForgotPass()' title='Forgot your password?'>Forgot password?</a>",
					required:  "Must be in the form of an email address (i.e.  example@newdigs.com)."
					},
				email2: "Must exactly match the other email address.",
				username: {
					remote: "Someone is already using that nickname :("
				},
				password1: "Your password must be at least 6 characters in length.",
				password2: "Your passwords don't match!"					
			},
			errorElement: "span",
			errorPlacement: function(error, element) { 
				drawErrors(error, element);
			},	
			unhighlight:function(element, errorClass, validClass) { $(element).removeClass("error"); $("#"+$(element).attr('id')+"Error").empty().remove();},
			submitHandler: function(){$(".errorMessage").empty().remove();}
		});
	} else {
		$.getScript('/js/jquery.validate.min.js', function() { configCreateAccount(); });
	}
}


function ftl_createAccount(){ POST("ftl_form", "/user/user.php?a=ftl-create-account", process_ftl_account_creation_response); }
function goHome() { window.location="/index.php?m=properties&g=" + document.mhForm.g.value; }
function maxZIndex(){
	var maxZ = 0; 
	$("div").each(function(){
		var z = parseInt($(this).css('z-index'));
		if(z!='auto'&&z<10000){	
			if (z>maxZ){
				maxZ=z;
			}	
		}
	});
return maxZ;
}
function redrawMast() {
	$("#mast ul").animate({});
	$("#mast div").empty();
	$("#mast").css({"margin-top":"-80px"}).load("/user/user.php?draw=mh", function() { $(this).animate({"margin-top":"0px"}); });
}

function drawErrors(error, element){
	if (!element || !element.is(":visible")) return;
	$(element).addClass("error"); 
	var offset = element.offset();
	var height = element.height();
	var width = element.width();
	if($("#"+$(element).attr('id')+"Error").length==0){9
		var pointer = $("<div class='pointer-left-outer' style='position:absolute; left: -8px; top: 3px; border-top: 7px solid transparent; border-bottom: 7px solid transparent; border-right: 8px solid #d28c00; border-left: 0;  z-index: 1002;'><div class='pointer-left-inner' style='position: absolute; left: 3px; top: -5.5px; border-top: 6px solid transparent; border-bottom: 6px solid transparent; border-right: 7px solid white; border-left: 0;'></div></div>");
		var errorDiv = $("<div id='"+$(element).attr('id')+"Error' class='errorMessage ui-corner-all' style='position: absolute; padding: 3px; left: "+(offset.left+width+5)+"px; top: "+(offset.top+(height/2)-4.5)+"px; background: white; border: 2px solid #d28c00; z-index: 1002;'></div>"); 
		errorDiv.appendTo("body");
		$(error).appendTo(errorDiv);
		$(pointer).appendTo(errorDiv);
		resizePointers();
		redrawErrors();
	}

}
function resizePointers(){
	$(".pointer-left-outer").each(function(){
		var height = parseInt($(this).parent().css('height'));
		height = (height/2-3);
		$(this).css('top', height);
	});
}
function redrawErrors(){
	$(".errorMessage").each(function(){
			var handle = $(this).attr('id');
			var input = handle.substring(0, handle.indexOf("Error"));
			var offset = $("#"+input).offset();
			var height = $("#"+input).height();
			var divHeight = parseInt($(this).height());
			var width = $("#"+input).width();
			var zIndex = maxZIndex();
			$(this).css({ 'left': offset.left+width+24, 'top': (offset.top-(divHeight/2)+9), 'z-index': zIndex});
			$(this).fadeIn('slow');
	});
	resizePointers();
	
}

function process_login_response(inc, refresh){
	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;
		if(refresh){
			window.location.reload();
			return;
		}
		var unique_id = $.gritter.add({ title: 'Logged in!', text: "You've been successfully logged in! Please note that your menu items have changed.", sticky: false, time: '5000' });
		redrawMast();
		break;
	case "2":
	case "3":
		LOGGINGIN = false;
		alert(tokens[2]);
		break;
	}
}

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 modalFB() {
	//pageTracker._trackPageview('/feedback/go');
	var fbmodal = $("#fbmodal"); 
	fbmodal.empty().remove();
	fbmodal = $("<div id='fbmodal'></div>").appendTo("body"); 
	fbmodal.load("/home/modals.php?fb", function() {
		$(this).dialog({
			width: 707,
			title:"Send <i>us your</i> <b>feedback!</b>",
			resizeable: false,
			dialogClass: "full message",
			modal: true
		});
	});
}


function feedbackSubmit() {
	var vars = {
		"fb_name": $("#fb_name").val(),
		"fb_email": $("#fb_email").val(),
		"fb_message": $("#fb_message").val(),
		"fb_contact": $("#fb_contact:checked").val()
	};
	$.post('/user/user_feedback.php?contact', vars, function(data) {
		var response = eval(data);
		var message = response.message;
		var errors = response.errors;
		var success = response.success;
		alert(message);
		if (success) {
			$("#fbmodal").dialog("close");
		}
	});
}

function insuranceSubmit() {
	$.post('/user/user_feedback.php?insurance', $("#insurForm").serialize(), function(data) {
		var response = eval(data);
		var message = response.message;
		var errors = response.errors;
		var success = response.success;
		alert(message);
		if (success) {
			$("#insurmodal").dialog("close");
		}
	});
}

function ndls_modal() {
	if ($("#ndlsno").length > 0) {
		$("#ndlsno").focus();
		$("html").scrollTop((($("#ndlsno").offset()).top)-100);
	} else {
		var ndls = $("#ndls");
		ndls.empty().remove();
		ndls = $("<div id='ndls'></div>").appendTo("body");
		ndls.load("/home/modals.php?ndls", function() {
				$(this).dialog({
						width: 400,
						dialogClass:"full forgotpass", 
						title:"<b>Listing lookup</b>",
						modal: true,
						close: function(){ hideTT(); $(this).empty().remove();}
					}).css({"overflow":"hidden"});
				$("#ndls_search").hover(
					function(){$("#ndls_lawnsign").attr("src", "/images/lawnsign_yourmom-wink.png") },
					function(){$("#ndls_lawnsign").attr("src", "/images/lawnsign_yourmom.png");}
				).click(function(){ndls_search();});
		});
	}
}

function ndls_search() {
	var val = $("#ndlsno").val();
	if (val && val !="" && val != "Listing #") $.post("/listing/getListing.php?a=fetch", "fetch=" + val, function(data){ndls_response(data); });
}

function ndls_response(inc) {
	if (!inc) return;
	var json = eval(inc);
	if (!json || json.length == 0) return;
	var val = $("#ndlsno").val();
	if (json.success) {
		if (json.code == 80) window.location.assign('/' + val);
		else if (json.code == 82) window.location.assign('/' + val);
	} else {
		var error = $("#errorModal"); 
		error.empty().remove();
		error = $("<div id='errorModal'><p>"+json.message+"</p></div>").appendTo("body");
		error.dialog({width: 300, dialogClass:"full", title:"<b>Uh oh!</b>", modal: true, buttons: { "Continue": function(){$("#errorModal").dialog("close").empty().remove(); } }});
	}
}

function showGroupList() {
	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 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;}
$.fn.center = function(){ this.css({"top": (($(window).height() - $(this).height()) / 2), "left": (($(window).width() - $(this).outerWidth()) / 2) }); return this; }
$.fn.centerHorizontal = function(callback){ this.css({"left": parseInt(($(window).width() - $(this).outerWidth(true)) / 2)}); if(typeof callback == 'function') callback.call(this); return this; }
$.fn.centerVertical = function(){ this.css({"top": (($(window).height() - $(this).outerHeight()) / 2)}); return this; }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Twitter

function getTwitterFeed(){
	$.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=Newdigs&count=8&callback=?", 
		function(data){
			var container = $("#tweet_container");
			container.empty();
			$.each(data, function(i,item){
					ct = item.text;
					ct = ct.replace(/http:\/\/\S+/g,'<a href="$&" target="_blank">$&</a>');
					ct = ct.replace(/\s(@)(\w+)/g,' @<a onclick="javascript:pageTracker._trackPageview(\'/outgoing/twitter.com/\');" href="http://twitter.com/$2" target="_blank">$2</a>');
					ct = ct.replace(/\s(#)(\w+)/g,' #<a onclick="javascript:pageTracker._trackPageview(\'/outgoing/search.twitter.com/search?q=%23\');" href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
					container.append("<p class='tweet'>"+ ct +"</div>");
			});
			rotateTwitterFeed();
		});
}

function rotateTwitterFeed() {
	setTimeout("rotateTwitterFeed()", 8000);
	var tweets = $("#tweet_container p");
	$(tweets).each(function(){
			if ($(this).hasClass("visible")) {
				$(this)	.fadeOut(function(){ $(this).removeClass("visible"); });
				if ($(this).next().length) $(this).next().fadeIn(function(){ $(this).addClass("visible"); });
				else $("#tweet_container .tweet").first().fadeIn(function(){ $(this).addClass("visible"); });
			}
	});
	tweets = $("#tweet_container .visible");
	if (tweets.length == 0) $("#tweet_container .tweet").first().fadeIn(function(){ $(this).addClass("visible"); });
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Login related material

function showLogin() {
	$("#loginform").empty().remove();
	var divText = "<form name='loginform' id='loginform' method='post' onsubmit=\"login();return false; javascript:pageTracker._trackPageview('/login/submit');\"><div class='ui-corner-all' id='div-login'><div class='content'><label for='username'>Email address:</label>";
	divText += "<div class='x'><input type='text' class='text' name='loginemail' id='loginemail'/></div><label for='loginpass'>Password:</label>";
	divText += "<div class='x'><input type='password' class='text' name='loginpass' id='loginpass'/><a class='forgot' title='Forgot your password?' onclick='modalForgotPass()'>Forgot password?</a></div>";
	divText += "<div class='c' style='padding-top: 10px;'><a onclick='login();' class='ui-corner-all nd-btn r xsm' id='btn-login' style='padding: 4px 10px'>Login!</a></div></div><div class='up'><div></div></div><a class='close' onclick='$(\"#loginform\").empty().remove();'>&nbsp;</a></div><button style='visibility: hidden' type='submit'></button></form>";
	$(divText).insertAfter("#btn-showlogin");
	$("#loginemail").focus();
}

function modalForgotPass() {
	var forgotmodal = $("#forgotPassModal"); 
	$("#loginform").empty().remove();
	forgotmodal.empty().remove();
	forgotmodal = $("<div id='forgotPassModal'></div>").appendTo("body");
	forgotmodal.load("/home/modals.php?forgotPass", function() {
			$(this).dialog({width: 300, dialogClass:"full forgotpass", title:"<b>Uh oh!</b>", modal: true, close: function(){redrawErrors();redrawErrors();}});
			configForgotPass();
			if($("#email1").val()) $("#forgot_email").val($("#email1").val());
			$("#forgotPassSubmit").click(function(){$('#forgotPassForm').submit();});
			var z = $(".errorMessage").first().css('z-index');
		var zIndex = function(){var a=parseInt(z); return (a-1);};
		$(".errorMessage").each(function(){$(this).css('z-index', zIndex);});
	});
	
}

function configForgotPass() {
	if (jQuery().validate) {
		$("#forgotPassForm").validate({ 
				rules: { forgot_email: { required: true, email: true } },
				errorPlacement: function(error, element) { $(element).addClass("error"); },
				unhighlight:function(element, errorClass, validClass) { $(element).removeClass("error"); },
				submitHandler: function() { }
		});
	} else {
		$.getScript('/js/jquery.validate.min.js', function() { configForgotPass(); });
	}
}

function forgotPassSubmit() {
	if (jQuery().validate) {
		if ($("#forgotPassForm").valid()) {
			var btn = $("#forgotPassSubmit");
			$("<img src='/images/loading_btn_g.gif'/>").prependTo(btn);
			btn.unbind("click");
			$.ajax({ type: "post", url: "/user/user.php?resetpass", data: $("#forgotPassForm").serialize(), success: function(data) { forgotPassHandler(data); }, datatype: "json" });
		}
	}
}

function forgotPassHandler(data) {
	if (!data) return;
	var json = eval(data);
	$("#forgotPassHandler").empty().remove();
	var wndw = $("<div id='forgotPassHandler'></div>").appendTo($("body"));

	if (json.success) $(wndw).html("<p>"+json.message+"</p>").dialog({modal: true, dialogClass: "warn", title: "Alert", buttons: { "Continue": function() { window.location.assign("/"); } } });
	else $(wndw).html("<p>"+json.message+"</p>").dialog({modal: true, dialogClass: "warn", title: "Alert - error: " + json.code, buttons: { "Continue": function() { $(wndw).dialog("close"); } } });
}

function checkTimer() { setTimeout('checkTimer()', 240000);	$.ajax({ type: "post", url: "/user/user.php?keepalive", success: function(data) { }, datatype: "json" }); }

$(document).ready(function(){
	$("#feedback").click(function() { modalFB(); return false;});
	checkTimer();
	$(window).resize(function(){redrawErrors();redrawErrors();});
	
	configMenu();
});

function configMenu() {
	var width = 0;
	$("#mast .menu").each(function(){
		$(this).find("li a").each(function(){
			var temp = $(this).outerWidth();
			if (temp > width) width = temp;
			$(this).css({"display":"block"});
		});
		$(this).find("ul").css({"width":width, "height":0, "right":0});
	}).live({
		mouseenter: function(){
			height = $("ul li", this).length * 34;
			$(this).find("ul").stop().css("visibility", "visible").animate({"height": height }, 300);
		},
		mouseleave: function(){
			$(this).find("ul").stop().animate({"height": 0}, 300, function(){ $(this).css("visibility", "hidden"); });
		}
	});
}


function getSkypeStatus(){
	$.ajax({
		url: "/home/getskypestatus.php",
		success: function(data){
			switch(data) { 
				case "Online": case "Away": $("span.icon-skype").each(function(){ $(this).removeClass("offline").addClass("online").fadeIn(); }); $("span.status-skype").html("Online"); break;
				default: $("span.icon-skype").each(function(){ $(this).removeClass("online").addClass("offline").fadeIn(); }); $("span.status-skype").html("Offline"); break;
			}
		},
		datatype: "xml"
	});
}

/* MINIMIZABLE JQUERY UI DIALOG
Extension of JQuery UI Dialog widget to add custom minimizing capabilities - Written by: Ryan Curtis - modified by Daniel Mooney - introduced toggleable minimize and close*/
(function($){ var _init = $.ui.dialog.prototype._init; $.ui.dialog.prototype._init = function() { var self = this; _init.apply(this, arguments); var uiDialogTitlebar = this.uiDialogTitlebar; this.options.originalWidth = this.options.width; this.options.originalHeight = this.options.height; this.resizeableHandle =  this.uiDialog.resizable().find('.ui-resizable-se'); this.titlebarHeight = parseInt(uiDialogTitlebar.css('height')) + parseInt(uiDialogTitlebar.css('padding-top')) + parseInt(uiDialogTitlebar.css('padding-bottom')) + parseInt(this.uiDialog.css('padding-top')) + parseInt(this.uiDialog.css('padding-bottom')) ; if (this.options.minimizable == true && this.options.modal == false) { uiDialogTitlebar.append('<a href="#" class="dialog-restore ui-dialog-titlebar-rest"><span class="ui-icon ui-icon-newwin ui-corner-all"></span></a>'); uiDialogTitlebar.append('<a href="#" class="dialog-minimize ui-dialog-titlebar-min"><span class="ui-icon ui-icon-minusthick ui-corner-all"></span></a>'); this.uiDialogTitlebarMin = $('.dialog-minimize', uiDialogTitlebar).hover( function(){ $(this).addClass('ui-state-hover'); }, function(){ $(this).removeClass('ui-state-hover'); }).click(function(){ self.minimize(); return false; }); this.uiDialogTitlebarRest = $('.dialog-restore', uiDialogTitlebar).hover( function(){ $(this).addClass('ui-state-hover'); }, function(){ $(this).removeClass('ui-state-hover'); }).click(function(){ self.restore(); self.moveToTop(true); return false; }).hide(); this.uiDialog.bind('dialogbeforeclose', function(event, ui) { self.uiDialogTitlebarRest.hide(); self.uiDialogTitlebarMin.show(); }); } if (this.options.removeClose == true) { uiDialogTitlebar.find(".ui-dialog-titlebar-close").empty().remove(); uiDialogTitlebar.find('.dialog-minimize').css({right: 0}); uiDialogTitlebar.find('.dialog-restore').css({right: 0}); } }; $.extend($.ui.dialog.prototype, { restore: function() { this.uiDialog.resizable( "option", "disabled", false ); var windowHeight = $(window).height(); var dialogHeight = this.options.originalHeight; var dialogTop = parseInt(this.uiDialog.css('top')); if(dialogHeight+dialogTop > windowHeight){ var newTop = windowHeight-dialogHeight-22; this.uiDialog.css('top',newTop); }			 var windowWidth = $(window).width(); var dialogWidth = this.options.originalWidth; var dialogLeft = parseInt(this.uiDialog.css('left')); if(dialogWidth+dialogLeft > windowWidth){ var newLeft = windowWidth-dialogWidth-2; this.uiDialog.css('left',newLeft); } this.uiDialog.css({width: this.options.originalWidth, height:this.options.originalHeight}); this.element.show(); this.resizeableHandle.show(); this.uiDialogTitlebarRest.hide(); this.uiDialogTitlebarMin.show(); }, minimize: function() {  this.uiDialog.resizable( "option", "disabled", true ); this.options.originalWidth = this.options.width; this.options.originalHeight = this.options.height; this.uiDialog.animate({width: 200, height:this.titlebarHeight},200); this.element.hide();this.uiDialogTitlebarMin.hide(); this.uiDialogTitlebarRest.show(); this.resizeableHandle.hide(); } }); })(jQuery);

/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 * Only slightly modified by Daniel Mooney, who thinks James is generally cool.
 */
(function(a){a.fn.autoResize=function(j){var b=a.extend({onResize:function(){},animate:true,animateDuration:150,animateCallback:function(){},extraSpace:20,limit:1000},j);this.filter('textarea').each(function(){var c=a(this).css({resize:'none','overflow-y':'hidden'}),k=c.height(),f=(function(){var l=['height','width','lineHeight','textDecoration','letterSpacing'],h={};a.each(l,function(d,e){h[e]=c.css(e)});return c.clone().removeAttr('id').removeAttr('name').css({position:'absolute',top:0,left:-9999}).css(h).attr('tabIndex','-1').insertBefore(c)})(),i=null,g=function(){f.height(0).val(a(this).val()).scrollTop(10000);var d=Math.max(f.scrollTop(),k)+b.extraSpace,e=a(this).add(f);if(i===d){return}i=d;if(d>=b.limit){a(this).css('overflow-y','');return}b.onResize.call(this);b.animate&&c.css('display')==='block'?e.stop().animate({height:d},b.animateDuration,b.animateCallback):e.height(d)};c.unbind('.dynSiz').bind('keyup.dynSiz',g).bind('click.dynSiz',g);});return this}})(jQuery);
/*!
 * jQuery Selectbox plugin 0.1.2
 *
 * Copyright 2011, Dimitar Ivanov (http://www.bulgaria-web-developers.com/projects/javascript/selectbox/)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
 * 
 * Date: Fri Mar 18 22:28:49 2011 +0200
 */
(function ($, undefined) {var PROP_NAME = 'selectbox',FALSE = false,TRUE = true;function Selectbox() {this._state = [];this._defaults = {classHolder: "sbHolder ui-corner-all",classHolderDisabled: "sbHolderDisabled",classSelector: "sbSelector",classOptions: "sbOptions",classToggleOpen: "sbToggleOpen",classToggle: "sbToggle",effect: "slide",onChange: null,onOpen: null,onClose: null};this._width = 0;}$.extend(Selectbox.prototype, {_isOpenSelectbox: function (target) {if (!target) {return FALSE;}var inst = this._getInst(target);return inst.isOpen;},_isDisabledSelectbox: function (target) {if (!target) {return FALSE;}var inst = this._getInst(target);return inst.isDisabled;},_attachSelectbox: function (target, settings) {if (this._getInst(target)) {return FALSE;}var $target = $(target),self = this,inst = self._newInst($target),sbHolder, sbSelector, sbToggle, sbOptions,s = FALSE, opts = $target.find("option"), olen = opts.length;$target.attr("sb", inst.uid);$.extend(inst.settings, self._defaults, settings);self._state[inst.uid] = FALSE;$target.hide();function closeOthers() {var key, uid = this.attr("id").split("_")[1];for (key in self._state) {if (key !== uid) {if (self._state.hasOwnProperty(key)) {if ($(":input[sb='" + key + "']")[0]) {self._closeSelectbox($(":input[sb='" + key + "']")[0]);}}}}}sbHolder = $("<div>", {"id": "sbHolder_" + inst.uid,"class": inst.settings.classHolder});sbSelector = $("<a>", {"id": "sbSelector_" + inst.uid,"href": "#","class": inst.settings.classSelector,"click": function (e) {e.preventDefault();closeOthers.apply($(this), []);var uid = $(this).attr("id").split("_")[1];if (self._state[uid]) {self._closeSelectbox(target);} else {self._openSelectbox(target);}}});sbToggle = $("<a>", {"id": "sbToggle_" + inst.uid,"href": "#","class": inst.settings.classToggle,"click": function (e) {e.preventDefault();closeOthers.apply($(this), []);var uid = $(this).attr("id").split("_")[1];if (self._state[uid]) {self._closeSelectbox(target);} else {self._openSelectbox(target);}}});sbToggle.appendTo(sbHolder);sbOptions = $("<ul>", {"id": "sbOptions_" + inst.uid,"class": inst.settings.classOptions});opts.each(function (i) {var that = $(this),li = $("<li>");if (that.is(":selected")) {sbSelector.text(that.text());s = TRUE;}if (i === olen - 1) {li.addClass("last");}$("<a>", {"href": "#" + that.val(),"rel": that.val(), "text": that.text(),"click": function (e) {e.preventDefault();var t = sbToggle,uid = t.attr("id").split("_")[1];self._changeSelectbox(target, $(this).attr("rel"), $(this).text());self._closeSelectbox(target);}}).appendTo(li);li.appendTo(sbOptions);});if (!s) {sbSelector.text(opts.first().text());}$.data(target, PROP_NAME, inst);sbSelector.appendTo(sbHolder);sbOptions.appendTo(sbHolder);sbHolder.css({top: -10000, left: -10000});sbHolder.insertAfter($target);sbHolder.find("li").each(function(){if ($(this).width() > self._width) self._width = $(this).outerWidth();});sbOptions.css({display: "none", width: self._width + 45});sbHolder.width(self._width + 45).css({top: "auto", left: "auto"});},_detachSelectbox: function (target) {var inst = this._getInst(target);if (!inst) {return FALSE;}$("#sbHolder_" + inst.uid).remove();$.data(target, PROP_NAME, null);$(target).show();},_changeSelectbox: function (target, value, text) {var inst = this._getInst(target),onChange = this._get(inst, 'onChange');$("#sbSelector_" + inst.uid).text(text);$(target).children("option[value='" + value + "']").attr("selected", TRUE);if (onChange) {onChange.apply((inst.input ? inst.input[0] : null), [value, inst]);} else if (inst.input) {inst.input.trigger('change');}},_enableSelectbox: function (target) {var inst = this._getInst(target);if (!inst || !inst.isDisabled) {return FALSE;}$("#sbHolder_" + inst.uid).removeClass(inst.settings.classHolderDisabled);inst.isDisabled = FALSE;$.data(target, PROP_NAME, inst);},_disableSelectbox: function (target) {var inst = this._getInst(target);if (!inst || inst.isDisabled) {return FALSE;}$("#sbHolder_" + inst.uid).addClass(inst.settings.classHolderDisabled);inst.isDisabled = TRUE;$.data(target, PROP_NAME, inst);},_optionSelectbox: function (target, name, value) {var inst = this._getInst(target);if (!inst) {return FALSE;}inst[name] = value;$.data(target, PROP_NAME, inst);},_openSelectbox: function (target) {var inst = this._getInst(target);if (!inst || inst.isOpen || inst.isDisabled) {return;}var	el = $("#sbOptions_" + inst.uid),viewportHeight = parseInt($(window).height(), 10),offset = $("#sbHolder_" + inst.uid).offset(),scrollTop = $(window).scrollTop(),height = el.prev().height(),diff = viewportHeight - (offset.top - scrollTop) - height / 2,onOpen = this._get(inst, 'onOpen');el.css({"top": height + "px","maxHeight": (diff - height) + "px"});inst.settings.effect === "fade" ? el.fadeIn() : el.slideDown(100);$("#sbToggle_" + inst.uid).addClass(inst.settings.classToggleOpen);this._state[inst.uid] = TRUE;inst.isOpen = TRUE;if (onOpen) {onOpen.apply((inst.input ? inst.input[0] : null), [inst]);}$.data(target, PROP_NAME, inst);},_closeSelectbox: function (target) {var inst = this._getInst(target);if (!inst || !inst.isOpen) {return;}var onClose = this._get(inst, 'onClose');inst.settings.effect === "fade" ? $("#sbOptions_" + inst.uid).fadeOut() : $("#sbOptions_" + inst.uid).slideUp(200);$("#sbToggle_" + inst.uid).removeClass(inst.settings.classToggleOpen);this._state[inst.uid] = FALSE;inst.isOpen = FALSE;if (onClose) {onClose.apply((inst.input ? inst.input[0] : null), [inst]);}$.data(target, PROP_NAME, inst);},_newInst: function(target) {var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1');return {id: id, input: target, uid: Math.floor(Math.random() * 99999999),isOpen: FALSE,isDisabled: FALSE,settings: {}}; },_getInst: function(target) {try {return $.data(target, PROP_NAME);}catch (err) {throw 'Missing instance data for this selectbox';}},_get: function(inst, name) {return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name];}});$.fn.selectbox = function (options) {var otherArgs = Array.prototype.slice.call(arguments, 1);if (typeof options == 'string' && options == 'isDisabled') {return $.selectbox['_' + options + 'Selectbox'].apply($.selectbox, [this[0]].concat(otherArgs));}if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') {return $.selectbox['_' + options + 'Selectbox'].apply($.selectbox, [this[0]].concat(otherArgs));}return this.each(function() {typeof options == 'string' ?$.selectbox['_' + options + 'Selectbox'].apply($.selectbox, [this].concat(otherArgs)) :$.selectbox._attachSelectbox(this, options);});};$.selectbox = new Selectbox();$.selectbox.version = "0.1.2";})(jQuery);
