/**
 * InCommon Federation Organization Inspector.
 *
 * Displays all organization metadata.
 *
 */

// helps prevent a "flash of unstyled content"
$('html').addClass('js');

$(document).ready(function () {
	"use strict";

	$('#page-content').hide().ajaxStop(
		function () { $(this).show(); }
	);
	$("#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(); });

	// handle successful ajax call for all entity metadata
	var handleDone = function (entities) {
		var i, entity, orgName, orgDisplayName, orgURL;
		var orgsByName = [], orgsByDisplayName = [];

		// dynamically build a list of organization objects
		for (i = 0; i < entities.length; i += 1) {
			entity = new SAMLEntity(entities[i]);

			orgName = entity.getOrganizationName();
			orgDisplayName = entity.getOrganizationDisplayName();
			orgURL = entity.getOrganizationURL();

			if (!(orgsByName[orgName] instanceof Object)) {
				orgsByName[orgName] = {};
				orgsByName[orgName].orgDisplayName = orgDisplayName;
				orgsByName[orgName].orgURL = orgURL;
			}

			if (!(orgsByDisplayName[orgDisplayName] instanceof Object)) {
				orgsByDisplayName[orgDisplayName] = {};
				orgsByDisplayName[orgDisplayName].orgName = orgName;
				orgsByDisplayName[orgDisplayName].orgURL = orgURL;
				orgsByDisplayName[orgDisplayName].mustFixOrgDisplayName = false;
				if (orgsByName[orgName].orgDisplayName !== orgDisplayName) {
					orgsByDisplayName[orgDisplayName].mustFixOrgDisplayName = true;
				}
				orgsByDisplayName[orgDisplayName].mustFixOrgURL = false;
				if (orgsByName[orgName].orgURL !== orgURL) {
					orgsByDisplayName[orgDisplayName].mustFixOrgURL = true;
				}
			}
		}

		// insert the metadata
		$.insertListAllOrgs(orgsByDisplayName);
	};

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

	$.getJSONMetadata4AllEntities(handleDone, handleFail);

});