// =============
// = Functions =
// =============

// VERTICAL ALIGN
$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = Math.ceil((ph-ah) / 2);
	$(this).css('margin-top', mh);
	});
};

// ======================
// = Sea of clouds tweet =
// ======================
(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: ["seaofclouds"],                // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      list: null,                               // [string]   optional name of list belonging to username
      avatar_size: null,                        // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                                 // [integer]  how many tweets to display?
      intro_text: null,                         // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                         // [string]   do you want text AFTER your tweets?
      join_text:  null,                         // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",        // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                   // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",               // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",     // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at",   // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                       // [string]   optional loading text, displayed while tweets load
      query: null,                              // [string]   optional search query
      refresh_interval: null ,                  // [integer]  optional number of seconds after which to reload tweets
      twitter_url: "twitter.com",               // [string]   custom twitter url, if any (apigee, etc.)
      twitter_api_url: "api.twitter.com",       // [string]   custom twitter api url, if any (apigee, etc.)
      twitter_search_url: "search.twitter.com"  // [string]   custom twitter search url, if any (apigee, etc.)
    };
    
    if(o) $.extend(s, o);
    
    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        // See http://daringfireball.net/2010/07/improved_regex_for_matching_urls
        var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?гхрсту]))/gi;
        this.each(function() {
          returning.push(this.replace(regexp,
                                      function(match) {
                                        var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
                                        return "<a href=\""+url+"\">"+match+"</a>";
                                      }));
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://"+s.twitter_url+"/$1\">@$1</a>"));        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://'+s.twitter_search_url+'/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'">#$1</a>'));
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'));
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(epic)\b/gi, '<span class="epic">$1</span>'));
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>"));
        });
        return $(returning);
      }
    });

    function parse_date(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

    function relative_time(time_value) {
      var parsed_date = parse_date(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      var r = '';
      if (delta < 60) {
	r = delta + ' seconds ago';
      } else if(delta < 120) {
	r = 'a minute ago';
      } else if(delta < (45*60)) {
	r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
      } else if(delta < (2*60*60)) {
	r = 'an hour ago';
      } else if(delta < (24*60*60)) {
	r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
	r = 'a day ago';
      } else {
	r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
      }
      return 'about ' + r;
    }

    function build_url() {
      var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
      if (s.list) {
        return proto+"//"+s.twitter_api_url+"/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+s.count+"&callback=?";
      } else if (s.query == null && s.username.length == 1) {
        return proto+'//'+s.twitter_api_url+'/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+s.count+'&include_rts=1&callback=?';
      } else {
        var query = (s.query || 'from:'+s.username.join(' OR from:'));
        return proto+'//'+s.twitter_search_url+'/search.json?&q='+encodeURIComponent(query)+'&rpp='+s.count+'&callback=?';
      }
    }

    return this.each(function(i, widget){
      var list = $('<div class="tweet_list">').appendTo(widget);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>';
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>';
      var loading = $('<p class="loading">'+s.loading_text+'</p>');

      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }

      if (s.loading_text) $(widget).append(loading);
      $(widget).bind("load", function(){
        $.getJSON(build_url(), function(data){
          if (s.loading_text) loading.remove();
          if (s.intro_text) list.before(intro);
          list.empty();
          var tweets = (data.results || data);
          $.each(tweets, function(i,item){
            // auto join text based on verb tense and content
            if (s.join_text == "auto") {
              if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
                var join_text = s.auto_join_text_reply;
              } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
                var join_text = s.auto_join_text_url;
              } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
                var join_text = s.auto_join_text_ed;
              } else if (item.text.match(/^(\w*ing) .*/i)) {
                var join_text = s.auto_join_text_ing;
              } else {
                var join_text = s.auto_join_text_default;
              }
            } else {
              var join_text = s.join_text;
            };
   
            var from_user = item.from_user || item.user.screen_name;
            var profile_image_url = item.profile_image_url || item.user.profile_image_url;
            var join_template = '<span class="tweet_join"> '+join_text+' </span>';
            var join = ((s.join_text) ? join_template : ' ');
            var avatar_template = '<a class="tweet_avatar" href="http://'+s.twitter_url+'/'+from_user+'"><img src="'+profile_image_url+'" height="'+s.avatar_size+'" width="'+s.avatar_size+'" alt="'+from_user+'\'s avatar" title="'+from_user+'\'s avatar" border="0"/></a>';
            var avatar = (s.avatar_size ? avatar_template : '');
            var date = '<span class="tweet_time"><a href="http://'+s.twitter_url+'/'+from_user+'/statuses/'+item.id_str+'" title="view tweet on twitter">'+relative_time(item.created_at)+'</a></span>';
            var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
   
            // until we create a template option, arrange the items below to alter a tweet's display.
            list.append('<p>' + avatar + join + text + '<br/>' + date + '</p>');
   
            list.children('p:first').addClass('tweet_first');
            list.children('p:odd').addClass('tweet_even');
            list.children('p:even').addClass('tweet_odd');
          });
          if (s.outro_text) list.after(outro);
          $(widget).trigger("loaded").trigger((tweets.length == 0 ? "empty" : "full"));
          if (s.refresh_interval) {
            window.setTimeout(function() { $(widget).trigger("load"); }, 1000 * s.refresh_interval);
          };
        });
      }).trigger("load");
    });
  };
})(jQuery);






$('.left .info img').vAlign();

// ================
// = Pseudo Fixes =
// ================

$('.base li:nth-child(3n+1)').addClass('clr');
$('.people li:nth-child(2n+1)').addClass('clr');
$('.ie .sub-nav li:last-child').addClass('last');

// ==============
// = Google Map =
// ==============

// Set the gmap background colour to the same as the background of the map, this has to be done with jquery because google sets it themself

$('.gmap').css({'background-color': '#ebe6dc !important'})

// First click on the link .find will load the googlemap

$('.find a').one("click" , function() {
	var centerPoint = new google.maps.LatLng(51.384777,-2.359599);
	var gmap = new google.maps.Map(document.getElementById('gmap'), {
		zoom: 16,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: centerPoint,
		panControl: false,
		zoomControl: false,
		mapTypeControl: false,
		scaleControl: false,
		streetViewControl: false,
		overviewMapControl: false
	});
	
	//Marker
	var marker = new google.maps.Marker({
		map: gmap,
		position: new google.maps.LatLng(51.3844,-2.363221),
		title: "The House",
		icon: '/images/assets/map-marker.png'
	});
});

//Show/Hide 

$('.find a').click(function() {
	$('.map').animate({ height: 'toggle'});
	$(this).toggleClass('active');
	return false;
});


// ================
// = Modal Window =
// ================

$('a.popup[href^=#]').click(function() {
	var popID = $(this).attr('rel'); //Get Popup Name
	var popURL = $(this).attr('href'); //Get Popup href to define size
	
	//Pull Query & Variables from href URL
	var query= popURL.split('?');
	var dim= query[1].split('&');
	var popWidth = dim[0].split('=')[1]; //Gets the first query string value
	
	//Fade in the Popup and add close button
	$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close bol">Close</a>');
	
	//Define margin for center alignment
	var popMargTop = ($('#' + popID).height() + 200) / 2; // Top/Bottom
	var popMargLeft = ($('#' + popID).width() + 60) / 2; // Left/Right
	
	//Apply Margin to Popup
	$('#' + popID).css({
		'margin-top' : -popMargTop,
		'margin-left' : -popMargLeft
	});
	
	//Fade in Background
	$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
	$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
	
	return false;
});

//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
	$('#fade , .popup-block').fadeOut(function() {
        stopAllVideos();
		$('#fade, a.close').remove();  //fade them both out
	});
	return false;
});

$(document).keyup(function(e) {
	if (e.keyCode == 27) { // 27 is the escape key
	$('#fade , .popup-block').fadeOut(function() {
       stopAllVideos();
	   $('#fade, a.close').remove();  //fade them both out
	});
  }
});


// ===========
// = Twitter =
// ===========

$(".tweet").tweet({
	username: "thehouse_bath",
	avatar_size: 0,
	count: 3,
	loading_text: "Loading tweets..."
});





// ===================
// = Homepage Slider =
// ===================

if($(".slider").length > 0){
	$(document).ready(function(){
		
		/*
		 * Collect nodes
		 */
		var $slider			= $("#sliderWrapper");
		var $sliderList 	= $("#sliderList");
		var $sliderItems	= $sliderList.find("li");
		var $upBtn			= $("#upBtn");
		var $downBtn		= $("#downBtn");
		var $sliderCaption	= $("#sliderCaption");
		
		/*
		 * State variables
		 */
		var $allItems	 	= $sliderList.find("li");
		var totalItems 		= $sliderItems.length;
		var currentItem 	= $allItems.length - 6 + 3;
		var nextItem 		= $allItems.length - 6 + 3;
		var animating		= false;
		
		/*
		 * Settings
		 */
		var itemHeight			= 82;
		var defaultListOffset 	= -82;
		var autoplay			= true;
		
		initUI();
		initEvents();
		autoPlayControl();
		
		
		
		
		function initUI () {
			
			/*
			 * Prepare List items
				Needs to:
					- Prepend the last item to the top of the stack
					- Shift the list up to hide the last item at the top
					- Remove all unnecessary items from the stack
			 */
			$sliderList.prepend($allItems.eq(totalItems-1))
			
			
			//If there are more than 6 items
			if($allItems.length > 6){
				for(var i = $allItems.length; i > 6; i--){
					$sliderList.prepend($allItems.eq(i-1))
				}
				
				defaultListOffset = -1*($allItems.length-6)*itemHeight;
				$sliderList.css("top", defaultListOffset);
				
			}
			
			
			
			
			//Reset the list
			$sliderItems = $slider.find("li")
			
			
			$sliderItems.each(function(i, node){
				$(node).data("position", i);
			})
			
		}
		
		function initEvents () {
			$upBtn.click(function(evt){
				if(!animating){
					evt.preventDefault()
					autoplay = false;
					animating = true;
				
					nextItem--;
					_slide();
				}
			})
			$downBtn.click(function(evt){
				if(!animating){
					evt.preventDefault()
					autoplay = false;
					animating = true;
				
					nextItem++;
					_slide();
				}
			})
			$sliderItems.click(function(evt){
				if(!animating && !$(this).hasClass("featured")){
					evt.preventDefault()
					autoplay = false;
					animating = true;
				
					nextItem = $(this).data("position");
					_slide();
				}
			})
		}
		
		
		function autoPlayControl() {
			if(autoplay){
				
				setTimeout(function(){
					if(autoplay){
						animating = true;
					
						nextItem++;
						_slide();
					}
				}, 6000)
				
				
			}
		}
		
		
		function _slide () {
			var d = (nextItem - currentItem)*-1;
			_setFocus(d);
			
			if(d > 0){
				//Slide Down
				$sliderList.animate({
					top: parseInt($sliderList.css("top")) + itemHeight * d
				}, 500, function(){
					_resetSlider(d)
				});
			}else{
				//Slide Up
				$sliderList.animate({
					top: parseInt($sliderList.css("top")) + itemHeight * d
				}, 500, function(){
					_resetSlider(d)
				});
			}

		}
		
		
		var first = true;
		function _resetSlider (direction) {
			var a;


			//Depending on direction, we need to rearrange the first of last items
			if(direction > 0){
				
				for(var i = 0; i < ((direction*direction)/direction); i++){
					//Slide Down
					a = $sliderList.find("li").eq(totalItems-1).detach();
					$sliderList.prepend(a);
				}
				
				$sliderList.css("top", defaultListOffset) // Reset the position of the list item
				
				//Reset the slider items
				$sliderItems = $slider.find("li")
			}else{
				
				//Slide Up
				a = $sliderItems.eq(0).detach()
				
				$sliderList.css("top", defaultListOffset) // Reset the position of the list item
				$sliderList.append(a);
				
				//Reset the slider items
				$sliderItems = $slider.find("li")
			}
			
			//Reset the counts
			$sliderItems.each(function(i, node){
				$(node).data("position", i)
			})
			
			animating = false
			currentItem = nextItem = $allItems.length - 6 + 3;
			autoPlayControl();
		}
		
		
		
		function _setFocus (direction) {
			var old = $slider.find("li.featured").removeClass("featured");
			var $newItem;
			
			if(direction > 0){
				if(direction == 1){
					$newItem = old.prev().addClass("featured")
				}
				if(direction == 2){
					$newItem = old.prev().prev().addClass("featured")
				}
				if(direction == 3){
					$newItem = old.prev().prev().prev().addClass("featured")
				}
				
			}else{
				$newItem = old.next().addClass("featured")
			}
			
			/*
			 * Caption
			 */
			$sliderCaption.animate({
				right: 250,
				opacity: 0
			}, 200, function(){
				$sliderCaption.find("h1 a").html($newItem.find("h3").html()).attr("href", $newItem.find("a").attr("href"))
				
				$sliderCaption.find("a.link").text($newItem.find("p.subheading").text()).attr("href", $newItem.find("a").attr("href"))
				
				
	
				$sliderCaption.animate({
					right: 318,
					opacity: 1
				}, 300)
			})
			
			/*
			 * Hero Image
			 */
			var oldHero = $slider.find("img.slide").css("zIndex", 1);
			var newHero = $("<img/>").attr("src", $newItem.find("img.heroImage").attr("src")).addClass("slide").css("zIndex", 0);
			oldHero.after(newHero)
			oldHero.fadeOut(500, function(){
				$(this).remove();
			})
			
		}
	})
}

// ==========
// = Flickr =
// ==========

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?ids=64706285@N03&lang=en-us&format=json&jsoncallback=?", function(data){
	$.each(data.items, function(index, item){
		var imageurl = item.media.m;
		var imageth = imageurl.replace("_m.jpg", "_s.jpg");
		
		$("<img/>").attr("src", imageth).appendTo("#flickr")
		.wrap("<a href='" + item.link + "' target='_blank'></a>");
		if (index == 5) return false;
	});
});


// ============
// = Video.js =
// ============

VideoJS.setupAllWhenReady();

// ============================
// = Case studies image popup =
// ============================

$('.right .popup span').hide();

$('.right .popup').hover(function(){
	$(this).children('span').slideToggle();
});


// ==================================
// = YouTube Video Embed
// ==================================
if(typeof videos !== 'undefined' && videos.length > 0 ){

    //Embed the YouTube player API
    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


    
}

function onYouTubePlayerAPIReady() {
    for(var i = 0; i < videos.length; i++){
        var player;
        
        player = new YT.Player(videos[i].node, {
            height: '349',
            width: '560',
            videoId: videos[i].id
        });
        
        videos[i].player = player; 
    }
}

function stopAllVideos() {
    if(typeof videos !== 'undefined' && videos.length > 0 ){
        for(var i=0;i < videos.length; i++){
            if( ! videos[i].player ) continue;
            
            //videos[i].player.seekTo(0,true);
            videos[i].player.stopVideo();
        }
    }
}

