/**
 * @project talenthouse
 * @package th.ui.panels
 * @since   07.05.2009
 *
 *	Handles ajax loaded, DOM cached panels
 * 
 */
		
th.ui.panels = {
		
	ajaxPanelLinkClass: 'thajaxpanellink',
	tabGroupClass: 'tabgroup',
	
	loadedPanels: [],
	initAjaxLinks: function ( ) {


		// Tab group stuff
		$('a.'+th.ui.panels.tabGroupClass).click( function() {
			th.ui.panels.markTabActive(this);
		});
		
		
		// To prevent duplicate bindings; unbind first
		$('a.'+th.ui.panels.ajaxPanelLinkClass).unbind( "click" );
		$('a.'+th.ui.panels.ajaxPanelLinkClass).unbind( "thajaxlink" );
		// bind events
		$('a.'+th.ui.panels.ajaxPanelLinkClass).each(function() {

			$(this).click(function() {
				
				$link = $(this);
				if ( $(this).hasClass('projectitem') ) {
					th.myprofile.leavingWarning.display(function() { $link.trigger('thajaxlink'); } );
				}
				else
				{
					$(this).trigger('thajaxlink');
				}
				
				// Disable href link
				return false;
			});

			$(this).bind('thajaxlink', function() {

				var sourceId = '#'+th.getObjectId(this);
				
				// try to use 'new method' th-href attribs
				var url = $(this).attr('th-href');
				if ( typeof url == 'undefined'  )
				{
					url = $(this).attr('href');
				}
				
				// try to use 'new method' th-target attrib
				var target = $(this).attr('th-target');
				if ( typeof target == 'undefined' )
				{
					target = $(this).attr('target');
				}
				var rel = $(target).attr('rel');
	

				// Load Panel:
				th.ui.panels.load( url, target, $(this).hasClass('reload') );
				
				//scroll
				if ($(this).hasClass('scrollto')){
	    			$.scrollTo(target);
				}
				
				
				return;
			});

		});
		
		$('a.'+th.ui.panels.tabGroupClass).click( function() {
			th.ui.panels.markTabActive(this);
		});
	},
	
	
	load: function( _url , _target , _forceReload , _callback, _scrollto, _showLoadingAnim) 
	{
		var target = _target;
		var url = _url;
		var forceReload = _forceReload;
		var callback = _callback;

		var sAnim = true;
		if (typeof _showLoadingAnim != 'undefined' && _showLoadingAnim === false ) {
			sAnim = false;
		}
		
		// parameter test:
		if ( typeof _target == 'undefined' || _target == '' ) {
			th.log('Target is a required parameter for th.ui.panels.load( _url , _target )');
		}

		try
		{
			// Hide any loading animations or error bubbletips
			$('.bt-wrapper').remove();
			th.ui.loadingAnimation.stop();
			
			// Hide related panels
			th.ui.panels.showDisplayRelatedChildPanels(target);
			
			
			// Check if panel already loaded
			var loaded = false;
			

			// Load panel content
			if ( ( forceReload == true || ( url != '' && th.ui.panels.isPanelLoaded( url , target ) != true )) && target != '')
			{
				if ( sAnim === true ) {
					$(target).html('');
				}
				th.ajax.ajaxLoad(
						url,
						target,
						sAnim,
						function(xhr) {
							// After loading a panel, initialise any ajax links inside it
							th.ui.panels.initAjaxLinks();
							
							// Hide any loading animations or error bubbletips
							$('.bt-wrapper').remove();
							th.ui.loadingAnimation.stop();
							
							// Process autoload
							var t = target;
							th.ui.panels.processAutoLoad(url, t + '');
							
							//scroll
                			if (typeof _scrollto != 'undefined' && _scrollto != false ){
                	    		$.scrollTo(target, 700);
                			}
							
							
							if ( typeof callback == 'function' ) {
								callback();
							}
						}
					);
			}
			else
			{
				// Process autoload just the same
				th.ui.panels.processAutoLoad(url, target + '');
				
				if ( typeof callback == 'function' ) {
					callback();
				}
				
			}
			
			// Load history object (to restore on 'back' click)
			/*
			th.history.store( {
					'data': { 
							'sourceid': sourceId,
							'target': target,
							'url': url,
							'rel': rel
							},
					'callback': function(data) { 
								// Hide related panels
								$('div[rel*=' + data.rel + ']').css('display','none');
								
								$(data.target).css('display','block');
								$(data.target).parents(':hidden').each(function() {
									$('div[rel*=' + data.rel + ']').css('display','none');
									$(this).css('display','block');
								});

								th.ui.panels.markTabActive(data.sourceid);
							}
					});
			*/
		}
		finally
		{
		}
	},

	markTabActive: function( target ) 
	{
		// deactivate links pointing to hidden panels
		$('a.thajaxpanellink:reallyvisible').each(function() {
			
			var t = $(this).attr('th-target');
			if (typeof t == 'undefined' || t == '' ) {
				t = $(this).attr('target');
			}
			
			if ( typeof t != 'undefined' && t != '' ) {

				if ( $('div'+t).is(':hidden') || $('div'+t).parents(':hidden').length > 0 ) {
					$(this).removeClass('active');
				}
			}
		});

		// Mark surrounding tab links as not active
		$('.active', $(target).parents('ul:first')).each(
				function(i, elem) {	
					// Timeouts used because of IE7 performance
					setTimeout( function() { $(elem).removeClass('active'); }, 0);
				}
			);
		
		// Timeouts used because of IE7 performance
		setTimeout( function() { $(target).addClass('active'); }, 0);
		
		return false;
	},
	
	isPanelLoaded: function( url , target ) 
	{
		for ( var i = 0; i < this.loadedPanels.length; i++) 
		{
			if ( this.loadedPanels[i].url == url && this.loadedPanels[i].target == target ) 
			{
				if ( $(this.loadedPanels[i].target).html() != '') {
					return true;
				}
			}
	    };
		
		return false;
	},
	
	markPanelLoaded: function( url , target ) 
	{
		if ($(target).size() > 1) {
			// only cache unique targets
			return;
		}
		
		for ( var i = 0; i < this.loadedPanels.length ; i++) 
		{
			if ( this.loadedPanels[i].target == target ) 
			{
				this.loadedPanels[i].url = url;
			}
	    };

	    this.loadedPanels.push( { 'url': url, 'target': target } );
		
	}
	
};


/**
 * @project talenthouse
 * @package th.ui.panels
 * @since   07.05.2009
 *
 *	AUTOLOADING - for deep links - called after AJAX load
 * 
 */
th.ui.panels.processAutoLoad = function(url, target, pageUrl)
{
	th.ui.panels.showDisplayRelatedChildPanels(target);
	
	// Init auto-click urls
	if (th.ui.panels.processAutoClickUrl(url) != true )
	{
		
		if (target)
		{
			if ( $('.autoload', $(target)).size() > 0 ) 
			{
				$('.autoload:first', $(target)).click();
			}
		} else {
			if ( $('.autoload').size() > 0 ) 
			{
				$('.autoload:first').removeClass('autoload').click();
			}
		}
	}
}



/**
 * @project talenthouse
 * @package th.ui.panels
 * @since   07.05.2009
 *
 * Make related child panels visible; 
 * 
 * e.g. if #pnl_Explore loaded, load #pnl_Explore_submenu
 * 
 */
th.ui.panels.showDisplayRelatedChildPanels = function(target)
{
	if (typeof target != 'string') return;
	if (target == '') return;

	
	
	// Hide related panels
	var rel = $(target).attr('rel');
	
	if (typeof rel != 'undefined') {
		$('div[rel*=' + rel + ']').each(function() {
			
			// Hide Item
			$(this).css('display','none');
			
			var thisId = $(this).attr('id');
			
			// Hide Related 
			$("div,ul").filter(function() { return ($(this).attr('id').match("^"+thisId)); }).each(function() {
				var x = $(this).attr('id');
				$('#'+x).css('display','none');
			});
		
		});
		
	}

	// find all divs in this namespace
	target = target.replace("#", "");
	$("div,ul").filter(function() { return ($(this).attr('id').match("^"+target)); }).each(function() {
		var id = $(this).attr('id');
		$('#'+id).css('display','block');
	});


	return false;
}






/**
 * @project talenthouse
 * @package th.ui.panels
 * @since   07.05.2009
 *
 *	AUTOLOADING - for deep links
 * 
 */
th.ui.panels.processAutoClickUrl = function(url, pageUrl)
{
	if (typeof url == 'undefined' || url == '') {
		return false;
	}
	
	if (url.indexOf('#')) {
		var arrUrl = url.split('#');
		if (typeof arrUrl[1] != 'undefined' && arrUrl[1] != '') {
			arrAutoClick = arrUrl[1].split('-');
			if (typeof arrAutoClick[0] != 'undefined' && arrAutoClick[0] != '') {
				// The target link to click
				var targetId = arrAutoClick[0];

				if (pageUrl) {
					window.location.hash = "#";
				}

				// Remove found target from not-loaded-yet links 
				arrAutoClick.splice(0, 1);

				var newHash = '';
				if (arrAutoClick.join('-') != '') {
					// Create not-loaded-yet links 
					newHash = '#' + arrAutoClick.join('-');

					// Get target click link href
					var href = $('#' + targetId).attr('href');
	
					if (typeof href != 'undefined') {
					
						// Replace any existing hash code with our version:
						var arr_Url = href.split('#');
						href = arr_Url[0] + newHash;
						$('#' + targetId).attr('href', href);
					}
					
				}

				// Click on the new updated link:
				$('#' + targetId).click();

				return true;
			}
		}
	}
	
	return false;
};




