/*
 *
 * main Object zum Aufbau der Seite
 *
 * @author: Nils Dehl		<nils.dehl@dkd.de>
 * @author: Jens Hoffmann	<jens.hoffmann@dkd.de>
 * @author: Dimitri Ebert	<dimitri.ebert@dkd.de>
 *
 */

var mainObj = {
	
	backgroundImg: ['backgroundHolder1', 'backgroundHolder2'],
	
	currentBackgroundHolder: null,
	hiddenBackgroundHolder: null,
	languageID: null,
	
	init: function() {
		// Set the Waiting Cursor while the first Load
		clickMan.waitCursor(true);
		// Remove the focus, if something was click before
		this.clearFocus();
		this.currentBackgroundHolder = 0;
		this.hiddenBackgroundHolder  = 1;
		this.initLanguage();
		var imgFileName = $('backgroundHolder1').getProperty('imgsrc');
		var imgPreloading = new Asset.image('uploads/media/' + imgFileName, {
			onload:	function() {
				mainObj.onPreloadComplete();		
			}
		});
	},
	
	onPreloadComplete: function() {
		var preLoader = $('loading');
		var fadePreOut = new Fx.Styles(preLoader, {duration: 400});
			fadePreOut.start(
				{'opacity': [0,1]}
			).chain(function(){
				// If the Preloader is faded out, switch the DIV off
				preLoader.setStyle('display', 'none');
			});
		// Prepair the Rootline-Menu
		iMenu.cropRootline();
		// Show the content with a short Intro
		this.siteIntro();
		
		if(typeof popup == 'function') {
			popup();
		} 
	},
	
	siteIntro: function() {
		var activeBG = $('backgroundHolder1');
			activeBG.setStyle('visibility', 'visible');
		var bgImage = new Fx.Styles(activeBG, {duration: 1000});
			bgImage.start(
				{'opacity':[0,1]}
			).chain(function(){
				var mainPage = $('page');
					mainPage.setStyle('opacity', '0');
					mainPage.setStyle('visibility', 'visible');
				var contentFade = new Fx.Styles(mainPage, {duration: 1000});
					contentFade.start(
						{'opacity':[0,1]}
					).chain(function(){
						clickMan.waitCursor(false); // Remove the Waiting Cursor after the Intro
					});
			});
	},	

	ajaxURLcreator: function(url, type) {
		var urlStart = "/";
		var	contentTypes = ["ajax_mainmenu","ajax_content","ajax_ctamenu","ajax_bgimage","ajax_headerimage","ajax_rootline","ajax_footermenu"];
		var finalType = type - 101;
	    var finalURL = urlStart + contentTypes[finalType] + urlStart + url;
	    return finalURL;
	},
	
	initLanguage: function() {
		var path = window.location.pathname;
		if ( path.length >= 3 ) {
			var lang = path.substring(1, 3);
			switch ( lang ) {
				case 'de': this.languageID = 0; break;
				case 'en': this.languageID = 1; break;
				case 'es': this.languageID = 3; break;
				default:   this.languageID = 0; break;
			}
		} else {
			// default Language is German
			this.languageID = 0;
		}		
	},

	getPageContent: function(url) {
		
		var c3i = $('col3_innen');
		var c3c = $('col3_content');

		// Whitebox einblenden	
		var whiteBoxDIV = new Element('div', { 'id': 'whitebox' }).inject(c3c,'inside');
		var whiteboxFx = new Fx.Styles(whiteBoxDIV, {
			duration: 350
		}).start(
			{'opacity': [0, 0.35]}
		);

		// Content ausblenden	
		var theContent = new Fx.Styles(c3i, { duration: 350 }).start(
			{'opacity': [1, 0]}
		).chain( 
			function() {				
				
				c3i.setHTML(""); // Clear old Contet
				
			    var ajaxCallType = 102;
	    		var urlTyped = mainObj.ajaxURLcreator(url, ajaxCallType);
				var pageContent = new Ajax(	urlTyped, {
												method: 'get',
												update: c3i,
												evalScripts: 'true',
												onComplete: function(e){
													mainObj.contentParserActions(url);
												}
									      });
				pageContent.request();
				
				// loading the CTA Menu
				iMenu.getCtaMenu(url);

				// refresh Rootline
				iMenu.getRootlineMenu(url);
				
				// refresh Footer Menu
				iMenu.getFooterMenu(url);
				
				// loading the Background Image
				mainObj.changeBackgroundImage(url);
				
				// refesh header Image
				mainObj.changeHeaderImage(url);
	
		});
		
		return false;
		
	},
	
	getPageContentPostRequst: function(url, formuid) {
		
		var c3i = $('col3_innen');
		var c3c = $('col3_content');

		// Whitebox einblenden	
		var whiteBoxDIV = new Element('div', { 'id': 'whitebox' }).inject(c3c,'inside');
		var whiteboxFx = new Fx.Styles(whiteBoxDIV, {
			duration: 350
		}).start(
			{'opacity': [0, 0.35]}
		);

		// Content ausblenden	
		var theContent = new Fx.Styles(c3i, { duration: 350 }).start(
			{'opacity': [1, 0]}
		).chain( 
			function() {	
				// Loading the Content

			    var ajaxCallType = 102;
	    		var urlTyped = mainObj.ajaxURLcreator(url, ajaxCallType);
				var pageContent = new Ajax(	urlTyped, {
												method: 	 'post',
												data:		 $(formuid).toQueryString(), // Formulardaten in URL String umwandeln
												update: 	 c3i,
												evalScripts: 'true',
												onComplete: function(e){
													mainObj.contentParserActions(url);
												}
										  });			
				pageContent.request();
				
				// loading the CTA Menu
				iMenu.getCtaMenu(url);
				
				// refresh Rootline
				iMenu.getRootlineMenu(url);
				
				// refresh Footer Menu
				iMenu.getFooterMenu(url);

				// loading the Background Image
				mainObj.changeBackgroundImage(url);
				
				// refesh header Image
				mainObj.changeHeaderImage(url);
				
		});
		
		return false;
		
	},
	
	contentParserActions: function(url) {
		scrollLayer.init();
		contentEfx.init();								
		utmMan.track(url);
		iMenu.checkMainMenu(url);
	}, 
	
	getPageOutOfRootline: function(url) {
		this.getPageContent(url);
		iMenu.refreshMainMenu(url);
		return false;
	},
	
	contentPreloaderGFX: function ( mode ) {
		var preloaderObj = $('loadingContent');
		switch (mode) {
			case 'on':  preloaderObj.setStyle('display', 'block'); break;
			case 'off': preloaderObj.setStyle('display', 'none');  break;
			default:    preloaderObj.setStyle('display', 'none');  break;
		}
	},
	
	changeBackgroundImage: function(url) {
	
		// backgroundImg: ['backgroundHolder1', 'backgroundHolder2'], ... placed at top ...
	
		var currentBgStyle = $(mainObj.backgroundImg[mainObj.currentBackgroundHolder]).getProperty('imgsrc');
		
		var ajaxCallType = 104;
		var urlTyped = mainObj.ajaxURLcreator(url, ajaxCallType);
		var pageBgImage = new Ajax(	urlTyped, {
								method: 'get',
						 		onComplete: function ( newBgImage ) {
									
									var cropNRafterIMG = /_[0-9]{2}\./;
									
									if ((currentBgStyle.replace(cropNRafterIMG, ".") !== newBgImage.replace(cropNRafterIMG, ".")) && (newBgImage !== "")) {
										
										var imgPreLoading = new Asset.image('uploads/media/' + newBgImage, {
											onload: function() {															
												
												// Store DOM-Objects in Vars.
												var newBG = $(mainObj.backgroundImg[ mainObj.hiddenBackgroundHolder  ]);
												var oldBG = $(mainObj.backgroundImg[ mainObj.currentBackgroundHolder ]);
											    
												newBG.setProperty( 'imgsrc', newBgImage );
												newBG.setStyle( 'background-image', 'url(uploads/media/' + newBgImage + ')' );
												
												// Fix Flash Bug >> Never have two BGs at same time
												newBG.setStyles({ opacity: '0',   display: 'block', zIndex: '12' });
												oldBG.setStyles({ opacity: '100', display: 'block', zIndex: '11' });
												
												var bgFadeEFX = new Fx.Styles(newBG, {
													duration: 1250,
													unit: '%'
												}).start({'opacity': [0,1]}).chain( function(e){
													newBG.setStyle( 'display', 'block' ); // Backup if clicked to fast ...
													oldBG.setStyle( 'display', 'none' ); // Fix Flash Bug by removing the old DIV
												});
												mainObj.hiddenBackgroundHolder  = mainObj.hiddenBackgroundHolder  ? 0 : 1;
												mainObj.currentBackgroundHolder = mainObj.currentBackgroundHolder ? 0 : 1;
												
										    }
										});	
									} 
								}						
							 });
							 
		pageBgImage.request();
		
	},
	
	changeHeaderImage: function(url) {
		
		var headerBGimg = $('nav_main');
		var currentBgStyle = headerBGimg.getProperty('imgsrc');

	    var ajaxCallType = 105;
		var urlTyped = mainObj.ajaxURLcreator(url, ajaxCallType);
		var headerImage = new Ajax(	urlTyped, {
										method: 'get',
										onComplete: function ( newBgImage ) { 
											if ((currentBgStyle !== newBgImage) && (newBgImage !== "")) {
												var imgPreLoading = new Asset.image('/uploads/media/' + newBgImage, {
													onload: function() {
																																								
														 if (window.ie) {
															// Static Header BG Switch
																var imgSRCie = "/uploads/media/" + newBgImage;
															 	var ieBGfake = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSRCie + "', sizingMethod='crop') !important;";
																	headerBGimg.setProperty('imgsrc', newBgImage);
																	headerBGimg.setStyle('background-image', 'none');
																	headerBGimg.setStyle('opacity', '1');
																	headerBGimg.setStyle('filter', ieBGfake);
														} else {
															var imgSRC   = "/uploads/media/" + newBgImage;
															var headerFX = new Fx.Style( headerBGimg, 'opacity', { duration:500	});
															// Fade old header out
																headerFX.start(1,0).chain( function() {
																	headerBGimg.setProperties({
																 		imgsrc: newBgImage,
																		style:  'background-image: url(' + imgSRC + ');'
																	});
																	// Fade new header in after old is out
																		headerBGimg.setStyle('opacity', '0');
																		headerFX.start(0,1); 
																});														 	
														
														}
												    }
												});													
											} 
										}
									 });
		headerImage.request();
	},	
	
	setLanguage: function(language_id, url) {
		this.languageID = language_id;
		
		// refresh Page Content
		this.getPageContent(url);
		iMenu.refreshMainMenu(url);
		this.setBackBTN(url);
	},
	
	buildRealURL: function(url) {
		var baseURL	= $$('base')[0].getProperty('href');
		var newCurl = baseURL + '#' + url;
		return newCurl;
	},

	setBackBTN: function(url) {
		// IF the URL is different than the current one, store it
		if (location.hash.substr(2) !== url) {
			window.hash('/' + url);
		}
	},

	getBackBTN: function() {
		window.addEvent('backbutton', function(event) {
			if (event.type == "backbutton" && event.hash !== "") {
				// Reload all content sections fitting to the BackBTN History status
				clickMan.clickAction('content', event.hash);
			}
		}.bind(this));
	},

	cropDomain: function(url) {
		if ( (url !== null) && (url.search(/http:/) !== -1) ) {
			var indexPos = 0; var cropPos = 0; var foundSlash = 0;
			while (foundSlash == url.indexOf ('/', foundSlash) + 1) {
				indexPos++;
				if (indexPos == 3) {
					cropPos = foundSlash;
					break;
				}
			}
			var cropedTarget = url.substr(cropPos);
			return cropedTarget;
		} else {
			return url;
		}
	},
		
	clearFocus: function() {
		if (!window.ie) {
			document.lostFocusFORM.lostFocusBox.focus();
		}
	},

	clearSelection: function(state) {
		if (state) { // true: Remove Selection
			$$('BODY#body').addEvent('onselectstart', function(){
				return false;
			});
		} 
	},
	
	cssPreloader: function() {

		this.assetLoader('css','/fileadmin/hss/css/js_hacks/jspreloader.css');
		this.assetLoader('css','/fileadmin/hss/css/js_hacks/modFallbackFix.css');
		
		var userOS = "";
		if (window.navigator.userAgent.indexOf("Windows") > 0) {
			userOS = "win";
		}
		if (window.navigator.userAgent.indexOf("Macintosh") > 0) {
			userOS = "mac";
		}

		if (window.ie && !window.ie7) {
			this.assetLoader('css', '/fileadmin/hss/css/hacks/iehacks_init.css');
		}
		if (window.ie7) {
			this.assetLoader('css', '/fileadmin/hss/css/hacks/iehacks_init_gt6.css');
		}
		if (window.webkit) {
			this.assetLoader('css', '/fileadmin/hss/css/hacks/hacks_safari.css');
		}
		if (window.gecko && userOS == "win") {
			this.assetLoader('css', '/fileadmin/hss/css/hacks/hacks_ff_pc.css');
		}
		if (window.opera) {
			this.assetLoader('css', '/fileadmin/hss/css/hacks/hacks_opera.css');
		}
		
	},
	
	flashFallbackCheck: function(minVersion) {
		if (deconcept.SWFObjectUtil.getPlayerVersion().major >= minVersion) {
			this.assetLoader('css','/fileadmin/hss/css/js_hacks/hideFallback.css');
		}		
	},

	assetLoader: function(type, file) {
		var asset = "";
		switch (type) {
			case "css": asset = new Asset.css(file);        break;
			case "js":  asset = new Asset.javascript(file); break;
			case "gfx": asset = new Asset.image(file); 	    break;
			default:    console.log("DEV. ERROR: Asset Type not found!"); break;
		}
		return asset;
	},
		
	globalInit: function () {
		this.cssPreloader();
		this.init();
		iMenu.init();
		scrollLayer.init();
		contentEfx.init();
		soundObj.init();
		utmMan.init();
		this.getBackBTN();
		// this.setBackBTN('Startseite');
		this.flashFallbackCheck('7');
	}
	
};


/* *******************************************************************************
* 																				 *
* Loading Process:																 *
* ================																 *
* 																				 *
* 1. Check if there is a Hash Link in the Start URL								 *
* 2. Preload all JS files defined in the Array									 *
* 3. Start the globalInit function												 *
* 4. Load all CSS Stuff															 *
* 5. If all Background GFX are there, fadein the Page							 *
* 																				 *
*********************************************************************************/

	window.addEvent('domready', function() {
		mainObj.globalInit();
	});
	
/* *******************************************************************************
* EOF																			 *
*********************************************************************************/