/**
 * This script will look for any <a class='panel-popup'> and create an ajax 
 * lightbox when the link is clicked.
 * 
 * The content for the lightbox comes from XML HTTP request. It will append the /format/include
 * parameter to the URL to strip out the barlesque stuff first.
 *
 * @author Matt Haynes <matt.haynes@bbc.co.uk>
 */
glow.ready(function() {

	// Add popup holder to body
	glow.dom.create('<div id="panel-popup-holder"></div>').appendTo(glow.dom.get('body'));
	
	/**
	 * Remove trailing slahs from link
	 * @param {String} link
	 * @return {String}
	 */
	function removeTrailingSlash(link) {
		
		var lastChar = link.substring(link.length - 1, link.length);
		
		if (lastChar == '/') {
			return link.substring(0, link.length -1);
		} else {
			return link;
		}
		
	}
	
	/**
	 * Add lightbox functionality to each link with the panel-popup class
	 */
	glow.dom.get('a.panel-popup').each(function() {

		var me = glow.dom.get(this);
		
		glow.events.addListener(
			me,
			'click',
			function () {
				
				var lnk = removeTrailingSlash(this.attr('href')) + '/include'
				
				// Get content via ajax
				var request = glow.net.get(lnk, {
				  onLoad: function(response) {
					
					var responseHtml = glow.dom.create('<div>' + response.text() + '</div>'),
						holder = glow.dom.get('#panel-popup-holder');
					
					// clear holder contents
					holder.empty();
					
					responseHtml.get('.header h2').addClass('hd').appendTo(holder);
					responseHtml.get('.content').children().appendTo(holder);
					
					var myPanel = new glow.widgets.Panel("#panel-popup-holder",
														  {
														   	width: 540,
														   	height:540,
															theme: "light",
															anim: "fade"
														  });
					myPanel.container.addClass("popup-panel");							  
					myPanel.show();
				  },
				  onError: function(response) {
				  	var errorMsg = '<h1 class="hd">Error</h1><p>'+ response.statusText() +'</p>';
					glow.dom.get('#panel-popup-holder').html(errorMsg);
					var myPanel = new glow.widgets.Panel("#panel-popup-holder", {theme: "light",adim:"fade"});
					myPanel.container.addClass("popup-panel");
					myPanel.show();
				  }
				});
				
				return false;
			},
			me
		);
	
	});

});