
// Check if we can use indexOf on array's, 
// if not, fix it, we need it!
if(!Array.indexOf){
   Array.prototype.indexOf = function(obj){
      for(var i=0; i<this.length; i++){
         if(this[i]===obj){
            return i;
         }
      }
      return -1;
   };
}

// Create conceptx object
var kgnconnect = {};

//Create the style element
var ss1 = document.createElement('style');
var def = 'div#kgnconnect_overlay{position:fixed;display:block;text-align:center;top:0pt;left:0pt;z-index:999;width:100%;height:100%;}div.kgnconnect_overlay_blackout{display:block;background-color:#000;position:absolute;top:0pt;left:0pt;width:100%;height:100%;opacity:0.4;-moz-opacity:0.4;filter:alpha(opacity=40);}div.kgnconnect_overlay_centered{width:373px; height:265px; position:absolute; left:50%; top:50%; margin:-132px 0 0 -186px;}div.kgnconnect_overlay_background{position:relative;background-color:transparent;background-image:url(http://cdn.rpxnow.com/images/bg_auth.png/072e699dadea176ace38e1f39c8b1c6f.png);background-repeat:no-repeat;background-position:left top;font-size: 17px;text-align:center;width:373px;height:265px;overflow:hidden;font-family:\'lucida grande\',Helvetica,Verdana,sans-serif;}img.kgnconnect_overlay_close{position:absolute;top:-10px;right:-10px;cursor:pointer;width:34px;height:34px;}div#kgnconnect_overlay_content *{background:none;border-spacing:0;border:0;color:#000;direction:ltr;font-family:tahoma, verdana, arial, sans-serif;font-size: 12px;font-style:normal;font-variant:normal;font-weight:normal;letter-spacing:normal;line-height:1;margin:0;overflow:visible;padding:10px;text-align:center;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;visibility:visible;white-space:normal;word-spacing:normal}div#kgnconnect_overlay_content{padding: 15px;}div#kgnconnect_overlay_content h1{padding:10px;margin:0px;font-size:20px;font-weight:bolder;}div#kgnconnect_overlay a{text-decoration:underline;}div#kgnconnect_overlay a:hover{text-decoration:none;}ul.kgnconnect_providers{list-style: none outside none;}ul.kgnconnect_providers li{}ul.kgnconnect_providers li a{cursor:pointer;} a.kgn_button {text-decoration: none;font-size: 13px;text-shadow: 1px 1px 2px #666;line-height: 16px;cursor: pointer;display: inline-block;outline: medium none;border: 1px solid #444;background-image: url("' + document.location.protocol + '//' + 'kgnconnect.com/images/iconsprite.png");_background-image: url("' + document.location.protocol + '//' + 'kgnconnect.com/images/iconsprite.gif");background-color: #999;background-repeat: no-repeat;-webkit-border-radius: 3px;-moz-border-radius: 3px;border-radius: 3px;margin: 1px;height: 25px;overflow: hidden;}a.kgn_button:hover {text-decoration: none;}a.kgn_button span {font-family: "lucida grande",tahoma,verdana,arial,sans-serif;font-weight: bold;color: #fff;display: block;padding: 3px 6px 5px 28px;border-top: 1px solid rgba(255, 255, 255, 0.4);}a.kgn_button span:hover {background-color: rgba(255, 255, 255, 0.2);}a.kgn_button span:active {background-color: rgba(0, 0, 0, 0.2);}.kgn_facebook {background-color: #627aac !important;background-position: 0 0;}.kgn_hyves {background-color: #F1AE2A !important;background-position: 0 -90px;}.kgn_linkedin {background-color: #0073B2 !important;background-position: 0 -120px;}.kgn_myopenid {background-color: #80C62E !important;background-position: 0 -150px;}.kgn_windowslive {background-color: #A2DDEF !important;background-position: 0 -210px;}.kgn_google {background-color: #DD4B39 !important;background-position: 0 -30px;}.kgn_hotmail{background-color: #2BB5DA !important;background-position: 0 -60px;}.kgn_netlog{background-color: #CC0000 !important;background-position: 0 -180px;}';
ss1.setAttribute("type", "text/css");
var hh1 = document.getElementsByTagName('head')[0];
hh1.appendChild(ss1);
if (ss1.styleSheet) {
	// IE
	ss1.styleSheet.cssText = def;
} else {
	// the world
	var tt1 = document.createTextNode(def);
	ss1.appendChild(tt1);
}

/**
 * Global object
 */
kgnconnect.global = {

	// Global settings
	_sApplicationName : 'banditi-nl',
	_aEnabledProviders : 'facebook[login],google[login;contacts],hotmail[login;contacts],hyves[login],',
	_aEnabledProvidersUsage : new Array(),
	_sButtonSize : 'normal',
	_oFacebookLoginStatus : null,
	_sTokenURL : null,
	_sTokenFrame : 'parent',
	_oContainer : {},
	_oLoginStatus : {},
	_sLoginButtonText : 'Login met %providerNameFormatted%',
	
	// 
	configuration : {
		sSiteRoot : document.location.protocol + '//' + 'kgnconnect.com'
		//sSiteRoot : document.location.protocol + '//' + 'dev.kgnconnect.com:8080'
	},
	
	
	/**
	 * initializeConfiguration
	 * 
	 * @param object poConfig User defined config params
	 * @param object poLoginParams User defined login params
	 */
	initializeConfiguration : function (poConfig, poLoginParams) {
		
		// Put the users configuration into our objects when we have a value
		if (poConfig.applicationName) {
			this._sApplicationName = poConfig.applicationName;
		}
		if (poConfig.enabledProviders) {
			this._aEnabledProviders = poConfig.enabledProviders.split(',');
		} else {
			this._aEnabledProviders = this._aEnabledProviders.split(',');
		}
		
		// Loop through the enabled providers
		for (var i = 0; i < this._aEnabledProviders.length; i ++) {
			
			// Retreive the providers usage string from the provider name
			var sProviderUsage = this._aEnabledProviders[i].replace(/^.*\[(.*)\]$/g, "$1");
			
			// Remove the providers usage from the provider name
			var sProviderName = this._aEnabledProviders[i].replace(/^(.*)\[.*\]$/g, "$1");
			
			// Check if we have a provider usage string
			if (sProviderUsage != sProviderName) {
				
				// Add the providers usage string to the enabled providers usage array
				this._aEnabledProvidersUsage[i] = this._aEnabledProviders[i].replace(/^.*\[(.*)\]$/g, "$1").replace(';', ',');
			} else {
				
				// No providers usage string configured, use blank
				this._aEnabledProvidersUsage[i] = '';
			}
			
			// Remove the providers usage string from the provider name
			this._aEnabledProviders[i] = sProviderName;
		}
		
		if (poConfig.buttonSize) {
			this._sButtonSize = poConfig.buttonSize;
		}
		if (poConfig.facebookLoginStatus) {
			this._oFacebookLoginStatus = poConfig.facebookLoginStatus;
		}
		if (poConfig.tokenURL) {
			this._sTokenURL = poConfig.tokenURL;
		}
		if (poConfig.tokenFrame == 'parent' || poConfig.tokenFrame == 'popup') {
			this._sTokenFrame = poConfig.tokenFrame;
		}
		if (document.getElementById(poLoginParams.containerID)) {
			this._oContainer = document.getElementById(poLoginParams.containerID);
		}
		if (poLoginParams.loginButtonText) {
			this._sLoginButtonText = poLoginParams.loginButtonText;
		}
		
		return;
	},
	
	/**
	 * openCenteredPopup
	 * 
	 * @param string psPopupURL
	 * @param string psPopupName
	 * @param integer piPopupWidth
	 * @param integer piPopupHeight
	 */
	openCenteredPopup : function (psPopupURL, psPopupName, piPopupWidth, piPopupHeight) {
		
		// Set popup dimensions
		var left = (screen.width / 2) - (piPopupWidth / 2);
		var top = (screen.height / 2) - (piPopupHeight / 2);
		var targetWin = window.open (
			psPopupURL, 
			psPopupName, 
			'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + piPopupWidth + ', height=' + piPopupHeight + ', top=' + top + ', left=' + left
		);
	},

	/**
	 * providerObject
	 * 
	 * @param string psProviderName
	 * @param string psProviderNameFormatted
	 * @param integer piPopupHeight
	 * @param integer piPopupWidth
	 */
	providerObject : function(psProviderName, psProviderNameFormatted, piPopupHeight, piPopupWidth) {
		
		// Set the provider properties
		this.providerName = psProviderName;
		this.providerNameFormatted = psProviderNameFormatted;
		this.popupHeight = piPopupHeight;
		this.popupWidth = piPopupWidth;
		
		this.toString = function() {
			return this.providerName;
		};
	},

	/**
	 * getProviderByName
	 * 
	 * @param string psPoviderName
	 */
	getProviderByName : function(psPoviderName) {
		
		// Loop through all the providers
		for (var i = 0; i < kgnconnect.global.aProviders.length; i++) {
			
			// Check if the provider names match
			if (kgnconnect.global.aProviders[i].providerName == psPoviderName) {
				
				// Return the matched object
				return kgnconnect.global.aProviders[i];
			}
		}
	},

	/**
	 * getCookie
	 * 
	 * @param string psCookieName
	 */
	getCookie : function (psCookieName) {
		
		// Cookies wil not be read correctly when this file is hosted on a location other that kgnconnect, 
		// try Xd communication?
		var i,x,y,aCookies=document.cookie.split(";");
		for (i=0;i<aCookies.length;i++) {
			x=aCookies[i].substr(0,aCookies[i].indexOf("="));
			y=aCookies[i].substr(aCookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==psCookieName) {
				return decodeURIComponent(y);
			}
		}
	}, 
	
	/**
	 * XD
	 */
	XD : function () {

	    var interval_id,
	    last_hash,
	    cache_bust = 1,
	    attached_callback,
	    window = this;
	    
	    return {
	        postMessage : function(message, target_url, target) {
	            
	            if (!target_url) {
	                return; 
	            }
	    
	            target = target || parent;  // default to parent
	    
	            if (window.postMessage) {
	                // the browser supports window.postMessage, so call it with a targetOrigin
	                // set appropriately, based on the target_url parameter.
	                target.postMessage(message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1'));

	            } else if (target_url) {
	                // the browser does not support window.postMessage, so set the location
	                // of the target to target_url#message. A bit ugly, but it works! A cache
	                // bust parameter is added to ensure that repeat messages trigger the callback.
	                //target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date()) + (cache_bust++) + '&' + message;
	            }
	        },
	  
	        receiveMessage : function(callback, source_origin) {
	            
	            // browser supports window.postMessage
	            if (window.postMessage) {
	                // bind the callback to the actual event associated with window.postMessage
	                if (callback) {
	                    attached_callback = function(e) {
	                        if ((typeof source_origin === 'string' && e.origin !== source_origin) || (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) !== 1)) {
	                            return !1;
	                        }
	                        callback(e);
	                    };
	                }
	                if (window.addEventListener) {
	                    window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
	                } else {
	                    window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
	                }
	            } else {
	                // a polling loop is started & callback is called whenever the location.hash changes
	                interval_id && clearInterval(interval_id);
	                interval_id = null;

	                if (callback) {
	                    interval_id = setInterval(function(){
	                        var hash = document.location.hash,
	                        re = /^#?\d+&/;
	                        if (hash !== last_hash && re.test(hash)) {
	                            last_hash = hash;
	                            callback({data: hash.replace(re, '')});
	                        }
	                    }, 100);
	                }
	            }   
	        }
	    };
	}()
};

/**
 * Login object
 */
kgnconnect.login = {
		
	/**
	 * showUI
	 * 
	 * @param object poConfig 
	 * @param object poLoginParams
	 */
	showButton : function(poConfig, poLoginParams) {
		
		// Initialize the configuration parameters, 
		// parameters will be accessible after this by kgnconnect.global.*
		if (poConfig && poLoginParams) {
			kgnconnect.global.initializeConfiguration(
				poConfig, 
				poLoginParams
			);
		}

		// Get login status (background process)
		kgnconnect.login.getLoginStatus();

		// Check if we have the last logged in provider name, 
		// we use this as the highest prio for the first provider.
		// Try to retrieve the the last logged in provider name
		var sProviderName = this.getLastProvider();
		
		// Check if we have the facebook object available, and that we want to check for the logged in user, and havn't received the 
		// last logged in provider name, the object is made available by the background process for facebook
		if (typeof FB == 'object' && kgnconnect.global._oFacebookLoginStatus && kgnconnect.global._oFacebookLoginStatus.checkUserLoggedIn === true && (typeof sProviderName == 'undefined' || sProviderName == 'undefined')) {
			
			// We have the object available, and there is no last logged in provider name available,
			// we can check the loginstatus of the user
			FB.getLoginStatus(function(response) {
				if (response.status != 'unknown') {
					
					// The user is logged in, 
					// we set the provider name for facebook
					sProviderName = 'facebook';
				}
			});
		}
		
		// Check if we have a provider name and if that name is configured in the enabled providers
		if (typeof sProviderName == 'string' && kgnconnect.global._aEnabledProviders.indexOf(sProviderName) != -1) {
			// Valid provider name
		} else if (kgnconnect.global._aEnabledProviders.length > 0) {  // We don't have a last logged in provider name,
			// check if user set enabled providers, when true use first occurance as provider name
			sProviderName = kgnconnect.global._aEnabledProviders[0];
		}
		
		// We should now have a last logged in provider name of the first occurance of the enabled providers, 
		// check if we can find a valid provider object
		var oProvider = kgnconnect.global.getProviderByName(sProviderName);
		if (typeof oProvider != 'object') {
			
			// Not a valid object, 
			// todo: Error handling
			return;
		}

		// If the parser comes here we have a valid provider name which we should use as first login provider, 
		// create the login button element
		var oButton = this.createButtonElement(oProvider);
		
		// Removing the childs from the container div before adding the button to it
		while (kgnconnect.global._oContainer.hasChildNodes()) {
			kgnconnect.global._oContainer.removeChild(kgnconnect.global._oContainer.firstChild);
		}
		
		// Insert the button into the container div
		kgnconnect.global._oContainer.appendChild(oButton);
		
		// Create the onClick function for the button
		this.createButtonOnClick(oButton.id, oProvider);
		
		// Check if we have used the last logged in provider name as provider, 
		// if not than we check at facebook if the user is logged in there.
		// We give a higher prioritization to the last logged in provider
		if (this.getLastProvider() != sProviderName) {
			
			// Check when we don't have facebook as provider if it is enabled in the provider list and if so 
			// start a background process to see if the user is logged in at facebook
			if (typeof FB != 'object' && kgnconnect.global._oFacebookLoginStatus && kgnconnect.global._oFacebookLoginStatus.checkUserLoggedIn === true && sProviderName != 'facebook' && kgnconnect.global._aEnabledProviders.indexOf('facebook') != -1) {
				FBSDK.load();
			}	
		}
	},
	
	/**
	 * showOverlay
	 */
	showOverlay : function () {

		// Check if we don't already have a container available for the more providers
		if (document.getElementById('kgnconnect_overlay') === null) {

			// We don't have a container available.
			// Create the container div for the overlay
			var div = document.createElement('div');
			div.id = 'kgnconnect_overlay';
			
			// Write the child divs needed
			div.innerHTML = [
				'	<div class="kgnconnect_overlay_blackout">',
				'	</div>',
				'	<div class="kgnconnect_overlay_centered">',
				'		<div class="kgnconnect_overlay_background">',
				'			<div id="kgnconnect_overlay_content">',
				'				<h1>',
				'					Sign in using your account with',
				'				</h1>',
				'			</div>',
				'		</div>',
				'		<img class="kgnconnect_overlay_close" alt="close" src="http://cdn.rpxnow.com/images/close.png/94726c11718cedfae4b35ca5dfcf8971.png" onClick="document.getElementById(\'kgnconnect_overlay\').style.display = \'none\';">',
				'	</div>'
			].join('');
			
			// Append elements as first element in the body
			document.body.insertBefore(div, document.body.firstChild);
			
			// Add the configured provider buttons to the page
			this.addProviderButtons();
		} else {
			
			// We already have a container available, 
			// we only need to make it visible now
			document.getElementById('kgnconnect_overlay').style.display = 'block';
		}
	},

	/**
	 * createButtonElement
	 * 
	 * @param object poProvider
	 */
	createButtonElement : function (poProvider) {
		
		// Create the button element, 
		// start with the href
		var href = document.createElement('a');
		href.id = new Date().getTime() + '_' + poProvider.providerName;
		href.className = 'kgn_button kgn_' + poProvider.providerName;
		
		// Create a span for inside the href
		var span = document.createElement('span');
		
		// Check with size login button we should use
		if (kgnconnect.global._sButtonSize == 'small') {
			
			// Show text for small login button
			span.innerHTML = 'Login';
		} else {
			
			// Show text for normal login button
			//span.innerHTML = 'Login met ' + poProvider.providerNameFormatted;
			span.innerHTML = kgnconnect.global._sLoginButtonText.replace('%providerNameFormatted%', poProvider.providerNameFormatted);
		}
		
		// Insert the span into the href element
		href.appendChild(span);
		
		// Return the element
		return href;
	},
		
	/**
	 * createButtonOnClick
	 * 
	 * @param integer piElementId
	 * @param object poProvider
	 */
	createButtonOnClick : function (piElementId, poProvider) {
		
		// Add an onclick event to this href (crossbrowser method)
		document.getElementById(piElementId).onclick = function () {
			
			// Open the provider authorization page in a centered popup
			kgnconnect.global.openCenteredPopup(
					kgnconnect.global.configuration.sSiteRoot.replace('http://', 'http://' + kgnconnect.global._sApplicationName + '.') + '/api/' + poProvider.providerName + '/authorize.php?token_url=' + kgnconnect.global._sTokenURL + '&token_frame=' + kgnconnect.global._sTokenFrame, // URL
					poProvider.providerNameFormatted, // Name
					poProvider.popupWidth, // Width
					poProvider.popupHeight // Height
				);
			return false;
		};
	},
	
	/**
	 * addProviderButtons
	 */
	addProviderButtons : function () {
	
		// Create the start element for the ul listing
		var ulProviderButton = document.createElement('ul');
		ulProviderButton.className = 'kgnconnect_providers';
		
		// Loop through the enabled providers
		for (var i = 0; i < kgnconnect.global._aEnabledProviders.length; i ++) {
			
			// Check if the provider name is not empty
			if (kgnconnect.global._aEnabledProviders[i] != '') {
			
				// Get the provider object for this provider
				var oProvider = kgnconnect.global.getProviderByName(kgnconnect.global._aEnabledProviders[i]);
				
				// Create the li element
				var liProviderButton = document.createElement('li');
				liProviderButton.id = 'kgnconnect_' + oProvider.providerName;
				liProviderButton.className = 'kgnconnect_provider_button';
				liProviderButton.innerHTML = '<strong><a href="#" onClick="return false;">' + oProvider.providerName + '</a></strong>'; // For testing purposes only, 
				// the li element should be styled with css
			
				// Append li to the ul list
				ulProviderButton.appendChild(liProviderButton);
			}
		}

		// Add the ul listing with all it's elements to the container div
		document.getElementById('kgnconnect_overlay_content').appendChild(ulProviderButton);
		
		// Get all li ellements
		var aElements = document.getElementsByTagName('li');
		
		// Loop through the elements
		for (i = 0; i < aElements.length; i++) {

			// Check if the class name is kgnconnect
			if (aElements[i].className == 'kgnconnect_provider_button') {

				// The class name is provider_button, 
				// we create the onClick for this button
				kgnconnect.login.createButtonOnClick(
					aElements[i].id, 
					kgnconnect.global.getProviderByName(aElements[i].id.replace('kgnconnect_', ''))
				);
			}
		}
	},
	
	/**
	 * getProviders
	 * 
	 * @param user defined callback function
	 */
	getProviders : function (callback) {
		
		var aProviders = [];
		aProviders.providers = [];
		
		// Loop through the enabled providers
		for (var i = 0; i < kgnconnect.global._aEnabledProviders.length; i ++) {
			
			// Check if the provider name is not empty
			if (kgnconnect.global._aEnabledProviders[i] != '') {
			
				// Get the provider object for this provider
				var oProvider = kgnconnect.global.getProviderByName(kgnconnect.global._aEnabledProviders[i]);
				
				// Push provider object into the providers array
				aProviders.providers.push({
					providerURL : kgnconnect.global.configuration.sSiteRoot.replace('http://', 'http://' + kgnconnect.global._sApplicationName + '.') + '/api/' + oProvider.providerName + '/authorize.php?token_url=' + kgnconnect.global._sTokenURL + '&token_frame=' + kgnconnect.global._sTokenFrame,
					providerName : oProvider.providerName,
					providerNameFormatted : oProvider.providerNameFormatted,
					popupHeight : oProvider.popupHeight,
					popupWidth : oProvider.popupWidth, 
					providerUsage : kgnconnect.global._aEnabledProvidersUsage[i],
					providerButtonElement : this.createButtonElement(oProvider)
				});
			}
		}

		// Check if we have a user defined callback function
		if (callback) {

			// Execute user defined callback function
			callback(aProviders);
		}
	},
		
	/**
	 * getLoginStatus
	 * 
	 * @param user defined callback function
	 */
	getLoginStatus : function (callback) {
		
		var i,x,y;
		var aLoginStatus = [];
		aLoginStatus.status = [];

		// Check if the xdframe hasn't been written yet
		if (document.getElementById('kgnconnect_xdframe') === null) {

			// To get the cookie information from the kgnconnect server we need to us a Xd receiver.
			// Create the XD iframe element
			var XDframe = document.createElement('iframe');
			XDframe.id = 'kgnconnect_xdframe';
			XDframe.width = '1';
			XDframe.height = '1';
			XDframe.style.display = 'none';
			
			// Pass the URL of the current parent page to the iframe using location.hash
			XDframe.src = kgnconnect.global.configuration.sSiteRoot + '/api/get_login_status.php#' + encodeURIComponent(document.location.href);
			document.getElementsByTagName('body')[0].appendChild(XDframe);
		}
		
		// Check if we don't already have the login status
		if (typeof kgnconnect.global._oLoginStatus.expectedUser !== 'string' && typeof kgnconnect.global._oLoginStatus.expectedProvider !== 'string') {
			
			// Setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
			// event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
			kgnconnect.global.XD.receiveMessage(function(message){
			
				// Split message
				var aLoginStatus = message.data.split('&');
				
				// Loop trough elements of the message
				aLoginStatus = message.data.split(";");
				for (i=0;i<aLoginStatus.length;i++) {
					x=aLoginStatus[i].substr(0,aLoginStatus[i].indexOf("="));
					y=aLoginStatus[i].substr(aLoginStatus[i].indexOf("=")+1);
					x=x.replace(/^\s+|\s+$/g,"");
					
					// Put key and value in the login status object
					kgnconnect.global._oLoginStatus[x] = decodeURIComponent(y);
				}
				
				// Show button
				kgnconnect.login.showButton(null, null);
				
				// Check if we have a user defined callback function
				if (callback) {
					
					// Execute user defined callback function
					callback(kgnconnect.global._oLoginStatus);
				}
		    }, kgnconnect.global.configuration.sSiteRoot);
		} else {
			
			// We already have the login status, we don't have to send a new request.
			// Check if we have a user defined callback function
			if (callback) {
				
				// Execute user defined callback function
				callback(kgnconnect.global._oLoginStatus);
			}
		}
	},
	
	/**
	 * getLastProvider
	 */
	getLastProvider : function () {
		
		// Check if we have a string, 
		// when true return the provider name
		if (typeof kgnconnect.global._oLoginStatus.expectedProvider == 'string') {
			return kgnconnect.global._oLoginStatus.expectedProvider;
		}
	}
};

/**
 * Facebook SDK
 */
var FBSDK = {
		
	/**
	 * Load Facebook SDK
	 */
	load : function () {
		
		var divFbRoot = document.createElement('div');
		divFbRoot.id = 'fb-root';
		document.getElementsByTagName('body')[0].appendChild(divFbRoot);
		
		var FbScript = document.createElement('script');
		FbScript.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		FbScript.async = true;
		document.getElementsByTagName('body')[0].appendChild(FbScript);
		
		/**
		 * Facebook init
		 */
		window.fbAsyncInit = function() {
			var oInit = {
				appId : kgnconnect.global._oFacebookLoginStatus.appId, // This appId should be replaced with the id from the user corresponding with domain which implements this javascript
				status :true,
				cookie :true,
				xfbml :true
			};
			FB.init(oInit);
			
			FB.getLoginStatus(function(response) {
				if (response.status != 'unknown') {
					kgnconnect.login.showButton(null, null);
				}
			});
		};
	}
};

/**
 * showOverlayClick
 * This functions has been made so we don't have to make this function in a loop
 */
function showOverlayClick() {
	return function () {

		// Show more providers
		kgnconnect.login.showOverlay();
		return false;
	};
}

/**
 * window.onload
 */
window.onload = function () {
	
	var aElements = [];
	
	// This function will be executed when everything else is loaded.
	// Get all a ellements
	aElements = document.getElementsByTagName('a');
	
	// Loop through the elements
	for (var i = 0; i < aElements.length; i++) {
		
		// Check if the class name is kgnconnect
		if (aElements[i].className == 'kgnconnect') {
			
			// The class name is concept x, 
			// we add an onclick event to this href (crossbrowser method)
			aElements[i].onclick = showOverlayClick();
		}
	}
};

/**
 * aProviders
 */
kgnconnect.global.aProviders = [
	new kgnconnect.global.providerObject(
		'facebook', // Provider name
		'Facebook', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'hyves', // Provider name
		'Hyves', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'myopenid', // Provider name
		'MyOpenID', // Prodiver name formatted
		'600', // Popup height
		'970' // Popup width
	),
	new kgnconnect.global.providerObject(
		'linkedin', // Provider name
		'LinkedIn', // Prodiver name formatted
		'205', // Popup height
		'490' // Popup width
	),
	new kgnconnect.global.providerObject(
		'windowslive', // Provider name
		'Windows Live', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'google', // Provider name
		'Google', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'hotmail', // Provider name
		'Hotmail', // Prodiver name formatted
		'620', // Popup height
		'980' // Popup width
	),
	new kgnconnect.global.providerObject(
		'netlog', // Provider name
		'Netlog', // Prodiver name formatted
		'510', // Popup height
		'660' // Popup width
	),
	new kgnconnect.global.providerObject(
		'twitter', // Provider name
		'Twitter', // Prodiver name formatted
		'650', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'aol', // Provider name
		'AOL', // Prodiver name formatted
		'400', // Popup height
		'530' // Popup width
	),
	new kgnconnect.global.providerObject(
		'blogger', // Provider name
		'Blogger', // Prodiver name formatted
		'400', // Popup height
		'760' // Popup width
	),
	new kgnconnect.global.providerObject(
		'flickr', // Provider name
		'Flickr', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'livejournal', // Provider name
		'Livejournal', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'verisign', // Provider name
		'Verisign', // Prodiver name formatted
		'500', // Popup height
		'960' // Popup width
	),
	new kgnconnect.global.providerObject(
		'wordpress', // Provider name
		'Wordpress', // Prodiver name formatted
		'600', // Popup height
		'600' // Popup width
	),
	new kgnconnect.global.providerObject(
		'yahoo', // Provider name
		'Yahoo', // Prodiver name formatted
		'400', // Popup height
		'500' // Popup width
	),
	new kgnconnect.global.providerObject(
		'foursquare', // Provider name
		'Foursquare', // Prodiver name formatted
		'555', // Popup height
		'950' // Popup width
	),
	new kgnconnect.global.providerObject(
		'typepad', // Provider name
		'Typepad', // Prodiver name formatted
		'555', // Popup height
		'845' // Popup width
	)
];
