/**
 * JS_SP Object
 * 
 * @author Bert Pattyn <bert@netlash.com>
 */
if (!JS_SP) { var JS_SP = new Object(); }

/**
 * JS_SP - general
 * 
 * @author Bert Pattyn <bert@netlash.com>
 * @author Dave Lens <dave@netlash.com>
 */
JS_SP.general = {

 	debug: true,


	/**
	 * init - hook the clicks
	 * @return void
	 */
	init: function() {
	 
		JS_SP.general._hookProfileBar();

		JS_SP.general._setExternalFavicons();

		JS_SP.general._hookModalBoxes();
		
		// navigation - last child
		$('#navigation li:last-child').addClass('lastChild');
	
		// navigation - first child
		$('.subNavigation li:first-child').attr('id', 'subNavFirstActive');
		
		// extra navigation - last child
		$('#extraNavigation li:last-child').addClass('lastChild');
	
		// Fix the a/img problem
		$(".content img").each(function() {
			var parentTag = $(this).parent().get(0).tagName;
			if (parentTag == 'A') {
				$(this).parent().addClass('linkedImage');
			};
		});
		
		// prettyphoto lightbox
		if(typeof $("a[rel^='lightbox']").prettyPhoto == 'function') $("a[rel^='lightbox']").prettyPhoto();
		
		// hide search extended
		$('#searchExtended').hide();
		
		// toggle view/hide
		$('.toggle').click(function(e){
			e.preventDefault();
			$($(this).attr('rel')).toggle();
			if($(this).is('.hide')) $(this).hide();
		});
	
		// handle the hiding of text on search focus
		$('#search-autocomplete, #newsletterSignup #email').focus(function(e){
			$(this).val('');
		});		
	},


	/**
	 * _hookLoginInTopBar - hook the login link in the topbar to show/hide the form
	 * @return void
	 */
	_hookProfileBar: function() {

		// "Login" link in topbar : show/hide the tiny form
		$('#activate-topbar-loginform').bind('click', function(evt) {

			// don't jump
			evt.preventDefault();

			// more importantly, don't propagate / stop bubbling upwards as otherwise the last clickhandler below would be invoked to!)
			evt.stopPropagation();

			// show/hide form
			$('#topbar-loginform').toggle();

			// focus input if visible
			if ($('#topbar-loginform').is(':visible')) $('#username').focus();

		});

		// bind click event on the login form, and stop the propagation (to bypasses the next clickhandler)
		$('#topbar-loginform').bind('click', function(evt) {
			evt.stopPropagation();
		});

		// hook click to body
		$(document.body).bind('click', function(evt) {
			// if the form is visible, hide!
			if ($('#topbar-loginform').is(':visible')) $('#topbar-loginform').toggle();
		});

		// ESC key pressed
		$(document.body).bind("keypress", function(evt) {
			if ($('#topbar-loginform').is(':visible') && (evt.keyCode == 27)) $('#topbar-loginform').toggle();
		});

	},


	/**
	 * _setExternalFavicons - attach favicons to external links
	 * @return void
	 */
	_setExternalFavicons: function() {

		$('#external-links-list a[href^="http://"]').each(function() {
			var faviconIMG 	= $('<img width="16" height="16" alt="' + $(this).attr('title') + '" title="' + $(this).attr('title') + '" class="externalLinkImage" />').prependTo($(this));
			var extImg 		= new Image();

			extImg.src 		= $(this).attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1') +'/favicon.ico';

			extImg.onload = function() { faviconIMG.attr('src', extImg.src); }
			extImg.onerror = function() { faviconIMG.attr('src', '/modules/core/layout/images/externalLink.gif'); }
			extImg.onabort = function() { faviconIMG.attr('src', '/modules/core/layout/images/externalLink.gif'); }
		});

	},


	/**
	 * _hookOverlay - add an overlay to the site
	 * @return void
	 */	
	_hookOverlay : function(show) {
		
		if($('#overlay').length == 0) $('#container').prepend('<div id="overlay"></div>');

		// set height
		$('#overlay').height($(document).height());
		$('#overlay').width($(document).width());

		if(show) $('#overlay').show();
		else $('#overlay').hide();
	},

	
	/**
	 * _hookModalBoxes - hook the main events of a modal box
	 * @return void
	 */		
	_hookModalBoxes	: function() {
		
		$('.modal-box-close, .modal-box-close-link').bind('click', function(evt) {
			
			// prevent default
			evt.preventDefault();

			// get id
			var id = $(this).attr('rel');

			// hide box
			$('#' + id).hide();

			// hide overlay
			JS_SP.general._hookOverlay(false);

		});

		$('.modal-box-toggle').bind('click', function(evt) {
			
			// get id
			var id = $(this).attr('rel');

			// show overlay
			JS_SP.general._hookOverlay(true);

			// show box
			$('#' + id).show();

			// break the event
			evt.stopPropagation();
			evt.preventDefault();

			// hook click to box itself, so we can click in it.
			$('#' + id).bind('click', function(evt) {
				evt.stopPropagation();
			});

			$(document.body).bind('click', function(evt) {
				
				$('#' + id).hide();

				// hide overlay
				JS_SP.general._hookOverlay(false);
			});

			// ESC key pressed
			$(document.body).bind("keypress", function(evt) {
				
				if (evt.keyCode == 27) {
					$('#' + id).hide();

					// hide overlay
					JS_SP.general._hookOverlay(false);
				}
			});
		});
	},


	/**
	 * end of object
	 */
	_eoo			: true

},

/**
 * JS_SP - search
 */	
JS_SP.search = {
		 
	url: '/ajax.php?module=theatretexts&action=autocomplete',
	
	init: function() {
 
		$('#search-form').submit(function(evt) {
			evt.preventDefault();
			if($('#search-autocomplete').val() == '') alert('No item found');
			return false;
		});
	
		// select the active module's corresponding option
		$('#search-type option').each(function(){
			if($(this).attr('class') == 'selected') $(this).attr('selected', 'selected');
		});
	
		$('#search-type').bind('change', function(evt) { 
			$('#search-autocomplete').val('');
			var selectedOption = $('#search-type').val();
	
			if(selectedOption == 'texts') JS_SP.search.url = '/ajax.php?module=theatretexts&action=autocomplete';
			if(selectedOption == 'authors') JS_SP.search.url = '/ajax.php?module=authors&action=autocomplete';
			if(selectedOption == 'organisations') JS_SP.search.url = '/ajax.php?module=organisations&action=autocomplete';
			if(selectedOption == 'publications') JS_SP.search.url = '/ajax.php?module=publications&action=autocomplete';
	
			// rebind
			JS_SP.search.bind();
		});
	
		// get current selection 
		var selectedOption = $('#search-type').val();
		
		if(selectedOption == 'theatretexts') JS_SP.search.url = '/ajax.php?module=theatretexts&action=autocomplete';
		if(selectedOption == 'authors') JS_SP.search.url = '/ajax.php?module=authors&action=autocomplete';
		if(selectedOption == 'organisations') JS_SP.search.url = '/ajax.php?module=organisations&action=autocomplete';
		if(selectedOption == 'publications') JS_SP.search.url = '/ajax.php?module=publications&action=autocomplete';
	
		// bind
		JS_SP.search.bind();
	},
	
	
	bind: function() {
		
		if($('#search-autocomplete').length > 0) {
			// unbind previous
			$('#search-autocomplete').unbind();
			
			$('#search-autocomplete').autocomplete(JS_SP.search.url, { 
				matchContains: true, 
				cacheLength: 0, 
				selectFirst: true, 
				delay: 2, 
				minChars: 0, 
				dataType: 'json', 
				maxItemsToShow: 50,
				parse: JS_SP.search.parseAutoComplete
			})
			$('#search-autocomplete').result(JS_SP.search.handleAutoComplete);
		}
	},
	
	parseAutoComplete: function(json) {
		var parsed = [];
		if (json.content.count > 0) {
			for (i in json.content.data) {
				var entryName 	= JS_NETLASH.utils.string.html_entity_decode(json.content.data[i].name);
				var entryUrl	= json.content.data[i].url;
				parsed[parsed.length] = { data: [entryName], value: entryUrl, result: entryName };
			}
		}
		return parsed;
	},
	
	handleAutoComplete : function(event, data, formatted) {
		window.location = formatted.replace('&eacute;', 'e');
	},

	/**
	 * end of object
	 */
	_eoo			: true

}
 

/**
 * Thunderbirds.are.go!
 */
jQuery(function($) {
	JS_SP.general.init();
	
	JS_SP.search.init();
});
