
var WebSiteMain = new Class({
	
	isDynamic: false,
	navigation: null,
	
	isFlashReady: false,
	
	initialize: function() {
		this.isDynamic = swfobject.hasFlashPlayerVersion("9");
		
		//window.addEvent('load', this.checkHeight.bind(this));
		window.addEvent('resize', this.onResize.bind(this));
		window.addEvent('domready', this.onDOMReady.bind(this));
		window.addEvent('load', this.onLoad.bind(this));
		window.addEvent('load', this.onResize.bind(this));
		
		this.initSWFObject();
	},
	
	initSWFObject: function() {
		if(this.isDynamic) {
			var absRoot = window.webSiteGlobalOptions.absRoot;
			var flashvars = {
				"host": absRoot.substr(0, absRoot.length - 1),
				"environment": "web",
				"assets_path": "/c/swfpub/assets/",
				"use_cache": 0
			};
			var params = {
				"menu": "false",
				"scale": "noscale",
				"salign": "tl",
				"wmode": "window",
				"swliveconnect": "true",
				"allowfullscreen": "true",
				"allownetworking":  "all",
				"allowscriptaccess": "always"
			};
			var attributes = { id: "flash" };
			// use_cache=0&host=" + absRoot + "&assets_path=/c/swfpub/assets/
			swfobject.embedSWF(absRoot + "_frontend/swfpub/MatthiasKaercher.swf", "flash", "100%", "100%", "9.0.0", absRoot + "c/lib/swfobject/expressInstall.swf", flashvars, params, attributes);
		
			/*swfobject.addLoadEvent(function() {
				var fl = swfobject.getObjectById("flash");
				if(fl && fl.focus) { try { fl.focus(); } catch(e) { } }
			});*/
		}
	},
	
	// [PUBLIC, IE] flash via external interface tells that it is loaded
	flashReady: function() {
		this.isFlashReady = true;
		this.flash = swfobject.getObjectById("flash");
		this.onResize();
		this.navigation.init();
	},
	
	
	onDOMReady: function() {
		this.contentMgmt = new WebSiteContentMgmt(this.isDynamic);
		this.navigation = new WebSiteNavigation(this.contentMgmt);
	},
	onLoad: function() {
		/*if(!swfobject.hasFlashPlayerVersion("9")) {
			$('flash').set('html', '<div id="info"><p>Lai aplūkotu šo lapu, jums nepieciešama jaunāka <em><a href="http://get.adobe.com/flashplayer/">Adobe Flash plugin</a></em> versija.</p><p><a href="http://get.adobe.com/flashplayer/"><img src="/c/assets/get_adobe_flash_player.png" /></a></div>');
		}*/
	},
	onResize: function() {
		if(this.isFlashReady) {
			var dims = window.getSize();
			//console.debug('resize, ', dims);
			this.flash.updateWindowDims(dims.x, dims.y)
		}
	}

});

var webSite = new WebSiteMain();







var WebSiteContentMgmt = new Class({
	
	isDynamic: false,
	isOpen: false,
	enableScrollUpAfterContentChange: false,
	
	navigation: null,
	
	initialize: function(isDynamic) {
		this.isDynamic = isDynamic;
		this.flashContainer = $('flashContainer');
		this.contentContainer = $('contentContainer');
		
		// turn off the content part if the flash shows up, as ajax will take care about the content
		if(this.isDynamic) 
			this.contentContainer.setStyle('display', 'none');
		else
			this.flashContainer.setStyle('width', '224px');
	},
	
	
	// [PUBLIC] called from navigation after ajax content is loaded into content area
	initLoadedContent: function(html) {
		this.disposeLoadedContent();
		this.contentContainer.set('html', html);
		this.content = $('content');
		this.contentContainer.getElements('a').addEvent('click', this.onContentLinkClick.bind(this));
		
		if(this.enableScrollUpAfterContentChange) {
			new Fx.Scroll(this.contentContainer).toTop();
			this.enableScrollUpAfterContentChange = false;
		} else {
			this.contentContainer.scrollTop = 0;
		}
		
		var galleryBlocks = this.contentContainer.getElements('.galleryBlock');
		if(galleryBlocks) {
			galleryBlocks.addEvent('mouseenter', this.galleryBlockOnOver.bindWithEvent(this));
			galleryBlocks.addEvent('mouseleave', this.galleryBlockOnOut.bindWithEvent(this));
			galleryBlocks.addEvent('click', this.galleryBlockOnClick.bindWithEvent(this));
		}
		
		var galleryImagesList = $('galleryImagesList');
		if(galleryImagesList) {
			galleryImagesList.getElements('a').addEvent('click', this.galleryImageListOnLinkClick.bindWithEvent(this));
		}
		
		this.contactForm = $('contactForm');
		if(this.contactForm) this.contactForm_init();
		
	},
	
	// [PUBLIC] called just before the content area is updated with new ajax content;
	// disposes the content in a way that avoids memory leaks
	disposeLoadedContent: function() {
		//console.debug('dispose content');
		this.contentContainer.getElements('a').removeEvents();
		var galleryBlocks = this.contentContainer.getElements('.galleryBlock');
		if(galleryBlocks) galleryBlocks.removeEvents();
		
		if(this.contactForm) this.contactForm.empty();
		
		this.contentContainer.empty();
	},
	
	
	// [PUBLIC] returns content element which should be updated with ajax content
	getContentAreaContainerElement: function() {
		return this.contentContainer;
	},
	
	// [PUBLIC, EI] adjust the content area
	ei_adjustFlashArea: function(toState, toX, fromState) {
		//console.debug('WebSiteContentMgmt: ei_adjustFlashArea(' + toState + ', ' + toX + ')');
		this.contentContainer.removeClass('normal').removeClass('narrow');
		if(toState == 'wide') {
			this.contentContainer.setStyle('display', 'none');
			this.flashContainer.setStyle('width', '100%');
		} else {
			this.flashContainer.setStyle('width', toX + 'px');
			this.contentContainer.setStyle('display', 'block');
			this.contentContainer.addClass(toState);
			
			//console.debug(toState, fromState, Browser.Engine.gecko && Browser.Platform.win);
			if(Browser.Engine.gecko && Browser.Platform.win && fromState == 'wide') {
				this.ff_resizeFix();
			}
		}
	},
	ei_startFlashAreaAnimation: function(isNewWidthBigger) {
		//console.debug(isNewWidthBigger);
		this.contentContainer.addClass('animating');
		if(isNewWidthBigger) {
			this.disposeLoadedContent();
		}
	},
	ei_stopFlashAreaAnimation: function() {
		this.contentContainer.removeClass('animating');
	},
	
	
	// [PRIVATE] handle click on any link in the content area
	onContentLinkClick: function(event) {
		var target = $(event.target);
		if(target.get('tag') != 'a') target = target.getParent('a');
		var href = target.get('href');
		
		// remove the server address part for IE
		var serverAddress = location.protocol + '//' + location.host;
		if(href.indexOf(serverAddress) == 0) href = href.substr(serverAddress.length);
		
		var anchor;
		if(href.substr(0, 1) == '/' && href.substr(1, 3) != '_fl') { 			// stop the event and navigate to the internal link
			event.stop();
			
			// test if there is a named anchor in the page that corresponds to the href
			var anchorName = (href.substr(1, href.length - 2)).replace(/\//g, '-');
			anchor = this.contentContainer.getElement('a[name="' + anchorName + '"]');
			if(!anchor) this.navigation.go(href);
		}
		
		// if href itself is an anchor pointer...
		if(!anchor && href.substr(0, 1) == '#') {
			event.stop();
			anchor = this.contentContainer.getElement('a[name="' + href.substr(1) + '"]');
		}
		
		// if anchor found, scroll to it.
		if(anchor) {
			var anchorPos = anchor.getPosition(this.contentContainer);
			
			var myFx = new Fx.Scroll(this.contentContainer);
			myFx.start(null, anchorPos.y - 32);
			target.blur();
		}
	},
	
	
	galleryBlockOnOver: function(event) {
		var target = $(event.target);
		if(!target.hasClass('galleryBlock')) target = target.getParent('.galleryBlock');
		target.addClass('galleryBlockHover');
	}, 
	galleryBlockOnOut: function(event) {
		var target = $(event.target);
		if(!target.hasClass('galleryBlock')) target = target.getParent('.galleryBlock');
		target.removeClass('galleryBlockHover');
	},
	galleryBlockOnClick: function(event) {
		var target = $(event.target);
		if(!target.hasClass('galleryBlock')) target = target.getParent('.galleryBlock');
		var href = target.getElement('a.readMore').get('href');
		
		// remove the server address part for IE
		var serverAddress = location.protocol + '//' + location.host;
		if(href.indexOf(serverAddress) == 0) href = href.substr(serverAddress.length);
		
		this.navigation.go(href);
	},
	galleryImageListOnLinkClick: function(event) {
		this.enableScrollUpAfterContentChange = true;
	},


	contactForm_init: function() {
		new Element('input', { 'type' : 'hidden', 'name': 'get', 'value': 'contacts_send' }).inject(this.contactForm);
		new Element('p').adopt(
			new Element('input', { 
				'type' : 'button', 'name': 'contact_submit', 'value': '// senden', 'class': 'contact-submit',
				'events': {
					'click': this.contactForm_onButtonClick.bindWithEvent(this)
				} })
		).inject(this.contactForm);
	},
	contactForm_validate: function() {
		var emailRegEx = /^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-.]+\.)+[A-Za-z]{2,4}$/;
		var name = $('contactsName').get('value').trim();
		var phone = $('contactsPhone').get('value').trim();
		var subject = $('contactsSubject').get('value').trim();
		var email = $('contactsEmail').get('value').trim();
		var text = $('contactsText').get('value').trim();
		if(name && email && subject && text) {
			if(emailRegEx.test(email)) {
				return true;
			} else {
				alert('Bitte überprüfen Sie die Email Adresse!');
				$('contactsEmail').focus();
			}
		} else {
			alert('Bitte füllen Sie die notwendigen Felder aus!');
			if(!text) $('contactsText').focus();
			if(!subject) $('contactsSubject').focus();
			if(!email) $('contactsEmail').focus();
			if(!name) $('contactsName').focus();
		}
		
		return false;
	},
	
	contactForm_onButtonClick: function(event) {
		event.stop();
		
		if(this.contactForm_validate()) {
			new Request({
				url: '/.data/',
				data: this.contactForm,
				method: 'post',
				onComplete: this.contactForm_onSubmitComplete.bind(this)
			}).send();
			this.contactForm.getElements('input').set('disabled', true);
			this.contactForm.getElements('textarea').set('disabled', true);
		}
	},
	contactForm_onSubmitComplete: function(response) {
		if(response == 1) {
			this.contactForm.empty();
			new Element('p').set('html', 'Ihre Nachricht wurde versandt!').inject(this.contactForm);
		} else {
			if(window.console) console.debug(response);
			alert('error!');
			this.contactForm.getElements('input').set('disabled', false);
			this.contactForm.getElements('textarea').set('disabled', false);
		}
		
	},
	
	
	
	// on firefox on PC 
	ff_resizeFix: function() {
		this.flash = swfobject.getObjectById("flash");
		this.flash.style.visibility = "hidden";
		this.ff_resizeFix2.delay(50, this);
	},
	ff_resizeFix2: function() {
		this.flash.style.visibility = "visible";
	}

});







var WebSiteNavigation = new Class({
	
	contentMgmt: null,
	
	initialize: function(cMgmt) {
		this.contentMgmt = cMgmt;
		this.contentMgmt.navigation = this;
		this.request = new Request.HTML({
			async: true,
			update: this.contentMgmt.getContentAreaContainerElement(),
			//onRequest: this.contentMgmt.disposeLoadedContent.bind(this.contentMgmt),	// collect content garbage before updating html
			onComplete: this.onRequestComplete.bind(this)
			
		});
		//this.request.addEvent('complete', this.onRequestSuccess.bind(this));
	},
	
	init: function() {
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.onSWFAddressChange.bind(this));
		var path = SWFAddress.getValue();
		if(path && path != '/') this.requestContent(path);
	},
	
	// [PUBLIC] navigate to the the given internal path
	go: function(path) {
		SWFAddress.setValue(path);
	},
	
	
	// [PRIVATE] starts AJAX request
	requestContent: function(path) {
		//console.debug('WebSiteNavigation: navigate to ', path);
		var absRoot = window.webSiteGlobalOptions.absRoot.substr(0, window.webSiteGlobalOptions.absRoot.length - 1);
		this.request.cancel();
		this.request.post(absRoot + path + '?get=content');
	},
	
	// [PRIVATE] handles SWFAddress "change" event - starts navigation to the internal link
	onSWFAddressChange: function(event) {
		//console.debug(event);
		var path = event.path;
		this.requestContent(path);
	},
	
	// [PRIVATE] request "complete" event handler
	onRequestComplete: function(r1, r2, r3) {
		this.contentMgmt.initLoadedContent(r3);
	}
	
	
});

