Index: itignore
===================================================================
--- .gitignore	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ 	(revision )
@@ -1,1 +1,0 @@
-config.php
Index: accounts.php
===================================================================
--- accounts.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ accounts.php	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -1,197 +1,0 @@
-<?php
-
-// The paage that is loaded for account related functions
-
-// Include the main PHP file
-include ('include.php');
-
-// Set the page name for display purposes
-$page_name = "Meraki Administrators";
-// Set the page name in the template
-// TODO: Allow better per-page customisation of the template
-$page_header = preg_replace ( '/PAGE_NAME/', $page_name, $page_header );
-
-// Check to see if this is an API call or a new call to the page
-//TODO: This is no longer required.  All calls should now go to api.php.  Check, and then remove this code. 
-if ( !isset ( $_POST['action'] ) || $_POST['action'] == "" ) {
-	// Send the page to the browser
-	echo ( $page_header );
-	new_request();
-	echo ( $page_footer );
-}
-else {
-	// API Call - Parse request in include.php
-	parse_request();
-}
-
-// Send the appropriate page to the browser	
-	function new_request() {
-		//If no specific page is requested, send a menu
-		if ( !isset ( $_GET['page'] ) || $_GET['page'] == "" ) { ?>
-		
-			<p>Please select a function:</p>
-			<ul>
-				<li><a href="accounts.php?page=admins_by_org">List Administrators by Organisation</a></li>
-				<li><a href="accounts.php?page=orgs_by_admin">List Organisations by Administrator</a></li>
-				<li><a href="accounts.php?page=remove_admin">Remove an Administrator</a></li>
-				<li><a href="accounts.php?page=add_admin">Add an Administrator</a></li>
-			</ul>
-		<?php }
-		else {
-			// A specific page has been requested - send that one
-			switch ($_GET['page']) {
-				case "admins_by_org":
-					page_admins_by_org();
-					break;
-				case "orgs_by_admin":
-					page_orgs_by_admin();
-					break;
-				case "remove_admin":
-					page_remove_admin();
-					break;
-				case "add_admin":
-					page_add_admin();
-					break;
-				default:
-					break;
-			}
-		}
-		
-		return;
-	}
-
-	
-//Functions to return appropriate page based on switch statement above
-
-function page_admins_by_org() {	?>
-		<div class="meraki_admins_by_org" id="meraki_admins_by_org">
-			<h2>List of Administrators by Organisation</h2>
-
-			<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-
-			<div class="meraki_container meraki_form">
-				<?php ro_key_fields(); ?>
-				<div class="meraki_row">
-					<div class="meraki_left">
-						<input type="button" class="meraki_button" name="meraki_go" id="meraki_go" value="Fetch Administrators" onclick="get_admins_by_org();">
-					</div>
-				</div>
-			</div>
-			
-			<div id="meraki_admins_output"></div>
-		</div>
-		<script>
-			var page = "admins_by_org";
-		</script>
-
-<?php }
-
-function page_orgs_by_admin() {	?>
-		<div class="meraki_orgs_by_admin" id="meraki_orgs_by_admin">
-			<h2>List of Organisations by Administrator</h2>
-
-			<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-
-			<div class="meraki_container meraki_form">
-				<?php ro_key_fields(); ?>
-				<div class="meraki_row">
-					<div class="meraki_left">
-						<input type="button" class="meraki_button" name="meraki_go" id="meraki_go" value="Fetch Administrators" onclick="get_admins_by_org();">
-					</div>
-				</div>
-			</div>
-			
-			<div id="meraki_admins_output"></div>
-		</div>
-		<script>
-			var page = "orgs_by_admin";
-		</script>
-<?php }
-
-function page_remove_admin() {	?>
-		<div class="orgs_by_admin" id="orgs_by_admin">
-			<h2>Delete Administrator</h2>
-			<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-			<div class="meraki_container meraki_form">
-			
-				<?php rw_key_fields(); ?>
-				
-				<input type="button" class="meraki_button" name="meraki_next1" id="meraki_next1" value="Next" onclick="get_admins_by_org();">
-			</div>
-			<div class="meraki_admins_output" id="meraki_admins_output">
-				<!--Dropdown list of Admins -->
-				<!--Next -->
-			</div>
-			
-			<div class="meraki_orgs_output" id="meraki_orgs_output">
-				<!-- Checkboxes for orgs -->
-				<!-- Remove -->
-			</div>
-			
-			
-			
-		</div>
-		
-		<script>
-			var page = "delete_admin";
-		</script>
-
-<?php }
-
-function page_add_admin() {	?>
-		
-
-
-		<div class="orgs_by_admin" id="orgs_by_admin">
-			<h2>Add Administrator</h2>
-			<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-			<div class="meraki_container meraki_form">
-			
-				<?php rw_key_fields(); ?>
-				
-				<div class="meraki_row">
-					<div class="meraki_left">
-						<label for="meraki_full_name">Full name: </label>
-					</div>
-					<div class="meraki_right">
-						<input type="text" name="meraki_full_name" id="meraki_full_name" length="40" />
-					</div>
-				</div>
-				<div class="meraki_row">
-					<div class="meraki_left">
-						<label for="meraki_email">Email Address: </label>
-					</div>
-					<div class="meraki_right">
-						<input type="text" name="meraki_email" id="meraki_email" length="40" />
-					</div>
-				</div>
-				<div class="meraki_row">
-					<div class="meraki_left">
-						<label for="meraki_access">Access Level: </label>
-					</div>
-					<div class="meraki_right">
-						<select name="meraki_access" id="meraki_access">
-							<option value="full">Full</option>
-							<option value="read-only">Read-Only</option>
-						</select>
-					</div>
-				</div>
-				<input type="button" class="meraki_button" name="meraki_next1" id="meraki_next1" value="Next" onclick="get_admins_by_org();">
-			</div>
-			
-
-			<div class="meraki_org_checkboxes meraki_container meraki_form2" id="meraki_orgsOutput">
-				<!-- Checkboxes for orgs -->
-				<!-- Add -->
-			</div>
-			
-		</div>
-			
-		<script>
-			var page = "add_admin";
-		</script>
-
-<?php }
-
-
-?>
Index: i.php
===================================================================
--- api.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ 	(revision )
@@ -1,18 +1,0 @@
-<?php
-
-//This file is simply a wrapper around include.php
-
-// Include the main PHP file
-include ('include.php');
-
-// Check to see if this is an API call or a new call to the page
-// We should only be dealing with API calls, so something is wrong if called
-// without an action
-if ( !isset ( $_POST['action'] ) || $_POST['action'] == "" ) {
-	die ('We shouldn\'t be here - something bad is happening');
-}
-else {
-    // API Call - Parse request in include.php
-	parse_request();
-}
-?>
Index: nfig.template.php
===================================================================
--- config.template.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ 	(revision )
@@ -1,14 +1,0 @@
-<?php
-// Meraki Server base URL - this should be correct
-// Please include trailing /
-// Eg: $SERVER='https://dashboard.meraki.com/api/';
-$SERVER='https://dashboard.meraki.com/api/';
-
-// The API version we wish to use
-// This is used in the request URL so must be correct
-$API_VERSION='v0';
-
-// A Read Only API key that can be used to get general information without
-// a user specific key
-$RO_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
-?>
Index: include.css
===================================================================
--- include.css	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ include.css	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -1,66 +1,0 @@
-.meraki_container {
-	display: table;
-	width:1%;
-	text-align: left;
-}
-.meraki_row  {
-	display: table-row;
-	width:1%;
-	text-align: left;
-}
-.meraki_left, .meraki_right, .meraki_middle {
-	display: table-cell;
-	width:1%;
-	white-space:nowrap;
-	padding-right: 25px;
-}
-.meraki_left p, .meraki_right p, .meraki_middle p {
-	margin: 1px 1px;
-}
-
-.meraki_output_group {
-	border: 1px solid;
-	border-color: black;
-}
-
-.meraki_output_header{
-}
-
-.meraki_output_header_group {
-	border: 1px solid;
-	border-color: black;
-}
-
-.meraki_output_table tr {
-	border: 1px solid;
-	border-color: black;
-}
-
-.meraki_success {
-	background-color: rgb(224, 255, 224);
-	font-color: rgb(0, 128, 0);
-	color: rgb(0, 128, 0);
-}
-
-.meraki_warning {
-	background-color: rgb(255, 255, 224);
-	font-color: rgb(128, 128, 0);
-	color: rgb(128, 128, 0);
-}
-
-.meraki_failure {
-	background-color: rgb(255, 224, 224);
-	font-color: rgb(128, 0, 0);
-	color: rgb(128, 0, 0);
-}
-
-.meraki_button_warning {
-	background-color: rgb(255, 0, 0);
-	font-color: rgb(255, 255, 255);
-	color: rgb(255, 255, 255);
-	font-weight: bold;
-}
-
-.meraki_ro_key {
-	display:none;
-}
Index: include.js
===================================================================
--- include.js	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ include.js	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -1,1097 +1,124 @@
-// Variable to hold fetched organisations
 var orgs;
+var number_of_orgs;
+var current_org=-1;
 
-// Variable to hold fetched networks
-var nets;
-
-// Number of Organisations expected
-var number_of_orgs;
-
-// Number of Networks expected
-var number_of_nets;
-
-// Number of Organisations fetched
-var orgs_completed=0;
-
-// Number of Networks fetched
-var nets_completed=0;
-
-// API Key
-var key="";
-
-//Rate limit APIs to 1 every xxx ms
-var ratelimit=600;
-
-//Extend _ with rate limit method:
-_.rateLimit = function(func, rate, async) {
-  var queue = [];
-  var timeOutRef = false;
-  var currentlyEmptyingQueue = false;
-  
-  var emptyQueue = function() {
-    if (queue.length) {
-      currentlyEmptyingQueue = true;
-      _.delay(function() {
-        if (async) {
-          _.defer(function() { queue.shift().call(); });
-        } else {
-          queue.shift().call();
-        }
-        emptyQueue();
-      }, rate);
-    } else {
-      currentlyEmptyingQueue = false;
-    }
-  };
-  
-  return function() {
-    var args = _.map(arguments, function(e) { return e; }); // get arguments into an array
-    queue.push( _.bind.apply(this, [func, this].concat(args)) ); // call apply so that we can pass in arguments as parameters as opposed to an array
-    if (!currentlyEmptyingQueue) { emptyQueue(); }
-  };
-};
-
-// Initialisation functions
-$( document ).ready(function() {
-
-	// Add a handler to hide and show API key when a read only key is allowed
-	$("#meraki_ro_key").change(function(event) {
-		var checkbox = event.target;
-		if (checkbox.checked) {
-			$(".meraki_ro_key").hide();
-		} else {
-			// Cannot use normal jQuery function to show as it requires the
-			// display property set to table-row
-			$(".meraki_ro_key").css('display', 'table-row');
-		}
-	});
-
-});
-
-
-// ADMIN FUNCTIONS
-
-// Called by button click
-function get_admins_by_org() {
-	// Update the status box
-    status_update("Fetching organisations...");
-	// Hide the form to prevent people clicking stuff
-	$(".meraki_form").hide();
-	// Get the key to use
-	set_key();
-	// Call the general function to get the list of organisations
-	// Using the success callback for this operation, and a general error catching callback
-    get_organisations(on_get_organisations_success_admins, on_get_organisations_error);
+function get_licence_state() {
+	
+	$("#licenceOutput").append("<p>Fetching organisations...</p>");
+	get_orgs();
+	return;
+	
 }
 
-// Callback from get_organisations which has succesfully returned data
-function on_get_organisations_success_admins(data) {
-	// Store the organisations received into the global variable
-	orgs = data;
-	// Get the number of organisations in the array
-	number_of_orgs = orgs.length;
-	// Update the status box
-	status_update("Found " + number_of_orgs + " organisations - fetching admins...");
-
-	// Get the admins for each organisation
-	function getadmin(org) {
-
-        $.ajax({
-            dataType: "json",
-            url: "api.php",
-			method: "post",
-			data: {
-				action: "get_org_admins",
-				orgid: 	data[org].id,
-				key: 	key
-			},
-            success: function (r) {on_get_admin_sucess(r, org);},
-            error: function (x, s, e) {on_get_admin_error(e, org);}
-        });
-	}
-	
-	var delaygetadmin = _.rateLimit(getadmin, ratelimit);
-	
-	$.each(data, function(org) {delaygetadmin(org);});
-}
-
-// Callback from AJAX call to get organisation admins which has succesfully returned data
-function on_get_admin_sucess(administrator, org_index) {
-	// Add the new information to the "administrator" object in
-	// the global organisation array
-    orgs[org_index].administrator = administrator;
-
-	// Mark it as a completed call
-	orgs_completed++;
-
-	// Check whether all calls have now returned
-		// If they have, print the output
-		// Otherwise do nothing as we're still waiting on more data
-    if(check_orgs_complete()) {
-        print_admins_output();
-    }
-}
-
-// Callback from AJAX call to get organisation admins which has returned an error
-function on_get_admin_error(error, org_index) {
-	// Add a new "administrator" object in the global organisation
-	// array and mark it with an ERROR value
-    orgs[org_index].administrator = [];
-	orgs[org_index].administrator[0] = "ERROR";
-
-	// Mark it as a completed call
-	orgs_completed++;
-
-	// Check whether all calls have now returned
-		// If they have, print the output
-		// Otherwise do nothing as we're still waiting on more data
-    if(check_orgs_complete()) {
-        print_admins_output();
-    }
-}
-
-// Print the output when the AJAX calls complete
-function print_admins_output() {
-	// Depending on the page we need to print the output differently
-	// The page is defined in a global variable in a script tag
-	// on the original HTML page
-	if ( page == "orgs_by_admin" ){
-		print_admins_output_by_admin();
-	}
-	else if ( page == "admins_by_org" ) {
-		print_admins_output_by_org();
-	}
-	else if ( page == "add_admin" ) {
-		print_orgs_to_add_admin();
-	}
-	else if ( page == "delete_admin" ) {
-		print_select_admin_to_remove();
+function get_next_licence(data) {
+	if ( current_org == -1 ){
+		//First one to fetch
+		$("#licenceOutput").append('<p id="licenceOutputCounter">Getting organisation ' + 1 + '/' + number_of_orgs +  ' (' + orgs[0].name + ')....</p>');
+		current_org++;
+		get_org_licences(orgs[current_org].id);
 	}
 	else {
-		// We define the pages so there shouldn't be any missing
-		status_update("Errrrrr - this shouldn't ever be reached - something went very wrong!");
+		//We should be in a success clause, so parse data
+		lic = data;
+		if (typeof data == 'undefined') {
+			//This shouldn't happen now
+			orgs[current_org].licStatus = "ERROR";
+			orgs[current_org].licExpirationDate = "ERROR";
+			orgs[current_org].licLicensedDeviceCounts = "ERROR";
+		}
+		else {
+			orgs[current_org].licStatus = lic['status'];
+			orgs[current_org].licExpirationDate = Date.parse(lic['expirationDate']);
+			orgs[current_org].licLicensedDeviceCounts = lic['licensedDeviceCounts'];			
+		}
+		
+		if (current_org < number_of_orgs-1) {
+			//More stuff to get....
+			current_org++;
+			$("#licenceOutputCounter").text('Getting organisation ' + parseInt(parseInt(current_org)+1) + '/' + number_of_orgs +  ' (' + orgs[current_org].name + ')....');
+			get_org_licences(orgs[current_org].id);
+		}
+		else {
+			//All done - print output...
+			print_licence_output();
+		}
 	}
 }
 
-// Prints the list of administrators grouped by organisation
-function print_admins_output_by_org() {
-	status_update('Sorting and generating output...');
-
-	// Sort the organisations by name A -> Z
-	sorted = orgs.sort(function(a, b) { return a.name - b.name; });
-
-	// Insert the table into the pre-created div
-	$("#meraki_admins_output").html('\
-		<table class="meraki_output_table" id="meraki_admins_output_table">\
-			<tr>\
-				<td class="meraki_output_header_group"><b>Organisation</b></td>\
-				<td class="meraki_output_header"><b>Name</b></td>\
-				<td class="meraki_output_header"><b>Email Address</b></td>\
-				<td class="meraki_output_header"><b>Access Level</b></td>\
-			</tr>\
-		</table>\
-	');
-
-	// Loop over each organisation
-	$.each(sorted, function(data) {
-		// Check we suceeded in fetching the admins of the network
-		if ( sorted[data].administrator[0] != "ERROR" ) {
-			// Store the number of admins in this organisation
-			number_of_admins = sorted[data].administrator.length;
-			// Output the organisation with an appropriate row span along
-			// with the first admnistrator
-			$("#meraki_admins_output_table").append('\
-				<tr>\
-					<td rowspan="'+number_of_admins+'" class="meraki_output_group">' + sorted[data].name + '</td>\
-					<td>' + sorted[data].administrator[0].name + '</td>\
-					<td>' + sorted[data].administrator[0].email + '</td>\
-					<td>' + sorted[data].administrator[0].orgAccess + '</td>\
-				</tr>\
-			');
-			// Loop oveer the remainig admins (note i=1 not 0) and output their details
-			for (i=1; i<number_of_admins; i++) {
-				$("#meraki_admins_output_table").append('\
-					<tr>\
-						<td>' + sorted[data].administrator[i].name + '</td>\
-						<td>' + sorted[data].administrator[i].email + '</td>\
-						<td>' + sorted[data].administrator[i].orgAccess + '</td>\
-					</tr>\
-				');
-			}
-		}
-		else {
-			//We failed to get data on this organisation
-			$("#meraki_admins_output_table").append('\
-				<tr>\
-					<td class="meraki_output_group">' + sorted[data].name + '</td>\
-					<td>ERROR</td>\
-					<td>ERROR</td>\
-					<td>ERROR</td>\
-				</tr>\
-			');
-		}
-	});
-	//Entire function is complete
-	status_update("Done...");
-}
-
-// Prints the list of organisations grouped by oadministrator
-function print_admins_output_by_admin() {
-	status_update('Sorting and generating output...');
-	
-	// Call another function to group organisations by administrator
-	// as this is non-trivial and needed elsewhere
-	admins = group_orgs_by_admin();
-
-	//TODO: Sort by admin alphabetically
-	sorted = admins; //.sort(function(a, b) { return a.name - b.name; });
-
-	// Insert the table into the pre-created div
-	$("#meraki_admins_output").html('\
-		<table class="meraki_output_table" id="meraki_admins_output_table">\
-			<tr>\
-				<td class="meraki_output_header_group"><b>Email Address</b></td>\
-				<td class="meraki_output_header_group"><b>Name</b></td>\
-				<td class="meraki_output_header"><b>Organisation</b></td>\
-				<td class="meraki_output_header"><b>Access Level</b></td>\
-				<td class="meraki_output_header"><b>Account Status</b></td>\
-			</tr>\
-		</table>\
-	');
-
-	// Loop over each administrator
-	$.each(sorted, function(j) {
-		// Store the number of organisations available to this admin
-		// TODO: Fix variable name but can't number_of_orgs (damn globals!)
-		number_of_admins = sorted[j].length;
-		// Output the admin with an appropriate row span along
-		// with the first organisation
-
-		if (sorted[j][0].accountStatus != 'ok' ) {
-			status_style="meraki_failure";
-		}
-		else {
-			status_style="meraki_success";
-		}
-
-		$("#meraki_admins_output_table").append('\
-			<tr>\
-				<td rowspan="'+number_of_admins+'" class="meraki_output_group">' + j + '</td>\
-				<td rowspan="'+number_of_admins+'" class="meraki_output_group">' + sorted[j].name + '</td>\
-				<td>' + sorted[j][0].name + '</td>\
-				<td>' + sorted[j][0].orgAccess + '</td>\
-				<td class="' + status_style + '">' + sorted[j][0].accountStatus + '</td>\
-			</tr>\
-		');
-		// Loop oveer the remainig organisations (note i=1 not 0) and output their details
-		for (i=1; i<number_of_admins; i++) {
-
-			if (sorted[j][i].accountStatus != 'ok' ) {
-				status_style="meraki_failure";
-			}
-			else {
-				status_style="meraki_success";
-			}
-
-			$("#meraki_admins_output_table").append('\
-				<tr>\
-					<td>' + sorted[j][i].name + '</td>\
-					<td>' + sorted[j][i].orgAccess + '</td>\
-					<td class="' + status_style + '">' + sorted[j][i].accountStatus + '</td>\
-				</tr>\
-			');
-		}
-	});
-	//Entire function is complete
-	status_update("Done...");
-}
-
-function print_orgs_to_add_admin() {
-	status_update('Sorting and generating output...');
-	
-	sorted = orgs.sort(function(a, b) { return (a.name < b.name)?-1:((b.name < a.name)?1:0); });
-	orgs = sorted;
-	
-	// Call another function to group organisations by administrator
-	// as this is non-trivial and needed elsewhere
-	admins = group_orgs_by_admin();
-	
-	// Check if the admin exists in organisations this key manages
-	// If not we can skip the per organisation checks later
-	var admin_to_add = $('#meraki_email').val().toLowerCase ();
-	var admin_exists;
-	if ( ! (admins[admin_to_add] ) ){
-		admin_exists=false;
-	}
-	else {
-		admin_exists = true;
-	}
-	
-	// Add to the HTML page a prompt and the select all box
-	$('#meraki_orgsOutput').append('\
-		<div class="meraki_row"><p>Please select the organisations to add this user to:</p></div>\
-	');
-	$('#meraki_orgsOutput').append('<div class="meraki_row" id="meraki_orgs_select_all"></div>');
-	$('#meraki_orgs_select_all').append('\
-		<div class="meraki_left">\
-			<label for="meraki_orgs_select_all_box">\
-				Select All\
-			</label>\
-		</div>\
-	');
-	$('#meraki_orgs_select_all').append('\
-		<div class="meraki_middle">\
-			<input type="checkbox" name="select_all" value="select_all" id="meraki_orgs_select_all_box" />\
-		</div>\
-	');
-	
-	//  Attach a function to the check all box to be triggered when changed
-	$("#meraki_orgs_select_all_box").change(function(event) {
-
-		// Define the checkbox we're working on
-		var checkbox = event.target;
-		
-		// If it's checked, tick all the organisation checkboxes that are not disabled and not already checked
-		if (checkbox.checked) {
-			$(':checkbox[name="org_checkboxes[]"]:not(:disabled):not(:checked)').each( function () {
-				//Note: "this" is the current object in the "each" loop, not the object which raised the event
-				this.checked = true;
-			});
-		}
-		// Otherwise, untick all the organisation checkboxes that
-		// are not disabled and are already checked
-		else {
-			$(':checkbox[name="org_checkboxes[]"]:not(:disabled):checked').each( function () {
-				//Note: "this" is the current object in the "each" loop,
-				// not the object which raised the event
-				this.checked = false;
-			});
-		}
-	});
-
-	// Loop over the organisations
-	$.each (orgs, function (k) {
-		// Add a new row to the table
-		$('#meraki_orgsOutput').append('<div class="meraki_row" id="meraki_orgs_'+k+'"></div>');
-		// Print the name
-		$('#meraki_orgs_'+k).append('\
-			<div class="meraki_left">\
-				<label for="meraki_org_'+orgs[k].id+'">\
-					'+orgs[k].name+'\
-				</label>\
-			</div>\
-		');
-		// Print a checkbox with a value and DOM id based on the Meraki id
-		$('#meraki_orgs_'+k).append('\
-			<div class="meraki_middle">\
-				<input type="checkbox" name="org_checkboxes[]" value="'+orgs[k].id+'" id="meraki_org_'+orgs[k].id+'" />\
-			</div>\
-		');
-		
-		// Add a status column
-		$('#meraki_orgs_'+k).append('<div class="meraki_right" id="meraki_org_output_'+orgs[k].id+'" ></div>');
-
-		// If we were unable to query the admins for the organisation
-			// Disable the checkbox
-			// Add an error to the output column
-			// Set the formatting (CSS class)
-		if ( orgs[k].administrator == "ERROR") {
-			$('#meraki_org_'+orgs[k].id).attr('disabled','disabled');
-			$('#meraki_org_output_'+orgs[k].id).html('Unable to read data');
-			$('#meraki_org_output_'+orgs[k].id).addClass('meraki_failure');
-		}
-		
-		// If the admin exists
-		if ( admin_exists ) {
-			// Loop over administrators organisations
-			$.each ( admins[admin_to_add], function (j) {
-				//If this organisation is already there
-					// Disable the checkbox
-					// Add an error to the output column
-					// Set the formatting (CSS class)
-				if ( admins[admin_to_add][j].id == orgs[k].id ) {
-					$('#meraki_org_'+orgs[k].id).attr('disabled','disabled');
-					$('#meraki_org_output_'+orgs[k].id).html('Already an admin ('+admins[admin_to_add][j].orgAccess+')');
-					$('#meraki_org_output_'+orgs[k].id).addClass('meraki_success');
-				}
-			});
-		}
-	});
-
-	// Add a button to submit form
-	$('#meraki_orgsOutput').append('\
-		<div class="meraki_row">\
-			<input type="button" class="meraki_button" name="meraki_go" id="meraki_go" value="Add to Selected Organisations" onclick="add_admin();">\
-		</div>\
-	');
-
-	// Need to wait for the user to click the button...
-	status_update('Waiting for user input...');
-}
-
-// Function to add the admin to the selected organisations
-function add_admin() {
-    status_update("Adding admins...");
-
-	// Hide the button to prevent double submissions
-	$("#meraki_go").hide();
-	
-	// Retrieve values from the form
-	var fname = $("#meraki_full_name").val();
-	var email = $("#meraki_email").val();
-	var orgaccess = $("#meraki_access").val();
-	
-	// Function to add admins
-	function addadmin(org_id) {
-		$.ajax({
-			dataType: "json",
-			url: "api.php",
-			method: "post",
-			data: {
-				action: 	"add_org_admin",
-				orgid:		org_id,
-				key: 		key,
-				fname: 		fname,
-				email: 		email,
-				orgaccess:	orgaccess
-			},
-			success: function (r) {on_add_admin_success(r, org_id);},
-			error: function (x, s, e) {on_add_admin_error(x, e, org_id);}
-		});
-	}
-
-	//Create a rate limited function
-	var delayaddadmin = _.rateLimit(addadmin, ratelimit);
-	
-	// Loop over selected check boxes in the org_checkboxes array
-	// Don't need to check for enabled as disabled ones are all unticked	
-	$(':checkbox[name="org_checkboxes[]"]:checked').each( function () {
-		// Get the Meraki organisation id which was stored as the checkbox value
-		var org_id = this.value;
-
-		// Update the output column
-		$('#meraki_org_output_'+org_id).html('Adding...');
-
-		// Queue an AJAX call to add the admin to the organisation
-		delayaddadmin(org_id);
-	});
-}
-
-// Callback to update output column on success
-function on_add_admin_success(r, org_id) {
-	$('#meraki_org_output_'+org_id).html('Success')
-	$('#meraki_org_output_'+org_id).addClass('meraki_success');
-}
-
-// Callback to update output column on error
-function on_add_admin_error(x, e, org_id) {
-	$('#meraki_org_output_'+org_id).html('HTTP Error: '+e+'<br />Server response (if any): '+x.responseText);
-	$('#meraki_org_output_'+org_id).addClass('meraki_failure');
-}
-
-
-function print_select_admin_to_remove() {
-	status_update('Sorting and generating output...');
-	
-	// Call another function to group organisations by administrator
-	// as this is non-trivial and needed elsewhere
-	admins = group_orgs_by_admin();
-	
-	// Create list box for admins
-	$('#meraki_admins_output').html('<select id="meraki_admin" name="meraki_admin"></select>');
-	
-	// Loop over admins and add as an option in the list box
-	// The index for the admins object is email and this is used by
-	// JQuery as the iterator (j) 
-	$.each ( admins, function (j) {
-		$('#meraki_admin').append('<option value="'+j+'">'+j+' ('+this.name+')</option>');
-	});
-	
-	// Add a button to submit form
-	$('#meraki_admins_output').append('\
-		<div class="meraki_row">\
-			<input type="button" class="meraki_button" name="meraki_next2" id="meraki_next2" value="Next" onclick="get_orgs_for_admin();"\
-		</div>\
-	');
-	status_update('Waiting for user input...');
-}
-
-//TODO: Rename this function (print_orgs_to_remove_admin?)
-function get_orgs_for_admin() {
-	status_update('Sorting and generating output...');
-	
-	// Hide the previous form to prevent resubmission
-	$('#meraki_admins_output').hide();
-	
-	// Get the admin to remove from the select box
-	var admin_to_remove = $('#meraki_admin').val();
-	
-	sorted = orgs.sort(function(a, b) { return (a.name < b.name)?-1:((b.name < a.name)?1:0); });
-	orgs = sorted;
-
-	// Call another function to group organisations by administrator
-	// as this is non-trivial and needed elsewhere
-	admins = group_orgs_by_admin();
-	
-	// Add to the HTML page a prompt and the select all box
-	$('#meraki_orgs_output').append('\
-		<div class="meraki_row"><p>Please select the organisations to remove this user from:</p></div>\
-	');
-	$('#meraki_orgs_output').append('<div class="meraki_row" id="meraki_orgs_select_all"></div>');
-	$('#meraki_orgs_select_all').append('\
-		<div class="meraki_left">\
-			<label for="meraki_orgs_select_all_box">\
-				Select All\
-			</label>\
-		</div>\
-	');
-	$('#meraki_orgs_select_all').append('\
-		<div class="meraki_middle">\
-			<input type="checkbox" name="select_all" value="select_all" id="meraki_orgs_select_all_box" />\
-		</div>\
-	');
-	
-	//  Attach a function to the check all box to be triggered when changed
-	$("#meraki_orgs_select_all_box").change(function(event) {
-		
-		// Define the checkbox we're working on
-		var checkbox = event.target;
-		
-		// If it's checked, tick all the organisation checkboxes that are not disabled and not already checked
-		if (checkbox.checked) {
-			$(':checkbox[name="org_checkboxes[]"]:not(:disabled):not(:checked)').each( function () {
-				//Note: "this" is the current object in the "each" loop, not the object which raised the event
-				this.checked = true;
-			});
-		}
-		// Otherwise, untick all the organisation checkboxes that
-		// are not disabled and are already checked
-		else {
-			$(':checkbox[name="org_checkboxes[]"]:not(:disabled):checked').each( function () {
-				// Note: "this" is the current object in the "each" loop,
-				// not the object which raised the event
-				this.checked = false;
-			});
-		}
-	});
-
-
-	// Loop over the organisations
-	$.each (orgs, function (k) {
-		// Add a new row to the table
-		$('#meraki_orgs_output').append('<div class="meraki_row" id="meraki_orgs_'+k+'"></div>');
-		// Print the name
-		$('#meraki_orgs_'+k).append('\
-			<div class="meraki_left">\
-				<label for="meraki_org_'+orgs[k].id+'">\
-					'+orgs[k].name+'\
-				</label>\
-			</div>\
-		');
-		// Print a checkbox with a value and DOM id based on the Meraki id
-		$('#meraki_orgs_'+k).append('\
-			<div class="meraki_middle">\
-				<input type="checkbox" name="org_checkboxes[]" value="'+orgs[k].id+'" id="meraki_org_'+orgs[k].id+'" disabled />\
-			</div>\
-		');
-		
-		// Add a status column
-		// We assume they're not an admin and set the formatting
-		$('#meraki_orgs_'+k).append('<div class="meraki_right" id="meraki_org_output_'+orgs[k].id+'" ></div>');
-		$('#meraki_org_output_'+orgs[k].id).html('Not an admin');
-		$('#meraki_org_output_'+orgs[k].id).addClass('meraki_success');
-		$('#meraki_orgs_'+k).hide();
-		
-		// If we were unable to query the admins for the organisation
-			// Disable the checkbox
-			// Add an error to the output column
-			// Set the formatting (CSS class)
-		if ( orgs[k].administrator == "ERROR") {
-			$('#meraki_org_'+orgs[k].id).attr('disabled','disabled');
-			$('#meraki_org_output_'+orgs[k].id).html('Unable to read data');
-			$('#meraki_org_output_'+orgs[k].id).addClass('meraki_failure');
-			$('#meraki_orgs_'+k).hide();
-		}
-	
-		// Loop over administrators organisations
-		$.each ( admins[admin_to_remove], function (j) {
-			//If this organisation is there
-					// Enable the checkbox
-					// Clear the output column
-					// Remove the formatting (CSS class)
-			if ( admins[admin_to_remove][j].id == orgs[k].id ) {
-				$('#meraki_org_'+orgs[k].id).removeAttr('disabled');
-				$('#meraki_orgs_'+k).css('display', 'table-row');
-				$('#meraki_org_'+orgs[k].id).val(orgs[k].id + ':' + admins[admin_to_remove][j].orgAdminId)
-				$('#meraki_org_output_'+orgs[k].id).html('');
-				$('#meraki_org_output_'+orgs[k].id).removeClass('meraki_success');
-			}
-		});
-	});
-	
-	// Add a button to submit form
-	$('#meraki_orgs_output').append('\
-		<div class="meraki_row">\
-			<input type="button" class="meraki_button class meraki_button_warning" name="meraki_go" id="meraki_go" value="DELETE from Selected Organisations" onclick="remove_admin();">\
-		</div>\
-	');
-	
-	// Need to wait for the user to click the button...
-	status_update('Waiting for user input...');
-}
-
-// Function to remove the admin from the selected organisations
-function remove_admin() {
-    status_update("Removing admin...");
-	
-	// Hide the button to prevent double submissions
-	$("#meraki_go").hide();
-	
-	// Fuction to remove an admin
-	function remadmin (org_id, admin_id) {
-		$.ajax({
-			dataType: "json",
-			url: "api.php",
-			method: "post",
-			data: {
-				action: 	"delete_org_admin",
-				orgid:		org_id,
-				adminid:	admin_id,
-				key:		key
-			},
-			success: function (r) {on_del_admin_success(r, org_id);},
-			error: function (x, s, e) {on_del_admin_error(e, org_id);}
-		});
-	}
-
-
-	//Create a rate limited function
-	var delayremadmin = _.rateLimit(remadmin, ratelimit);
-
-	// Loop over selected check boxes in the org_checkboxes array
-	// Don't need to check for enabled as disabled ones are all unticked
-	$(':checkbox[name="org_checkboxes[]"]:checked').each( function () {
-		// Get the Meraki organisation and admin id which were stored in the checkbox value seperated by :
-		var ids = this.value.split(':');
-		var org_id = ids[0];
-		var admin_id = ids[1];
-		
-		// Update the output column
-		$('#meraki_org_output_'+org_id).html('Removing...');
-		
-		// Queue an AJAX call to remove the admin from the organisation
-		delayremadmin(org_id, admin_id);
-
-	});
-}
-
-// Callback to update output column on success
-function on_del_admin_success(r, org_id) {
-	$('#meraki_org_output_'+org_id).html('Success')
-	$('#meraki_org_output_'+org_id).addClass('meraki_success');
-}
-
-// Callback to update output column on error
-function on_del_admin_error(e, org_id) {
-	$('#meraki_org_output_'+org_id).html('Error: '+e);
-	$('#meraki_org_output_'+org_id).addClass('meraki_failure');
-}
-
-
-//GET INVENTORY
-
-// Called by button click
-function get_inv_orgs() {
-	// Update the status box
-	status_update("Fetching organisations...");
-	// Hide the form to prevent people clicking stuff
-	$(".meraki_form").hide();
-	// Get the key to use
-	set_key();
-	// Call the general function to get the list of organisations
-	// Using the success callback for this operation, and a general error catching callback
-	get_organisations(on_get_organisations_success_inventory, on_get_organisations_error);	
-}
-
-// Callback from get_organisations which has succesfully returned data
-function on_get_organisations_success_inventory(data) {
-	// Update the status box
-	status_update('Sorting and generating output...');
-	// Store the organisations received into the global variable
-	orgs = data;
-	// Sort the organisations by name A - Z
-	sorted = orgs.sort(function(a, b) { return (a.name < b.name)?-1:((b.name < a.name)?1:0); });
-	
-	// Create list box for organisations
-	$('#meraki_orgs_output').html('<select id="meraki_org" name="meraki_org"></select>');
-	
-	// Loop over organisations and add as an option in the list box
-	$.each ( orgs, function (j) {
-		$('#meraki_org').append('<option value="'+this.id+'">'+this.name+'</option>');
-	});
-	
-	// Add a button to submit form
-	$('#meraki_orgs_output').append('\
-		<div class="meraki_row">\
-			<input type="button" class="meraki_button" name="meraki_go" id="meraki_go" value="Get Inventory" onclick="get_inventory();">\
-		</div>\
-	');
-	status_update('Waiting for user input...');
-}
-
-// Called by button click
-// TODO: Rename this function
-function get_inventory() {
-	// Update the status box
-	status_update("Fetching networks...");
-	// Hide the form to prevent people clicking stuff
-	$('#meraki_orgs_output').hide();
-	// Get the organisation id to use
-	var orgid=$('#meraki_org').val();
-	// Get the networks in this organisation
-	$.ajax({
-		dataType: "json",
-		url: "api.php",
-		method: "post",
-		data: {
-			action:	"get_org_networks",
-			orgid:	orgid,
-			key:	key
-		},
-		success: function (r) {on_get_network_success(r, orgid);},
-		error: function (x, s, e) {on_get_network_error(e, orgid);}
-	});
-}
-
-// Callback from AJAX call to get organisation networks which has succesfully returned data
-function on_get_network_success(r, orgid) {
-	nets = r;
-	number_of_nets = nets.length;
-	status_update("Found " + number_of_nets + " networks - fetching device details...");
-	
-	// Get the devices for each network
-    
-	function getnetwork (id,orgid,network) {
-        $.ajax({
-            dataType: "json",
-            url: "api.php",
-			method: "post",
-			data: {
-				action:	"get_network_devices",
-				orgid:	orgid,
-				networkid: id,
-				key:	key
-			},
-            success: function (r) {on_get_devices_success(r, network);},
-            error: function (x, s, e) {on_get_devices_error(e, network);}
-        });
-	}
-	var delaygetnetwork = _.rateLimit(getnetwork, ratelimit);
-	$.each(r, function(network) {
-		delaygetnetwork(this.id,orgid,network);
-	});
-}
-
-// Callback from AJAX call to get network devices which has succesfully returned data
-function on_get_devices_success(devices, net_index) {
-	nets[net_index].devices = devices;
-	nets_completed++;
-    if(check_nets_complete()) {
-        print_inventory_output();
-	}
-}
-
-function on_get_network_error(e, net_index) {
-	status_update("Error fetching networks: " + e);
-}
-
-function on_get_devices_error(e, net_index) {
-	status_update("Error fetching devices: " + e);
-	nets[net_index].devices = ["ERROR"];
-	nets_completed++;
-    if(check_nets_complete()) {
-        print_inventory_output();
-    }
-}
-
-function  print_inventory_output() {
-	status_update('Sorting and generating output...');
-	
-	var csv="Network Name,Network Type,Device Name,Device Serial,Device Model,Device IP,Device MAC\r\n";
-	
-	sorted = nets; //.sort(function(a, b) { return a.name - b.name; });
-	$("#meraki_inventory_output").html('\
-		<table class="meraki_output_table" id="meraki_inventory_output_table">\
-			<tr>\
-				<td class="meraki_output_header_group"><b>Network Name</b></td>\
-				<td class="meraki_output_header_group"><b>Network Type</b></td>\
-				<td class="meraki_output_header"><b>Device Name</b></td>\
-				<td class="meraki_output_header"><b>Device Serial</b></td>\
-				<td class="meraki_output_header"><b>Device Model</b></td>\
-				<td class="meraki_output_header"><b>Device IP</b></td>\
-				<td class="meraki_output_header"><b>Device MAC</b></td>\
-			</tr>\
-		</table>\
-	');
-	$.each(sorted, function(j) {
-		devices = sorted[j].devices;
-		number_of_devices = devices.length;
-		if ( number_of_devices > 0 ) {
-			$("#meraki_inventory_output_table").append('\
-				<tr>\
-					<td rowspan="'+number_of_devices+'" class="meraki_output_group">' + this.name + '</td>\
-					<td rowspan="'+number_of_devices+'" class="meraki_output_group">' + this.type + '</td>\
-					<td>' + devices[0].name + '</td>\
-					<td>' + devices[0].serial + '</td>\
-					<td>' + devices[0].model + '</td>\
-					<td>' + devices[0].lanIp + '</td>\
-					<td>' + devices[0].mac + '</td>\
-				</tr>\
-			');
-			csv = csv + ([this.name, this.type, devices[0].name, devices[0].serial, devices[0].model, devices[0].lanIp, devices[0].mac].join()) + "\r\n";
-			for (i=1; i<number_of_devices; i++) {
-				$("#meraki_inventory_output_table").append('\
-					<tr>\
-						<td>' + devices[i].name + '</td>\
-						<td>' + devices[i].serial + '</td>\
-						<td>' + devices[i].model + '</td>\
-						<td>' + devices[i].lanIp + '</td>\
-						<td>' + devices[i].mac + '</td>\
-					</tr>\
-				');
-				csv = csv + ([sorted[j].name, sorted[j].type, devices[i].name, devices[i].serial, devices[i].model, devices[i].lanIp, devices[i].mac].join()) + "\r\n";
-			}
-		}
-		else {
-			$("#meraki_inventory_output_table").append('\
-				<tr>\
-					<td class="meraki_output_group">' + this.name + '</td>\
-					<td class="meraki_output_group">' + this.type + '</td>\
-					<td>No devices found</td>\
-					<td></td>\
-					<td></td>\
-					<td></td>\
-					<td></td>\
-				</tr>\
-			');
-		}
-	});
-	$("#meraki_inventory_output").append('<p><br/><br/>Please find below in CSV format:</p>');
-	$("#meraki_inventory_output").append('<textarea name="meraki_inventory_csv_output" id="meraki_inventory_csv_output" style="width:100%" rows="50" ></textarea>');
-	$('#meraki_inventory_csv_output').text(csv);
-	status_update("Done...");
-}
-
-function check_nets_complete() {
-    if( nets_completed != number_of_nets) { 
-		status_update("Retrieved data for " + nets_completed + " / " + number_of_nets + " networks - waiting for more data...");
-        return false;
-    }
-    return true;
-}
-
-//GET LICENCES
-
-function get_licence_state() {
-	
-	status_update("Fetching organisations...");
-	$(".meraki_form").hide();
-	set_key();
-	get_organisations(on_get_organisations_success_licences, on_get_organisations_error);	
-}
-
-
-function on_get_organisations_success_licences(data) {
-	orgs = data;
-	number_of_orgs = orgs.length;
-	status_update("Found " + number_of_orgs + " organisations - fetching licence states...");
-
-	function getlic (org) {
-        $.ajax({
-            dataType: "json",
-            url: "api.php",
-			method: "post",
-			data: {
-				action:	"get_org_licences",
-				orgid:	data[org].id,
-				key:	key
-			},
-            success: function (r) {on_get_licence_sucess(r, org);},
-            error: function (x, s, e) {on_get_licence_error(e, org);}
-        });
-	}
-	var delaygetlic = _.rateLimit(getlic, ratelimit);
-
-    $.each(data, function(org) {delaygetlic(org)});
-}
-
-function on_get_licence_sucess(lic, org_index) {
-	orgs[org_index].licStatus = lic['status'];
-	orgs[org_index].licExpirationDate = Date.parse(lic['expirationDate']);
-	orgs[org_index].licLicensedDeviceCounts = lic['licensedDeviceCounts'];	
-	orgs_completed++;
-    if(check_orgs_complete()) {
-        print_licence_output();
-    }
-}
-
-function on_get_licence_error(error, org_index) {
-	orgs[org_index].licStatus = "ERROR";
-	orgs[org_index].licExpirationDate = Date.parse(0);
-	orgs[org_index].licLicensedDeviceCounts = "ERROR";
-	orgs_completed++;
-    if(check_orgs_complete()) {
-        print_licence_output();
-    }
-}
-
 function print_licence_output() {
-	status_update('Sorting and generating output...');
+	$("#licenceOutput").append('<p>Sorting and generating output...</p>');
 	sorted = orgs.sort(function(a, b) { return a.licExpirationDate - b.licExpirationDate; });
-	$("#meraki_licence_output").html('\
-		<table id="merkai_licence_output_table">\
-			<tr>\
-				<td class="meraki_output_header_group"><b>Organisation</b></td>\
-				<td class="meraki_output_header_group"><b>Status</b></td>\
-				<td class="meraki_output_header_group"><b>Expiration Date</b></td>\
-				<td class="meraki_output_header_group"><b>Device Type</b></td>\
-				<td class="meraki_output_header_group"><b>Device Count</b></td>\
-			</tr>\
-		</table>\
-	');
+	$("#licenceOutput").html('<table id="licenceOutputTable">		<tr><td><b>Organisation</b></td><td><b>Status</b></td><td><b>Expiration Date</b></td><td><b>Devices</b></td></tr></table>');
 	$.each(sorted, function(data) {
 		d = new Date(sorted[data].licExpirationDate);
 		n = d.toDateString();
-		licenced_devices = dump_licenced_devices(sorted[data].licLicensedDeviceCounts);
-		number_of_types=licenced_devices.length;
-		var status_class = '';
-		switch (sorted[data].licStatus) {
-			case "ERROR":
-			case "Expired":
-			case "License Required":
-				status_class = 'meraki_failure';
-				break;
-			case "License Expires Soon":
-				status_class = 'meraki_warning';
-				break;
-			case "OK":
-				status_class = 'meraki_success';
-				break;
-			default:
-				break;
-		}
-		
-		$("#merkai_licence_output_table").append('\
-			<tr>\
-				<td rowspan="'+number_of_types+'" class="meraki_output_group">' + sorted[data].name + '</td>\
-				<td rowspan="'+number_of_types+'" class="meraki_output_group ' + status_class + '">' + sorted[data].licStatus + '</td>\
-				<td rowspan="'+number_of_types+'" class="meraki_output_group">' + n + '</td>\
-				<td class="meraki_output_group">'+ licenced_devices[0].type + '</td>\
-				<td class="meraki_output_group">'+ licenced_devices[0].count + '</td>\
-			</tr>\
-		');	
-		for (i=1; i<number_of_types; i++) {
-			$("#merkai_licence_output_table").append('\
-				<tr>\
-					<td class="meraki_output_group">' + licenced_devices[i].type + '</td>\
-					<td class="meraki_output_group">' + licenced_devices[i].count + '</td>\
-				</tr>\
-			');
-		}
+		$("#licenceOutputTable").append('<tr><td>' + sorted[data].name + '</td><td>' + sorted[data].licStatus + '</td><td>' + n + '</td><td>'+ dump_licenced_devices(sorted[data].licLicensedDeviceCounts) + '</td></tr>');		
 	});
-	status_update("Done...");
 }
 
 function dump_licenced_devices(data) {
 	var i = 0;
-	var list = [];
+	var list = '';
 	if (data != 'ERROR'){
 		for (type in data) {
-			list[i] = { type: type, count: data[type] };
+			if ( i != 0 ) {
+				list = list + '<br/>';
+			}
+			list = list + type + ' --> ' + data[type];
 			i++;
 		}
 	}
 	else {
-		list[i] = {type:'ERROR', count:'ERROR'};
+		list = 'ERROR';
 	}
 	return list;
 }
 
-
-
-//GENERAL FUNCTIONS
-
-function check_orgs_complete() {
-    if( orgs_completed != number_of_orgs) { 
-		status_update("Retrieved data for " + orgs_completed + " / " + number_of_orgs + " organisations - waiting for more data...");
-        return false;
-    }
-    return true;
+function get_orgs_success(data) {
+	orgs = data;
+	number_of_orgs = orgs.length;
+	$("#licenceOutput").append('<p>Got ' + number_of_orgs + ' organisations.  Fetching details....</p>');
+	get_next_licence(0);
 }
 
-
-function do_this_when_all_loops_are_done() {
-	status_update("Done...");
+function get_orgs() {
+	var key = $('#api-key').val();
+	//Check if the user has entered anything
+	//if(key == ''){
+	//	key = 'rokey';
+	//}
+	$.ajax({
+		dataType: "json",
+		url: "licences.php?action=get_orgs&key=" + key,
+		success: function(data) {get_orgs_success(data);} 
+	});
 }
 
-function get_organisations(callback_success, callback_error) {
-        $.ajax({
-            dataType: "json",
-            url: "api.php",
-			method: "post",
-			data: {
-				action:	"get_orgs",
-				key:	key
-			},
-            success: function(r) {callback_success(r);},
-            error: function(x, s, e) {callback_error(e);}
-        });     
+function get_org_licences(orgid) {
+	var key = $('#api-key').val();
+	//Check if the user has entered anything
+	//if(key == ''){
+	//	key = 'rokey';
+	//}
+	$.ajax({
+		dataType: "json",
+		url: "licences.php?action=get_org_licences&orgid=" + orgid + "&key=" + key,
+		success: function(data) { get_next_licence(data); },
+		error: function (jqXHR, textStatus, errorThrown ) {
+			console.log("Status: " + textStatus  + ", Error: " + errorThrown);
+			orgs[current_org].licStatus = "ERROR";
+			orgs[current_org].licExpirationDate = "ERROR";
+			orgs[current_org].licLicensedDeviceCounts = "ERROR";
+			if (current_org < number_of_orgs-1) {
+				//More stuff to get....
+				current_org++;
+				$("#licenceOutputCounter").text('Getting organisation ' + parseInt(parseInt(current_org)+1) + '/' + number_of_orgs +  ' (' + orgs[current_org].name + ')....');
+				get_org_licences(orgs[current_org].id);
+			}
+			else {
+				//All done - print output...
+				print_licence_output();
+			}
+		}
+	});
 }
-
-function on_get_organisations_error (jqXHR, textStatus, errorThrown) {
-	status_update("Error..." + errorThrown);
-}
-
-function group_orgs_by_admin () {
-	var admins = {};
-	$.each (orgs, function(j) {
-		$.each (orgs[j].administrator, function (k) {
-			if (orgs[j].administrator[k] != "ERROR") {
-				var current_admin = orgs[j].administrator[k];
-				if (!admins[current_admin.email]) {
-
-					admins[current_admin.email]=[];
-					
-					admins[current_admin.email].name = current_admin.name;
-				}
-
-				var next_org = admins[current_admin.email].length;
-
-				admins[current_admin.email][next_org]= { id: 			orgs[j].id,
-														 name:			orgs[j].name,
-														 orgAdminId: 	current_admin.id,
-														orgAccess: 	current_admin.orgAccess,
-														accountStatus:	current_admin.accountStatus
-														};
-				
-			}
-			
-			
-		});
-	});
-	return admins;
-}
-
-function status_update(t) {
-    $("#meraki_status").html("<pre>Current status: " + t + "</pre>");
-	return 1;
-}
-
-function set_key() {
- 	if (!($("#meraki_ro_key").is(':checked'))) {
-		key = $("#meraki_api_key").val();
-	}
-	else{
-		key = "rokey";
-	}
-}
Index: include.php
===================================================================
--- include.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ include.php	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -1,98 +1,31 @@
 <?php
+###########################################
+## Constants to customise to the install ##
+###########################################
 
-// Main PHP file containing most of the functionality required
+##Meraki Server
+$SERVER='https://dashboard.meraki.com/api/';
+$API_VERSION='v0';
+$RO_API_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
 
-// Populate configuration variables with local values
-include 'config.php';
-
-// Load in the header and footer for the HTML pages
 $page_header = file_get_contents ( "page_header.html" );
 $page_footer = file_get_contents ( "page_footer.html" );
 
-// Function to add a row to the forms with the standard fields for
-// The API key where using the built in read only key would be acceptable
-function ro_key_fields() { ?>
-				<div class="meraki_row">
-					<div class="meraki_left">
-							<label for="meraki_ro_key">Use Read Only Key: </label>
-					</div>
-					<div class="meraki_right">
-						<input type="checkbox" name="meraki_ro_key" id="meraki_ro_key" value="rokey" checked>
-					</div>
-				</div>
-				<div class="meraki_row meraki_ro_key">
-					<div class="meraki_left">
-							<label for="merkai_api_key">Your API Key: </label>
-					</div>
-					<div class="meraki_right">
-						<input type="password" name="meraki_api_key" id="meraki_api_key" length="40" />
-					</div>
-				</div>
-<?php }
 
-// Function to add a row to the forms with the standard fields for
-// The API key where using the built in read only key would NOT be acceptable
-// This is generally where people need to make changes
-function rw_key_fields() { ?>
-				<div class="meraki_row meraki_rw_key">
-					<div class="meraki_left">
-							<label for="merkai_api_key">Your API Key: </label>
-					</div>
-					<div class="meraki_right">
-						<input type="checkbox" name="meraki_ro_key" id="meraki_ro_key" value="rokey" style="display:none" disabled>
-						<input type="password" name="meraki_api_key" id="meraki_api_key" length="40" />
-					</div>
-				</div>
-<?php }
-
-
-	// Parse API calls
 	function parse_request() {
 		global $RO_API_KEY;
-	
-		// If a key is sent, use that one, otherwise use the readonly key	
-		if ( !isset ( $_POST['key'] ) || $_POST['key'] == "" || $_POST['key'] == "rokey" ) {
+		
+		if ( !isset ( $_GET['key'] ) || $_GET['key'] == "" || $_GET['key'] == "rokey" ) {
 			$key = $RO_API_KEY;
 		}
 		else {
-			$key = $_POST['key'];
+			$key = $_GET['key'];
 		}
-		
-		// Truncate the key for logging so we can see who's using who's key
-		$truncated_key = preg_replace ( '/^[0-9a-fA-F]{36}/', '******', $key );
-		
-		// Switch on the action requested, log the request and reply with the return value of the appropriate function
-		switch ($_POST['action']) {
+		switch ($_GET['action']) {
 			case "get_orgs":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
 				echo ( get_orgs($key) );
 				break;
 			case "get_org_licences":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				echo ( get_org_licences($_POST['orgid'], $key) );
-				break;
-			case "get_org_admins":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				echo ( get_org_admins($_POST['orgid'], $key) );
-				break;
-			case "get_org_networks":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				echo ( get_org_networks($_POST['orgid'], $key) );
-				break;
-			case "get_network_devices":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				echo ( get_network_devices($_POST['orgid'], $_POST['networkid'], $key) );
-				break;
-			case "add_org_admin":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				error_log("orgid: " . $_POST['orgid'] . " Name: " . $_POST['fname'] . " Email: " . $_POST['email'] . " OrgAccess: " . $_POST['orgaccess'], 0);
-				echo ( add_org_admin($_POST['orgid'], $_POST['fname'], $_POST['email'], $_POST['orgaccess'], $key) );
-				break;
-			case "delete_org_admin":
-				error_log("Username: " . $_SERVER['REMOTE_USER'] . " Key: " . $truncated_key . " Action: " . $_POST['action'], 0);
-				error_log("orgid: " . $_POST['orgid'] . " Adminid: " . $_POST['adminid']);
-				echo ( delete_org_admin($_POST['orgid'], $_POST['adminid'], $key) );
-				break;
-			default:
+				echo ( get_org_licences($_GET['orgid'], $key) );
 				break;
 		}
@@ -105,57 +38,68 @@
 
 
-	// Get a list of organisations
+	//Get a list of organisations
 	function get_orgs($key) {
 		return get_request('/organizations/', $key);
 	}
 	
-	// Get a list of networks in an organisation
-	function get_org_networks($orgid, $key) {
+	//Get a list of networks in an organisation
+	function get_org_nets($orgid, $key) {
 		return get_request('/organizations/' . $orgid . '/networks', $key);
 	}
-	
-	// Get a list of devices in an organisation
-	function get_network_devices($orgid, $netid, $key) {
-		return get_request('/networks/' . $netid . '/devices', $key);
-	}
 
-	// Get an array of licences for an organisation
+	//Get an array of licences for an organisation
 	function get_org_licences($orgid, $key) {
 		return get_request('/organizations/' . $orgid . '/licenseState', $key );
 	}
 		
-	// Get a list of APs in a network
+	//Get a list of APs in a network
 	function get_net_aps($netid, $key) {
 		return get_request('/networks/' . $netid . '/devices', $key );
 	}
 	
-	// Get a list of admins in an organisation
+	//Get a list of admins in an organisation
 	function get_org_admins($orgid, $key) {
-		return get_request('/organizations/' . $orgid . '/admins', $key );
+		return get_request('/organizations/' . $org_id . '/admins', $key );
 	}
+	//SAMPLE RESPONSE
+	//[
+	// {
+	//	"id":"1",
+	//	"name":"Miles Meraki",
+	//	"email":"miles@meraki.com",
+	//	"orgAccess":"none",
+	//	"tags":[
+	//	  {
+	//		"tag":"west",
+	//		"access":"read-only"
+	//	  }
+	//	],
+	//	"networks":[
+	//	  {
+	//		"id":"N_249",
+	//		"access":"full"
+	//	  }
+	//	]
+	//  }
+	//]
 	
-	// Add and admin to and organisation
-	function add_org_admin($orgid, $name, $email, $access, $key) {
-		$data = array ("name" => $name, "email" => $email, "orgAccess" => $access);
-		$call = "/organizations/" . $orgid . "/admins/";
-		return post_request($call, $data, $key);
-	}
+	//Add Admin
+	//POST /organizations/[organization_id]/admins
+	//sample post data:
+	//{"name":"Miles Meraki", "email":"miles@meraki.com", "orgAccess":"none", "tags":[{"tag":"west", "access":"read-only"}]}
 	
-	// Delete an admin from an organisation
+	//Delete an admin from an organisation
 	function delete_org_admin($orgid, $adminid, $key) {
 		return delete_request('/organizations/' . $orgid . '/admins/' . $adminid, $key);
 	}
-
 	
 	
 	
 	
-	// General function to submit a GET call
+	
+	//General function to submit a GET call
 	function get_request($call, $key) {
 		global $SERVER;
 		global $API_VERSION;
-	
-		// TODO: Move to CURL
-
 		$opts = array(
 			'http'=>array(
@@ -169,56 +113,28 @@
 		// Open the file using the HTTP headers set above
 		$json = file_get_contents($SERVER . $API_VERSION . $call, false, $context);
-		// TODO:  Catch exceptions and return errors
-
-		// Sanitise the ID for Javascript (enclose in " so it's a string rather than a number)
+		//TODO:  Catch exceptions and return errors
 		$resp = preg_replace ( '/"id":([0-9]+),/', '"id":"$1",', $json );
 		return $resp;
 	}
 
-	// General function to submit a POST call
-	function post_request($call, $data, $key) {
-
-		// Use the values defined in the config.php file
+	//General function to submit a POST call
+	function post_request($call, $post_data, $key) {
 		global $SERVER;
 		global $API_VERSION;
-		
-		// Initialise curl
-		$ch = curl_init();
+		$opts = array(
+			'http'=>array(
+				'method'	=>	"POST",
+				'header'	=>	"X-Cisco-Meraki-API-Key: " . $key . "\r\n" .
+								"Content-type: application/x-www-form-urlencoded\r\n",
+				'content'	=>	$post_data
+			)
+		);
 
-		// Set the request URL
-		curl_setopt($ch, CURLOPT_URL,$SERVER . $API_VERSION . $call);
-		// Define a POST request
-		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
-		// Follow redirects
-		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-		// Encode the data to be sent and attach to the request
-		curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
-		// Return the result of request instead of Truse/False
-		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+		$context = stream_context_create($opts);
 
-		// Define request headers
-		$headers = [	"X-Cisco-Meraki-API-Key: " . $key,
-						"Content-type: application/json"
-					];
-
-		// Attach the headers to the request
-		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
-		// Execute the curl request and get the returned data and HTTP code
-		$json = curl_exec ($ch);
-		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-		
-		// Sanitise the ID for Javascript (enclose in " so it's a string rather than a number)
+		// Open the file using the HTTP headers set above
+		$json = file_get_contents($SERVER . $API_VERSION . $call, false, $context);
+		//TODO:  Catch exceptions and return errors
 		$resp = preg_replace ( '/"id":([0-9]+),/', '"id":"$1",', $json );
-
-		error_log("url: " . $SERVER . $API_VERSION . $call . " data: " . json_encode($data) . " http code: " . $httpcode . " Response: " . $resp, 0);
-
-		// Tidy up
-		curl_close ($ch);
-
-		// Send the return code back to the requesting browser
-		header('HTTP/1.1 ' . $httpcode);
-
-		// Send any data we may or may not have
 		return $resp;
 	}
@@ -226,45 +142,20 @@
 	//General function to submit a DELETE call
 	function delete_request($call, $key) {
-
-		// Use the values defined in the config.php file
 		global $SERVER;
 		global $API_VERSION;
+		$opts = array(
+			'http'=>array(
+				'method'	=>	"DELETE",
+				'header'	=>	"X-Cisco-Meraki-API-Key: " . $key . "\r\n"
+			)
+		);
 
+		$context = stream_context_create($opts);
 
-		// Initialise curl
-		$ch = curl_init();
-
-		// Set the request URL
-		curl_setopt($ch, CURLOPT_URL,$SERVER . $API_VERSION . $call);
-		// Define a DELETE request
-		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
-		// Follow redirects
-		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-		// Return the result of request instead of Truse/False
-		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
-		// Define request headers
-		$headers = [	"X-Cisco-Meraki-API-Key: " . $key,
-						"Content-type: application/json"
-					];
-
-		// Attach the headers to the request
-		curl_setopt($ch, CURLOPT_HEADER, true);
-		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
-		// Execute the curl request and get the returned data and HTTP code
-		$json = curl_exec ($ch);
-		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-		
-		// Sanitise the ID for Javascript (enclose in " so it's a string rather than a number)
-		$resp = preg_replace ( '/"id":([0-9]+),/', '"id":"$1",', $json );
-
-		// Tidy up
-		curl_close ($ch);
-
-		// Send the return code back to the requesting browser
-		header('HTTP/1.1 ' . $httpcode);
-
-		// Send any data we may or may not have
+		// Open the file using the HTTP headers set above
+		$json = file_get_contents($SERVER . $API_VERSION . $call, false, $context);
+		//TODO:  Catch exceptions and return errors
+		//Successful HTTP Status: 204
+		//Return HTTP Code
 		return $resp;
 	}
Index: index.php
===================================================================
--- index.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ index.php	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -11,7 +11,5 @@
 	<p>Please select a function:</p>
 	<ul>
-		<li><a href="inventory.php">Inventory</a></li>
 		<li><a href="licences.php">Licences</a></li>
-		<li><a href="accounts.php">Account Administration</a></li>
 	</ul>
 	
Index: ventory.php
===================================================================
--- inventory.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ 	(revision )
@@ -1,53 +1,0 @@
-<?php
-
-// The paage that is loaded for account related functions
-
-// Include the main PHP file
-include ('include.php');
-
-// Set the page name for display purposes
-$page_name = "Meraki Inventory";
-// Set the page name in the template
-// TODO: Allow better per-page customisation of the template
-$page_header = preg_replace ( '/PAGE_NAME/', $page_name, $page_header );
-
-// Check to see if this is an API call or a new call to the page
-//TODO: This is no longer required.  All calls should now go to api.php.  Check, and then remove this code.
-if ( !isset ( $_POST['action'] ) || $_POST['action'] == "" ) {
-    // Send the page to the browser
-	echo ( $page_header );
-	new_request();
-	echo ( $page_footer );
-}
-else {
-    // API Call - Parse request in include.php
-	parse_request();
-}
-
-// Send the page to the browser
-function new_request() { ?>
-	
-	<div class="meraki_licence_state" id="meraki_licence_state">
-		<h2>Inventory of Organisation</h2>
-		<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-			<div class="meraki_container meraki_form">
-			<?php ro_key_fields(); ?>
-			<input type="button" class="meraki_button" name="meraki_next1" id="meraki_next1" value="Next" onclick="get_inv_orgs();">
-		</div>
-		
-		<div id="meraki_orgs_output"></div>
-		
-		<div id="meraki_inventory_output"></div>
-	</div>
-			
-
-
-		
-	<script>
-		var page = "inventory";
-	</script>
-	<?php
-	return;
-}
-
-?>
Index: licences.php
===================================================================
--- licences.php	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ licences.php	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -1,19 +1,9 @@
 <?php
-
-// The paage that is loaded for account related functions
-
-// Include the main PHP file
 include ('include.php');
 
-// Set the page name for display purposes
 $page_name = "Meraki Licencing";
-// Set the page name in the template
-// TODO: Allow better per-page customisation of the template
 $page_header = preg_replace ( '/PAGE_NAME/', $page_name, $page_header );
 
-// Check to see if this is an API call or a new call to the page
-//TODO: This is no longer required.  All calls should now go to api.php.  Check, and then remove this code.
-if ( !isset ( $_POST['action'] ) || $_POST['action'] == "" ) {
-    // Send the page to the browser
+if ( !isset ( $_GET['action'] ) || $_GET['action'] == "" ) {
 	echo ( $page_header );
 	new_request();
@@ -21,35 +11,25 @@
 }
 else {
-    // API Call - Parse request in include.php
 	parse_request();
 }
 
-// Send the page to the browser
-function new_request() { ?>
-	
-	<div class="meraki_licence_state" id="meraki_licence_state">
-		<h2>Licence State for Organisations</h2>
-		<div id="meraki_status"><pre>Current status: Awaiting user input</pre></div>
-			<div class="meraki_container meraki_form">
-			<?php ro_key_fields(); ?>
-			<div class="meraki_row">
-				<div class="meraki_left">
-					<input type="button" class="meraki_button" name="meraki_go" id="meraki_go" value="Fetch Licence State" onclick="get_licence_state();">
-				</div>
-			</div>
+	function new_request() { ?>
+		
+		<div class="licenceState" id="divlicenceState">
+			<h2>Licence State for Organisations</h2>
+			<div id="licenceOutput"></div>
 		</div>
 		
-		<div id="meraki_licence_output"></div>
-	</div>
-			
-
-
+		<div class="key" style="display:none">
+			<label for="api-key">Your API Key: </label>
+			<input type="password" name="api-key" id="api-key" length="40" />
+		</div>
 		
-	<script>
-		
-	</script>
-	<?php
-	return;
-}
+		<script>
+			get_licence_state();
+		</script>
+		<?php
+		return;
+	}
 
 ?>
Index: page_header.html
===================================================================
--- page_header.html	(revision 15edf86c83205cf1ba097fb446d2d92d2f2cd65f)
+++ page_header.html	(revision 1ef418221dfb9aac8c2e099d46b49cf494a47f04)
@@ -24,5 +24,4 @@
 
 		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
-		<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
 		<script src="include.js"></script>
 		
@@ -63,11 +62,5 @@
 						<div class="col-md-12">
 							<div class="btn-group btn-breadcrumb hidden-xs hidden-sm">
-								<a href="/" title="PAHE_NAME" class="btn btn-default">/</a>
-							</div>
-							<div class="btn-group btn-breadcrumb hidden-xs hidden-sm">
-								<a href="/meraki" title="PAHE_NAME" class="btn btn-default">Meraki API</a>
-							</div>
-							<div class="btn-group btn-breadcrumb hidden-xs hidden-sm">
-								<a href="#" title="PAHE_NAME" class="btn btn-default" onclick="location.reload(true);">PAGE_NAME</a>
+								<a href="https://noc.wanstor.com/meraki_api/" title="PAHE_NAME" class="btn btn-default">PAGE_NAME</a>
 							</div>
 						</div>      
