/* Author: Coordinate

*/

(function($){
	
	//$.fn.slider = function() {
//		$.inAnimation = false;
//		
//		$(window).bind("load", function(){
//			if ($('#featuredImg .slide').length == 0)
//			$('#featuredImg .slide:first').addClass('activeslide');
//			$('#featuredImg .slide:last').addClass('prevslide');
//		});
//	};
//	
//	//Randomise the photo order
//	$.fn.shuffle = function() {
//		return this.each(function(){
//			var items = $(this).children().clone(true);
//			return (items.length) ? $(this).html($.shuffle(items)) : this;
//		});
//	}
//	
//	$.shuffle = function(arr) {
//		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
//		return arr;
//	}
//	
//	$('#mask').shuffle().slider();
	
//		$('#featuredImg .slide').find('img').clone().prependTo('.slide');
		$('.menu-header ul li:first').addClass('first');
		$('#contentArea article:first').addClass('first');
		
			//$('#featuredImg').find('img').clone().prependTo('#featuredImg');
//			$('#featuredImg img:first').pixastic("desaturate");
//			
//			$('#featuredImg canvas').hover(function() {
//				$(this).stop().fadeTo(250, 0.5);
//			}, function() {
//				$(this).stop().fadeTo(250, 1);
//			});	
				
		$('.subMenu a').click(function() {
			$('.subMenu').find('a.current').removeClass('current');
			$(this).addClass('current');
		});
	
	
	
	//Set Twitter feed
	
	$.getJSON('http://twitter.com/status/user_timeline/contentgroup.json?count=3&callback=?', function(data){
		$.each(data, function(index, item){
			$('.home #twitter').append('<div class="tweet"><p>' + item.text.linkify() + '<br /><span>' + relative_time(item.created_at) + '</span></p></div>');
			$('.home #twitter a').attr('target', '_blank');
		});
	
	});
	
	//Set relative time e.g. posted 2 hours ago
	function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
		r = 'a minute ago';
	  } else if(delta < 120) {
		r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
		r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
		r = '1 day ago';
	  } else {
		r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  
	  return r;
	}
	
	//Turn tweeted links into links
	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
			return m.link(m);
		});
	};
	
	var placeholder = $('#mainContainer');
	var view = $(window);
	
	function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
	
	view.bind('scroll resize', function() {
		var placeholderTop = placeholder.offset().top;
		var viewTop = view.scrollTop();
		if ($.browser.msie && $.browser.version.substr(0,1)<8 || isiPhone()) {
			
		} else {

		if ( (viewTop > placeholderTop) ) {
			$('.hasSubs #headerBar, .hasSubs #leftCol, .hasSubs #contentArea').addClass('fixed');	
		} else {
			$('.hasSubs #headerBar, .hasSubs #leftCol, .hasSubs #contentArea').removeClass('fixed');
		}
		}
	});
	
	$('.topLink').removeAttr('href');
	$('.topLink').click(function(){
		$('html, body').animate({scrollTop:0}, 400);
		$('.subMenu').find('a.current').removeClass('current');
	});

	
	
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');
	
	$('.subMenu a:first').addClass('first');
  	
	$('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        
        $(this).click(function(event) {
		var targetOffset = $target.offset().top;
          event.preventDefault();
		  	var placeholderTop = placeholder.offset().top;
			var viewTop = view.scrollTop();
			
			if ( (viewTop > placeholderTop) || !$(this).hasClass('first')) {
				 $(scrollElem).animate({scrollTop: targetOffset - 45}, 400, function() {
					//location.hash = target - 60;
				  });	
			} else {
				$(scrollElem).animate({scrollTop: targetOffset - 92}, 400, function() {
					//location.hash = target - 60;
				  });
			}
			
        });
      }
    }
	
});  

  $.fn.slider = function() {
		$.inAnimation = false;
		
		$(window).bind("load", function(){
			//$('#featuredInfo').animate({bottom : '-40px'}, 250);
			if ($('#slideshow .activeslide').length == 0)
			$('#slides .slide:first').addClass('activeslide');
			$('#infoHeadings h2:first').addClass('activeslide');
			$('#thumbs a:first').addClass('activeslide');
			slideshow_interval = setInterval("nextslide()", 5000);
		});
	};
	
	//Randomise the photo order
	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}

	
	$('#featuredImg').slider();
	
	//$('#featuredContainer').hover(function() {
//		$('#featuredInfo').stop().animate({bottom : 0}, 250);
//	}, function() {
//		$('#featuredInfo').stop().animate({bottom : '-40px'}, 250);
//	});


})(jQuery)

	

	// use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }
  
  $.event.special.load = {
add: function (hollaback) {
if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
// Image is already complete, fire the hollaback (fixes browser issues were cached
// images isn't triggering the load event)
if ( this.complete || this.readyState === 4 ) {
hollaback.handler.apply(this);
}

// Check if data URI images is supported, fire 'error' event if not
else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
$(this).trigger('error');
}

else {
$(this).bind('load', hollaback.handler);
}
}
}
};

//Slideshow Next Slide
	function nextslide() {
		if($.inAnimation) return false;
		else $.inAnimation = true;
	    var currentslide = $('#slides .activeslide');
		var currenttitle = $('#infoHeadings .activeslide');
		var currentThumb = $('#thumbs .activeslide');
	    currentslide.removeClass('activeslide');
		currenttitle.removeClass('activeslide');
		currentThumb.removeClass('activeslide');
		
		if ( currentslide.length == 0 ) currentslide = $('#slides .slide:last');
		if ( currenttitle.length == 0 ) currenttitle = $('#infoHeadings h2:last');
		if ( currentThumb.length == 0 ) currentThumb = $('#thumbs a:last');
			
	    var nextslide =  currentslide.next().length ? currentslide.next() : $('#slides .slide:first');
		var nexttitle =  currenttitle.next().length ? currenttitle.next() : $('#infoHeadings h2:first');
		var nextThumb =  currentThumb.next().length ? currentThumb.next() : $('#thumbs a:first');
	    var prevslide =  nextslide.prev().length ? nextslide.prev() : $('#slides .slide:last');
		var prevtitle =  nexttitle.prev().length ? nexttitle.prev() : $('#infoHeadings h2:last');
		var prevThumb =  nextThumb.prev().length ? nextThumb.prev() : $('#thumbs a:last');
		
		$('#slides .prevslide').removeClass('prevslide');
		$('#infoHeadings .prevslide').removeClass('prevslide');
		$('#thumbs .prevslide').removeClass('prevslide');
		prevslide.addClass('prevslide');
		prevtitle.addClass('prevslide');
		prevThumb.addClass('prevslide');
		
	    nextslide.hide().addClass('activeslide')
		nexttitle.hide().addClass('activeslide')
		nextThumb.addClass('activeslide')
	    nextslide.fadeIn(750, function(){$.inAnimation = false;});
		nexttitle.fadeIn(750, function(){$.inAnimation = false;});
	    
	}
	
	function getThumbs() {
		$('#featuredInfo').append('<div id="thumbs">');
		$('#slides .slide').each(function (i) {
			var i = i+1;
			var slideNo = 'slide' + i;
			$(this).addClass(slideNo);
			$('#thumbs').append('<a>' + i + '</a>');
		});
		$('#infoHeadings h2').each(function (i) {
			var i = i+1;
			var slideNo = 'slide' + i;
			$(this).addClass(slideNo);
		});
	};
	getThumbs();
	
	//Thumbs click function
	$('#thumbs a').each(function (i) {
		var i = i+1;
		var slideNo = 'slide' + i;
		$(this).attr('class', slideNo);
			
		$('#thumbs .' + slideNo).click(function() {
			if ($(this).hasClass('activeslide')) {
				return false;
			}
			
			if($.inAnimation) return false;
			else $.inAnimation = true;
			var currentslide = $('#slides .activeslide');
			var currenttitle = $('#infoHeadings .activeslide');
			var currentThumb = $('#thumbs .activeslide');
			currentslide.removeClass('activeslide');
			currenttitle.removeClass('activeslide');
			currentThumb.removeClass('activeslide');
			
			if ( currentslide.length == 0 ) currentslide = $('#slides .slide:last');
			if ( currenttitle.length == 0 ) currenttitle = $('#infoHeadings h2:last');
			if ( currentThumb.length == 0 ) currentThumb = $('#thumbs a:last');
					
			var nextslide =  currentslide.next().length ? currentslide.next() : $('#slides .slide:first');
			var nexttitle =  currenttitle.next().length ? currenttitle.next() : $('#infoHeadings h2:first');
			var nextThumb =  currentThumb.next().length ? currentThumb.next() : $('#thumbs a:first');
			var prevslide =  nextslide.prev().length ? nextslide.prev() : $('#slides .slide:last');
			var prevtitle =  nexttitle.prev().length ? nexttitle.prev() : $('#infoHeadings h2:last');
			var prevThumb =  nextThumb.prev().length ? nextThumb.prev() : $('#thumbs a:last');
			
			$('#slides .prevslide').removeClass('prevslide');
			$('#infoHeadings .prevslide').removeClass('prevslide');
			$('#thumbs .prevslide').removeClass('prevslide');
			prevslide.addClass('prevslide');
			prevtitle.addClass('prevslide');
			prevThumb.addClass('prevslide');
			
			$('#slides .' + slideNo).hide().addClass('activeslide');
			$('#infoHeadings .' + slideNo).hide().addClass('activeslide');
			$('#slides .' + slideNo).fadeIn(750, function() {
				$.inAnimation = false;
			});	
			$('#infoHeadings .' + slideNo).fadeIn(750, function() {
				$.inAnimation = false;
			});
			
			clearInterval(slideshow_interval);
			slideshow_interval = setInterval("nextslide()", 5000);
			
			$(this).addClass('activeslide');
		});
	});
