var BrowserSupp = {}, McLaren = {}, 
	scroll, ajaxify, pushboxInstance;

window.addEvent('domready', function(){
	
	BrowserSupp.iPad = navigator.userAgent.match(/iPad/i) != null;
	BrowserSupp.BaseUrl = $(document.head).getElement('base').get('href');
	
	if (BrowserSupp.iPad){
		$(document.html).addClass('ipad');
		//$$('.large-buttons')[0].getSize().y = 225
		if($(document.body).getSize().y < 690) {
			var height = 225 + 60;
			$$('#home #pushbox div.slides ul li').setStyle('height', height);
		}
	}
	
	var buttonsHeight = $$('.large-buttons')[0].getSize().y + 60;
	var height = $(document.body).getSize().y - buttonsHeight;
	$$('#home #pushbox div.slides ul li').setStyle('height', height);
	
	var homepage = $('home'),
		pushbox = $('pushbox'),
		content = $(document.body);
		
	if (homepage && pushbox){
		if (!BrowserSupp.iPad){
			new McLaren.Home({
				wrapper: homepage,
				pushbox: pushbox,
				footer: homepage.getElement('a.group')
			});
		}
		
		pushboxInstance = new McLaren.Pushbox({
			wrapper: pushbox,
			slider: pushbox.getElement('div.slides ul'),
			items: pushbox.getElements('div.slides ul li'),
			buttons: pushbox.getElements('ul.buttons li a')
		});
	}
	
	ajaxify = new McLaren.Ajaxify({
		linkSelector: 'a.ajaxify',
		content: $('content')
	});
	
	scroll = new McLaren.ScrollPage({
		links: $$('a.scrollTo'),
		contentWrap: content 
	});

});

McLaren.initPage = function(wrap){
	if (!wrap){ wrap = $(document.body); }
	
	wrap.getElements('.gallery').each(function(gallery, i){
		new McLaren.Gallery({
			wrapper: gallery,
			pictures: gallery.getElements('div.items ul li'),
			descriptions: gallery.getElements('div.desc ul li'),
			nav: gallery.getElements('ul.nav li a'),
			totalTxt: gallery.getElement('span.total'),
			curTxt: gallery.getElement('span.current')
		});
	});
	
	if (wrap.getElement('#map-contact')){
		var latlng = new google.maps.LatLng(51.346408,-0.547596);
		var options = {
			zoom: 10,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(wrap.getElement('#map-contact'), options);

		var marker = new google.maps.Marker({
			position: latlng, 
			map: map, 
			title: 'McLaren Technology Centre'
		});
	}
}

McLaren.Ajaxify = new Class({
	options: {
		linkSelector: null,
		links: null,
		current: null,
		content: null,
		home: true,
		homeUrls: ['/', 'home'],
		keys: ['down', 'up', 'tab', 'home', 'end', 'pagedown', 'pageup'],
		pages: ['what-we-do', 'inside-the-mtc', 'media'],
		fxScroll: null,
		init: true,
		urlSplitter: '|',
		back: false
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.options.fxScroll = new Fx.Scroll($(document.html), { link: 'cancel', onComplete: function(){
			this.postScroll();
		}.bind(this) });
		
		this.findLinks();
		this.addHashChange();
		this.addEvents();
	},
	addHashChange: function(){		
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function(event){
			// Strip first / From url
			var url = event.value.substr(1, event.value.length - 1);
			
			// Init & Homepage, do nothing
			if (this.options.init && (this.options.homeUrls.contains(url.split(this.options.urlSplitter)[0]) || event.value == '/')){
				this.options.init = false;
				return false;
			}
			this.options.init = false;
			
			if (_gaq){
				_gaq.push(['_trackPageview', event.value]);
			}
			
			// Not Home
			if (!this.options.homeUrls.contains(url.split(this.options.urlSplitter)[0]) && event.value != '/'){
				// Loaded Page, don't load page, scroll from Home
				if (url.split(this.options.urlSplitter)[0] == this.options.current && this.options.home){
					this.toContent();
				}
				else {
					// Same Page, other anchor
					if (url.split(this.options.urlSplitter)[0] == this.options.current){
						if (url.split(this.options.urlSplitter)[1]){
							scroll.find(url.split(this.options.urlSplitter)[1]);
							this.activateNav(url);
						}
						return false;
					}
					
					// Get new Page
					this.getPage(url);
				}
			}
			else {
				this.toHome();
			}
		}.bind(this));
	},
	addEvents: function(){
		// Disable Keys
		window.addEvent('keydown', function(e){
			if (this.options.home && this.options.keys.contains(e.key)){
				e.stop();
			}
		}.bind(this));
	},
	setAddress: function(value){
		var currentUrl = window.location.hash.replace('#/', '');
		if(currentUrl === 'media%7Ccontact' && value === 'media|contact') {
			return false;
		} else {
			SWFAddress.setValue(value);
		}
	},
	findLinks: function(){
		this.options.links = $$(this.options.linkSelector);		
		this.options.links.each(function(link,i){
			if (!link.retrieve('isAjax')){
				link.addEvent('click', function(e){
					e.stop();
					if (link.get('data-type') && link.get('data-type') == 'back'){
						this.options.back = true;
					}
					this.setAddress(link.get('href').replace(BrowserSupp.BaseUrl, ''));
				}.bind(this));
				link.store('isAjax', true);
			}
		}.bind(this));
	},
	getPage: function(url){
		var req = new Request.HTML({
			method: 'get',
			url: BrowserSupp.BaseUrl + url.split(this.options.urlSplitter)[0],
			onComplete: function(tree, elems, html, js){
				this.setPage(html, url);
			}.bind(this)
		}).send();
	},
	setPage: function(html, id){
		var delay = 0;
		if (window.getScroll().y > 0){
			delay = 500;
			new Fx.Scroll(window).toTop();
		}
		
		var currentPage = $(this.options.current),
			h = (this.options.content.getSize().y.toInt() > $(window).getSize().y.toInt() ? this.options.content.getSize().y.toInt() : $(window).getSize().y.toInt()),
			w = $(window).getSize().x.toInt();
			
		if (currentPage){			
			var curInt = 0, nextInt = this.options.pages.length;
			this.options.pages.each(function(page, i){
				if (page.contains(id)){
					nextInt = i;
				}
				else if(page.contains(currentPage.get('id'))){
					curInt = i;
				}
			});
			if (nextInt < curInt){
				this.options.back = true;
			}
		}
		
		(function(){

			// Set Current Content Height	
			this.options.content.setStyle('height', h);

			// Slide/Remove Current Page
			if (currentPage){
				currentPage.set('tween', {
					duration: 500,
					onComplete: function(){
						this.element.dispose();
					}
				}).setStyles({
					'width': w
				}).addClass('inActive').tween('left', (this.options.back ? w : -w));
			}

			var newHtml = Browser.ie ? innerShiv(html) : html;		
			var elm = new Element('section', {
				'id': id.split(this.options.urlSplitter)[0],
				'class': 'content-holder inActive',
				'styles': {
					'left': (this.options.back ? -w : w),
					'width': w
				}
			});
			if (Browser.ie){
				elm.appendChild(newHtml);
			} else {
				elm.set('html', newHtml);
			}

			// Create new Page
			elm.set('tween', {
				duration: 500,
				onComplete: function(){
					elm.setStyles({ 'width': 'auto', 'left': 0 }).removeClass('inActive');
					this.options.content.setStyle('height', 'auto');
				}.bind(this)
			}).inject(this.options.content).tween('left', 0);

			// Set Current & Back
			this.options.current = id.split(this.options.urlSplitter)[0];
			this.options.back = false;

			// Scroll from Home to Content
			if (this.options.home){
				(function(){
					this.toContent(id);
				}).delay(500, this);
			}
			else {
				(function(){
					// Scroll to Anchor on Page
					if (id.split(this.options.urlSplitter)[1]){
						scroll.find(id.split(this.options.urlSplitter)[1]);
					}
				}).delay(500, this);
			}

			// Init Page Functions
			this.initPage(id);
		}).delay(delay, this);
	},
	initPage: function(id){
		McLaren.initPage($(this.options.current));
		
		this.findLinks();
		this.activateNav(id);
		
		this.options.fxScroll.toTop();
	},
	toHome: function(){
		this.options.home = true;
		this.options.disableKeys = true;
		
		this.preScroll();	
		this.options.fxScroll.toElement('home');
	},
	toContent: function(id){
		this.options.home = false;
		this.options.disableKeys = false;
		
		if (pushboxInstance){
			pushboxInstance.stop();
		}
		
		// iPad scrollBug, Content height = auto
		if (BrowserSupp.iPad){
			this.options.content.setStyle('height', 'auto');
		}
		
		this.options.fxScroll.toElement(this.options.content);
		
		if (id && id.split(this.options.urlSplitter)[1]){
			(function(){
				scroll.find(id.split(this.options.urlSplitter)[1]);
			}).delay(1000, this);
		}
	},
	preScroll: function(){
		if (this.options.home){
			// Fadeout Navigation
			this.options.content.getElement('> header').setStyle('position', 'absolute').fade(0);
			
			// Set ContentHeight
			this.options.content.setStyle('height', this.getMaxHeight());
			(function(){
				this.options.content.setStyle('height', 'auto');
			}).delay(500, this);
			
			// Scroll to Content
			$('home').setStyle('height', 'auto');
			window.scrollTo(0, window.getSize().y);
			$(document.html).addClass('home');
			window.fireEvent('resize');
		}
		else {
			// Scroll to Home
			window.scrollTo(0, 0);
			this.options.content.setStyle('height', this.getMaxHeight());
			(function(){
				this.options.content.setStyle('height', 'auto');
			}).delay(500, this);
		}
	},
	postScroll: function(){
		if (!this.options.home){
			// SHow Navigation
			if(this.options.content.getElement('> header').getStyle('display') == 'none'){
				this.options.content.getElement('> header').set('tween', {
					duration: 400,
					onComplete: function(){
						if (this.element.getStyle('opacity').toInt() == 0){
							this.element.setStyles({
								'position': 'fixed',
								'display': 'none'
							});
							if (BrowserSupp.iPad){
								this.element.setStyle('position', 'absolute');
							}
						}
					}
				}).setStyle('display', 'block').fade('hide').fade(1);
			}
			
			// Scroll to Content
			$('home').setStyle('height', 0);
			window.scrollTo(0,0);
			$(document.html).removeClass('home');
		}
		else {
			// iPad scrollBug, Content height = 0
			if (BrowserSupp.iPad){
				this.options.content.setStyle('height', 0);
			}
		}
	},
	getMaxHeight: function(){
		return (this.options.content.getSize().y.toInt() > $(window).getSize().y.toInt() ? this.options.content.getSize().y.toInt() : $(window).getSize().y.toInt());
	},
	activateNav: function(href){
		this.options.links.each(function(a, i){
			if (a.get('href') == href){
				a.addClass('active');
				a.getParent().addClass('active');
			}
			else {
				a.removeClass('active');
				a.getParent().removeClass('active');
			}
		}.bind(this));
	}
});

McLaren.ScrollPage = new Class({
	options: {
		links: null,
		contentWrap: null,
		fxScroll: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);		
		this.options.fxScroll = new Fx.Scroll(this.options.contentWrap, { link: 'cancel' });
		
		this.addEvents();
	},
	addEvents: function(){
		this.options.links.each(function(a, i){
			a.addEvent('click', function(e){
				e.stop();
				this.find(a.get('href'));
			}.bind(this));
		}.bind(this));
	},
	find: function(id){
		var to = $(id);
		if (to){
			var scrollPos = this.options.fxScroll.toElement(to).to;
			this.options.fxScroll.start(scrollPos[0], scrollPos[1] - ajaxify.options.content.getElement('> header').getSize().y);
		}
	}
});

McLaren.Home = new Class({
	options: {
		wrapper: null,
		pushbox: null,
		percentage: 60,
		maxHeight: 225,
		footer: null,
		dimensions: {
			window: { x: 0, y: 0 },
			pushbox: { x: 0, y: 0 },
			footer: 0
		},
		init: true
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.getFooterHeight();
		this.addEvents();
	},
	getFooterHeight: function(){
		this.options.dimensions.footer = this.options.footer.getSize().y.toInt();
	},
	getDimensions: function(){
		if (pushboxInstance){
			pushboxInstance.stop();
			pushboxInstance.start();
		}
		this.options.dimensions.window = window.getSize();
		
		this.options.dimensions.pushbox.x = this.options.dimensions.window.x;
		this.options.dimensions.pushbox.y = this.options.dimensions.window.y / 100 * this.options.percentage;
		
		this.setPushboxHeight();
	},
	setPushboxHeight: function(){		
		var h = this.options.dimensions.window.y - this.options.dimensions.pushbox.y - this.options.dimensions.footer;
		
		if (h > this.options.maxHeight){
			this.options.dimensions.pushbox.y = this.options.dimensions.window.y - this.options.dimensions.footer - this.options.maxHeight;
			$$('ul.large-buttons').each(function(wrap, i){
				wrap.setStyle('height', this.options.maxHeight);
				wrap.getElements('li').setStyle('height', this.options.maxHeight - 1);
				wrap.getElements('a').setStyle('height', this.options.maxHeight - 9);
			}.bind(this));
		}
		else {
			$$('ul.large-buttons').each(function(wrap, i){
				wrap.setStyle('height', h);
				wrap.getElements('li').setStyle('height', h - 1);
				wrap.getElements('a').setStyle('height', h - 9);
			});
		}
		
		this.options.pushbox.setStyle('height', this.options.dimensions.pushbox.y);
		this.options.pushbox.getElements('li').setStyle('height', this.options.dimensions.pushbox.y);
		
		if (this.options.init){
			this.options.pushbox.getElements('li img').each(function(img, i){			
				new Asset.image(img.src, {
					onLoad: function(){
						this.setImage(img);
					}.bind(this)
				});			
			}.bind(this));
			this.options.init = false;
		}
		else {
			this.options.pushbox.getElements('li img').each(function(img, i){			
				this.setImage(img);
			}.bind(this));
		}
	},
	addEvents: function(){
		window.addEvent('resize', this.getDimensions.bind(this));
	},
	setImage: function(img){
		img.setStyles({
			'height': this.options.dimensions.pushbox.y + 2,
			'width': 'auto'
		});
		if (img.getSize().x.toInt() < this.options.dimensions.window.x){
			img.setStyles({
				'height': 'auto',
				'width': this.options.dimensions.window.x + 2
			});
		}
		img.setStyles({
			'marginLeft': -(img.getSize().x.toInt() / 2)
		});
	}
	
});

McLaren.Pushbox = new Class({
	options: {
		wrapper: null,
		slider: null,
		items: null,
		buttons: null,
		active: 0,
		total: 0,
		itemWidth: 0,
		fx: null,
		fxSet: null,
		timer: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);		
		this.options.total = this.options.items.length;
		
		this.addEvents();
		this.setClasses();
		this.set();
		this.setPeriodical();
	},
	setPeriodical: function(){
		this.options.timer = this.nextPeriod.periodical(10000, this);
	},
	addEvents: function(){
		window.addEvent('resize', function(){
			this.setItemSize();
		}.bind(this)).fireEvent('resize');
		
		this.options.buttons.each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				this.preSlide();
				this.activate(i);
			}.bind(this));
		}.bind(this));
		
		if (BrowserSupp.iPad){
			this.options.wrapper.store('swipe:cancelVertical', true);
			this.options.wrapper.addEvent('swipe', function(e){
				switch (e.direction){
					case 'left': this.preSlide(); this.next(); break;
					case 'right': this.preSlide(); this.prev(); break;
				}
			}.bind(this));
		}
	},
	setItemSize: function(){
		this.options.itemWidth = $(window).getSize().x.toInt();		
		this.options.items.setStyle('width', this.options.itemWidth);
		
		this.set();
	},
	activate: function(i){
		if (i == this.options.active){ return false; }
		this.options.active = i;
		this.slide();
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = 0;
			return false;
		}
		this.slide();
	},
	next: function(){
		++this.options.active;
		if (this.options.total - this.options.active < 1){
			this.options.active = this.options.total - 1;
			return false;
		}
		this.slide();
	},
	nextPeriod: function(){
		++this.options.active;
		if (this.options.total - this.options.active < 1){
			this.options.active = 0;
		}
		this.slide();
	},
	preSlide: function(){
		this.stop();
		this.start();
	},
	slide: function(){
		this.options.slider.set('tween', { duration: 400, transition: Fx.Transitions.Quad.easeOut, link: 'cancel' });
		this.options.slider.tween('marginLeft', -(this.options.itemWidth * this.options.active));
		this.setClasses();
	},
	set: function(){
		this.options.slider.setStyle('marginLeft', -(this.options.itemWidth * this.options.active));
	},
	setClasses: function(){
		this.options.buttons.each(function(btn, i){
			if (i == this.options.active){
				btn.addClass('active');
			}
			else {
				btn.removeClass('active');
			}
		}.bind(this));
		
		this.options.items.each(function(itm, i){
			if (i < this.options.active){
				itm.addClass('lft').removeClass('rgt');
			}
			else if(i > this.options.active){
				itm.addClass('rgt').removeClass('lft');
			}
			else {
				itm.removeClass('lft').removeClass('rgt');
			}
		}.bind(this));
	},
	start: function(){
		this.setPeriodical();
	},
	stop: function(){
		clearInterval(this.options.timer);
		this.options.timer = null;
	}
});

McLaren.Gallery = new Class({
	options: {
		active: 0,
		total: 0,
		wrapper: null,
		pictures: null,
		descriptions: null,
		fxPictures: null,
		fxDesc: null,
		nav: null,
		totalTxt: null,
		curTxt: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.pictures.length;
		
		this.setTotalTxt();
		
		this.options.fxPictures = new Fx.Scroll(this.options.pictures[0].getParent('div'), { duration: 400, link: 'cancel' });
		this.options.fxDesc = new Fx.Scroll(this.options.descriptions[0].getParent('div'), { duration: 400, link: 'cancel' });
		
		this.addEvents();
		this.slide();
	},
	addEvents: function(){
		this.options.nav.each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				switch(btn.get('href').replace(BrowserSupp.BaseUrl, '')){
					case 'prev': this.prev(); break;
					case 'next': this.next(); break;
				}
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = this.options.total - 1;
		}
		this.slide();
	},
	next: function(){
		++this.options.active;
		if (this.options.total - this.options.active < 1){
			this.options.active = 0;
		}
		this.slide();
	},
	slide: function(){
		this.options.fxPictures.toElement(this.options.pictures[this.options.active]);
		(function(){
			this.options.fxDesc.toElement(this.options.descriptions[this.options.active]);
		}).delay(300, this);
		this.setCurrentTxt();
	},
	setCurrentTxt: function(){
		this.options.curTxt.set('text', BrowserSupp.str_pad(this.options.active + 1, 2, '0', 'STR_PAD_LEFT'));
	},
	setTotalTxt: function(){
		this.options.totalTxt.set('text', BrowserSupp.str_pad(this.options.total, 2, '0', 'STR_PAD_LEFT'));
	}
});

BrowserSupp.str_pad = function(input, pad_length, pad_string, pad_type){
    var half = '', pad_to_go; 
    var str_pad_repeater = function(s, len){
        var collect = '', i; 
        while (collect.length < len){
            collect += s;
        }
        collect = collect.substr(0, len); 
        return collect;
    }; 
    input += '';
    pad_string = pad_string !== undefined ? pad_string : ' ';
 
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {
        pad_type = 'STR_PAD_RIGHT';
    }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') {
            input = str_pad_repeater(pad_string, pad_to_go) + input;
        } else if (pad_type == 'STR_PAD_RIGHT') {
            input = input + str_pad_repeater(pad_string, pad_to_go);
        } else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    } 
    return input;
}

BrowserSupp.getScrollbarWidth = function(webkitWidth){
	if (Browser.chrome || Browser.safari){
		return webkitWidth;
	}
	
	var div = new Element('div', {
		'html': '<div style="height:100px;"></div>',
		'styles': { 'width':50, 'height':50, 'overflow':'hidden', 'position':'absolute', 'top':50, 'left':-200 }
	}).inject('content');
    var w1 = div.getElement('div').getWidth();
	div.setStyle('overflow-y', 'scroll');
    var w2 = div.getElement('div').getWidth();
    div.dispose();
    return (w1 - w2);
}
