var Base = new Class({

	options: {},
	initialize: function(){},

	ajaxGroupStackSize: '2',
	activeBrand: 'alex',

	addFormEvents: function (formArray) {
		formArray.forEach(
			function(el) {
				// Add file upload
				var jsLintFrameFU = new IframeFileUpload(el);
				var elHref = el.getProperty('action');
				var baseURL = hashDealer.getBaseUrl();
				// Fix for IE6/7 (If the baseURL is in the Link URL, remove it now)
				if (window.ie) {
					if ((elHref !== null || elHref !== "") && elHref.contains(baseURL)) {
						el.setProperty('action', elHref.replace(baseURL, ""));
					}
				}
				el.addEvent('submit', function(e) {
					var jsLintEvent = new Event(e).stop();
					var url = el.getProperty('action');
					this.getContent(url, el);
				}.bind(this));
		}.bind(this));
	},

	// add Onclick Events to dom elements
	addEventOnClick: function(linkArray){
		linkArray.forEach(
			function(el){
				var elHref = el.getProperty('href');

				var baseURL = hashDealer.getBaseUrl();
				// Fix for IE6/7 (If the baseURL is in the Link URL, remove it now)
				if (window.ie) {
					if ((elHref !== null || elHref !== "") && elHref.contains(baseURL)) {
						el.setProperty('href', elHref.replace(baseURL, ""));
						// reinitialize elHref because href was edit for IE
						elHref = el.getProperty('href');
					}
				}
				if (
					elHref  !== null &&
					elHref  !== "" &&
					elHref !== "standorte/bar-cologne/bar-cologne/" &&
					elHref !== "marken-standorte/bar-cologne/bar-cologne/" && (
						elHref  == baseURL	|| (
							(elHref.search(/www\./)			== -1) &&  // Posible External Link
						    (elHref.search(/http:/)			== -1) &&  // Posible External Link
						    (elHref.search(/#/)				== -1) &&  // Anchor Link
						    (elHref.search(/javascript/)	== -1) &&  // Javascript Link
						    (elHref.search(/mailto/)		== -1) &&  // eMail Link
						    (elHref.search(/\.pdf/)			== -1) &&  // PDF File
						    (elHref.search(/\.avi/)			== -1) &&  // AVI File
						    (elHref.search(/\.flv/)			== -1) &&  // FLV File
						    (elHref.search(/\.swf/)			== -1) &&  // SWF File
						    (elHref.search(/\.mov/)			== -1) &&  // MOV File
						    (elHref.search(/\.mp3/)			== -1) &&  // MP3 File
						    (elHref.search(/\.jpg/)			== -1) &&  // JPG File
						    (elHref.search(/\.gif/)			== -1) &&  // GIF File
						    (elHref.search(/\.png/)			== -1)     // PNG File
						)
					)
				) {
					el.addEvent('click', function(e) {
						e = new Event(e);
							var parentID = el.getParent().getParent().getParent().getProperty('id');
							if (parentID != "menu_main") {
								var url = el.getProperty('href');
								url = (baseURL == url) ? '' : url;
								this.getContent(url);

							}
						e.stop();
					}.bind(this));
				}
			}.bind(this)
		);
	},

	getContent: function(url, form){
		// close submenu

		this.chain( function(){
			this.ajaxPreloaderIcon('on');
			theMain.theMenu.hideSubMenu(theMain.theMenu.activeSubMenu);
			theMain.theClickManager.activate();
			this.contentOutro(par.contentId);
		}.bind(this));

		this.chain( function(){
			if (form) {
				this.replacePostContent( url, par.contentId, par.ajaxTypes.content, form );
			} else {
				this.replaceContent( url, par.contentId, par.ajaxTypes.content );
			}
			this.replaceContent( url, par.rootlineId, par.ajaxTypes.rootline );
			this.checkFurnishing( url );
		}.bind(this));

		this.chain( function(){
			theMain.theClickManager.deactivate();
			this.callChain();
		}.bind(this));

		this.callChain();
	},

	// fetch content via ajax
	// Gallery wird nicht automaisch inizialisiert ... code muss da raus oder so ... daher erstmal wieder evalScripts = true ...
	replaceContent: function (url,elementID,ajaxCallType) {
		var contentObj = $(par.contentId);
		var galleryObj = $ES('.myGallery', contentObj);
			galleryObj.each(function(el){
				var galleryObjID = el.getProperty('id');
				if (this.alexGalleryX && this.galleryObjID!=='') {
					this.alexGalleryX.destroySlideShow($(galleryObjID));
				}

			}.bind(this));



		var urlTyped = this.ajaxURLcreator(url, ajaxCallType);
		var pageContent = new Ajax(	urlTyped, {
				method:      'get',
				update:      elementID,
				evalScripts: false,
				onComplete:  (function(e) {
					this.onCompleteAction(elementID, url, ajaxCallType);
				}.bind(this))
			 });
		pageContent.request();
	},

	replacePostContent: function(url, elementID, ajaxCallType, form){
		var urlTyped = this.ajaxURLcreator(url, ajaxCallType);
		var pageContent = new Ajax(	urlTyped, {
			method:      'post',
			data:        form.toQueryString(), // Formulardaten in URL String umwandeln
			update:      elementID,
			evalScripts: 'true',
			onComplete: (function(e) {
				this.onCompleteAction(elementID, url, ajaxCallType);
			}.bind(this))
		});
		pageContent.request();
		return false;
	},

	// fetch content via ajax
	checkFurnishing: function (url) {
		var urlTyped = this.ajaxURLcreator(url, par.ajaxTypes.furnishing);
		var pageContent = new Ajax(	urlTyped, {
				method: 'get',
				evalScripts: false,
				onComplete: ( function(e) {
					var floorObj = $(par.furnishingId);
					var newFurnishing = pageContent.response.text.clean();
					if (par.furnishing.currentContent !== "") {
						if (newFurnishing != par.furnishing.currentContent) {
							floorObj.empty().setHTML(newFurnishing);
						}
						this.onCompleteAction(par.furnishingId, url, par.ajaxTypes.furnishing);
					}
					par.furnishing.currentContent = newFurnishing;
				}.bind(this) )
			 });
		pageContent.request();
	},

	onCompleteAction: function(elementID, url, ajaxCallType) {

		// Do the magic with the Content-Section
		if (ajaxCallType == par.ajaxTypes.content) {
			// Submit current URL to Google Analytics
			theMain.theUtmMan.trackURL(url);
			// Submit URL to BackBTN
			theMain.theBackBTN.setBackBTN(url);
			// Set new Title
			this.setTitle();
			// Parse Content
			this.contentIdent();
			// Set Brand
			this.setActiveBrand();

			theMain.theFloor.controlAutoHide();
			theMain.theFloor.getTimendEmotions();
			// restyle SiFR-Controlled Elements
			sIFRman.replace();
			// Look for a FLVplayer and load it
			swfObjectLoader.init();
			// Show new Content if everything is done
			this.contentIntro(elementID, ajaxCallType);
			// IE6 sucks with PNG
			theMain.fixPNG();
			// update JS scroller
			theMain.theScroller.update();
			// update JS scroller

			if(autocompleter){
				autocompleter.init();
			}

		}

		// Do the magic with the Floor-Section
		if (ajaxCallType == par.ajaxTypes.furnishing) {
			theMain.theFloor.getTimendEmotions();
			Reflection.addFromClass();
			theMain.fixPNG();
		}

		// Get all Links out of the ContentDIV
		this.addEventOnClick( $ES('a', elementID) );
		// Get all forms out of the ContentDIV
		this.addFormEvents( $ES('form', elementID) );

		// Lower the AJAX Stack
		this.ajaxGroupStackSize = this.ajaxGroupStackSize.toInt() - 1;

		// If all ajax calles are done .. go to next chain block
		if (this.ajaxGroupStackSize === 0) {
			(function(){
				this.ajaxGroupStackSize = '2';
				this.callChain();
			}.bind(this)).delay(100);
		}

	},

	contentIdent: function() {

		var contentObj = $(par.contentId);

		// Check if a eCard is in the content
			var ifEcard = $ES('.eCardLink', contentObj).length > 0 ? true:false;
		// Load Lightbox if eCard is found and Lightbox is not loaded
			if (ifEcard) {
				Lightbox.init( {
					resizeDuration:      500,
					resizeTransition:    Fx.Transitions.sineInOut,
					opacity:             0.6,
					opacityDuration:     500,
					initialWidth:        250,
					initialHeight:       250,
					animateCaption:      1,
					showNumbers:         0,
					defaultIframeWidth:  500,
					defaultIframeHeight: 300,
					iframeScrolling:     'auto',
					enablePrintButton:   0,
					enableSaveButton:    0,
					llPage:              'Seite',
					llOf:                'von',
					psScriptPath:        '/typo3conf/ext/pmkslimbox/savefile.php'
				});
			}
		// Init the IScroller if the Locationfinder was found
			var ifLocatioFinder = $ES('#location-finder', contentObj).length > 0 ? true:false;
			if (ifLocatioFinder) {
				theScroller.init();
			}
		// Remove the Price field in IE if no real Price is in there!
			if (window.ie) {
				var noGoodPrize = $ES('.teaser-box .price', contentObj);
				noGoodPrize.each(function(el){
					if (el.getText().length <= 1) {
						el.setStyle('display','none');
					}
				});
			}

		// Init GoogleMaps if the GoogleMaps was found
			var ifGoogleMaps = $ES('#map_canvas', contentObj).length > 0 ? true:false;
			if ( ifGoogleMaps ) {
				activateGoogleMaps();
			}

		// Init JM Gallery if the ".myGallery" was found
			var galleryObj = $ES('.myGallery', contentObj);
				galleryObj.each(function(el){

// TODO: Dynamic VAR Obj. or something like this ...
					var galleryObjID = el.getProperty('id');
					this.alexGalleryX = new gallery($(galleryObjID), {
						timed:				true,
						delay:				7000,
						showArrows:			true,
						showCarousel:		false,
						textShowCarousel:	'Thumbnails',
						embedLinks:			true,
						lightbox:			true
					});

				}.bind(this));

	},

	contentIntro: function (elementID, ajaxCallType) {
		if (elementID) {
			var efx = new Fx.Style(elementID,'opacity', {duration:1000});
			efx.start(0,1).chain(function(){
				this.ajaxPreloaderIcon('off');
			}.bind(this));
		} else {
			console.error("DEV ERROR :: ElementID is %o of AjaxCallType: %o", elementID ,ajaxCallType);
		}
	},

	contentOutro: function (elementID) {
		var efx = new Fx.Style(elementID,'opacity', {duration:1000});
		efx.start(1,0).chain(function(){
			this.callChain();
		}.bind(this));
	},

	ajaxURLcreator: function(url, type) {

		var finalURL = '/ajax_' + type + '/' + this.cleanURL(url);
		return finalURL;
	},

	cleanURL: function(url) {
		var baseURL = hashDealer.getBaseUrl();

		if (url.substring(0, 1) == '/') {
			url = url.substring(1);
		}

		if (url.test(baseURL)) {
			return url.substr(baseURL.length);
		} else {
			return url;
		}
	},

	ajaxPreloaderIcon: function(mode) {
		var loaderObj = $(par.preloader.contentID);
		switch(mode) {
			case 'on':  loaderObj.setStyle('visibility','visible'); break;
			case 'off': loaderObj.setStyle('visibility','hidden' ); break;
			default:    loaderObj.setStyle('visibility','hidden' ); break;
		}
	},

	setTitle: function() {
		var lastTitle = "";
		$$('#rootlinecontent A').each(function(el){
			lastTitle = el.getText();
		});
		document.title = par.SiteTitle + ": " + lastTitle + " ";
	},

	setActiveBrand: function(){
		currentBrand = $(par.brand).getProperty('class');
		if (this.activeBrand != currentBrand) {
			this.activeBrand = currentBrand;
			this.setLogo();
		}
	},

	setLogo: function(){
		var logo = $(par.logo.id);
		logo.empty();

		var src = '';

		switch(this.activeBrand){
			case 'alex':
				src  = par.logo.path + par.logo.file.alex;
				break;
			case 'alexBrasserie':
				src  = par.logo.path + par.logo.file.alexbrasserie;
				break;
			case 'alexEventLounge':
				src  = par.logo.path + par.logo.file.alexeventlounge;
				break;
			case 'allBarOne':
				src  = par.logo.path + par.logo.file.allbarone;
				break;
			default:
				src = par.logo.path + par.logo.file.alex;
				break;
		}

		/*
		var logoImg = new Element('img', {
    						'src': src,
							'class': 'reflect',
							'alt': par.logo.alt
							});
		*/

		var logoImg = new Asset.image(src, {
									'class': 'reflect',
									'alt': par.logo.alt,
									onload: function(){
										logoImg.injectInside(logo);
										Reflection.addFromClass();
									}
									});
		//logoImg.injectInside(logo);

		//Reflection.addFromClass();


	}

});

Base.implement(new Options());
Base.implement(new Events());
Base.implement(new Chain());
