var App = {
	videoExtensions: ['flv', 'mp4', 'mov'],
	imageExtensions: ['jpg', 'gif', 'png'],
	fileExtensions: ['pdf'],
	baseUrl: location.href.substring(0,location.href.lastIndexOf('/')+1),
	debugging: false,
	marginOffset: 60,
	pageContent: null,
	footerPos: 611,
	pageContentHolder : null,
	pageContentSize: 0,
	contentUrl: null,
	formData: new Hash,
	url404: '404error.html',
	pageShown: false,
	initPage: true,
	pageLoading: false,
	flashVariables : {
		config: '/'+ window.sitelng +'/xml/config.xml',
		startupLocale: 'development',
		startupNavigable: 'passie'
	},	
	flashParameters : {
		wmode: 'transparent',
		allowscriptaccess:'always'
	},	
	flashAttributes : {
		id: 'header'
	},	
	
	boot: function() {
		
		this.pageContent = $('pagecontent');
		this.pageContentHolder = $('pagecontentholder');
		this.setEvents();
		this.setHomeButton();
		this.setDynamicAnchors(this.pageContent);
		this.initStyles();
		this.setFonts();
		this.buildFaq();
		this.footer();
		//this.mouseTest();
		
		swfobject.embedSWF(
			'swf/Preloader.swf',
			'flash',
			'1032',
			'510',
			'9.0.0',
			'swf/expressInstall.swf',
			App.flashVariables,
			App.flashParameters,
			App.flashAttributes
		);
		
		Shadowbox.init({
			skipSetup: true,
			handleOversize: 'drag',
			viewportPadding: 0,
			displayCounter: false,
			onFinish: function(){
				Cufon.set('fontFamily', 'Highlander');
				Cufon.replace('div#sb-title-inner');
				$('sb-title-inner').setStyle('visibility', 'visible');
				App.flashMute(0);
			},
			onClose: function(){
				$('sb-title-inner').setStyle('visibility', 'hidden');
				App.flashUnMute(0);
			}
		});
		
		//this.showInitPage();

	},
	mouseTest: function(){
		window.addEvent('mousemove', function(event){
			var mouseX = event.page.x;
			var mouseY = event.page.y;
			console.log(mouseX+' '+mouseY);
		})
	},
	
	muteUnmute: function(){
		if($chk('audio')){
			var audio = $('audio');
			audio.addEvent('click', function(e){
				if(audio.hasClass('muted')){
					audio.removeClass('muted');
					App.flashUnMute(1);
				}
				else{
					audio.addClass('muted');
					App.flashMute(1);
				}
			});
		}
	},
	
	flashMute: function(forced){
		$(App.flashAttributes.id).mute(forced);
	},
	
	flashUnMute: function(forced){
		$(App.flashAttributes.id).unmute(forced);
	},
	
	setEvents: function(){
		window.addEvent('loadPage', function(){
			var post = new Hash(this.formData);
			var url = this.contentUrl
			post.set('loader', 'ajax');
			var myHTMLRequest = new Request.HTML({
				url:url,
				onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
					// split pagecontent and footer
					items = responseHTML.split('<!-- splitter -->')

					this.initPage = false;
					//set page content
					this.pageContent.set('html', items[0]);
					// set footer and rebuild
					$('footer').set('html', items[1]);
					this.footer();
					this.setFonts();
					this.buildFaq();
					this.setDynamicAnchors(this.pageContent);
					this.showPage(url);
				}.bind(this),
				onFailure: function(xhr){
					if(xhr.status == '404' && this.contentUrl != this.url404){
						this.contentUrl = this.url404;
						window.fireEvent('loadPage');
					}
					else {
						alert('Loading failed:'+xhr.status);
					}
				}.bind(this),
				onException: function(headerName, value){
					alert('Loading failed:'+headerName+'='+value);
				}
			}).post(post);
		}.bindWithEvent(this));	
	},
	
	processFormData: function(form){
		if(!$chk(this.formData)) this.formData = new Hash;
		$each(form.getElements('input:[type="text"], input:[type="hidden"], input:checked, textarea, select'), function(obj){
			var name = obj.get('name');
			var value = obj.get('value');
			this.formData.set(name, value);
		}.bind(this));
	},
	
	footer: function(){
		$each($$('div#footer ul li a'), function(obj){
			obj.addEvent('click', function(e){
				e.stop();
				if($chk(obj.get('href')) && obj.get('href') != ''){
					this.loadContent(obj.get('href'));
				}
			}.bind(this))
		}.bind(this));
	},
	
	setFonts: function(){
		Cufon.set('fontFamily', 'Highlander');
		Cufon.replace('h1');
		Cufon.replace('h2');
		Cufon.replace('div.subnavigation ul li a', { hover: true });
		Cufon.replace('div#footer ul li a', { hover: true });
		Cufon.replace('div.product-overview a.more span', { hover: true });
	},
	
	buildFaq: function(){
		var faq = $$('ul.faq');
		if($chk(faq[0])){
			faq = faq[0];
			faqChildren = faq.getChildren('li')
			$each(faqChildren, function(obj, index){
				var link = obj.getChildren('a')[0];
				var nextObj = faqChildren[index+1];
				var answerHolder = obj.getChildren('div.answer')[0];
				var answer = answerHolder.getChildren('div')[0];
				var answerSize = answer.getSize().y;
				var pageContentHolder = this.pageContentHolder;
				
				answer.setStyles({
					'margin-top' : -answerSize,
					'display' : 'none'
				});
				var animating = false;
				
				link.addEvent('click', function(){
					if(link.hasClass('active')){
						if(animating == false){
							animating = true;
							pageContentHolder.tween('height', pageContentHolder.getStyle('height').toInt() - answerSize - 1);
							this.setFooterPosition(this.footerPos + pageContentHolder.getStyle('height').toInt() - answerSize - 1);
							answer.tween('margin-top', -answerSize);
							var fx = new Fx.Tween(answerHolder);
							fx.start('height', 0).chain(function() {
								if($chk(nextObj)) nextObj.removeClass('helper');
								answer.setStyle('display', 'none');
								link.removeClass('active');
								animating = false;
							}.bind(this));
						}
					}
					else{
						if(animating == false){
							animating = true;
							answer.setStyle('display', 'block');
							answerHolder.tween('height', answerSize);
							answer.tween('margin-top', 0);
							if($chk(nextObj)) nextObj.addClass('helper');
							this.setFooterPosition(this.footerPos + pageContentHolder.getStyle('height').toInt() + answerSize + 1);
							var fx = new Fx.Tween(pageContentHolder);
							fx.start('height', pageContentHolder.getStyle('height').toInt() + answerSize + 1).chain(function() {
								link.addClass('active');
								animating = false;			
							}.bind(this))
						}
					}
				}.bind(this));
			}.bind(this));
		}
	},
	
	initStyles: function(){
		if($chk(this.pageContent) && this.pageContent.getSize().y > 15){
			var contentSize = this.pageContent.getSize().y;
			this.pageContent.setStyles('visibility', 'visible');
			this.pageContentHolder.setStyle('height', contentSize+this.marginOffset);
			this.pageShown = true;
		}
	},
	
	loadContent: function(contentUrl, form){
		if(!App.pageLoading){
			App.pageLoading = true;
			this.contentUrl = contentUrl;
			if($chk(form)) {
				this.processFormData(form);
			}
			if(this.pageShown == true){
				this.hidePage();
			}
			else {
				window.fireEvent('loadPage');
			}
		}
		else{
			return null;
		}
	},
	
	setHomeButton: function(){
		$$('#logo, #home').addEvent('click', function(e){
			e.stop();
			SWFAddress.setValue(this.flashVariables.startupNavigable);
			this.hidePage(true);
		}.bind(this));
	},
	
	hidePage: function(stop){
		this.pageShown = false;
		var contentSize = $('pagecontent').getSize().y;
		this.pageContentHolder.tween('height', 0);
		this.setFooterPosition(this.footerPos);
		var fx = new Fx.Tween(this.pageContent);
		fx.start('margin-top', -contentSize -this.marginOffset).chain(function() {
			this.pageContent.setStyle('visibility', 'visible');
			this.pageContent.empty();
			if(!$chk(stop))window.fireEvent('loadPage');
		}.bind(this));
	},
	
	showPage: function(url){
		this.formData = null;
		this.lastanchor = url.split('#')
		if (this.lastanchor.length > 1) {
		    this.lastanchor = this.lastanchor[this.lastanchor.length-1]
		} else {
		    this.lastanchor = ''
		}
		
		this.pageContent.setStyles({
			'visibility' : 'hidden',
			'margin-top' : (-10000).toInt()
		});
		
		var images = this.pageContent.getElements('img');
		if(images.length > 0){
			$each(images, function(image){
				if($chk(image.get('src')) && image.get('src') != ''){
					var imageSrc = image.get('src');
					image.set('src', '');
					image.addEvent('load', function(){
						image.set('loaded', 'true');
						this.checkPageLoaded();				
					}.bind(this))
					image.addEvent('error', function(){
						image.set('load_error', 'true');
						this.checkPageLoaded();				
					}.bind(this))					
					image.set('src', imageSrc);
				}
				else{
					image.set('load_error', 'true');
					this.checkPageLoaded();
				}
			}.bind(this));
		}
		else this.animatePageIn();
	},
	
	showInitPage: function(){
		if (this.pageContent.get('html').length > 20){
			//there is some content, so animate the page in
			this.showPage();
		}
	},
	
	checkPageLoaded: function(){
		var images = this.pageContent.getElements('img');
		var counter = 0;
		$each(images, function(image){
			if(image.get('loaded') == 'true' || image.get('load_error') == 'true'){
				counter++;
			} 
		}.bind(this));
		if(images.length == counter){
			this.animatePageIn();
		}
	},
	
	animatePageIn: function(){
	    
		var contentSize = this.pageContent.getSize().y;
		this.pageContent.setStyles({
			'visibility' : 'visible',
			'margin-top' : (-contentSize -this.marginOffset).toInt()
		});
		this.pageContentHolder.tween('height', contentSize+this.marginOffset);
		
		this.pageShown = true;
		this.setFooterPosition(this.footerPos + contentSize +this.marginOffset);
		var fx = new Fx.Tween(this.pageContent);
		fx.start('margin-top', 0).chain(function() {
			App.pageLoading = false;
		    if (this.lastanchor.substr(0, 6) == 'open__') {
		        var anchor = this.lastanchor.substr(6)
		        anchor = $$('a[name="'+anchor+'"]')
		        if (anchor.length > 0) {
		            try {
		                anchor.fireEvent('click');
	                } catch (err){}
		            var fxScroll = new Fx.Scroll($(document.body),{duration: 1000}).toElement(anchor[0]);
		        } else {
		            var fxScroll = new Fx.Scroll($(document.body),{duration: 1000}).start(0, 430);
		        }
    	    } else {
    	        var fxScroll = new Fx.Scroll($(document.body),{duration: 1000}).start(0, 430);
    	    }
		}.bind(this));	
	},

	scrollTop: function(){
		App.hidePage(true);
		var fx = new Fx.Tween(this.pageContent);
		fx.start('margin-top', 0).chain(function() {
			var fxScroll = new Fx.Scroll($(document.body),{duration: 1000}).start(0, 0);
		}.bind(this));		
	},
	
	setFooterPosition: function(y){
		$('footer').tween('top', y);
	},
	
	setDynamicAnchors: function(target){
		if(!$chk(target)){
			target = $$('body')[0];
		}
		Shadowbox.clearCache();
		var anchors = target.getElements('a');
		var videoAnchors = new Array();
		var imageAnchors = new Array();
		var fileAnchors = new Array();
		var internalAnchors = new Array();
		var externalAnchors = new Array();
		
	
		$each(anchors, function(anchor){
			if($chk(anchor.get('href'))){
				var href = anchor.get('href')
				var extension = href.split('.');
				if(extension.length > 1) extension = extension.getLast();
				else extension = null;
				
				if(this.videoExtensions.contains(extension)){
					videoAnchors.push(anchor);
				}
				else if(this.imageExtensions.contains(extension) ) {
					imageAnchors.push(anchor);
				}
				else if (this.fileExtensions.contains(extension) ) {
					fileAnchors.push(anchor);
				}
				else{						
					//interal links	
					if(!href.contains('www') && !href.contains('http') && !href.contains('static') && href.split('/').length > 1) {
						internalAnchors.push(anchor);
					}
					else{
						externalAnchors.push(anchor);
					}
				}
			}
		}.bind(this));
				
		$each(videoAnchors, function(anchor){
			this.makeVideoElement(anchor);
			Shadowbox.addCache(anchor, {
				width: 640,
				height: 370,
				gallery: 'gallery'
			});
			anchor.addEvent('click', function(e){
				e.stop();
				Shadowbox.open();
			});
		}.bind(this));
		
		$each(imageAnchors, function(anchor){
			Shadowbox.addCache(anchor, {
				width: 640,
				height: 370,
				gallery: 'gallery'
			});
			anchor.addEvent('click', function(e){
				e.stop();
				Shadowbox.open();
			});
		});
		
		/*** TODO: Can't mootools work with videoAnchors.addEvent()  instead of looping throught them ***/
		$each(fileAnchors, function(anchor){
			anchor.addEvent('click', function(e){
				e.stop();
				window.open(anchor.get('href'), '');
			}.bind(this));
		}.bind(this));
		
		$each(internalAnchors, function(anchor){
			anchor.addEvent('click', function(e){
				e.stop();
				this.loadContent(anchor.get('href'));
			}.bind(this));
		}.bind(this));
		
		$each(externalAnchors, function(anchor){
			anchor.addEvent('click', function(e){
				e.stop();
				window.open(anchor.get('href'), '');
			}.bind(this));
		}.bind(this));
				
		$each($$('form'), function(obj){
			obj.addEvent('submit', function(e){
				e.stop();
				this.loadContent(obj.get('action'), obj);
			}.bind(this))
		}.bind(this));		
	},
	
	makeVideoElement: function(anchor){
		if(anchor.getChildren('img').length > 0){
			var image = anchor.getChildren('img')[0];
			$(image).addEvent('load', function(e){ 
				var div = new Element('div');
				div.addClass ('video-link');
				div.setStyles({
					width: image.getSize().x,
					height: image.getSize().y
				});
				anchor.setStyles({
					width: image.getSize().x,
					height: image.getSize().y,
					display: 'block'
				});
				openButton = new Element('div');
				openButton.addClass('openbutton');
				openButton.setStyles({
					width: image.getSize().x,
					height: image.getSize().y
				});
				anchor.insertBefore(openButton, image);			
				anchor.getParent().insertBefore(div, anchor);
				div.grab(anchor);			
			}.bind(this));
		}
	}
}

if(console == null){
	var console = {
		log: function(value){
			//alert(value);
		}
	}
}

