Cufon.replace('.cufonStyle', { hover: true} ); 

// some globals of sorts
var currentPos = 0, portfolioHTML = '<div class="arrow" id="previous"><img src="/style/arrow-left.jpg" width="87" height="550" alt="Previous"/></div><div class="image_container" id="imageContainer"><div id="touchBox"></div></div><div class="arrow" id="next"><img src="/style/arrow-right.jpg" width="87" height="550" alt="Next"/></div>', videoHTML = '<div class="video_player"><video  id="video_player" width="850" height="478"></video><div id="videoControls"><div id="playPause"><div id="pauseButton"></div><div id="playButton"></div></div><div id="videoDragBar"></div><div id="videoSeekBar"><div id="videoLoaderBar"></div></div></div></div>', contactHTML = '<div class="video_player cufonStyle">Elliott Smedley<br/>5th Floor<br/>New Gallery House<br/>6 Vigo Street<br/>London<br/>W1S 3HF<br/><br/>telephone +44 (0) 207 734 2100<br/>fax +44 (0) 207 287 0493<br/>email <a href="mailto:info@elliottsmedley.com ">info@elliottsmedley.com </a></div>';

window.addEvent('domready', function(){
	
	// lets see if we have a target
	var url = window.location.hash.replace(/^#/,'');
	  
	var historyManager = new HistoryManage(url);
	historyManager.refreshLoad();

	historyManager.startListener();
	 
	var curURLArray = new Array();
	curURLArray = url.split('/');
	
	if(curURLArray[1]) { currentPos = curURLArray[1];  } else { currentPos = 0; }		
});

function buildContact()
{ 
	// make sure sub is hidden
	document.id('videoNav').setStyle('visibility', 'hidden');
	
	// load in content
	document.id('pageContent').empty();
	document.id('pageContent').set('html', contactHTML)
	
	
	Cufon.refresh('.cufonStyle', { hover: true} )
}

function buildVideo(file)
{ 
	// make sure sub is hidden
	document.id('videoNav').setStyle('visibility', 'visible');
	
	// load in content
	document.id('pageContent').empty();
	 
	// if we are without a file
	if(!file) { file = 'ss12-ww'; }
	
	
	// its IE ! so good old Flash video please
	if(Browser.Engine.trident)
	{
		// inject
		document.id('pageContent').set('html', '<div class="video_player"><div  id="video_flash"></div></div>');
			
		var flashvars = {};
			flashvars.video_asset = file + '.mp4';
		var params = {};
		var attributes = {};
			
		swfobject.embedSWF("video_player.swf", "video_flash", "800", "506", "10.0.0",false, flashvars, params, attributes); 
	}
		else
	{
		
			// inject html
			document.id('pageContent').set('html', videoHTML);
	
			// start video
			var myVideo = document.id('video_player'), videoFile = file, videoExtension = '.mp4', videoControls = document.id('videoControls'), playPause = document.id('playPause'), videoLoaderBar = document.id('videoLoaderBar'), playPause  = document.id('playPause'), videoSeekBar = document.id('videoSeekBar'), videoDragBar = document.id('videoDragBar'), videoPlayBtn = document.id('playButton'), videoPauseBtn = document.id('pauseButton');
			
			// check what html5 codex
			if(Browser.Engine.webkit){ videoExtension = '.mp4'; } else { videoExtension = '.ogg' } 
			videoExtension = '.mp4'
			myVideo.setAttribute('src', "http://elliottsmedley.com/video/" + videoFile + videoExtension); 
			myVideo.load();
			myVideo.play();
					
			videoPlayBtn.setStyle('display', 'none');
			videoPauseBtn.setStyle('display', 'block');
		 	
		 	// bug in safari 5.1 that means we have to update the status manually
		 	var videoStatus = myVideo.paused;
		
			playPause.addEvent('click', function() {
		 	
				if(videoStatus == true)
				{  
					myVideo.play(); 
					trackPlayProgress();
					videoPlayBtn.setStyle('display', 'none');
					videoPauseBtn.setStyle('display', 'block');		
				}
				
				if(videoStatus == false)
				{ 
					myVideo.pause(); 
					stopTrackingPlayProgress();
					videoPlayBtn.setStyle('display', 'block');
					videoPauseBtn.setStyle('display', 'none');
				}
			});
			
			function updatePlayProgress(){
		  		videoLoaderBar.setStyle('left',  ((myVideo.currentTime / myVideo.duration) * (videoSeekBar.offsetWidth) ) + "px");
		  		videoStatus = myVideo.paused;
			}
			
			function trackPlayProgress(){
			  playProgressInterval = setInterval(updatePlayProgress, 100);
			}
			 
			function stopTrackingPlayProgress(){
			  clearInterval(playProgressInterval);
			  videoStatus = myVideo.paused;
			}
			
			// start the track bar
			trackPlayProgress(); 
			
			var draggingBool = false; 
			 		
			// seeking
			videoDragBar.addEvents({
				'mousedown' :  function(e,el){
					stopTrackingPlayProgress();
					myVideo.pause(); 
					draggingBool = true;
					$(document.body).focus();
				},
				
				'mouseup' :function(e,el){
					draggingBool = false;
					trackPlayProgress();
					myVideo.play();
				},
				'click': function(e)
				{
					var clickX = parseInt(parseInt(e.page.x)  - 236); 	
					var newPercent = Math.max(0, Math.min(1, clickX / videoSeekBar.offsetWidth));
					myVideo.currentTime = newPercent * myVideo.duration
					videoLoaderBar.setStyle('left', newPercent * (videoSeekBar.offsetWidth - 15)  + "px"); 
				}
			});
			
			$(document.body).addEvents({
				'mouseup' :function(e,el){
					 
					draggingBool = false;
					trackPlayProgress();
					myVideo.play(); 
				},
				'mousemove' : function(e)
				{
					if(draggingBool) { 
					var clickX = parseInt(parseInt(e.page.x)  - 236); 		
					var newPercent = Math.max(0, Math.min(1, clickX / videoSeekBar.offsetWidth));
						myVideo.currentTime = newPercent * myVideo.duration
						videoLoaderBar.setStyle('left', newPercent * (videoSeekBar.offsetWidth - 15)  + "px");
					}
				}
			});
		
	}
}

function buildPortfolio(page)
{ 
	// make sure sub is hidden
	document.id('videoNav').setStyle('visibility', 'hidden');
	
	// load in images
	/*var totalItems = 27;
	var imageContainer = document.id('imageContainer');
	
	
	var thumbImgArray = new Array();
	for(var i=0; i<totalItems; i++) { thumbImgArray.push('/images/'+i+'.jpg'); }
	
	var newImage  = new Array();
	
	var thumbImages = new Asset.images(thumbImgArray, {
    	onComplete: function(){
       		thumbImgArray.each(function(im, index) { 
       			
	   			// inject image
	   			var newEl = new Element('div',{  id:'img'+index, 'class' : 'portfolioImage' }).inject(imageContainer); 
				var newImg = new Element('img',{ src:im}).inject(newEl); 
				newEl.setStyle('opacity',0);
				newImage.push(newEl);
				    	
				// if we are on the last elment
				if(index == Math.round(thumbImgArray.length-1)){
	    			// fade in our image
	    			newImage[currentPos].setStyle('left',0);
					(function() { newImage[currentPos].fade('in')}).delay(500)
 				}
			});        			
   		}
	});
	*/
	var imageContainer = document.id('imageContainer');
	var preloadArray = new Array(),  totalItems = 0, newEl=[], newImg=[], newVideo =[], imagesLoaded=0, imagesToLoad=0;
	var jsonRequest = new Request.JSON({
		url: 'json/portfolio.json', 
		onSuccess: function(items)
		{
			totalItems = items.length;
				
			items.each(function(item, index){
				
				newEl[index] = new Element('div',{  id:'item'+index, 'class' : 'portfolioImage' }).inject(imageContainer); 
				newEl[index].setStyle('opacity',0);
				
				if(item.type=='image')
				{
					imagesToLoad++;
					
					newImg[index] = new Image();
					newImg[index].onload =function()
					{
						imagesLoaded++;
						if(imagesLoaded >= currentPos)
						{
							newEl[currentPos].setStyle('left',0);
							(function() { newEl[currentPos].fade('in')}).delay(500)
						}
					}
					
					newImg[index].src = 'images/' + item.file;
					$(newImg[index]).inject(newEl[index]); 
				}
				
				if(item.type=='video')
				{	
				
					if(navigator.userAgent.match(/iPhone/i) != null || navigator.userAgent.match(/Android/i) != null || navigator.userAgent.match(/iPad/i) != null ) 
					{  
						$(newEl[index]).set('html', '<video src="http://elliottsmedley.com/video/'+item.file+'" controls autoplay width="850" height="478">Your browser does not support the HTML5 video element</video>');
					}
						else
					{
						var flashvars = {};
						flashvars.video_asset =  item.file;
						var params = {};
						var attributes = {};
						var tmpDiv = new Element('div',{  id:'video'+index}).inject(newEl[index]);
						swfobject.embedSWF("video_player.swf", 'video'+index , "800", "506", "10.0.0",false, flashvars, params, attributes); 
					}				
				}

			});
		}
    }).get();
    
	// controls for arrows
	var nextArrow = document.id('next'), previousArrow = document.id('previous');	 
	function goNext()
	{
		currentPos++;
		if(currentPos>=totalItems) { currentPos = 0; }
	 	window.location.hash = '#portfolio/'+currentPos;
	}
	
	function goPrevious()
	{
		currentPos--;
		if(currentPos<0) { currentPos = totalItems-1; }
		window.location.hash = '#portfolio/'+currentPos;
	}
	nextArrow.fade(0.1,0.1);
	nextArrow.addEvents({
		'click' :  function(e)
		{  
			goNext();
		},
		'mouseover' : function(e)
		{
			this.fade(0.5);
		},
		'mouseout' : function(e)
		{
			this.fade(0.1);
		}
	});
	
	previousArrow.fade(0.1,0.1);
	previousArrow.addEvents({
		'click' :  function(e)
		{	
			goPrevious();	
		},
		'mouseover' : function(e)
		{
			this.fade(0.5);
		},
		'mouseout' : function(e)
		{
			this.fade(0.1);
		}
	});
	
	// touch events
	var touchBox = document.id('touchBox'), previousTouchPos = 0, currentTouchPos = 0;
	 
	touchBox.addEvents({
		'mousedown' : function(evt, el)
		{
			previousTouchPos = evt.page.x;
		},
		'mouseup' : function(evt, el)
		{
			currentTouchPos =  evt.page.x;
		 	
		 	if(currentTouchPos> previousTouchPos)
		 	{
		 		goPrevious();
		 	}
		 	
		 	if(previousTouchPos > currentTouchPos)
		 	{
		 		goNext();
		 	}
		},
		'click' : function(evt, el)
		{
			goNext();
		}
	});
}

var HistoryManage = new Class({
    
	iframe:null,
	ieHistory:0,
	urlValue : null,
	
	initialize: function(firstUrlValue){
       
		this.urlValue = firstUrlValue;
		this.createIframe();
    }, 
    
	createIframe : function(){ 
	
		this.iframe = new IFrame({
			src		: 'blank.htm',
			styles	: { 
				'position'	: 'absolute',
				'top'		: 0,
				'left'		: 0,
				'width'		: '500px', 
				'height'	: '80px',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		
		if(Browser.Engine.trident && (typeof(document.documentMode)=='undefined' || document.documentMode < 8))
		{ 
			doc	= (this.iframe.contentDocument) ? this.iframe.contentDocument  : this.iframe.contentWindow.document;
			doc.open();
			doc.write('<html><body id="state">' + this.checkURL() + '</body></html>');
			doc.close(); 
		}
	},
	
	checkURL: function()
	{
		var page_var = location.hash.replace(/^#/,'');
		return page_var;
	},
	
	checkState: function()
	{		 	
	
			
		if(Browser.Engine.trident && (typeof(document.documentMode)=='undefined' || document.documentMode < 8))
		{ 
			doc	= (this.iframe.contentDocument) ? this.iframe.contentDocument  : this.iframe.contentWindow.document;
			var docURL = doc.body.innerHTML;
			if(this.urlValue !== docURL)
			{	
				var prevURLArray = new Array();
				prevURLArray = this.urlValue.split('/');
			
				var myURI = new URI('#' + docURL).go();
			 
				this.urlValue = docURL;
				
				var curURLArray = new Array();
				curURLArray = this.urlValue.split('/');
			 	 
				// psuedo htaccess 
				if(curURLArray[0] == 'portfolio')
				{
			 		// url is portfolio
				 	var newImage = $$('.portfolioImage');
				 	var windowSize = document.window.getSize();
				 		 			
				 	if(!prevURLArray[1]) { prevURLArray[1] = 0;  }
				 	if(!curURLArray[1]) {   curURLArray[1] = 0; }
				 	
				 	currentPos = curURLArray[1];
				 	
				 	if(parseInt(curURLArray[1]) > parseInt(prevURLArray[1]))
				 	{	 			
				 		newImage[prevURLArray[1]].morph({'left': [ 0, -(windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [windowSize.x, 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) > parseInt(curURLArray[1]))
				 	{
						newImage[prevURLArray[1]].morph({'left': [ 0, (windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [-(windowSize.x), 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) == (newImage.length-1) && parseInt(curURLArray[1]) == 0)
				 	{	 			
				 		newImage[prevURLArray[1]].morph({'left': [ 0, -(windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [windowSize.x, 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) == 0 && parseInt(curURLArray[1]) == (newImage.length-1))
				 	{
						newImage[prevURLArray[1]].morph({'left': [ 0, (windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [-(windowSize.x), 0], 'opacity' : 1})
					}
				}			 
			}
			
			
		}
 
		if(this.checkURL() != this.urlValue  )
		{	
			// prev
			var prevURLArray = new Array();
			prevURLArray = this.urlValue.split('/');
			
			// set values for history
			this.urlValue = this.checkURL();
							
							
			// check what kind of page it is, e.g. collection
			var curURLArray = new Array();
			curURLArray = this.checkURL().split('/');
		 	 
			_gaq.push(['_trackPageview', curURLArray]);
				
			// psuedo htaccess 
			if(curURLArray[0] == 'portfolio')
			{
		 		// url is portfolio
			 	var newImage = $$('.portfolioImage');
			 	var windowSize = document.window.getSize();
			 		 			
			 	if(!prevURLArray[1]) { prevURLArray[1] = 0;  }
			 	if(!curURLArray[1]) {  curURLArray[1] = 0; }
			 	
			 	currentPos = curURLArray[1];
			 	
				// check that it isn't empty, if it is rebuild
				if(!document.id('imageContainer'))
			 	{	
			 		document.id('pageContent').empty();
			 	 	document.id('pageContent').set('html', portfolioHTML);
			 		
		 			buildPortfolio(prevURLArray[1]);
			 	}	 	
			 		else
			 	{
				 	// show content
				 	if(parseInt(curURLArray[1]) > parseInt(prevURLArray[1]))
				 	{	 			
				 		newImage[prevURLArray[1]].morph({'left': [ 0, -(windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [windowSize.x, 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) > parseInt(curURLArray[1]))
				 	{
						newImage[prevURLArray[1]].morph({'left': [ 0, (windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [-(windowSize.x), 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) == (newImage.length-1) && parseInt(curURLArray[1]) == 0)
				 	{	 			
				 		newImage[prevURLArray[1]].morph({'left': [ 0, -(windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [windowSize.x, 0], 'opacity' : 1})
					}
					
					if(parseInt(prevURLArray[1]) == 0 && parseInt(curURLArray[1]) == (newImage.length-1))
				 	{
						newImage[prevURLArray[1]].morph({'left': [ 0, (windowSize.x)], 'opacity' : 0})
						newImage[curURLArray[1]].morph({'left': [-(windowSize.x), 0], 'opacity' : 1})
					}
				}
			}
			
			// video
			if(curURLArray[0] == 'videos')
			{ 
				buildVideo(curURLArray[1]);
			}
			
			// contact
			if(curURLArray[0]  == 'contact')
			{ 
				buildContact();
			}
				
			// ie 
			if(Browser.Engine.trident && (typeof(document.documentMode)=='undefined' || document.documentMode < 8))
			{ 
				doc	= (this.iframe.contentDocument) ? this.iframe.contentDocument  : this.iframe.contentWindow.document;
				doc.open();
				doc.write('<html><body id="state">' + this.checkURL() + '</body></html>');
				doc.close(); 
			}
		} 
	},
	
	refreshLoad: function()
	{ 
		this.urlValue = this.checkURL();
			
		var url_array = new Array();
		url_array = this.urlValue.split('/');
		var section = url_array[0];
			if(!section) { section = 'portfolio' }
		var page = url_array[1];
			if(!page) { page = 0 }
	
			if(section == 'portfolio')
			{
				buildPortfolio(page);
			}
			
			if(section == 'videos')
			{ 
				buildVideo(page);
			}
			
			if(section == 'contact')
			{ 
				buildContact();
			}
			
	},
	
	startListener: function()
	{
		this.checkRefresh = this.checkState.bind(this).periodical(100);
	},
	
	stopListener: function()
	{
		$clear(this.checkRefresh);
	}
});
