/**
 * InCommon Federation Member Organization web application.
 *
 * Requires:
 *   jquery.utils.js
 */
$(document).ready(function () {
	"use strict";

	$('#page-content').hide();
	$("#loading").ajaxStart(function () {
		// the image is 31x31 pixels
		var x = Math.round((document.body.clientWidth - 31) / 2);
		$(this).css('left', x);
		$(this).show();
	}).ajaxStop(function () { $(this).hide(); });

	// The 'linkObj' parameter is a JavaScript Link object
	// with exactly one query string parameter
	(function (linkObj) {

		// a redirect page
		var redirectPage = "./all-orgs.html";

		// handle a missing query string
		if (linkObj.search == null || linkObj.search == "") {
			// redirect the browser
			window.location = redirectPage;
			return;
		}

		var orgName = utils.getParameterByName(linkObj, 'orgName');
		// handle an ill-formatted query string
		if (orgName == null || orgName == "") {
			// redirect the browser
			window.location = redirectPage;
			return;
		}

		// comparison function used to sort arrays of SAML entities
		var comparison_function = function (a, b) {
			var a_key = a.getDefaultDisplayName();
			var b_key = b.getDefaultDisplayName();
			return (a_key < b_key) ? -1 : ((a_key > b_key) ? 1 : 0);
		};

		// handle successful ajax call for all entity metadata
		var handleDone = function (entities) {
			var i, entity, org;

			// dynamically build a list of organization objects
			for (i = 0; i < entities.length; i += 1) {
				entity = new SAMLEntity(entities[i]);
				if (entity.getOrganizationName() == orgName) {
					if (org == undefined) {
						org = {};
						org.displayName = entity.getOrganizationDisplayName();
						org.url = entity.getOrganizationURL();
						org.idps = []; org.sps = [];
					}
					if (entity.isIdP()) {
						org.idps.push(entity);
					} else if (entity.isSP()) {
						org.sps.push(entity);
					} else {
						$.displayErrorMsg("Unable to determine the entity type");
					}
				}
			}

			// no entities found
			if (org == undefined) {
				$.displayErrorMsg("Unable to find any entities");
				window.location = redirectPage;
				return;
			}

			// set document title
			document.title += ": " + org.displayName;

			// sort and insert the metadata
			org.idps.sort(comparison_function);
			org.sps.sort(comparison_function);
			$.insertListOrgEntities(org);

			$('#page-content').show();
		};

		// handle failed ajax call for all entity metadata
		var handleFail = function () {
			$.displayErrorMsg("Unable to retrieve all entity metadata");
		};

		$.getJSONMetadata4AllEntities(handleDone, handleFail);

	}(window.location));

	// handle clicked entity links
	var dialogOptions = null;  // unused
	$('#page-content').handleClickedEntityLinks(dialogOptions);
});