var talkDropdown = {
	init: function() {
		$('.opener').each(function() {
			$(this).click(function(event) {
				talkDropdown.toggle($(this).attr('id'),$(this).attr('href'));
				event.preventDefault();
			});
			if($('#error-message').text() == "") {
				talkDropdown.reset($(this).attr('href'));
			}
		});
	},
	reset: function(toggleable) {
		$('#error-message').hide();
		$(toggleable+' .width-container').hide();
	},
	toggle: function(opener,toggleable) {
		$(toggleable+' .width-container').slideToggle(400, function() {
			if($(this).css('display') == "block") {
				$('#'+opener).css('background-position', 'right -69px');
				$('html,body').animate({scrollTop:$(toggleable).position().top},400);
			}else{
				$('#'+opener).css('background-position', 'right 0');
			}
		});
	}
};

var workShowcase = {
	showcaseObj: {},
	currentShowcase: "",
	init: function() {
		if($('.work-container .work-nav').size() > 0) {
			// Loop through showcase nav
			$('.work-container .work-nav A').each(function() {
			
				// Calculate ID
				var showcaseId = ($(this).attr('href')).replace('#','');
	
				// Hide the showcase by default
				$($(this).attr('href')).hide();
				
				// Add 'onclick' event handler to nav to switch showcases 
				$(this).click(function(event) {
					event.preventDefault();
					workShowcase.show($(this).attr('href').replace('#',''));
					$('html,body').animate({scrollTop:$('.some-recent-work').position().top},400);
				});
				
				// Initalise image Array
				workShowcase.showcaseObj[showcaseId] = new Array();
				
				$('.work-container #'+showcaseId+' .image-slider LI').each(function() {
					workShowcase.showcaseObj[showcaseId].push(($(this).find('img').attr("src")));
				});
			});
						
			this.show($('.work-container .nav LI:first A').attr('href').replace('#',''));
		}
	},
	show: function(newShowcase) {
		if(this.currentShowcase != newShowcase) {
			for(var key in this.showcaseObj) {
				$('#'+key).hide();
				$('.work-container .work-nav LI').removeClass('selected');
			}
			
			$('.work-container .work-nav LI:has(A[href="#'+newShowcase+'"])').addClass('selected');
			$('#'+newShowcase).show();
			clientImages.init(newShowcase);
			this.currentShowcase = newShowcase;
		}
	}
};

var clientImages = {
	count: 0,
	timer: {},
	clientId: "",
	contentImg: [],
	currentSlide: 0,
	bgOnHex: "#ed1164",
	bgOffHex: "#989898",
	init: function(client) {
		this.reset();
		this.clientId = client;
		
		this.contentImg = workShowcase.showcaseObj[client];
		
		this.count = this.contentImg.length;

		$('#'+clientImages.clientId+" .image-slider .image LI:not(:first)").remove();

		this.generatePagination();
		
		$('#'+clientImages.clientId+" .image-slider .image IMG").load(function(responseText, textStatus, XMLHttpRequest) {
			$(this).fadeIn('normal');
		});
		
		$('#'+clientImages.clientId+" .image-slider .image IMG").error(function(i) {
			//TODO: do something if src is invalid
		});
		
		this.resetSlides();
		
		if(clientImages.count > 1) {
			this.autoStart();
		}
	},
	reset: function() {
		this.count = 0;
		clearTimeout(this.timer);
		this.clientId = "";
		this.contentImg = [];
		this.currentSlide = 0;
	},
	generatePagination: function() {
		if($('#'+clientImages.clientId+" .image-slider .inner .pagination").size() == 0) {
			$('#'+clientImages.clientId+" .image-slider .inner").append('<ol class="pagination"></ol>');
		
			for(var i=0; i<clientImages.count; i++) {
				$('#'+clientImages.clientId+" .image-slider .inner .pagination").append('<li><a href="#" onclick="clientImages.autoStop(); clientImages.changeSlide('+i+'); return false">'+(i+1)+'</a></li>');
			}
		}
		
		$('#'+clientImages.clientId+" .image-slider .inner .pagination LI:first A").css("backgroundColor", this.bgOnHex);
		$('#'+clientImages.clientId+" .image-slider .inner .pagination LI:not(:first) A").css("backgroundColor", this.bgOffHex);
	},
	resetSlides: function() {
		$('#'+clientImages.clientId+" .image-slider .image IMG").attr("src",clientImages.contentImg[0]);
		clientImages.changeNav(0);
	},
	changeSlide: function(i) {
		$('#'+clientImages.clientId+" .image-slider .image IMG").fadeOut("normal", function(){
			$(this).attr("src",clientImages.contentImg[i]);
			clientImages.changeNav(i);
		});
	},
	changeNav: function(i) {
		$('#'+clientImages.clientId+" .image-slider .inner .pagination LI:eq("+clientImages.currentSlide+") A").animate({
			"backgroundColor": clientImages.bgOffHex
		}, 100, "linear", function(){ 
			$('#'+clientImages.clientId+" .image-slider .inner .pagination LI:eq("+i+") A").animate({
				"backgroundColor": clientImages.bgOnHex
			}, 100, "linear", function() { clientImages.currentSlide = i; });
		});
	},
	nextSlide: function() {
		var nextSlideIndex = clientImages.currentSlide + 1;
		if(nextSlideIndex >= clientImages.count){ nextSlideIndex = 0; }
		clientImages.changeSlide(nextSlideIndex);
	},
	autoStart: function() {
		clientImages.timer = setTimeout("clientImages.nextSlide(); clientImages.autoStart();", 10000);
	},
	autoStop: function() { 
		clearTimeout(clientImages.timer);	
	}
};

/*
var latestThinking = {
	init: function() {
		$('div.our-latest-thinking OL.ordered-thinking > LI').each(function(inc) {
			var summary = new String($(this).find('div.copy p:first').text());

			var patt1=new RegExp("[\.\?\!]");

			firstPunct = (patt1.exec(summary));

			if(firstPunct){
				summary = summary.substr(0,summary.indexOf(firstPunct)+1);
			}
			
			$(this).find('div.description').before('<p class="summary">'+summary+' <a href="#" class="summariser">Read more</a></p>')
			$(this).find('div.copy').append('<p><a href="#" class="hider">Close</a></p>');

			latestThinking.summarise($(this).attr('id'));

		});
	},
	summarise: function(id) {
		$('#'+id+' h2').html('<a href="#" class="summariser">'+$('#'+id+' h2').text()+'</a>');
		$('#'+id+' p.summary').show();
		$('#'+id+' div.description').hide(200);
		$('#'+id+' .summariser').show().unbind();


		$('#'+id+' .summariser').click(function(e) {
			latestThinking.full(id);
			e.preventDefault();
		});

	},
	full: function(id) {
		$('html,body').animate({scrollTop:$('.our-latest-thinking #'+id+' H2').position().top - 20},400);
		
		$('#'+id+' h2').text($('#'+id+' h2 a').text());
		$('#'+id+' p.summary').hide();
		$('#'+id+' div.description').slideDown(300).unbind();
		$('#'+id+' .summariser').hide();

		$('#'+id+' .hider').click(function(e){
			latestThinking.summarise(id);
			e.preventDefault();
		});
	}
}
*/

/*
var currentRollovers = { 
	init: function() {
		$('div.current-projects .copy P').hide();
		$('div.current-projects DIV.copy').css('cursor', 'help');
		$('div.current-projects DIV.copy').hover(function() {
			$(this).find('P').show()
		}, function() {
			$(this).find('P').hide();
		}); 
	}
};
*/
var currentRollovers = { 
	init: function() {
		$('div.current-projects .copy P').hide();
		$('div.current-projects li > div').css('cursor', 'help').hover(function() {
			$(this).find('P').slideDown(200)
		}, function() {
			$(this).find('P').hide(100);
		}); 
	}
};

var contactForm = {
	id: '#contact-form',
	statusMsgId: '#error-message',
	init: function() {
		$(this.id).submit(function(event) {
			contactForm.validate();
			event.preventDefault();
		});		
	},
	validate: function() {
		if($("input#name").val() == "" || $("input#email").val() == "" || $("textarea#message").val() == "") {
			$(this.statusMsgId).show().text('Please enter all required fields');
		}else{
			$(this.statusMsgId).text('').hide();
			contactForm.postForm();
		}	
	},
	postForm: function() {
		$(this.statusMsgId).load($(this.id).attr('action')+"/1", $(this.id).serializeArray(), function() {
			$(contactForm.statusMsgId).show();
		});
	}
};

var signupForm = {
	id: '#signup-form',
	idAdd: '#signup-add',
	placeholder: "",
	action: "",
	data: "",
	init: function() {
		this.placeholder = "."+$(this.id).attr('class');
		this.action = $(this.id).attr('action')+"/1";
		this.attachEventHandlers();
	},
	attachEventHandlers: function() {
		$(this.id).submit(function(event) {
			signupForm.validate();
			event.preventDefault();
		});	
		$(this.idAdd).click(function(event) {
			signupForm.reset();
			event.preventDefault();
		});
	},
	validate: function() {
		if($("input#signup-name").val() == "" || $("input#signup-email").val() == "" || $("input#signup-name").val() == "Your Name" || $("input#signup-email").val() == "Your Email") {
			$('#error-message-signup').show().text('Please enter a name and email addres');
		}else{
			$('#error-message-signup').text('').hide();
			this.postForm();
		}
	},
	postForm: function() {
		$.post(this.action, $(this.id).serialize(), function(data) {
			signupForm.data = data;
			signupForm.showResult();
		});
	},
	showResult: function(data) {
		$(this.placeholder).hide('normal', function() {
			$(signupForm.placeholder).replaceWith(signupForm.data);
			$(signupForm.placeholder).show('normal', function() {
				signupForm.attachEventHandlers();
			});
		});
	},
	reset: function() {
		$.get(this.action, function(data) {
			signupForm.data = data;
			signupForm.showResult();
		});
	}
};

$(document).ready(function() {
	talkDropdown.init();
	workShowcase.init();
//	latestThinking.init();
	currentRollovers.init();
	
	$('a[href^="http://"]').attr('target', '_blank').attr('title', '[opens in a new window]');
	
	contactForm.init();
	signupForm.init();
	
	$('input#signup-name').focus(function() { if($('input#signup-name').val() == "Your Name") { $('input#signup-name').val(""); }});
	$('input#signup-name').blur(function() { if($('input#signup-name').val() == "") { $('input#signup-name').val("Your Name"); }});
	
	$('input#signup-email').focus(function() { if($('input#signup-email').val() == "Your Email Address") { $('input#signup-email').val(""); }});
	$('input#signup-email').blur(function() { if($('input#signup-email').val() == "") { $('input#signup-email').val("Your Email Address"); }});
	

	
	$('#error-message-signup').hide();
});

