/**
 * jQuery.Preload - Multifunctional preloader
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/25/2009
 * @author Ariel Flesler
 * @version 1.0.8
 */
;(function($){var h=$.preload=function(c,d){if(c.split)c=$(c);d=$.extend({},h.defaults,d);var f=$.map(c,function(a){if(!a)return;if(a.split)return d.base+a+d.ext;var b=a.src||a.href;if(typeof d.placeholder=='string'&&a.src)a.src=d.placeholder;if(b&&d.find)b=b.replace(d.find,d.replace);return b||null}),data={loaded:0,failed:0,next:0,done:0,total:f.length};if(!data.total)return finish();var g=$(Array(d.threshold+1).join('<img/>')).load(handler).error(handler).bind('abort',handler).each(fetch);function handler(e){data.element=this;data.found=e.type=='load';data.image=this.src;data.index=this.index;var a=data.original=c[this.index];data[data.found?'loaded':'failed']++;data.done++;if(d.enforceCache)h.cache.push($('<img/>').attr('src',data.image)[0]);if(d.placeholder&&a.src)a.src=data.found?data.image:d.notFound||a.src;if(d.onComplete)d.onComplete(data);if(data.done<data.total)fetch(0,this);else{if(g&&g.unbind)g.unbind('load').unbind('error').unbind('abort');g=null;finish()}};function fetch(i,a,b){if(a.attachEvent&&data.next&&data.next%h.gap==0&&!b){setTimeout(function(){fetch(i,a,1)},0);return!1}if(data.next==data.total)return!1;a.index=data.next;a.src=f[data.next++];if(d.onRequest){data.index=a.index;data.element=a;data.image=a.src;data.original=c[data.next-1];d.onRequest(data)}};function finish(){if(d.onFinish)d.onFinish(data)}};h.gap=14;h.cache=[];h.defaults={threshold:2,base:'',ext:'',replace:''};$.fn.preload=function(a){h(this,a);return this}})(jQuery);

jQuery.fn.animateIcons = function(options) {
	
    var settings = $.extend({}, jQuery.fn.animateIcons.defaults, options);
    var $this = $(this);
    var row = $this.data('row');
	
    if(!row)
    {
        row = 1;
    }
	
    var timeout = (row == 7 ? 3000 : 300);
    var cnt = (row > 4 ? 8 - row : row);
    var start = (row > 4 ? row - 4 : 0);
	
    for (i = 0; i < cnt; i++) {
        $('.stage' + (row + ((i + start) * 3)) + ' img').animate({opacity: 1},300,'easeInCirc');
    }
	
    if (row++ >= 7) {
		$('.icon-tree').fadeTo(10000, 1, function(){
			$('.icon-tree').fadeTo(1000, 0.01, function(){
				$('.icon-tree img').animate({opacity: 0.01},1,function() {
					$('.icon-tree').fadeTo(1, 1);
					var img = $(this);
					if (img.attr('src').substring(img.attr('src').length - 5) == 'b.gif') {
						img.attr('src', img.attr('src').replace (/b.gif$/, '.gif'));
					}
					else {
						img.attr('src', img.attr('src').replace (/.gif$/, 'b.gif'));
					}
				});
				$this.data('row', 1);
				setTimeout("$('.icon-tree').animateIcons()", 300);
			});
		});
    }
	else {
		$this.data('row', row);
		setTimeout("$('.icon-tree').animateIcons()", timeout);
	}
}

$(function(){
	
	// services page decoration - hide then animate
	$('.services #feature .icon-tree').css('display', 'none');
	$('.icon-tree img').animate({opacity: 0.01},1,function() {
		$('.icon-tree').show();
	});
	setTimeout("$('.icon-tree').animateIcons()",1000);
	
	$(".home #feature li").css('top', '-300px');
	// append elements to DOM so we can animate bits
	//$('.home #summary-container').before('<span class="loading">&nbsp;</span><img src="/media/images/img-mask.png" class="mask" />');
	//$('.work #summary-container #feature img').before('<span class="loading">&nbsp;</span>');
	$('.home #summary-container').before('<img src="/media/images/img-mask.png" class="mask" />');
	$(".home #feature .controls span").after('<a class="info" href="#none"><img src="/media/images/btn-info.png" alt="more" width="54" height="29" /></a>');
	
	// make call to inital animation.
	animateFeatureIn(1, 1500); // was 2500
	
	// on every .control link thats not an info button animate feature to show case study
	$('.controls a:not(.info)').click(function() {
		var rel = $(this).attr('rel');	
		// slide out all previously show features
		animateFeatureOut();
		// give it a sec (0.3 of a sec to be exact) then animate the next one in.
		$(this).oneTime(300, function() {
			animateFeatureIn(rel,300); // was 1000		  
		});
		$(this).blur();
		// give the number link an active class
		$(this).addClass('current');
		return false;
	}).attr('href', '#none');

	// on the info button animate the info
	$('.info').click(function() {
		animateInfo();
		$(this).blur();
		return false;
	});
	
	$('#project-gallery .active img').fadeTo(1,0.50);
	bindGalleryHovers();
	
	// projects click functionality
	$('#project-gallery a').click(function() {

		$(this).blur();
		if(!$(this).hasClass('active'))
		{
			
			// reset defaults
			$('#project-gallery .active').removeClass('active');
			$(this).addClass('active');
			resetGalleryHovers();
			
			var rel = $(this).attr('rel');
			bindGalleryHovers();
		
			$('#feature img').fadeTo('fast',0.01,function() {
				
				//$('.loading').show();
				$(this).attr('src', rel);	
				$(this).load(function() {
					//$('.loading').hide();
					$(this).fadeTo('fast',1);					   
				});
			})
			
		}
		return false;
	});
	
	// News ajax functionality
	$('.news #content li a').click( function() {
		$('li.highlight').removeClass('highlight');
		$(this).parent().parent().addClass('highlight');
		$.getJSON('/news/json/' + $(this).attr('rel') + '/', '', function(data) {
			if (data.article != null) {
				$('#feature').fadeOut('normal', function() {
					if (data.imageurl != null) {
						var img = new Image();
						$(img).load(function () {
							$('#feature').html(data.article).prepend(this);
							$('#feature').fadeIn();
						})
						.attr('src', data.imageurl)
						.error( function() {
							$('#feature').html(data.article);
							$('#feature').fadeIn();
						});
					}
					else {
						$('#feature').html(data.article);
						$('#feature').fadeIn();
					}
				});
				document.title = data.title;
			}
		});
		return false;
	});
	
	$('#frm-directions').submit(function(){
		usePointFromPostcode(this.postcode.value, setDirections);
		return false;
	});
	
	$('#frm-contact').submit(function(){
		pageTracker._trackPageview('/contactform/');
	});


	// Safari bugfix required
	$('.about #feature a, .about #feature li:not(.expanded) .thumb').live('click', function(){
		var detail = $(this).parent('li');
		if ($(this).hasClass('close')) {
			if ($(this).hasClass('reset')) {
				return true;
			}
			$('.about #feature ul').fadeTo(300, 0.01, function(){
				$(this).fadeTo(100, 0.01, function(){
					detail.removeClass('expanded');
					detail.siblings('li').removeClass('collapsed');
					$(this).fadeTo(500, 1);
				});
			});
		}
		else {
			$('.about #feature ul').fadeTo(300, 0.01, function(){
				$(this).fadeTo(100, 0.01, function(){
					detail.addClass('expanded');
					detail.siblings('li').addClass('collapsed');
					$(this).fadeTo(500, 1);
				});
			});
		}
		return false;
	});
	
	// Soak Card Activation page
	
	if ($('#frm-prize').length > 0) {
		$.preload(['/media/images/soak-card/img-naked-wines-voucher.jpg']);
	}

	$('#frm-prize').submit(function(){

		$(this).ajaxSubmit({
			type: 'POST',
			url: '/media/card-submit.php',
			dataType: 'json',
			success: function(data, textStatus){
				
				if (data.errors) {
					if (data.errors.length) {
						if ($('#page-notes ul').length) {
							$('#page-notes ul').slideUp(function(){
								$('#page-notes ul').remove();
								html = '';
								for (var i = 0; i < data.errors.length; i++) {
									html += '<li>' + data.errors[i] + '</li>';
								}
								$('#page-notes').append('<ul class="errors">' + html + '</ul>');
							});
						}
						else {
						
							html = '';
							for (var i = 0; i < data.errors.length; i++) {
								html += '<li>' + data.errors[i] + '</li>';
							}
							$('#page-notes').append('<ul class="errors">' + html + '</ul>');
						}
					}	
				}
				else {
					if ($('#page-notes ul').length) {
						$('#page-notes ul').slideUp(function() {
							$(this).remove();
						});
					}
					
					if ($('#feature #voucher').length == 0) {
						$('#frm-prize').slideUp(function(){
							$(this).remove();
							$('#feature').append(data.html);
							$('#feature #voucher').slideDown();
						});
					}
				}
			}
		});
		
		return false;
	});

});

function resetGalleryHovers() {
	$('#project-gallery a:not(.active) img').fadeTo(1,1);
}

function bindGalleryHovers() {
	// projects hover functionality
	$('#project-gallery a').hover(function() {
		$(this).children('img').fadeTo(1,0.50);									   
	},
	function() {
		if(!$(this).hasClass('active'))
		{
			$(this).children('img').fadeTo(1,1);
		}
	});
}

var slideVisible = false;

function animateInfo()
{
	
	if(slideVisible)
	{
		slideVisible = false;
		$('.detail').animate({ 
			height: "0"
			}, 400,'easeInCirc'
		);	
		$('.info img').attr('src','/media/images/btn-info.png');
	}
	else
	{
		slideVisible = true;
		$('.detail').animate({ 
			height: "120px"
			}, 400,'easeOutCirc'
		);	
		$('.info img').attr('src','/media/images/btn-info-minus.png');
	}
	
}


// used on homepage
function animateFeatureIn(num,time) {
	//$('.home .loading').show();
	$(this).oneTime(time, function() {
		//$('.home .loading').hide();
		$(".home #feature li.feature"+num).animate({ 
        top: "70px"
     	}, 800,'easeOutBounce' );
	});	
}

// used on homepage
function animateFeatureOut() {
	
	if(slideVisible)
	{
		animateInfo();
	}
	$('p.controls .current').removeClass('current');
	$(".home #feature li").animate({ 
	top: "-400px"
	}, 300,function() {
		//$('.home .loading').show();
	});
	
}
