/**
 * audi.navigation.js
 * $URL: https://svn.pvtool.org/svn/day_audi_ngw/trunk/ngw_base/frontend/js/audi/audi.navigation.js $
 *
 * @author 		$Author: mguderley $
 * @version     $Revision: 10562 $
 * @copyright   NEUE DIGITALE GmbH, Berlin
 */

audi_ngw.namespace(audi_ngw, 'navigation');
audi_ngw.namespace(audi_ngw, 'navigation.parameters');
audi_ngw.namespace(audi_ngw, 'navigation.container');


audi_ngw.navigation.container.page = 'audi_content_wrapper';
audi_ngw.navigation.currentPagelevel = '';
audi_ngw.navigation.title = audi_ngw.navigation.baseTitle = document.title;
audi_ngw.navigation.activeContext = '';
audi_ngw.navigation.history = '';
audi_ngw.config.version = '$Revision: 10562 $';






audi_ngw.navigation.bindLinks = function () {
	
	jQuery('a').live('click.liveLinks', audi_ngw.navigation.clickedLink);
	
};

audi_ngw.navigation.clickedLink = function (event) {
	

	// DANG-3710: workaround for firefox firing click-live-event for right click on links
	// DANG-3808: if a click-event is triggered by jQuery, there seems to be no event.button defined
	if( event.button && 0 !== event.button ) {
		return true;
	}

	// we store some variables we need later
	var $link = jQuery(event.target);
	if( !$link.attr('href') ) {
		$link = $link.closest('a');
	}	
		
	var	rel = $link.attr('rel'),
		href = $link.attr('href'),
		$linkMeta = $link.metadata();

	// save active context
	audi_ngw.navigation.activeContext = rel;

	// we track every link clicked
	audi_ngw.track.onClick($link); //TRACK
	

	if( 'page' == rel || 'distributor' == rel || 'tabAjax' == rel || 'layerModal' == rel || 'layerModalContent' == rel ) {
		
		// check if this is a valid url, we are allowed to load (false || url)
		if( false === audi_ngw.url.validate(href) ) {

			if( 'page' == rel ) {
				window.location.href = href;
			} else {
				window.open(href, 'external');		
			}

			return false;
		}
		

		// if the clicked tab-link is inside a layer, we change the rel to tabAjaxLayer
		if( 'tabAjax' === rel && 0 < $link.parents('#audi_modal_wrapper').size() ) {
			rel = 'tabAjaxLayer';
		}
		
		audi_ngw.navigation.historyLoad('source=' + href + '&container=' + rel);
		
		return false;
	
	} else if( 'modal_close' === $link.attr('id') ) {
		
		audi_ngw.layer.modal.hide();
		
		// rollback page title on modal close
		audi_ngw.navigation.title = audi_ngw.navigation.baseTitle;
		audi_ngw.navigation.doSetTitle();
		
		return false;
	
	
	} else if( 'confirm' === rel && typeof($linkMeta.confirm) === 'object' ) {
		
		audi_ngw.question.showDialog(jQuery($linkMeta.confirm), {posCallback: function() {
			window.location = href;
			return false;
		}});
		return false;
		

	} else if( 'print' == rel ) {
		audi_ngw.navigation.popup(href, {name: 'funcPrint', maximized: 'true', scrollbars: 'true'});
		return false;
	

	} else if( 'popup' === rel || 'popupOnload' === rel ) {
				
		if( 'undefined' != typeof($linkMeta.popupOnload) ) {
			$linkMeta.redirect = href;
			href = $linkMeta.popupOnload;
		}

		// DANG-3056: socialize-popups should be resizable and ma
		if( 1 == $link.closest('ul.audi_share_services').length ) {
			$linkMeta.resizable = true;
			$linkMeta.scrollbars = true;
		}

		return audi_ngw.navigation.popup(href, $linkMeta);
		


	} else if( 'layerSimple' == rel ) {
		
		audi_ngw.layer.simple.show(event);
		return false;		


	} else if( 'ajaxContentAdvice' == rel ) {
		
		// check if this is a valid url, we are allowed to load (false || url)
		if( false === audi_ngw.url.validate(href) ) {
			window.open(href, 'external');		
			return false;
		}
		
		audi_ngw.layer.modal.loadAjaxContentAdvice(href, $link);
		return false;
	

	} else if( 'tabStatic' == rel ) {
			
		audi_ngw.navigation.tab.handleClick(event);
		return false;
		

	} else if( 'tabAblage' == rel ) {
		
		audi_ngw.myaudi.initMyAudiAblageActive(event);
		return false;
	

	} else if( 'tabForm' == rel ) {

		audi_ngw.myaudi.handleFormChangeLink(event);
		return false;
	
		
	} else if ('myAudiLogout' == rel) {
		
		audi_ngw.myaudi.handleLogoutRequest($link);
		return false;

		
	} else if ($link.hasClass("effizienzSwitch")) {
		// Effizienz Fade

		jQuery("body").append('<div id="effizienzBlende" />');
		jQuery("#effizienzBlende").fadeIn(500, function() { window.location.href = $link.attr("href"); });
		return false;

		
		/* For future use to separate between two parts
		// vdt => brand portal
		if ($("div.vdtTeaserStart").size() > 0) {
			$("#effizienzBlende").fadeIn(500, function() { window.location.href = $link.attr("href"); });
		} else {
		// brand portal => vdt 
			$("#effizienzBlende").fadeIn(500, function() { window.location.href = $link.attr("href"); });
		}
		*/
	}

	return true;
};



audi_ngw.navigation.loadGalleryExtended = function() {

	var url = jQuery(this).val();

	if(  url && true === audi_ngw.url.validate(url) ) {
		var hash = 'source=' + url + '&container=galleryExtended';
		return audi_ngw.navigation.historyLoad(hash);
	}
	
	return true;	
	
};

audi_ngw.navigation.onAjaxModalContentReady = function(event, xhr){

	
	var $scope = jQuery('#' + audi_ngw.url.getContentId());

	
	audi_ngw.navigation.ajaxLoad($scope);
	audi_ngw.controller.callLoadFunctions();
	
	//TODO JavaScript-Steuerung Ã¼ber eine allgemeine body-Klasse
	jQuery('.audi_js').removeClass('audi_js');
	jQuery('ul.func_pagelinks').show();
	
	audi_ngw.navigation.initiateSocialize($scope);
	
	// initialize the gallery
	audi_ngw.gallery.initiate($scope);
		
	// opens an interstitial-link in a modal layer
	jQuery('#audi_content_wrapper a[rel*=popupOnload]', $scope).click();
	
 	// trigger another event 
	audi_ngw.event.trigger('ajaxModalContentPrepared');
	
};


/**
 * Custom Event: wil be fired as soon as we injected the xhr-snippet 
 * @param {Object} event
 * @param {Object} data {sId: new HTML parent Id}
 */
audi_ngw.navigation.onAjaxSnippetReady = function(event, data){
 
	var $scope = jQuery(data.sId);
	
	audi_ngw.navigation.ajaxLoad($scope);
	audi_ngw.controller.callLoadFunctions();
	
	//TODO JavaScript-Steuerung Ã¼ber eine allgemeine body-Klasse
	jQuery('.audi_js').removeClass('audi_js');
	jQuery('ul.func_pagelinks').show();
	
	audi_ngw.navigation.initiateSocialize($scope);
		
	// opens an interstitial-link in a modal layer
	jQuery('#audi_content_wrapper a[rel*=popupOnload]', $scope).click();
	
	
	// trigger event 
	audi_ngw.event.trigger('ajaxSnippetPrepared',[event,data]);
};


/**
 * Wrapper for the load-function of the history-plugin
 * @method historyLoad
 * @public
 * @param {String} hash
 * @return {Void}
 */
audi_ngw.navigation.historyLoad = function(hash) {
	
	if( audi_ngw.animation.accordionPagelevel.getRunning() || audi_ngw.animation.slideDistributor.getRunning() ) {
		return false;
	}
	
	// get new source from hash
	var _sSourceUrl = hash.split('source=')[1].split('&')[0],
		_regexp,
		// construct new url by replacing hash 
		url = (window.location.href.split('#')[0] + '#' + hash);
	
	// check for protocol changes
	if ( (url.indexOf(audi_ngw.config.sHostHTTPS) !== -1 &&  window.location.protocol === 'http:') ) {
		// reload whole page with similar protocols
		_regexp = new RegExp(audi_ngw.config.sHostHTTP,"g");
		window.location.href = url.replace(_regexp,audi_ngw.config.sHostHTTPS);
		// skip history
		return false;
	}
	if ( (url.indexOf(audi_ngw.config.sHostHTTP) !== -1 &&  window.location.protocol === 'https:') ) {
		// reload whole page with similar protocols
		_regexp = new RegExp(audi_ngw.config.sHostHTTPS,"g");
		window.location.href = url.replace(_regexp,audi_ngw.config.sHostHTTP);
		// skip history
		return false;
	} 
 
	hash = hash.replace(/#/, '');
	hash = hash.replace(/container=breadcrumb/, 'container=distributor');

	// DAU-1074
	hash = hash.replace(/\%2F/g, '/');

	// DANG-1712
	var tmp = window.location.href;
	if( -1 == tmp.indexOf('layerModal') ) {
		audi_ngw.navigation.history = '';
	}
	
	// make sure history is initialized DANG-2161
	audi_ngw.controller.initHistory();
	return jQuery.history.load(hash);

};


/**
 * Calls the popup-function when called by audi_ngw.dom.select.initialize()
 * @method loadFromSelect
 * @public
 * @param {Object} event
 * @return {Void}
 */
audi_ngw.navigation.loadFromSelect = function(event) {

	// get the element (we receive the select, not the selected option!!!)
	var $element = jQuery(event.target) || jQuery(event);

	// get the url
	var url = $element.val();
	
	// get the selected option and receive the metadata from it
	var data = $element.find('option[value=' + url + ']').metadata();

	// if it is a popup or a modal layer, call the popup method
	if( 'undefined' !== typeof(data.type) ) {
		switch( data.type ) {
			case 'popup':
				if( true === audi_ngw.url.validate(url) ) {
					return audi_ngw.navigation.popup(url, data);
				}
				break;
			case 'layerModal':

				if( true === audi_ngw.url.validate(url) ) {
					return audi_ngw.layer.modal.showHistory(url);
				}
				break;
		}
	}
	
	
	
	// if we get here, it's no popup and we open the url in this window
	window.location.href = url;
	
	return false;
};


/**
 * Opens a popup with some options, saved as metadata
 * @method popup
 * @public
 * @param {String} url
 * @param {Object} data
 * @return {Void}
 */
audi_ngw.navigation.popup = function(url, data) {

	data.width = ( 'undefined' == typeof(data.width) ) ? 640 : data.width;
	data.height = ( 'undefined' == typeof(data.height) ) ? 480 : data.height;
	data.scrollbars = ( 'undefined' !== typeof(data.scrollbars) && ('true' === data.scrollbars  || true === data.scrollbars) ) ? 'yes' : 'no';
	data.resizable = ( 'undefined' !== typeof(data.resizable) && ('true' === data.resizable  || true === data.resizable || 'yes' === data.resizable) ) ? 'yes' : 'no';
	data.maximized = ( 'undefined' !== typeof(data.maximized) && ('true' === data.maximized  || true === data.maximized) ) ? 'yes' : 'no';
	data.menubar = ( 'undefined' !== typeof(data.menubar) && ('true' === data.menubar  || true === data.menubar) ) ? 'yes' : 'no';
	data.toolbar = ( 'undefined' !== typeof(data.toolbar) && ('true' === data.toolbar  || true === data.toolbar) ) ? 'yes' : 'no';
	
	
	
	// if the popup should be maximized, overwrite the given width/height with the max values
	if( 'yes' === data.maximized ) {
		data.width = screen.availWidth;
		data.height = screen.availHeight;
	}

	var params = 'width=' + data.width + ',height=' + data.height + ',scrollbars=' + data.scrollbars + ',resizable=' + data.resizable + ',menubar=' + data.menubar + ',toolbar=' + data.toolbar;
	

	data.name = data.name || 'audi_' + parseInt(Math.random(), 10);
	var PopupWindow = window.open(url, data.name, params);
	
	if( null !== PopupWindow && 'undefined' !== typeof(data.redirect) && false !== audi_ngw.url.validate(data.redirect) ) {
		window.location.href = data.redirect;
	}
	
	return false;
};



/**
 * handle link-calls from flashmovies
 * @method handleFlashLink
 * @public
 * @param {String} href
 * @return {String} rel 
 * @return {Array} metadata
 */
audi_ngw.handleFlashLink = function(url, rel, metaData){
	
	// popup
	if( 'popup' === rel ) {
		return audi_ngw.navigation.popup(url, metaData);
	}
	
	// check if the url is valid
	if( false === audi_ngw.url.validate(url) ) {
		window.open(url, 'external');
		return false;
	}
	
	// check if there has been a context-switch between http and https
	if( false === audi_ngw.url.validateContext(url) ) {
		return false;
	}
	
	// layerModal/layerModalContent
	if( 'layerModal' !== rel|| 'layerModalContent' !== rel  ) {
		return audi_ngw.layer.modal.showHistory(url);
	}
	
	
	
	
	
	return false;
};


/**
 * handle AJAX-calls from the history-plugin
 * @method handleClick
 * @public
 * @param {String} hash
 * @return {Void}
 */

audi_ngw.navigation.handleClick = function(hash){
	
	var parameterError = false,
		_sUrl,
		$link;
	
	
	// parse the parameters
	try {
		audi_ngw.navigation._parseParameters(hash);
    } catch (e) {
		//There are parameters but they don't have the right format
		parameterError = true;
    }

	// remember the first page
	if( 'undefined' === typeof(audi_ngw.navigation.entryPage) ) {

		audi_ngw.navigation.entryPage = window.location.href;

		if( '' === hash ) {
			return false;
		}

// TODO handle back-button back to first page in ajax-queue (= empty hash && set audi_ngw.navigation.entryPage)
	} else if( '' === hash && 'undefined' !== typeof(audi_ngw.navigation.entryPage) ) {

		audi_ngw.navigation.parameters.source = audi_ngw.navigation.entryPage;

		if( 0 !== jQuery('#audi_nav_distributor').size() ) {
			audi_ngw.navigation.parameters.container = 'distributor';
		} else {
			audi_ngw.navigation.parameters.container = 'page';
		}

	}
		

// TODO when is this code executed?	
	else if( '' === hash || true === parameterError ) {


		audi_ngw.navigation.parameters.source = window.location.href;

		if( 1 == jQuery('#audi_nav_distributor').size() ) {
			audi_ngw.navigation.parameters.container = 'distributor';
		} else {
			audi_ngw.navigation.parameters.container = 'page';
		}
		

	//This must be a normal anchor - let the browser do his thing.
	} else if( '' !== hash && true === parameterError ) {
		return true;
	}

// TODO needed anymore or in audi_ngw.url?
// TODO integrate this into one check-url method-call?
	// reload whole page in case of https / http switch
	if ( (audi_ngw.navigation.parameters.source.indexOf('https:') !== -1 &&  window.location.protocol === 'http:') ) {
		window.location.href = window.location.href.replace(/http:/g,'https:');
		return false;
	}
	if ( (audi_ngw.navigation.parameters.source.indexOf('http:') !== -1 &&  window.location.protocol === 'https:') ) {
		window.location.href = window.location.href.replace(/https:/g,'http:');
		return false;
	}
		
// TODO integrate this into one check-url method-call?
	// check if this is a valid url, we are allowed to load (false || url)
	if( false === audi_ngw.url.validate(audi_ngw.navigation.parameters.source) ) {
		//window.location.href = audi_ngw.navigation.parameters.source;
		window.open(audi_ngw.navigation.parameters.source, 'external');
		
		return false;
	}
// TODO integrate this into one check-url method-call?
	// check if there has been a context-switch between http and https
	if( false === audi_ngw.url.validateContext(audi_ngw.navigation.parameters.source) ) {
		return false;
	}
	

	
	// remove fragment 
	_sUrl = audi_ngw.url.removeAjaxFragment(audi_ngw.navigation.parameters.source);
	
	
// TYPE: page (link needed in dom)
	if( 'page' == audi_ngw.navigation.parameters.container ) {
		
		// save the current pagelevel-navigation-item if we need to roll back in case of an error later
		audi_ngw.navigation.currentPagelevel = jQuery('#audi_nav_pagelevel .current');

		// find the link in the pagelevel or return false
		$link = jQuery('#audi_nav_pagelevel a[href*=' + _sUrl + '], #audi_tab_navigation a[href*=' + _sUrl + '], #audi_navigation_gallery_extended option[value*=' + _sUrl + ']');

		// if there is no link to the url and it is not the url from the first page we return
		if( $link.length === 0 && audi_ngw.navigation.parameters.source !== audi_ngw.navigation.entryPage ) {
			return false;		
		} 
		
		// TODO what is this code doing here?
		// obviously just closing a modal layer, but why!?
		if( audi_ngw.layer.modal.isVisible() ) {
			audi_ngw.layer.modal.hide();
			return false;
		}
		
		audi_ngw.animation.accordionPagelevel.animate($link);
		
		// it is a page, so let's load it
		audi_ngw.navigation.loadPage(audi_ngw.navigation.parameters.source, jQuery("#" + audi_ngw.navigation.container.page));		
		
		return false;


// TYPE: modal layer
	} else if( 'layerModal' == audi_ngw.navigation.parameters.container ) {
		
		audi_ngw.layer.modal.showHistory(audi_ngw.navigation.parameters.source + audi_ngw.navigation.parameters.get);
		return false;


// TYPE: modal layer
	} else if( 'layerModalContent' == audi_ngw.navigation.parameters.container ) {

		audi_ngw.layer.modal.showHistory(audi_ngw.navigation.parameters.source + audi_ngw.navigation.parameters.get);
		return false;


// TYPE: galleryExtended	

	} else if( 'galleryExtended' == audi_ngw.navigation.parameters.container ) {

		audi_ngw.navigation.loadPage(audi_ngw.navigation.parameters.source, jQuery("#audi_gallery_extended_container"), audi_ngw.fragmentGallerySelector);
	


// TYPE: tabAjax (link needed in dom)
	} else if( 'tabAjax' == audi_ngw.navigation.parameters.container ) {

		// find the link
		$link = jQuery('.audi_tab_navigation a[href*=' + _sUrl + ']');
		var $layerLink = jQuery('#audi_modal_wrapper .audi_tab_navigation a[href*=' + _sUrl + ']');
		
		
		if( 0 !== $layerLink.length ) {
	
			$link = $layerLink;
	
		} else {
	
			audi_ngw.layer.modal.hide();
	
		}		
		
		// Link auf der Seite gefunden?
		if ($link.length > 0) {
		
			var id = $link.metadata().tabOptions.sSelectorRelated;
		
			// find out if we are in the context of the gallery_extended
			if( 0 !== jQuery('#audi_navigation_gallery_extended_form').length && 0 !== $link.length ) {
		
				audi_ngw.navigation.tab.linkHandlingAjaxClick($link, id);
		
			// or if the link is inside a layer
			} else if( 0 !== $layerLink.length ) {
						
				audi_ngw.navigation.tab.linkHandlingAjaxClick($link, 'audi_modal_wrapper', id);
		
			// or, last option, the link is in the content-area...just load it
			} else {
		
				audi_ngw.navigation.loadPage(audi_ngw.navigation.parameters.source, jQuery("#" + audi_ngw.navigation.container.page));
		
			}
		
		// Wenn nicht, dann laden...
		} else {
		
			audi_ngw.navigation.loadPage(audi_ngw.navigation.parameters.source, jQuery("#" + audi_ngw.navigation.container.page));
		
		}
		
		
		
		return false;


// TYPE: tabAjaxLayer		
	} else if( 'tabAjaxLayer' == audi_ngw.navigation.parameters.container ) {
		
		// find the link
		$link = jQuery('#audi_modal_wrapper .audi_tab_navigation a[href*=' + _sUrl + ']');

		if( 0 === $link.length ) {

			audi_ngw.layer.modal.showHistory(audi_ngw.navigation.parameters.source + audi_ngw.navigation.parameters.get);

		} else {

			audi_ngw.navigation.tab.linkHandlingAjaxClick($link, 'audi_modal_tab_navigation_container');

		}
		
		return false;


// TYPE: distributor (link needed in dom)
	} else if( 'distributor' == audi_ngw.navigation.parameters.container || 'breadcrumb' == audi_ngw.navigation.parameters.container ) {


		// find the link in the pagelevel or return false
		$link = jQuery('#audi_nav_distributor a[href*=' + audi_ngw.navigation.parameters.source + ']');
	
		if( 'breadcrumb' == audi_ngw.navigation.parameters.container ) {

			if( true === $link.parents('ul').hasClass('first') ) {

				audi_ngw.navigation.parameters.source = audi_ngw.navigation.entryPage;
				$link = jQuery('#audi_nav_distributor a[href*=' +_sUrl + ']');

			} else {

				$link = $link.parents('li').children('a');

			}
		}
		


		
		if( $link.length === 0 && audi_ngw.navigation.entryPage != audi_ngw.navigation.parameters.source ) {
			return false;		
		} 
		
		audi_ngw.layer.modal.hide();

		audi_ngw.animation.slideDistributor.animate($link.get());
		audi_ngw.breadcrumb.update($link);
		
		// it is a page, so let's load it
		audi_ngw.navigation.loadPage(audi_ngw.navigation.parameters.source, jQuery("#" + audi_ngw.navigation.container.page));


// TYPE: unknown		
	} else {
		
		return true;
	
	}
	

	return false;
	
};


/**
 * loads a page
 * @method loadPage
 * @public
 * @param {String} source
 * @return {Void}
 */

audi_ngw.navigation.loadPage = function(source, $scope, fragment, selector){
	
	audi_ngw.navigation._prepareEnvironment($scope);
	
	if( !fragment ) {
		fragment = audi_ngw.fragmentSelector;
	} 
	
	audi_ngw.navigation.lastUrl = source;
	source = audi_ngw.url.addAjaxFragment(source, fragment);
	
	if( !selector ) {
		selector = audi_ngw.navigation.container.page;
	}

	if (selector.indexOf('#') === 0) {
		selector = selector.slice(1);
	}
	
	var _sIdScope = $scope.attr('id');

// TODO write a global ajax-function for all purposes
	jQuery.ajax({		
		url: source + audi_ngw.navigation.parameters.get,
		type: 'GET',
		dataType: "html",
		complete: function(data){	
		
			var _sRes = data.responseText;
			var status = data.status;
			var $scope;
			
			// status can either be 'success' or 'error'
			// xhr.status will give us the http-code (e.g. 404)
			if ('error' != status) {
				
				$scope = jQuery('#'+_sIdScope);
				
				// insert everything below selector 
				// copy of $.load but without replacing all the scripts
				
				// remove all objects/embed nodes by using an apropriate function 
			   // due to related ie bugs on empty() and remove(), whose source is .removeChild on flash-movies
				if (jQuery.browser.msie) {
			       jQuery('object, embed', $scope).each(function(){
						audi_ngw.flash.remove(this);
					});
				}
			
				$scope.html(
					// Create a dummy div to hold the results
					jQuery("<div/>")
						// inject the contents of the document in, removing the scripts
						// to avoid any 'Permission Denied' errors in IE 
						.append(_sRes.replace(/<script(.|\s)*?\/script>/g,''))
						// Locate the specified elements
						.find(" #" + selector +" > *")
				);
				// evaluate all scripts below "selector"
				audi_ngw.navigation.loadScript(_sRes);			
				
				
				
				// current wrapper class name should equal xhr.reponseText's wrapper class name
				jQuery("#audi_content_wrapper")
					.removeClass('template-c-2')
					.removeClass('template-c-3')
					.addClass((_sRes.match(/id=\"audi_content_wrapper\".*?class=\"(.*)\"/) || [''])[1]);
				
				$scope = jQuery('#' + _sIdScope);
				audi_ngw.navigation._restoreEnvironment($scope);
				
				audi_ngw.navigation.setTitle(_sRes);
				 
				
				audi_ngw.navigation.updateSocialize($scope, audi_ngw.navigation.lastUrl);
				
				// if there is a new clicktip teaser, insert it
				var $teaser = $scope.find('.audi_clicktip_teaser');
				if (1 === $teaser.size()) {
					// throw away the old clicktip-teaser
					jQuery('.audi_navigation_sub .audi_clicktip_teaser').remove();
					
					$teaser.insertAfter('#audi_nav_pagelevel');
					audi_ngw.animation.teaserclicktip.prepareContent();
				}
				
				audi_ngw.event.trigger('ajaxSnippetReady', [{
					sId: '#' + selector
				}]);
				
				return false;
				
			}
			else {
			
				audi_ngw.navigation._restoreEnvironment($scope);
				
				
				// roll back page-levelnavigation
				audi_ngw.animation.accordionPagelevel.animate(audi_ngw.navigation.currentPagelevel);
				
				
				return false;
			}

		}

	});
	
	return false;
};



audi_ngw.navigation.updateSocialize = function ($scope, url) {

	var newTitle 		= document.title,
		newShortTitle	= 'Audi ',
		lastPathPos		= newTitle.lastIndexOf('>'),
		$scopeOverlay	= $scope.find('ul.audi_share_overlay'),
		$globalOverlay	= jQuery('div#audi_container_navigation ul.audi_share_overlay');
	
	// Berechnen des Short-Title 
	// => Audi + Title nach dem letzten >
	// oder Title
	if( -1 !== lastPathPos ) {
		newShortTitle = newTitle.substr(lastPathPos);
	} else {
		newShortTitle = newTitle;
	}
	
	// url-kodieren der betreffenden Werte
	newTitle = encodeURI(newTitle);
	newShortTitle = encodeURI(newShortTitle);
	url = encodeURI(url);
	
	// Ersetzen der href der einzelnen Share-Links
	$globalOverlay.find('ul.audi_share_services a').each(function(){
		
		var $link 			= jQuery(this),
			metadata 		= $link.metadata(),
			href			= '';
		
		if( metadata.shareUrl ) {
			href = metadata.shareUrl.replace(/{{url}}/, url);
			href = href.replace(/{{title}}/, newTitle);			
			href = href.replace(/{{short_title}}/, newShortTitle);
			
			$link.attr('href', href);
		}
		
		
		
	});
	
	// Wenn im Contentbereich ein Share-Overlay vorhanden ist
	if( 0 < $scopeOverlay.length ) {
		
		var $sendfriend 		= $scopeOverlay.find('li.sendfriend'),
			$store				= $scopeOverlay.find('li.store');
		
		if( 0 < $sendfriend.length && !$sendfriend.hasClass('audi_share_hide') ) {
			$globalOverlay.find('.audi_share_additional .sendfriend a').attr('href', $sendfriend.find('a').attr('href')).removeClass('audi_share_hide');
		} else {
			$globalOverlay.find('.audi_share_additional .sendfriend a').addClass('audi_share_hide');
		}
		
		if( 0 < $store.length && !$store.hasClass('audi_share_hide') ) {
			$globalOverlay.find('.audi_share_additional .store a').attr('href', $store.find('a').attr('href')).removeClass('audi_share_hide');
		} else {
			$globalOverlay.find('.audi_share_additional .store a').addClass('audi_share_hide');
		}
		
	}
	
	
	
};


audi_ngw.navigation.loadScript = function (data) {
	
	var allScriptsArray = data.match(/<script(.|\s)*?\/script>/g);
	if( !allScriptsArray ) {
		return;
	}


	if (allScriptsArray !== null && allScriptsArray.length) {

		// iterate through all scripts found
		jQuery.each(allScriptsArray, function(){
			
			// use jQuery and the dom to find the src of the script
			var script = this + '',
				scriptSrc = jQuery(script).attr('src');
		
			// if there is no src, this is an inline script and we just append it to the body
			if( !scriptSrc ) {

				jQuery('body').append(jQuery(script));

			} else {

				jQuery.ajax({'url': scriptSrc, 'dataType': 'script', 'cache': true, 'async': false});

			}
		
		});
		
	}

};



audi_ngw.navigation.ajaxLoad = function($scope) {

	jQuery('div.audi_ajax_load', $scope).each(function(){

		var $element = jQuery(this),
			elementData = $element.metadata();
		
		if( 'undefined' != typeof(elementData.url) && true === audi_ngw.url.validate(elementData.url) ) {
			
			$element.removeClass('audi_ajax_load');
			
			elementData.url = audi_ngw.url.getContext(elementData.url);
			
			jQuery.get(elementData.url, null, function(data){
				
				if (jQuery.browser.msie) {
			       jQuery('object, embed', $element).each(function(){
						audi_ngw.flash.remove(this);
					});
				}

				$element.html(data);
				audi_ngw.navigation.updatePage($element.parent());

			});
		
		}
		
	});
};


audi_ngw.navigation.updatePage = function($scope){
	
	// initialize the foldouts
	audi_ngw.animation.simpleAccordion.initialize($scope);
	
	// initialize flash films
	audi_ngw.flash.replaceHeadlines();
	audi_ngw.flash.initiate();
	
	audi_ngw.navigation.ajaxLoad($scope);
	audi_ngw.navigation.loadShopTeaser($scope);
		
	if( 'undefined' != audi_ngw.navigation.windowLoaded ) {
		audi_ngw.flash.initiate();
	}
	
	//TODO JavaScript-Steuerung Ã¼ber eine allgemeine body-Klasse jsEnabled
	jQuery('.audi_js').removeClass('audi_js');
	jQuery('ul.func_pagelinks').show();
	
	// initialize the tabs
	audi_ngw.navigation.tab.initialize({});

	// initialize the gallery
	audi_ngw.gallery.initiate($scope);

	// initialize rounded corners
	audi_ngw.dom.rounded_corners.createOn();
	
	// opens an interstitial-link in a modal layer
	jQuery('#audi_content_wrapper a[rel*=popupOnload]', $scope).click();
	
};


/**
 * Set the title for the html-page after an ajax-load
 * @method setTitle
 * @public
 * @param {String} sHTML
 * @return {Void}
 */
audi_ngw.navigation.setTitle = function(data){

	// set the variable
	var pageTitle = '';

	// search for the title-tag in the ajax-data
	if ('undefined' != typeof(data) && data.indexOf('<title>') !== -1 && data.indexOf('</title>') !== -1) {

		// extract the title from the data
		pageTitle = audi_ngw.html_entidiy_decode(data.split('title>')[1].split('<')[0].replace(/#/g,''));
		
	}

	// if we don't have a title, return
	if( '' === pageTitle ) {
		return true;
	}	
	
	// save the title
	audi_ngw.navigation.title = pageTitle;
	
	// save base title on page context
	if (audi_ngw.navigation.activeContext == 'page')
		audi_ngw.navigation.baseTitle = pageTitle;
	
	// call the function to actually set the title
	return audi_ngw.navigation.doSetTitle();	
};


audi_ngw.navigation.doSetTitle = function() {
	
	// if the saved title is empty, we don't set it
	if( '' === audi_ngw.navigation.title ) {
		return false;
	}
	
	// set the document-title
	document.title = audi_ngw.navigation.title;

	// for ie: set the iframe, too
	var $iframe = jQuery("#jQuery_history");
	if( 0 !== $iframe.size() ) {
		$iframe[0].document.title = audi_ngw.navigation.title;	
		
		// maybe not needed anymore
		window.setTimeout(function(){
			$iframe[0].document.title = audi_ngw.navigation.title;
			document.title = audi_ngw.navigation.title;
		}, 500);
	}
		
	
	return true;
};

/**
 * Splits a parameter string concatenated with '&' and stores it into audi_ngw.navigation.parameters
 * @param {String} hash
 * @throws ParameterException
 */
audi_ngw.navigation._parseParameters = function(hash){

	// reset the parameters variable
	audi_ngw.navigation.parameters = {
		source: '',
		container: '',
		get: ''
	};
	
	// split the hash
    var parts = hash.split('&');

	if( parts.length >= 2 ) {
		
		var newParts = [];
		jQuery(parts).each(function(){
			
			var firstGet = this.split('?');
			if( firstGet.length >= 2 ) {

				newParts.push(firstGet[0]);
				newParts.push(firstGet[1]);      
			} else {
				newParts.push(firstGet[0]);
			}
			
		});

		// go through every part of the hash, split it and save it into the parameters-array
	    jQuery(newParts).each(function(){
	        var keyValueSet = this.split('=');

	        if( keyValueSet.length != 2 ) {
	            throw "ParameterException";
			} else {
	            if( 'source' != keyValueSet[0] && 'container' != keyValueSet[0] ) {
					var tmp = keyValueSet[0] + '=' + keyValueSet[1];
					if( 0 !== audi_ngw.navigation.parameters.get.length ) {
						tmp = audi_ngw.navigation.parameters.get + '&' + tmp;
					} else {
						tmp = '?' + tmp;
					}
					
					audi_ngw.navigation.parameters.get = tmp;
				} else {
					audi_ngw.navigation.parameters[keyValueSet[0]] = keyValueSet[1];
				}
				
			}
	    });

		if( audi_ngw.navigation.parameters.source === '' || audi_ngw.navigation.parameters.container === '' ) {

			throw "ParameterException";		
		}
	}

};


/**
 * Prepares page by hidning unnecessary elements during loading process
 * @method _prepareEnvironment
 * @public
 * @param {Object} $element
 * @return {Void}
 */
audi_ngw.navigation._prepareEnvironment = function ($element) {
	
	jQuery('#audi_container_footer').css('visibility', 'hidden');
    
	// save the height of the content-area so the page does not "hop" during load
	if( jQuery('#audi_content_wrapper').height() ) {
		jQuery('#audi_content_wrapper').css('height', jQuery('#audi_content_wrapper').height() + 'px');
	}
	// set loading on $scope element 
	if ($element) {
		if ($element.outerHeight() === 0) { $element.css({'minHeight':'150px'}); }
		audi_ngw.animation.setLoading({
			sId: audi_ngw.dom.identify($element),
			sCN: 'preload'
		});
	
	}
	// default
	else {
		audi_ngw.animation.setLoading({
			sId: '#audi_content_wrapper',
			sCN: 'preload'
		});
	}


};


/**
 * restores page by displaying unnecessary elements after loading process
 * @method _restoreEnvironment
 * @public
 * @param {Object} $element
 * @return {Void}
 */
audi_ngw.navigation._restoreEnvironment = function ($element) {

	// delete the height for the content area
	jQuery('#audi_content_wrapper').css('height','');
	jQuery('#audi_container_footer').css('visibility', '');
 
    // unset loader 
	// set loading on $scope element 
	if ($element) {
		audi_ngw.animation.unsetLoading($element.attr('id'));
	} 
	
	audi_ngw.animation.unsetLoading('#audi_content_wrapper');


};

audi_ngw.navigation.loadShopTeaser = function ($scope) {
	
	// initiate the variables
	var data;
	
	// use given scope or use body
	$scope = ( 'object' === typeof($scope) ) ? $scope : jQuery('body');
	
	// get the metadata from the teaser
	var teaser = jQuery('div.audi_shop_teaser', $scope);
	if (teaser.length > 0) {
		data = teaser.metadata();	
		// if the url is set, we get the teaser-json
		if( data.url ) {
			data.url = data.url + '?callback=?';
			jQuery.getJSON(data.url, audi_ngw.navigation.showShopTeaser);
		}
	}
};

audi_ngw.navigation.showShopTeaser = function (data, textStatus) {
	
	// find the shop-teaser
	var $shopTeaser = jQuery('div.audi_shop_teaser');
			
	// replace the content
	$shopTeaser.find('h3').text(data.headline).addClass('sIFR');
	$shopTeaser.find('a.audi_shop_teaser_iframe_url').attr('href', data.linkUrl).hide();
	$shopTeaser.find('li > a').text(data.linkText).attr('rel', data.linkRel);
	$shopTeaser.find('div > a').attr('rel', data.linkRel).find('span').text(data.contentText).end().find('img').attr({'src': data.imageUrl, 'alt': data.imageAlt});
	
	// show the teaser
	$shopTeaser.show();
	
	// replace the headline and prepare the links for ajax
	audi_ngw.flash.replaceHeadlines();
	
};

audi_ngw.navigation.initiateSocialize = function ($scope) {
	
	if( !$scope ) {
		$scope = jQuery('body');
	}
	
	jQuery('ul.audi_share, li.audi_share', $scope).hover(function(){
			var $this = jQuery(this);
			if( 1 == $this.parents('ul.toolbox').size() ) {
				var	$overlay = $this.find('ul.audi_share_overlay'),
				top = $overlay.height() + 19;
				$overlay.css('top', '-' + top + 'px');	
			} 
			
			$this.addClass('audi_share_active').find('ul.audi_share_overlay').css('position', 'absolute');
			
		}, function(){
			//jQuery(this).removeClass('audi_share_active');
	});
	
	// DANG-4008: VerzÃ¶gerung des schlieÃŸens von Social layer
	jQuery('ul.audi_share, li.audi_share').mouseleave(function(){
		var audi_share = jQuery(this);
		var timeout = window.setTimeout(function(){
			audi_share.removeClass('audi_share_active');
		}, 500);
	});
	
};



/*
DEPRECATED FUNCTIONS 
*/


/**
 * Prepare all links in the main-container for AJAX-calls, bridges to _doPrepareLink()
 * @method prepareLinks
 * @public
 * @return {Void}
 * @deprecated
 */
audi_ngw.navigation.prepareLinks = function () { return; };

/**
 * Binds click events on a single anchor element
 * @param {jQueryElement} $link
 * @return {Bool}
 */
audi_ngw.navigation.doPrepareLink = function () { return; };
