//TODO: add code to align image to the bottom....

var EffectSpeed = 1000,
	  //Easing = 'swing';
	  Easing = 'linear';

$(function(){

	var proj_list = $('#project_list'),
		writeup = $('#writeup'),
		services = $("#services"),
		assets = $("#assets"),
		body = $("body");

	function select_thumb( thumb ){
		$("#assets li img.thumb.selected")
			.removeClass('selected')
			.fadeTo(EffectSpeed,1,Easing);
			
		thumb
			.addClass('selected')
			.fadeTo(EffectSpeed, 0.5, Easing);
	}
	
	
	//////////////////////
	//// NAVIGATION
	
	var currentPage = { cls:"splash", els: $("#splash") }, 
		previousPage = currentPage, isChanging = false;
	
	function showPage(cls, els, cb){
		if(isChanging) return;
		isChanging = true;
		if(currentPage.els.length == 0)
			fadeIn();
		else
			currentPage.els.fadeOut(EffectSpeed,Easing).promise().done( fadeIn );
		
		function fadeIn(){
			previousPage = currentPage;
			currentPage = { cls: cls, els:els };
			body.removeClass().addClass(cls);
			if(els.length == 0)
				fire_cb();
			else
				els.fadeIn(EffectSpeed,Easing).promise().done( fire_cb );
		}
		function fire_cb(){ 
			isChanging = false;
			if(cb) cb(); 
		}
	}
	function isPageVisible( name ){
		return currentPage.cls == name;
	}
	
	function showPreviousPage( cb ){
		var tmp = previousPage;
		previousPage = currentPage;
		showPage( tmp.cls, tmp.els, cb );
	}
	
	
	
	////////////////////
	//// FEATURE
	
	var feature = $("#feature").gallery({
		anim: showcase_config.anim,
		images:[],
		click: feature_img_click,
		change: feature_img_change,
		before_change: feature_before_img_change
	});
	
	
	
	function showFeature( cls, items ){
		if(feature.is('.gallery'))
			feature.gallery('hide');
		else if(feature.is('.video')){
			var e =feature.data('video_el');
			if(e)e.remove();
		}else if(feature.is(".image")){
			feature.find("img.single").remove();
		}
		feature.removeClass().addClass(cls);
		if(cls == 'video'){
			showVideo( feature, items );
		}else if( cls == 'gallery')
			feature.gallery( 'load', items );
		else if(cls == 'image')
			$('<img class="single" />')
			.load(function(){
				var img = $(this);
				img
					.attr('data-original-width', img.width())
					.attr('data-original-height', img.height())
					.resizeImage({scale: calcScale( img.attr('data-original-width'), img.attr('data-original-height'), feature.width(), feature.height() )})
					.fadeIn(EffectSpeed,Easing);
			})
			.hide()
			.css('margin', '0 auto')
			.appendTo(feature)
			.attr('src',items);
	}
	
	function feature_img_click(item){
		if(item.type == 'client-image') {
			
		}else{
			pages.client( $( "#client_" + item.client ), item);
		}
		
	}
	function feature_before_img_change(item){
		if(item.type == 'client-image' && item.thumb.is(".selected")){
			select_thumb($());
		}
	}
	
	var first = true;
	function feature_img_change(item){
		if(first){
			// hack: sometimes gallery misscalculates
			//feature.gallery('move',0);
			first = false;
		}
		if(item.type == 'client-image' && !item.thumb.is('.selected')){
			select_thumb(item.thumb);
		}
	}
	

	var pages = {
		splash: function (){
			showPage( 'home', $("#page"), function(){
				currentPage.els = $(); // dont want to hide #page again;
				//setTimeout( function(){// wierd flash happens here????
					pages.showcase();
				//},1000);
			});
		},
		services: function(){
			if( isPageVisible( 'splash' ) ) return;
			if( isPageVisible( 'services' ) ){
				showPreviousPage( function(){
					currentPage.els = currentPage.els;//.not("#nav");
					feature.gallery('show');
				});
			}else{
				
				// make #nav fade out on page change
				currentPage.els = currentPage.els;//.add("#nav");
				feature.gallery('hide');
				
				showPage( 'services', $("#services")/*.add("#splash" )*/);
			}
		},
		showcase:function(){
			if( isPageVisible( 'showcase' ) ) return;
			
			showPage('showcase', $());
			showFeature( 'gallery', showcase_config.images );
		},
		projects: function(  ){
			if( isPageVisible( 'projects' ) ) return;
			if( isPageVisible( 'splash' ) ) return;
			
			showPage('projects', $("#project_list"));
		},
		client: function(link, item){
		
			if(pages.client.name == link.attr('id'))
				return;
			
			var images = [];
			
			// load asset markup from server
			$("#inject").load(link.attr('href')+"/ajax", function(){
					// update dom
					$("#writeup")
						.hide()
						.empty()
						.append($("#inject #inject_left div:first"));
						
					$("#assets")
						.empty()
						.hide()
						.append($("#inject #inject_right div:first"))
						.find("img.still")
							.each( image_loader );
							
					pages.client.name = link.attr('id');
					
					
					
					
					showPage( 'client', $("#writeup").add($("#assets")), function(){
					
					
						
						
						var thumbs = $("img.thumb.still");
						if(thumbs.length == 1){
							thumbs.addClass('single').click();
							//showFeature('image', thumbs[0].src.replace('thumb.jpg','feature.jpg'))
							return ;
						}
						
						if(!item['url']){
							var first_thumb = $("#assets img.still:first");
							if(first_thumb.length == 0)
								first_thumb = $("#assets img.film:first");
							first_thumb.click();
							return;
						}
						
						var thumbUrl = item.url.replace('feature.jpg','thumb.jpg');
						var parts = thumbUrl.split('assets/');
						if(parts.length > 1)
							thumbUrl = parts[1];
						else
							thumbUrl = thumbUrl.replace("assets/",'');
						thumbs.each(function(){
							var thumb = $(this);							
							if( thumb.attr('src').split('assets/')[1] == thumbUrl ){
								thumb.click();
							}
						});
					});
					
					if(images.length > 1){
							showFeature( 'gallery', images );
					}
			});
			
			function image_loader(){
				var img = $(this);
				img .css("visibility","hidden")
					.load(function(){ 
						img	.css("visibility","visible")
							.fadeIn(EffectSpeed,Easing)
							.parent()	
								.removeClass('loading'); 
					});
					//.error(function(){ img.css("visibility","visibile"); })
				if(img.is('.still'))
					images.push({ url: img.attr('data-asset')+'feature.jpg', thumb: img, type: 'client-image', asset:  img.attr('data-asset') });
					
				// reload img, this forces the load event to fire (if it was cached, the image might have 
				// fire load event before we added the event listener above )
				var src = img.attr('src');
				img.attr('src','');
				img.attr('src', src);
			};
		}
	};

	var base = $("base").attr("href");
	$("body").delegate('a','click',function(e){
		var _this = $(this),
			cmd = _this.attr('href') || "";
		cmd = cmd.replace(base,'').replace('index.php/','');
		cmd = cmd.split("/")[0];
		if(!pages[cmd]) return;
		e.preventDefault();
		pages[cmd](_this,e);
	});

	
	

	var videoHtml = 
	'<div class="video-js-box" style="display:none"> \
		<video id="video" class="video-js" width="#WIDTH#" height="#HEIGHT#" controls="controls" preload="auto" autoplay="true"> \
			<source src="#OGV_SRC#" type="video/ogg" /> \
		  <source src="#MP4_SRC#" type="video/mp4" /> \
		  <object id="flash_fallback_1" class="vjs-flash-fallback" width="#WIDTH#" height="#HEIGHT#" type="application/x-shockwave-flash" \
			data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"> \
			<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /> \
			<param name="allowfullscreen" value="true" /> \
			<param name="flashvars" value=' + "'" +
				'config={"playlist":["#POSTER#", {"url": "#MP4_SRC#","autoPlay":true,"autoBuffering":true}]}' +"'" + ' /> \
		  </object> \
		</video> \
	</box>';
	

	function getVideoSize(  ){
		var w = 1280,
			  h = 720,
			  controlsHeight = 15,
			  scale = calcScale( w,h, feature.width(), feature.height() - controlsHeight );
			  
		w = parseInt(w * scale);
		h = parseInt(h * scale);
		
		return [w,h];
	}
	
	function showVideo( feature, asset ){
		//feature.addClass("loading");
		
		var size = getVideoSize(),
			html = videoHtml
						.replace( /#WIDTH#/g, size[0] )
						.replace( /#HEIGHT#/g,size[1] )
						.replace( /#POSTER#/g,asset+'thumb.jpg' )
						.replace( /#MP4_SRC#/g,asset+'video.mp4' )
						.replace( /#OGV_SRC#/g,asset+'video.ogv' ),
			el = $(html);
		
		feature.data('video_el', el);
		feature.append( el );
		
		VideoJS.setup("video",{controlsHiding: false,controlsBelow: true, autoplay:true,controlsAtStart: true});
		
		$(".vjs-fullscreen-control").html('<span id="enlarge">enlarge</span><span id="close_fullscreen">close</span>');
		
		
		setTimeout(function(){
			feature.removeClass().addClass("video");
			//feature.css('height', 'auto');
			$(".video-js-box").width(size[0]+"px");
			$(".video-js-box", feature).fadeIn(EffectSpeed,Easing);
			try{
				// sometimes autoplay doesnt work
				document.getElementsByTagName("video")[0].player.play();
			}catch(x){}
		//	flyTo("#feature", {offset:-50, speed:EffectSpeed,Easing});
		},1000);
	}
	
	$("body").delegate('.thumb','click',function(e){
	
		var _this = $(this), action = function(){};
		
		if(_this.is('.selected')) return;
		
		select_thumb(_this);
		
		if(_this.is('.film')){
			action = function(){ 
				feature.removeClass().addClass('video');
				showVideo(  feature, _this.attr('data-asset') ); 
			}
		}else if(_this.is('.single')){
			action = function(){
				feature.removeClass().addClass('image');
				showFeature('image',  _this.attr('src').replace('thumb.jpg','feature.jpg')) 
			};
		}else{
			action = function(){
					feature.removeClass().addClass('gallery');
					feature.gallery('select', function(item){
						return item.item.asset == _this.attr('data-asset');
					});
			};
			/*if(feature.is('.video')){
				$("#feature .video-js-box").fadeOut(EffectSpeed,Easing,function(){
					$(this).remove();
					//_this.addClass('selected').fadeTo(EffectSpeed, 0.5, Easing);
					feature.removeClass().addClass('gallery').gallery('show');
					feature.gallery('select', function(item){
						return item.item.asset == _this.attr('data-asset');
					});
				});
			}else if(feature.is('.gallery')){
				// img clicked, move gallery to index
				feature.gallery('select', function(item){
					return item.item.asset == _this.attr('data-asset');
				});
			}else if(feature.is('.image')){
					showFeature('image',  _this.attr('src').replace('thumb.jpg','feature.jpg'));
			}*/
		}
		
		
		if(feature.is('.gallery')){
			if(_this.is('.film') || _this.is('.single')){
				feature.gallery('hide',action);
			}else
				action();
		}else if(feature.is('.video')){
			$("#feature .video-js-box").fadeOut(EffectSpeed,Easing,function(){
				$(this).remove();
				action();
			});
		}else if(feature.is('.image')){
			feature.find('img.single').fadeOut(EffectSpeed,Easing,action);
		}
	});
	
	function flyTo(el, settings, complete){
		settings = $.extend({speed : 2100, offset: 0},settings || {});
		var y = $(el).offset().top + settings.offset;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: y}, settings.speed, complete);
	}
	
	function calcScale( w,h, mw, mh ){
		var sx = w / mw,
			  sy = h / mh,
			  m = Math.max(sx,sy);
		
		if( m > 0 ){
			m = 1/m;
		}
		return m;
	}
	
	function resizeFeature(){
		// 47 px is the size of the nav text
		//var offeset = 47;
		var offeset = -50;
		feature
			.css('height',  (($(window).height() /2 ) - offeset)  + 'px')
			.css('min-height',  (($(window).height() /2) - offeset) + 'px');
	}
	
	resizeFeature();

	
	$("#feature img").live("mouseover mouseout", function(event) {
		var _this= $(this),
			cfg = _this.data('infinate_config') || {};
		if(!cfg || !cfg.item.type == 'showcase')
			return false;
		//cfg.tooltip = "<h2>TEst</h2><p>THISISISIASD as sdsd s fdfgh AASDasda  asddas asdasdasd asasdasd asd</p><p>asdsadasd sadasd asd a dasd ada</p>";
		if ( event.type == "mouseover" ) {
			$("#tooltip").html(cfg.item.tooltip||"").show();
		} else {
			$("#tooltip").hide();
		}
	});
	
	
	
	
	
	function resize(){
	
		resizeFeature();
		
		
		
		if(feature.is('.video')){
			// only support resize on html5 video, this is mainly for ipad orientation change
			var video = $("video");
			 var size = getVideoSize();
			 video[0].width = size[0];
			 video[0].height = size[1];
			 $(".video-js-box").css( "width", size[0]+"px" );
		}else if(feature.is('.gallery')){
			feature.gallery('resize');
		}else if(feature.is('.image')){
			var img = feature.find('img.single');
			img.resizeImage({scale: calcScale( img.attr('data-original-width'), img.attr('data-original-height'), feature.width(), feature.height() )});
		}
	}
	$(window).resize(resize);
	window.onorientationchange = resize;
});

///https://raw.github.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.js

/*!
 * jQuery UI Touch Punch 0.1.0
 *
 * Copyright 2010, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function ($) {

  $.support.touch = 'ontouchend' in document;

  if (!$.support.touch) {
    return;
  }

  var mouseProto  = $.ui.mouse.prototype,
      _mouseInit  = mouseProto._mouseInit,
      _mouseDown  = mouseProto._mouseDown,
      _mouseUp    = mouseProto._mouseUp,

      mouseEvents = {
        touchstart: 'mousedown',
        touchmove:  'mousemove',
        touchend:   'mouseup'
      };

  function makeMouseEvent (event) {

    var touch = event.originalEvent.changedTouches[0];

    return $.extend(event, {
      type:    mouseEvents[event.type],
      which:   1,
      pageX:   touch.pageX,
      pageY:   touch.pageY,
      screenX: touch.screenX,
      screenY: touch.screenY,
      clientX: touch.clientX,
      clientY: touch.clientY
    });
  }

  mouseProto._mouseInit = function () {

    var self = this;

    self.element.bind('touchstart.' + self.widgetName, function (event) {
      return self._mouseDown(makeMouseEvent(event));
    });

    _mouseInit.call(self);
  };

  mouseProto._mouseDown = function (event) {

    var self = this,
        ret  = _mouseDown.call(self, event);

    self._touchMoveDelegate = function (event) {
      return self._mouseMove(makeMouseEvent(event));
    };
    
    self._touchEndDelegate = function(event) {
      return self._mouseUp(makeMouseEvent(event));
    };

    $(document)
      .bind('touchmove.' + self.widgetName, self._touchMoveDelegate)
      .bind('touchend.' + self.widgetName, self._touchEndDelegate);

    return ret;
  };

  mouseProto._mouseUp = function (event) {

    var self = this;

    $(document)
      .unbind('touchmove.' + self.widgetName, self._touchMoveDelegate)
      .unbind('touchend.' + self.widgetName, self._touchEndDelegate);

    return _mouseUp.call(self, event);
  };

})(jQuery);
