/**
  * SSO jQuery plugin
  *
  * Single Sign On, by method of CAS (Central Authentication System) works by
  * redirecting the user to a central login page and setting a cookie. Every
  * other site redirects to that same page, so they share the same cookie.
  *
  * If you have pages that are visible for everybody, but have special
  * privileges for logged in users, you still need to check if the user is
  * logged in. But redirecting the user would be a hassle and slow.
  *
  * This script creates an iframe that does this for you. After the iFrame has
  * loaded, some parts will be replaced, so the user will see that he/she is
  * logged in, in an instant.
  *
  * The page that checks (the checkSignInUrl parameter) needs to do a call to
  * the CAS-server with the 'gateway=true' parameter attached. It needs to
  * render a similar page and call this script again.
  *
  * Usage:
  *
  * $.SSO({...});
  *
  * Required options:
  *
  * checkSignInUrl: string with a url (see above)
  * replacers: string or array of strings with ids that you want to replace.
  *
  * Optional options:
  *
  * debug: boolean if you want to log messages to the console (default: false)
  */
jQuery.SSO = function(options) {
	
	var sso = function(options) {
		this.options = jQuery.extend({debug: false}, options);
		
		if (this.runningInIframe()) { 
			this.replaceParts(); 
		} 
		else { 
			this.checkSignedIn(); 
		}
	}

	sso.prototype = {
	
		// check if it is running in an iframe, because we don't
		// want to create iframes recursively
		runningInIframe: function() { 
			return(window.location != window.parent.location); 
		},
		// Open the iFrame
		checkSignedIn: function() { 
			this.makeIFrame(this.options['checkSignInUrl']); 
		},
		makeIFrame: function(url) { 
			this.log('Making iframe with this src: ' + url); 
			this.iframe = jQuery("<iframe src='" + url + "' style='display: none;' class='made-for-sso'></iframe>"); 
			jQuery('body').append(this.iframe); 
		},
		replaceParts: function() {
			this.log('Replacing parts in parent iFrame');
			var replacers = jQuery.makeArray(this.options['replacers']);
			for (var i = 0; i < replacers.length; i++) { 
				jQuery(replacers[i], window.parent.document).html(jQuery(replacers[i]).html()) 
			}
		},
		log: function(message) {
			if(this.options['debug'] && window.console) {
				if (typeof(message) == "string") { 
					console.log('* SSO: ' + message); 
				} 
				else { 
					console.log('* SSO: ');
					console.log(message); 
				}
			}
		}
	};
	
	// Perform the SSO when the DOM is ready
	$(function() { 
		new sso(options) 
	});
};
