var redirects = [];
var endpoints = [];
var eCount = -1;
var brothers = [];
var bCount = -1;
var brothersData = [];
/* var loaderImg = "asset/ajax-loader.gif"; */
var mouseup_fce;

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

function ping(order, baseUrl, callback) {
	$.getJSON(baseUrl + "?service=page/RemoteAuth&callback=?", {
		order : order,
		url : baseUrl,
		method : "ping"
	}, callback);
}

function logon(order, baseUrl, username, password, callback) {
	if (baseUrl == endpoints[0]) {
		$.postJSON(baseUrl + "?service=page/RemoteAuth&callback=?", {
			order : order,
			url : baseUrl,
			method : "logon",
			username : username,
			password : password
		}, callback);
	} else {
		ping(order, baseUrl, function(data) {
			$.postJSON(endpoints[0] + "?service=page/RemoteAuth&callback=?", {
				proxy_to : baseUrl + "?service=page/RemoteAuth",
				order : order,
				url : baseUrl,
				method : "logon",
				username : username,
				password : password,
				session_id : data.session_id
			}, callback);
		});
	}
}

function meet(order, baseUrl, friends, callback) {
	$.getJSON(baseUrl + "?service=page/RemoteAuth&callback=?", {
		order : order,
		url : baseUrl,
		method : "meet",
		friends : friends.join()
	}, callback);
}

function logout(order, baseUrl, callback) {
	$.getJSON(baseUrl + "?service=page/RemoteAuth&callback=?", {
		order : order,
		url : baseUrl,
		method : "logout"
	}, callback);
}

function addEndpoint(data) {
	if (data.status == "success" && data.redirect != null) {
		redirects.push(data);
		brothers.push(data.url);
	}
	eCount--;

	if (eCount == 0) {
		redirect();
	}
}

function redirect() {
	var friends = jQuery.map(redirects, function(item) {
		return item.url;
	});

	var redirect_data;
	$.each(redirects, function(i, data) {
		if (redirect_data === undefined || data.order < redirect_data.order) {
			redirect_data = data;
		}
		meet(i, data.url, friends);
	});
	redirects = [];

	if (redirect_data !== undefined) {
		setTimeout("window.location = '" + redirect_data.redirect + "'", 500);
	} else {
		// failed to redirect, trigger original event
		$("#ajaxLogonForm").unbind("submit");
		$("#ajaxLogonForm :submit").click();
	}
}

function setupLogon() {
	$("#ajaxLogonForm").submit( function(e) {
		$("#ajaxLogonForm td").fadeTo("fast", .20);
		/*
		 * var loader = "<div style='width: " + $("#ajaxLogonForm").width() + ";
		 * height: " + $("#ajaxLogonForm").height() + "; position:absolute;
		 * z-index: 10'>" + "<img id='login-ajax-loader' src='" + loaderImg + "' " +
		 * "style='display: block; margin: auto auto; margin-top: 3em'></div>";
		 * $("#ajaxLogonForm").prepend(loader);
		 */

		e.preventDefault();
		redirects = [];

		eCount = endpoints.length;
		$.each(endpoints, function(i, endpoint) {
			var username = $("#ajaxLogonForm :text").val();
			var password = $("#ajaxLogonForm :password").val();
			logon(i, endpoint, username, password, addEndpoint);
		});

		setTimeout("eCount = 0; redirect()", 5000);
	});
}

function setupLogout() {
	$("#logout-link").click( function(e) {
		e.preventDefault();
		$.each(brothers, function(i, endpoint) {
			logout(i, endpoint);
		});

		setTimeout("window.location = '" + e.target.href + "'", 500);
	});

	mouseup_fce = eval($("table[summary = 'main menu'] td:last").attr(
			"onmouseup"));
	$("table[summary = 'main menu'] td:last").attr("onmouseup", "");
	$("table[summary = 'main menu'] td:last").mouseup( function(e) {
		e.preventDefault();
		$.each(brothers, function(i, endpoint) {
			logout(i, endpoint);
		});

		setTimeout("mouseup_fce()", 500);
	});
}

function recordBrother(data) {
	if (data.status == "success") {
		brothersData.push(data);
	}
	bCount--;

	if (bCount == 0) {
		processBrothers();
	}
}

function processBrothers() {
	var lnks = [];
	$.each(brothersData, function(i, b) {
		if (b.logged == "true") {
			lnks.push("<a class='brother-link' href='" + b.link + "' brother='"
					+ b.url + "'>" + b.instance + "</a>");
		}
	});
	$("#brothers-links.topMenu-bro-links").append(
			"<li><b>" + lnks.join("</b></li>\n<li><b>") + "</b></li>");
	$("#brothers-links.tenderMenu-bro-links").append(
			"| " + lnks.join(" | ") + "");

	$(".brother-link").click( function(e) {
		e.preventDefault();
		var friends = [ endpoints[0] ];
		$.merge(friends, brothers);
		meet(0, $(this).attr("brother"), friends);

		setTimeout("window.location = '" + e.target.href + "'", 500);
	});
}

function pingBrothers() {
	brothersData = [];
	bCount = brothers.length;
	$.each(brothers, function(i, endpoint) {
		ping(i, endpoint, recordBrother);
	});
}

function setupPing() {
	$(window).load( function() {
		setTimeout("pingBrothers()", 300);
	});
}

$( function() {
	/* $("body").append("<img src='" + loaderImg + "' style='display: none'>"); */
	$("#navlist li:has(a[href $= 'service=page/UserPreference'])").before(
			"<span id='brothers-links' class='topMenu-bro-links'></span>");
	$("#tenderMenuDiv td:last").append(
			"<span id='brothers-links' class='tenderMenu-bro-links'></span>");

	$.ajaxSetup( {
		complete : function(xhr, status) {
			if (status !== undefined && status != "success") {
				bCount--;
				if (bCount == 0) {
					processBrothers();
				}

				eCount--;
				if (eCount == 0) {
					redirect();
				}
			}
		},
		timeout : 5000
	});

	setupLogon();
	setupLogout();
	setupPing();
});