var _deviceWidth;
var _deviceHeight;
var _hasInternet = false;
var video;

MenuController = function() {
}
MenuController.prototype = {
	init: function() {
		if(device == 'browser') {
			var that = this;
			this.buildBrowserMenu();
			$(window).bind('pageLoaded', function() {
				if(Navigation.getCurrentPage().method == 'home') {
					that.fadeOutMenu();
				}
				
			});
		} else if (device == 'mobile') {
			this.buildTouchMenu();
		}
	},
	buildBrowserMenu : function() {
		var i = 0;
		$(xml).find('page[id="home"] >pages> page' ).each( function() {
			var el = document.createElement('div');
			el = $(el);
			el.addClass('menu');
			el.css('left', $(this).attr('x')* GrayBlocks.BLOCKSIZE);
			el.css('top', $(this).attr('y') * GrayBlocks.BLOCKSIZE);

			el.css('background-color', '#'+$(this).attr('menuColor'));
 			
 			
 			if($(this).find('subPage[nr='+Navigation.getCurrentPage().params.id+']').length > 0 || $(this).attr('id') == Navigation.getCurrentPage().params.id || Navigation.getCurrentPage().method == 'home' ){
				el.mouseover( function() {
					$(this).stop(true);
					$(this).fadeTo(250,1);
				});
				el.bind('mouseout', function() {
					$(this).fadeTo( 250, 0.8);
				});
				el.css('opacity',0.8)
			}
			else{
				el.mouseover( function() {
					$(this).stop(true);
					$(this).fadeTo(250,0.9);
				});
				el.bind('mouseout', function() {
					$(this).fadeTo( 250, 0.4);
				});
				el.css('opacity',0.4)
			}
			el.attr('page', $(this).attr('id'));
			el.hide();
			el.delay(i*250).fadeIn(500);
			i++;

			var plus = ($(this).attr('id') == 'offer' ? '' : '+');
			var spanClass = ($(this).attr('x') == 9 ? 'bottom' : 'top');

			var str = '<span class="'+spanClass+'"><span style="font-family:arial">'+plus+'</span><br />'+$(this).attr('name') + '</span>';
			el.html(str);
			$('#wrapper').append(el);
		});

		$('.menu, .menu2').click( function() {
			Navigation.navigateToPage($(this).attr('page'));
			var that = this;
			$(this).fadeTo(250,0.9);
			//$(this).css('background-color','#617580');
			$(this).unbind('mouseout');
			// #617580
			$('.menu, .menu2').each( function(menu) {
				if($(this).attr('page') != $(that).attr('page')) {
					$(this).fadeTo( 250, 0.4);
					$(this).bind('mouseout', function() {
						$(this).fadeTo( 250, 0.4);
					});
				}
			});
			return false;
		});
	},
	buildTouchMenu : function() {
		$(xml).find('page[id="home"] >pages> page' ).each( function() {
			var str = $(this).attr('name');
			var plus = ($(this).attr('id') == 'offer' ? '&nbsp;&nbsp;' : '+');

			var el =  '<li page="'+$(this).attr('id')+'">'+plus+' '+str+'</li>';
			$('#menu').append(el);
		});
		$('#menu li').click( function() {
			Navigation.navigateToPage($(this).attr('page'));
			return false;
		});
	},
	fadeOutMenu: function() {
		var i = 0;
		$('.menu, .menu2').each( function(item) {
			$(this).fadeTo(250,0.8);

			$(this).unbind('mouseover');
			$(this).unbind('mouseout');

			$(this).bind('mouseover', function() {
				$(this).stop(true);
				$(this).fadeTo(250,1);
			});
			$(this).bind('mouseout', function() {
				$(this).fadeTo( 250, 0.8);
			});
			i++;
		});
	}
}

function writePageVideo(videoUrl, posterUrl, element){
	
	/*
		New Add Video Function
		Based on CLS
		1) Serve HTML5
		2) No HTMl5 - Serve Flash
		3) Neither? Show Error
	*/
	
	var pageName = Navigation.getCurrentPage().params.id; // Grab the page name
	var size = {
		x: (device == 'mobile') ? 295 : 574,
		y: (device == 'mobile') ? 185 : 328
	}
	
	var dataWebM = baseUrl + videoUrl + '.webm';
	var dataOGV = baseUrl + videoUrl + '.ogv';
	var dataMP4 = baseUrl + videoUrl + '.mp4';
	
	if(isHTML5Video()){
		// HTML5
		var controls = 'controls'
		var videoInner = '<video id="videoPlayer" class="video-js" poster="'+posterUrl+'" width="'+size.x+'" height="'+size.y+'" preload autoplay '+controls+'><source src="'+dataWebM+'" type=\'video/webm; codecs="vp8, vorbis"\' /><source src="'+dataOGV+'" type=\'video/ogg; codecs="theora, vorbis"\' /><source src="'+dataMP4+'" />';
		$('#mainContent').attr('class', 'video-js-box');
		
		$('#mainContent').append(videoInner);
		
		if(!$.browser.safari){
			var videoPlayer = VideoJS.setup('videoPlayer');
			videoPlayer.play();
		} else {
			$('video')[0].load();
			$('video')[0].play();
		}
		
		$('video').css('background', '#000');
		$('video').css('left', 0);
		$('video').css('top', 0);
		$('video').css('height', 328);
		$('video').css('width', 574);
		$('video').css('position', 'absolute');
		$('video')[0].addEventListener("play", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Play', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		$('video')[0].addEventListener("ended", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Completed', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		$('video')[0].addEventListener("pause", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		
		return;
		
	} else if(checkValidFlashVersion()) {
		// Flash
		var el = document.createElement('div');
		var id = 'videoPlayer';// + Math.floor(Math.random()*20);
		$(el).css('width', size.x);
		$(el).css('height', size.y);
		$(el).css('position', 'absolute');

		$(el).attr('id', id);
	 	if(element == undefined) {
			$('#mainContent').append(el);

		} else {
			element.append(el);
		}
		$f(id, {src: "flowplayer-3.2.7.swf", wmode: 'direct'},  {
		    clip: {
		        url: baseUrl + videoUrl+".m4v?456",
		        scaling: "noscale",
		        autoPlay: true,
		        autoBuffering: true,
		        onBegin: function () {
		        	this.getPlugin("play").css({opacity: 0});
			    }
		    },
		    plugins: {
		        controls: {}
		    },
		    onLoad: function(){
		    },
		    onStart: function(){
				_gaq.push(['_trackEvent', 'Videos', 'Play', 'Video - ' + pageName + ' - Desktop']);
		    },
		    onStop: function(){
				_gaq.push(['_trackEvent', 'Videos', 'Stop', 'Video - ' + pageName + ' - Desktop']);
		    },
		    onPause: function(){
				_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Video - ' + pageName + ' - Desktop']);
		    }
		});
		return;
	} else {
		// Error
		writeFlashError();
		return;
	}
}

function addPageVideo(videoUrl, posterUrl, element) {
 	var pageName = Navigation.getCurrentPage().params.id;
 	
 	if(!checkValidFlashVersion() && !isHTML5Video()){
		writeFlashError();
		return;
	}
	else if(!checkValidFlashVersion() && isHTML5Video()){
		var el = '<video id="videoPlayer" controls="controls" autoplay  width="574" height="328" src="'+baseUrl + videoUrl+'.m4v"  > </video>';
		$('#mainContent').append(el);
		$('video').css('background', '#000');
		$('video').css('left', 0);
		$('video').css('top', 0);
		$('video').css('height', 328);
		$('video').css('width', 574);
		$('video').css('position', 'absolute');
		$('video')[0].addEventListener("play", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Play', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		$('video')[0].addEventListener("ended", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Completed', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		$('video')[0].addEventListener("pause", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Video - ' + pageName + ' - Desktop']);
		}, true);
		
		return;
	}
	var width = (device == 'mobile') ? 295 : 574;
	var height = (device == 'mobile') ? 185 : 328;

	var el = document.createElement('div');
	var id = 'videoPlayer'; //+ Math.floor(Math.random()*100);
	$(el).css('width', width);
	$(el).css('height', height);
	$(el).css('position', 'absolute');
	
	$(el).attr('id', id);
 	if(element == undefined) {
		$('#mainContent').append(el);
		
	} else {
		element.append(el);
	}
	$f(id, { src: "flowplayer.commercial-3.2.7.swf", key: '#$04f03132f05ba656a11', wmode: 'direct'}, {
    clip: {
        url: baseUrl + videoUrl+".m4v?456",
        scaling: "noscale",
        autoPlay: true,
        autoBuffering: true,
        onBegin: function () {
        // disable play button for this playlist item
        	this.getPlugin("play").css({opacity: 0});
	    }
    },
    plugins: {
        controls: {}
    },
    onLoad: function(){
    },
    onStart: function(){
		_gaq.push(['_trackEvent', 'Videos', 'Play', 'Video - ' + pageName + ' - Desktop']);
    },
    onStop: function(){
		_gaq.push(['_trackEvent', 'Videos', 'Stop', 'Video - ' + pageName + ' - Desktop']);
    },
    onPause: function(){
		_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Video - ' + pageName + ' - Desktop']);
    }
});
}
function stopVideo(){
	if($('#videoPlayer').length == 0) return;
	//jwplayer().stop();
	//$('#videoPlayer').remove();
}

function addHomeVideo(videoUrl, posterUrl) {
	if(!checkValidFlashVersion()) {
		addHomeVideoFallback();
		return;
	}

	var wrap = document.createElement('div');
	$(wrap).attr('id', 'introPlayer');
	$('#wrapper').append(wrap);

	var el = document.createElement('div');
	$(el).attr('id', 'introVidPlayer');
	$(wrap).append(el);

	var flashvars = false;
	var params = {
		wmode:"transparent",
		allowscriptaccess : "always"
	};
	var attributes = {
	};
	swfobject.embedSWF("intro.swf", "introVidPlayer", "560", "325", "9.0.0","expressInstall.swf", flashvars, params, attributes);
}

function addHomeVideoFallback() {
	// Init the intro animation

	var wrap = document.createElement('div');
	$(wrap).attr('id', 'introPlayer');
	$('#wrapper').append(wrap);

	var el = document.createElement('div');
	$(el).attr('id', 'introVidPlayer');
	$(wrap).append(el);

	imageSeq = new ImageSequence();
	imageSeq.start();
	imageSeq.oncomplete = function() {
		carImage.addCar();
		imageSeq.removeSequence();
		carImage.showRegular();
		onStop();
	}
}

var  removeVideo = function() {
	$('#videoPlayer').remove();
	showCar();
	removeVideo = function() {
	};
}
ImageSequence = function() {
}
ImageSequence.prototype = {
	oncomplete: function() {
	},
	imageBase: "",
	loadedNr: 0,
	images: new Array(),
	basePath: '_video/sequence/',
	MAXIMAGES: 18,
	interval: null,
	played: false,
	currentFrame: 0,
	imageHolder: new Image(),

	start: function() {
		this.images = [];
		this.currentFrame = 0;
		this.imageHolder.width = "560";
		this.imageHolder.height = "325";
		var i = 0;
		for(var i=0; i < this.MAXIMAGES;i++) {
			var img = new Image();
			$(img).attr('nr', i);
			var nr = (i<10) ? '0'+i : i;
			img.src = this.basePath + 'introiPad_'+this.zeroPad(5,i)+'.png';
			this.images.push(img);
			var that = this;
			img.onload = function() {
				if(that.images.length == that.MAXIMAGES) {
					if(!that.played)
						that.play();
				}
				img.onload = null;
			}
		}
	},
	getImageHolder: function() {
		return this.imageHolder;
	},
	play: function() {
		$('#introVidPlayer').append(this.imageHolder);
		this.imageHolder.src = this.images[this.currentFrame].src;
		this.played = true;
		this.nextFrame();
		var that = this;
		if(this.interval == null)
			this.interval = setInterval( function() {
				that.nextFrame();
			}, 100);
	},
	nextFrame: function() {
		this.imageHolder.src = this.images[this.currentFrame].src;
		this.currentFrame++;
		if(this.currentFrame == this.MAXIMAGES) {
			this.currentFrame = 0;
			clearTimeout(this.interval);
			this.oncomplete.call();
		}
	},
	zeroPad: function(length, val) {
		var str = ''+val;
		while(str.length < length) {
			str = '0'+str;

		}
		return str;
	},
	removeSequence: function() {
		$(this.images).each( function() {
			this.src = '_css/img/1x1.gif';
		});
		this.images = [];
		$('#introVidPlayer').remove();
	}
};

Car = function () {
	if(device == 'browser') {
		this.carImage.src = '_img/car.png';
		this.carImagePixelated.src = '_img/carPixelated.png';
	}
}
Car.prototype = {
	carImage : new Image(),
	carImagePixelated : new Image(),
	show : function() {
		if($.browser.msie) {
			$(this.carImagePixelated).hide();
			$(this.carImage).show();
		} else {
			$(this.carImagePixelated).delay(200).fadeOut(500);
			$(this.carImage).fadeIn(0);
		}
	},
	hide : function() {
		if($.browser.msie)
			$(this.carImagePixelated).hide();
		else
			$(this.carImagePixelated).fadeOut(500);

	},
	removeSwf: function() {
		swfobject.removeSWF('introVidPlayer');
		$('#introPlayer').remove();
	},
	showRegular: function() {
		if($.browser.msie) {
			$(this.carImage).show();
		} else {
			$(this.carImagePixelated).show();
			$(this.carImage).show();
			$(this.carImagePixelated).delay(0).fadeOut(500);
			//$(this.carImage).delay(500).fadeOut(0);
		}
	},
	showPixelated: function() {
		if($('.carImage').length == 0) {
			this.addCar();
			$(this.carImage).show()
		}
		if($('#introPlayer').length >0) {
			setTimeout(this.removeSwf, 100);
		}
		return;
		if($.browser.msie) {
			$(this.carImagePixelated).show();
			$(this.carImage).hide();
		} else {
			$(this.carImagePixelated).fadeIn(500);
			$(this.carImage).delay(500).fadeOut(0);
		}
	},
	addCar: function() {
		var container = document.createElement('div');
		$(container).addClass('carImage');
		$(this.carImage).click( function() {
			Navigation.navigateToHome();
		});
		$(this.carImagePixelated).click( function() {
			Navigation.navigateToHome();
		});
		$('#wrapper').prepend(container);
		$(this.carImage).hide();
		$(this.carImagePixelated).hide();
		$(container).prepend(this.carImage);
		$(container).append(this.carImagePixelated);
	}
};
carImage = new Car();

function showCar() {
	carImage.showPixelated();
}

function positionGrid() {
	
	var offsetX;
	if($(window).width() < $('#wrapper').width()){
		offsetX = 0;
	}
	else{
		offsetX = (($(window).width() - $('#wrapper').width())/2)/82;
		offsetX = ((1-(offsetX - Math.floor(offsetX))) * -1 * 82);
		offsetX = ($.browser.msie && $.browser.version.indexOf('6') != -1) ? offsetX-1 : offsetX;
	}
	
	var offsetY = ($.browser.msie && $.browser.version.indexOf('6') != -1 ? '-35px' : '-37px');
	$('#grid').css('background-position',(offsetX)+'px '+(offsetY));
	$('#grid').css('height', '100%');
}

function onPlay() {
}

function onStop() {
	menu = new MenuController();
	menu.init();
}

function addPageVideoMobile(videoUrl, posterUrl, element, pageName) {
	var width = 295;
	var height = 185;
//	var id = 'videoPlayer'
 
	if(isHTML5Video()) {
		// HTML 5 Video enabled
		// videoUrl = MP4 video
		var dataMP4 = videoUrl + '.mp4';
		var dataWebM = videoUrl + '.webm';
		var dataOGV = videoUrl + '.ogv';

		var el = document.createElement('video');
		element.append(el);

  		$(el).attr('id', 'videoPlayer');
 		$(el).attr('src',baseUrl+'/'+dataMP4);
		$(el).attr('poster', posterUrl);
		$(el).attr('width', width);
		$(el).attr('height', height);
		$(el).attr('preload','preload');
		$(el).attr('autoplay','autoplay');
		
		$(el).attr('controls','controls');
	//	var videoInner = '<source src="'+dataWebM+'" type=\'video/webm; codecs="vp8, vorbis"\' /><source src="'+dataOGV+'" type=\'video/ogg; codecs="theora, vorbis"\' /><source src="'+dataMP4+'" />';
		var videoInner = '<source src="'+baseUrl+'/'+dataMP4+'" type="video/mp4" />';
 	//	$(el).html(videoInner);
		// Add
		// Add event listeners (for tracking)
		

		el.addEventListener('click',function(){
  	  		$('video')[0].play();
		},false);

		el.addEventListener("play", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Play', 'Video - ' + pageName + ' - Mobile']);
		}, true);
		el.addEventListener("ended", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Completed', 'Video - ' + pageName + ' - Mobile']);
		}, true);
		el.addEventListener("pause", function() {
			_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Video - ' + pageName + ' - Mobile']);
		}, true);
		// End HTML5 Video
	} else {
		// Flash
		writeFlashError();
	}
}

function writeFlashError(){
	var el = document.createElement('div');
	$('#mainContent').append(el);
		var id = 'videoPlayer';// + Math.floor(Math.random()*20);
	$(el).attr('id', id);
	$(el).html('<p>Sorry, your browser must either support HTML5 video or Adobe Flash (version 10 or greater)<br />Please upgrade your browser now, or download the latest version at <a href="http://get.adobe.com/flashplayer" target="_blank">http://get.adobe.com/flashplayer</a></p>');
	$('#mainContent').css('background-color','#000000');
	$('#mainContent p').css('padding','20px');
}

function isHTML5Video() {
	return !!document.createElement('video').canPlayType;
}

function getFlashVersion() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try {
				axo.AllowScriptAccess = 'always';
			} catch(e) {
				return '6,0,0';
			}
		} catch(e) {
		}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
		// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {
		}
	}
	return '0,0,0';
}

function checkValidFlashVersion() {
	// We need to check a few things here:
	// 1) If the user has flash installed
	// 2) If the version of flash is above 9.1
	// Return true if both conditions are true or false if not
	var flashVersion = this.getFlashVersion();
	var flashVersionArray = flashVersion.split(",");

	if(flashVersionArray[0] > 9)
		return true;
	else if(flashVersionArray[0] == 9 && flashVersionArray[1] > 1)
		return true;
	else
		return false;
}
