$(document).ready(function(){
	license = new LicenseNotifier();
	license.init();
});


function LicenseNotifier () {
	/**
		licenseNotifier
		Display a message when the number of users has exceeded the number of licenses
	*/	
};

// REFACT: active and valid got completely mixed up
// show license notifier only when license is active + not valid
// this requires that the license admin page does not reset 'is_active' on display of licensing page

$.extend(LicenseNotifier.prototype, {
	init: function() {
		this.getLicense();
	},
	
	getLicense: function() {
		// Get the Agilo Pro JSON API
		// http://localhost:8080/master/json/licensing/active/Agilo%20Pro/
		
		var self = this;
		var url = encodedURLFromComponents('json', 'licensing', 'valid', 'Agilo Pro');
		$.getJSON(url, function(licenseData) {
			if (self.shouldShowNotifier(licenseData))
				self.addToDOM();
				self.checkLicense(licenseData);
		});
	},
	
	shouldShowNotifier: function(licenseData) {
		return ( ! licenseData.active || this.reasons(licenseData).length > 0);
	},
	
	reasons: function(licenseData) {
		
		if (licenseData.reasons && licenseData.reasons.length > 0)
			return licenseData.reasons;
		return [];
	},
	
	checkLicense: function(licenseData) {
		// {'active': true|false, 'reason': 'foo bar'}
		// fs: temporary workaround, see above
		
		if (this.reasons(licenseData).length > 0) {
			this.notify(this.reasons(licenseData));
		};
	},
	
	notify: function(messages) {
		// Render the message
		html = messages.join(' ') +
			' <a href="mailto:sales@agile42.com?subject=Agilo Pro Request">' +
			'Click here to extend your license</a> or disable it by removing the <b>agilo_pro</b> and <b>agilo_common</b> components from the configuration file.';
		$("#licenseNotifier").html(html);
		this.showNotification();
	},
	
	showNotification: function() {
		$("#licenseNotifier").animate({margin: 0},2000).css("display", "block").animate({bottom: 0},1500);
	},
	
	addToDOM: function() {
		$("body").append(this.template());
	},
	
	template: function() {
		return '<div id="licenseNotifier"></div>';
	}

});