| {% extends 'layout.html' %}
| {% from '_macros/_navigation.html' import navigation_tabs %}

| {% set title = 'organizations' %}
| {% block page_title %}Organizations{% endblock %}

| {% block og %}
meta(property="og:title", content="Dashboard")
meta(name="twitter:title", content="Blender Cloud")

meta(property="og:url", content="https://cloud.blender.org/{{ request.path }}")
meta(property="og:type", content="website")

meta(property="og:image", content="{{ url_for('static', filename='assets/img/backgrounds/cloud_services_oti.jpg')}}")
meta(name="twitter:image", content="{{ url_for('static', filename='assets/img/backgrounds/cloud_services_oti.jpg')}}")
| {% endblock %}

| {% block body %}
.dashboard-container
	section#main
		| {{ navigation_tabs(title) }}

		section#projects

			| {% if can_create_organization %}
			section#sub-nav-tabs.projects
				ul#sub-nav-tabs__list
					li.result#create_organization_result_panel
					li.create
						button.btn.btn-success(onclick='createNewOrganization(this)')
							i.pi-plus
							| Create Organization
			| {% endif %}

			section.nav-tabs__tab.active#own_projects
				ul.projects__list
					| {% if organizations %}
					| {% for organization in organizations['_items']  %}
					| {% set link_url = url_for('pillar.web.organizations.view_embed', organization_id=organization._id) %}
					li.projects__list-item(
						data-url="{{ link_url }}",
						id="organization-{{ organization._id }}")
						a.projects__list-thumbnail(
							href="{{ link_url }}")
							i.pi-users
						.projects__list-details
							a.title(href="{{ link_url }}")
								| {{ organization.name }}

							ul.meta
								li(title="Members")
									| {{ organization.members|hide_none|count }} Member{{ organization.members|hide_none|count|pluralize }}
									| {% if (organization.unknown_members|count) != 0 %}
									| ({{ organization.unknown_members|hide_none|count }} pending)
									| {% endif %}
								li(title="Seats")
									| {{ organization.seat_count }} Seat{{ organization.seat_count|pluralize }}

					| {% endfor %}
					| {% else %}
					li.projects__list-item
						a.projects__list-thumbnail
							i.pi-blender-cloud
						.projects__list-details
							span Create an Organization to get started!
					| {% endif %}

	section#side
		section.box
			#item-details

| {% endblock %}


| {% block footer_scripts %}
script(src="{{ url_for('static_pillar', filename='assets/js/vendor/jquery.typeahead-0.11.1.min.js')}}")
script(src="{{ url_for('static_pillar', filename='assets/js/vendor/algoliasearch-3.19.0.min.js')}}")
script(src="{{ url_for('static_pillar', filename='assets/js/vendor/jquery.autocomplete-0.22.0.min.js') }}", async=true)

script.

	/* Returns a more-or-less reasonable message given an error response object. */
	function xhrErrorResponseMessage(err) {
		if (typeof err.responseJSON == 'undefined')
			return err.statusText;

		if (typeof err.responseJSON._error != 'undefined' && typeof err.responseJSON._error.message != 'undefined')
			return err.responseJSON._error.message;

		if (typeof err.responseJSON._message != 'undefined')
			return err.responseJSON._message

		return err.statusText;
	}

	/**
	 * Open an organization in the #item-details div.
	 */
	function item_open(item_id, pushState)
	{
		if (item_id === undefined ) {
			throw new ReferenceError("item_open(" + item_id + ") called.");
		}

		// Style elements starting with item_type and dash, e.g. "#job-uuid"
		var clean_classes = 'active processing';
		var current_item = $('#organization-' + item_id);

		$('[id^="organization-"]').removeClass(clean_classes);
		current_item
			.removeClass(clean_classes)
			.addClass('processing');

		var item_url = '/o/' + item_id;
		statusBarSet('default', 'Loading organization…');

		$.get(item_url, function(item_data) {
			statusBarClear();
			$('#item-details').html(item_data);

			current_item
				.removeClass(clean_classes)
				.addClass('active');

		}).fail(function(xhr) {
			if (console) {
				console.log('Error fetching organization', item_id, 'from', item_url);
				console.log('XHR:', xhr);
			}

			current_item.removeClass(clean_classes);
			statusBarSet('error', 'Failed to open organization', 'pi-warning');

			if (xhr.status) {
				$('#item-details').html(xhr.responseText);
			} else {
				$('#item-details').html('<p class="text-danger">Opening ' + item_type + ' failed. There possibly was ' +
				'an error connecting to the server. Please check your network connection and ' +
				'try again.</p>');
			}
		});

		// Determine whether we should push the new state or not.
		pushState = (typeof pushState !== 'undefined') ? pushState : true;
		if (!pushState) return;

		// Push the correct URL onto the history.
		var push_state = {itemId: item_id};

		window.history.pushState(
				push_state,
				'Organization: ' + item_id,
				item_url
		);
	}

	$('li.projects__list-item').click(function(e){
		url = $(this).data('url');
		if (typeof url === 'undefined') return;

		window.location.href = url;
		if (console) console.log(url);

		$(this).addClass('active');
		$(this).find('.projects__list-thumbnail i')
			.removeAttr('class')
			.addClass('pi-spin spin');
	});


	{% if open_organization_id %}
		$(function() { item_open('{{ open_organization_id }}', false); });
	{% endif %}

	{% if can_create_organization %}
	function createNewOrganization(button) {
		$(button)
			.attr('disabled', 'disabled')
			.fadeTo(200, 0.1);
		$('#create_organization_result_panel').html('');

		// TODO: create a form to get the initial info from the user.
		$.post(
			'{{ url_for('pillar.web.organizations.create_new') }}',
			{
				name: 'New Organization',
				seat_count: 1,
			}
		)
		.done(function(result) {
			var $p = $('<p>').text('organization created, reloading list.')
			$('#create_organization_result_panel').html($p);

			window.location.href = result.location;
		})
		.fail(function(err) {
			var msg = xhrErrorResponseMessage(err);
			$('#create_organization_result_panel').html('Error creating organization: ' + msg);

			$(button)
				.fadeTo(1000, 1.0)
				.queue(function() {
					$(this)
						.removeAttr('disabled')
						.dequeue()
					;
				})
		})
		;
		return false;
	}
	{% endif %}
| {% endblock %}
