// MWA
// Web Guru: Clayton Graul
site = function (){
	// constants strings
	this.HOME = 'home';
	this.DEFAULT = 'default';
	this.EXPLORE = 'explore';
	this.CONTACT = 'contact';
	this.VIDEO = 'video';
	this.TO_BACKGROUND_IMAGES = 'img/backgrounds/';
	this.TO_VIDEOS = 'http://cdn.markwoollen.com/video/';
	this.TO_FLASH_VIDEOS = '../'+this.TO_VIDEOS;
	// constants intss
	this._VISIBLE_THUMBS = 5;
	this._HIDE_NAV = -200;
	this._START_SHOW_NAV = 990;
	this._END_SHOW_NAV = 0;
	this._SHOW_PAGE = -40;
	this._HIDE_PAGE = 500;
	// elements
	this.swipeElement = null;
	this.eVideo = null
	// ints
	this.iCurrentTrailer = 0;
	this.iThumbWidth = 0;
	this.currentExplore = 1;
	this.totalExplore = siteData.pages[this.EXPLORE].text.length;
	// booleans
	this.bNavOpen = false;
	this.bHomePage = false;
	this.bAllowPlayback = false;
	this.bInitPlay = false;
	// strings
	this.sCurrentBackground = 'none';
	this.sSlidable = 'thumbs';
	this.sFallback = '';
	// arrays
	this.aThumbKeep = [];

}
site.prototype = {
	gTracking:function (pTrackingString)
	{
		_gaq.push(['_trackPageview', '/html5/'+pTrackingString]);
	},
	prepTracking:function(msg)
	{
		var trackingItem = msg[0];
		var trackingSlash = '';
		var page = msg[1] ? msg[1] : '';
		if(page != '')
			trackingSlash = '/';
		if(page == site.HOME)
		{
			page = site.VIDEO;
			trackingItem = siteData.trailers[msg[0]].id;
		}
		site.gTracking( page + trackingSlash + trackingItem);
	},
	prepContent:function()
	{
		siteData.trailers.sort( function(a, b){
			if (a.sortOrder < b.sortOrder)
				return 1;
			if (a.sortOrder > b.sortOrder)
				return -1;
			return 0;
		});
		for(i=0; i<siteData.trailers.length; i++)
		{
			var tmpName = siteData.trailers[i].abr ? siteData.trailers[i].abr : siteData.trailers[i].name;
			var thumbDiv = $('<div class="thumb" id="'+siteData.trailers[i].id+'" pos="'+i+'" style="background-image:url(img/thumbs/'+siteData.trailers[i].id+'.jpg);"><div id="thumbTitle">'+tmpName+'</div></div>');
			thumbDiv.click((function(){$.address.value($(this).attr('pos')+'/'+site.HOME);}));
			thumbDiv.mouseover(function(){
				$(this).find("#thumbTitle").show();
			})
			thumbDiv.mouseout(function(){
				$(this).find("#thumbTitle").hide();
			})
			$('#thumbWrapper').append(thumbDiv);
			site.aThumbKeep.push(thumbDiv);
		}
		siteData.iThumbWidth = (thumbDiv.width() + ((thumbDiv.css("margin-left").replace("px", "")/1)*2))*(siteData.trailers.length+2);
		$('#thumbWrapper').css('width', siteData.iThumbWidth+'px');
		site.checkNav(true);
	},
	pageEvent: function(msg)
	{
		site.removeWrappers();
		site.sFallback = '';
		
		if(msg.toString() == "[object Object]" || msg.length <= 0 || msg[0] == '/')
		{
			site.bHomePage = true;
			site.home();
			return;
		} else {
			$('.homePage').hide();
			site.bHomePage = false;
		}
		//index.html#/4/explore
		if(!site.bHomePage && msg[1])
			site.sFallback = msg[1];
		
		site.prepTracking(msg);
		
		if(msg[0].indexOf(site.EXPLORE+"_") == 0)
		{
			var exploreConfig = msg[0].split("_")
			
			if(site.currentExplore != (exploreConfig[1])/1)
			{
				site.currentExplore = exploreConfig[1];
				//site.exploreNext(null)
			}
			msg[0] = exploreConfig[0]
		}
		
		
		switch (msg[0])
		{
			case site.HOME:
				site.home()
				break;
			default :
				site.transitionOut(msg[0]);
				break;
		}
		site.bHomePage = true;
    },
	init: function(pStarOn)
	{
		$('.navItem').click(function(){
			$.address.value($(this).attr('id'));
		});
		$('.homePage').click(function(){
			site.playPromo()
			//$.address.value($(this).attr('id'));
		});
		site.prepContent();
		site.gTracking('load', '#exContainer');
	},
	home:function()
	{
		site.bAllowPlayback = true
		$('.homePage').show();
		site.changeBackground(siteData.openingImage);
		$('#pageWrapper').animate({opacity:0}, 1500, function(){$('#pageWrapper').remove();});
		if(!site.bInitPlay)
			site.playPromo()
		site.sSlidable = site.DEFAULT;
		site.checkNav(true);
	},
	playPromo:function()
	{
		$('#videoWrapper').remove();
		$('#pageLoader').append('<div id="videoWrapper"></div>');
			
		var tmpAutoPlay = !site.bInitPlay ? "autoplay" : "autoplay";
		site.bInitPlay = true;
		var videoString = '<div id="videoCenter" style="width:640px;">';
		videoString += '<video class="video" id="videoContent" '+tmpAutoPlay+' controls style="float:left; position:absolute; height:359px; top:55px; left:0px">';
		videoString += '<source src="video/ITRL_Promo.mp4" id="tmpVideo" video/mp4; codecs="avc1.42E01E, mp4a.40.2"/>';
		videoString += '<source src="video/ITRL_Promo.webm" id="tmpVideo" video/webm; codecs="vp8, vorbis"/>';
		videoString += '<source src="video/ITRL_Promo.ogg" id="tmpVideo" video/ogg; codecs="theora, vorbis"/>';
		videoString += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="trailer" style="height:359px; top:50px" width="640" height="359" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">';
		videoString += '<param name="movie" value="swf/player.swf?v=video/ITRL_Promo&s=359"/>';
		videoString += '<param name="quality" value="high" />';
		videoString += '<param name="bgcolor" value="#000000" />';
		videoString += '<param name="wmode" value="opaque" />';
		videoString += '<param name="allowScriptAccess" value="sameDomain" />';
		videoString += '<embed src="swf/player.swf?v=video/ITRL_Promo&s=359" quality="high" bgcolor="#000000"';
		videoString += 'width="640" height="359" name="flashVideo" ';
		videoString += 'quality="high" wmode="opaque" allowScriptAccess="sameDomain"';
		videoString += 'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
		videoString += '</object>';
		videoString += '</video></div>';
		
		$('#videoWrapper').append(videoString);

		site.eVideo = $("video")[0];
		if(site.eVideo)
		{
			site.eVideo.volume = 1;
			site.eVideo.setAttribute("ontimeupdate", "site.updateTime();");
		}
		$('.homePage').hide();
	},
	updateTime:function()
	{
		if(!site.bAllowPlayback)
		{
			$('video').each(function(pIndex){
				if($('video')[pIndex] && $('video')[pIndex].pause)
					$('video')[pIndex].pause();
			})
		}
		if(site.eVideo.currentTime >= site.eVideo.duration)
		{

			$('video').each(function(pIndex){
				if($('video')[pIndex] && $('video')[pIndex].pause)
					$('video')[pIndex].pause();
			})
			if(site.eVideo)
				site.eVideo.removeAttribute("ontimeupdate");
				
			$('#videoWrapper').animate({opacity:0}, 500, function(){$('#videoWrapper').remove();$.address.value('explore');});
		}	
	},
	transitionOut:function(pNextPage)
	{
		if( siteData.pages[pNextPage] )
		{
			site.bNavOpen = false;
			site.sSlidable = site.DEFAULT;
		}
		if(pNextPage == site.HOME)
		{
			site.home();
			return;
		}
		
		if(siteData.pages[pNextPage])
		{
			site.changeBackground(siteData.pages[pNextPage].background);
			
			if($('#pageWrapper').attr('class') != pNextPage)
			{
				if($('#pageWrapper').length)
					$('#pageWrapper').animate({opacity:0}, 1500, function(){site.transitionIn(pNextPage)});
				else
					site.transitionIn(pNextPage);
			}
		}
		else
		{
			site.iCurrentTrailer = pNextPage
			site.checkNav(true);
 		    $('#thumbWrapper').animate({left:((site.aThumbKeep[site.iCurrentTrailer].position().left)*-1)+380}, 1000);
			site.showITrailer(pNextPage);
		}
	},
	transitionIn:function(pNextPage)
	{
		$('#videoWrapper').remove();
		$('#pageWrapper').remove();
		$("#pageLoader").append('<div id="pageWrapper" class="'+pNextPage+'"></div>')
		
		
		$.ajax({
		        dataType: 'html',
		        type: 'GET',
		        url: "embeds/"+pNextPage+".html",
		        success: function(data, textStatus, xhr) {
					$("#pageWrapper").animate({opacity:0}, 0)
					$("#pageWrapper").html($(data))
		         // $teamDetailSection = $.browser.msie ? $(innerShiv(data, false)) : $(data);  
					if(pNextPage == site.EXPLORE)
					{
						$('#exContainer').animate({left:-900}, 0)
						$('#exContainer').animate({left:-800}, {duration:500, complete:function(){site.nextFunction(pNextPage)}})
					}
					else
					{
						window[site[pNextPage]()];
					}        
		        }
		      });
		
		
		return
		
		
		$.get("embeds/"+pNextPage+".html", function(html){
			$("#pageWrapper").animate({opacity:0}, 0)
			$("#pageWrapper").html(html);
			if($('#exContainer').length)
			{
				$('#exContainer').animate({left:-900}, 0)
				$('#exContainer').animate({left:-800}, {duration:500, complete:function(){site.nextFunction(pNextPage)}})
			}
			else
			{
				window[site[pNextPage]()];
			}
		})
	},
	nextFunction:function(pNextPage)
	{
		//console.log(pNextPage)
		window[site[pNextPage]()];
	},
	explore:function()
	{
		if(site.currentExplore > 1)
		{
			$("#exTitle").css("background-image", "url(img/explore/title"+site.currentExplore+".jpg)");
			$('#bodyText').html(siteData.pages[site.EXPLORE].text[site.currentExplore-1].text);
			$("#exContentSlider").css("background-image", "url(img/explore/slide"+site.currentExplore+".png)");
		}
		$('#exContainer').animate({left:-800}, 0)
		$("#pageWrapper").delay(0).animate({opacity:1}, {duration:0})
		$('#exContainer').delay(1000).animate({left:0}, 1000)
		$("#exTitle").delay(2300).animate({opacity:1}, {duration:1000})
		$("#bodyText").delay(2500).animate({opacity:1}, {duration:1000})
		$("#exContentSlider").delay(1800).animate({left:0}, {duration:1000})
		$('#exHit').click(function()
		{
			$.address.value($('#thumbWrapper').find('#'+siteData.pages[site.EXPLORE].text[site.currentExplore-1].id).attr('pos')+'/'+site.EXPLORE);
		})
		$('.exNav').click(site.exploreNext)
		
	},
	exploreNext:function(pButton)
	{
		
		if(pButton != null)
		{
			if($(this).attr('id')=="exNext")
				site.currentExplore ++
			else
				site.currentExplore --
		}	
		if(site.currentExplore > site.totalExplore)
			site.currentExplore = 1;
		else if(site.currentExplore < 1)
			site.currentExplore = site.totalExplore;
			
		$.address.value('/'+site.EXPLORE+'_'+site.currentExplore);
			
		$("#exTitle").delay(000).animate({opacity:0}, {duration:350, complete:site.showExploreTitle})
		$("#exContentSlider").delay(500).animate({left:-465}, {duration:1000, complete:site.showExploreSlide})
		$("#bodyText").delay(000).animate({opacity:0}, {duration:200})
	},
	contact:function()
	{
		$("#contactInfo").animate({opacity:0}, {duration:0})
		$("#pageWrapper").delay(0).animate({opacity:1}, {duration:0})
		$("#contactInfo").delay(900).animate({opacity:1}, {duration:1000})
	},
	profile:function()
	{
		$("#profileInfo").animate({opacity:0}, {duration:0})
		$("#pageWrapper").delay(0).animate({opacity:1}, {duration:0})
		$("#profileInfo").delay(900).animate({opacity:1}, {duration:1000})
	},
	showExploreTitle:function()
	{
		$("#exTitle").css("background-image", "url(img/explore/title"+site.currentExplore+".jpg)");
		$('#bodyText').html(siteData.pages[site.EXPLORE].text[site.currentExplore-1].text);
		$("#exTitle").delay(500).animate({opacity:1}, {duration:500, easing: "easeInCubic"})
		$("#bodyText").delay(500).animate({opacity:1}, {duration:500, easing: "easeInCubic"})
		
	},
	showExploreSlide:function()
	{
		$("#exContentSlider").css("background-image", "url(img/explore/slide"+site.currentExplore+".png)");
		$("#exContentSlider").delay(1000).animate({left:0}, {duration:400})
	},
	
	hideNav:function(pDelay)
	{
		// site.bNavOpen = true;
		// 		$('#thumbWrapper').delay(pDelay).animate({top:site._HIDE_NAV, alpha:0}, {duration: 1500, easing: "easeOutCubic"}, function(){$('#thumbWrapper').hide();});
	},
	addBackButton:function(){
		$('#pageWrapper').append('<div id="videoTitle"><div id=videoName></div><div id="close" style="color:#fff; left:860px;top:60px">X</div></div>');
		$('#close').click(function(){
			if(site.sFallback == '')
				window.history.back()
			else
				$.address.value(site.sFallback);
		});
	},
	showMap:function()
	{
		$('body').append('<div id="iTrailerWrapper"></div>');
		$('#iTrailerWrapper').animate({opacity:0}, 0);
		$('#iTrailerWrapper').append('<div id="videoCenter"><div id="videoTitle"><div id=videoName>i-Trailers LLC, 207 Ashland Ave. Santa Monica, CA 90405</div><div id="close">X</div></div>'+siteData.map+'</div>');
		$('#iTrailerWrapper').animate({opacity:1}, 1000);
		$('#close').click(site.removeWrappers);
	},
	showITrailer:function(pPos)
	{
		pVideo = siteData.trailers[pPos].id;
		var vHeight = Math.ceil(siteData.trailers[pPos].height * 1.25);
		var vTop = 0;
		
		site.bAllowPlayback = false;

		if($('#iTrailerWrapper').length)
			$('#iTrailerWrapper').replaceWith('<div id="iTrailerWrapper"></div>');
		else
			$('body').append('<div id="iTrailerWrapper"></div>');
			
		$('#iTrailerWrapper').animate({opacity:0}, 0);
		var videoString = '<div id="videoCenter" style="width:800px;"><div id="videoTitle"><div id=videoName>'+siteData.trailers[pPos].name +'</div><div id="close">X</div></div>';
		videoString += '<iframe src="embeds/embed_'+siteData.trailers[pPos].id+'.html" width="800" height="575" scrolling="no" frameborder="0"></iframe>';
		videoString += '</div>';
		$('#iTrailerWrapper').append(videoString);
		$('#iTrailerWrapper').animate({opacity:1}, 0);
		$('#iTrailerWrapper').find('#close').click(site.removeWrappers);
		
		if($('#videoWrapper').length)
			$('#videoWrapper').remove()
	},
	removeWrappers:function()
	{
		if($('#iTrailerWrapper').length)
		{
			$('#iTrailerWrapper').stop(true, false);
			$('#iTrailerWrapper').delay().animate({opacity:0}, 1500, function(){$('#iTrailerWrapper').remove();});
		};
		if($('#iFrameWrapper').length)
		{
			$('#iFrameWrapper').stop(true, false);
			$('#iFrameWrapper').delay().animate({opacity:0}, 1500, function(){$('#iFrameWrapper').remove();});
		};
			
		if(site.sFallback != '')
			$.address.value(site.sFallback);
		
		site.sFallback = '';
		
		site.bAllowPlayback = true;
		
	},
	nextOn:function()
	{
		$('#next').click(function(){site.moveNext()});
		$('#next').css('cursor','pointer');
		$('#next').show();
		//$('#next').animate({opacity:1}, 250);
	},
	nextOff:function()
	{
		$('#next').unbind('click');
		$('#next').css('cursor','auto');
		$('#next').hide();
		//$('#next').animate({opacity:0}, 250);
	},
	prevOn:function()
	{
		$('#prev').click(function(){site.movePrev()});
		$('#prev').css('cursor','pointer'); 
		$('#prev').show();
		//$('#prev').animate({opacity:1}, 250);
	},
	prevOff:function()
	{
		$('#prev').unbind('click');
		$('#prev').css('cursor','auto');
		$('#prev').hide();
		//$('#prev').animate({opacity:0}, 250);
	},
	checkNav:function(pSimpleCheck)
	{
		site.addTouch($('#thumbWrapper'));
		$('#prev').unbind('click');
		$('#next').unbind('click');
		
		if((siteData.trailers.length -5) - (site.iCurrentTrailer) > 0)
			site.nextOn();
		else
			site.nextOff();

		if(site.iCurrentTrailer > 0)
			site.prevOn();
		else
			site.prevOff();

		if(!pSimpleCheck)
			$('#thumbWrapper').animate({left:((site.aThumbKeep[site.iCurrentTrailer].position().left)*-1)}, { duration: 1000,  easing: "easeOutCubic"});
	},
	moveNext:function()
	{
			site.iCurrentTrailer = (site.iCurrentTrailer/1 + 2);
			if(!site.aThumbKeep[site.iCurrentTrailer])
				site.iCurrentTrailer = siteData.trailers.length-1;
			site.checkNav();
	},
	movePrev:function()
	{
			site.iCurrentTrailer -= 2;
			if(!site.aThumbKeep[site.iCurrentTrailer])
				site.iCurrentTrailer = 0;
			site.checkNav();
	},
	addTouch:function (pElemet){
		if(pElemet.attr('swipt') == 'true')
			return;
		
		if(site.swipeElement == null || site.swipeElement.attr('id') != pElemet.attr('id'))
		{
			if(site.swipeElement != null)
				$(site.swipeElement).unbind('touchwipe');
				
			site.swipeElement=pElemet;
			site.swipeElement.attr('swipt', "true");
			site.swipeElement.touchwipe({wipeLeft: function(pEndX){site.moveNext();},wipeRight: function(pEndX){site.movePrev();}});
		}
	},
	changeBackground: function(pStartOn)
	{
		
		if(site.sCurrentBackground == pStartOn)
			return;
			
		if(site.sCurrentBackground != "none")
			$('#slideWrapper').css('background-image', 'url('+site.TO_BACKGROUND_IMAGES+site.sCurrentBackground+'.jpg)');
		
		site.sCurrentBackground = pStartOn;
		$('.moveable').remove();
		var newImage = $('<img src='+site.TO_BACKGROUND_IMAGES+site.sCurrentBackground+'.jpg>');
		newImage.load(function(){
			var moveMe = $('<div class="moveable"></div>');
			$('#slideWrapper').append(moveMe);
			moveMe.css('background-image', 'url('+site.TO_BACKGROUND_IMAGES+pStartOn+'.jpg)');
			moveMe.show();
			moveMe.animate({opacity:0}, {duration: 0});
			var opacity = site.sCurrentBackground == site.HOME ? 1 : 1;
			moveMe.delay(500).animate({opacity:opacity}, {duration: (500)});
			//$('#logo').delay(0).animate({opacity:0}, 1000, function(){$('#logo').remove();});
			
		});
	}
}
