/* jQuery ScrollTo - Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com/2007/10/jqueryscrollto.html */
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);
/* jQuery Auto Expanding Text Area (1.2.2) - Copyright (c) 2008 Chrys Bader (www.chrysbader.com) */
(function(jQuery){var self=null;jQuery.fn.autogrow=function(o){return this.each(function(){new jQuery.autogrow(this,o)})};jQuery.autogrow=function(e,o){this.options=o||{};this.dummy=null;this.interval=null;this.line_height=this.options.lineHeight||parseInt(jQuery(e).css('line-height'));this.min_height=this.options.minHeight||parseInt(jQuery(e).css('min-height'));this.max_height=this.options.maxHeight||parseInt(jQuery(e).css('max-height'));this.textarea=jQuery(e);if(this.line_height==NaN)this.line_height=0;this.init()};jQuery.autogrow.fn=jQuery.autogrow.prototype={autogrow:'1.2.2'};jQuery.autogrow.fn.extend=jQuery.autogrow.extend=jQuery.extend;jQuery.autogrow.fn.extend({init:function(){var self=this;this.textarea.css({overflow:'hidden',display:'block'});this.textarea.bind('focus',function(){self.startExpand()}).bind('blur',function(){self.stopExpand()});this.checkExpand()},startExpand:function(){var self=this;this.interval=window.setInterval(function(){self.checkExpand()},400)},stopExpand:function(){clearInterval(this.interval)},checkExpand:function(){if(this.dummy==null){this.dummy=jQuery('<div></div>');this.dummy.css({'font-size':this.textarea.css('font-size'),'font-family':this.textarea.css('font-family'),'width':this.textarea.css('width'),'padding':this.textarea.css('padding'),'line-height':this.line_height+'px','overflow-x':'hidden','position':'absolute','top':0,'left':-9999}).appendTo('body')}var html=this.textarea.val().replace(/(<|>)/g,'');if($.browser.msie){html=html.replace(/\n/g,'<BR>new')}else{html=html.replace(/\n/g,'<br>new')}if(this.dummy.html()!=html){this.dummy.html(html);if(this.max_height>0&&(this.dummy.height()+this.line_height>this.max_height)){this.textarea.css('overflow-y','auto')}else{this.textarea.css('overflow-y','hidden');if(this.textarea.height()<this.dummy.height()+this.line_height||(this.dummy.height()<this.textarea.height())){this.textarea.animate({height:(this.dummy.height()+this.line_height)+'px'},100)}}}}})})(jQuery);
/* jQuery Twitter - Created by Damien du Toit http://coda.co.za/blog/2008/10/26/jquery-plugin-for-twitter */
(function($){$.fn.getTwitter=function(options){var o=$.extend({},$.fn.getTwitter.defaults,options);$(this).hide();if(o.showHeading){$(this).append('<h2>'+o.headingText+'</h2>')}$(this).append('<ul id="twitter_update_list"><li></li></ul>');$("ul#twitter_update_list").hide();var pl=$('<p id="'+o.preloaderId+'">'+o.loaderText+'</p>');$(this).append(pl);if(o.showProfileLink){$(this).append('<a id="profileLink" href="http://twitter.com/'+o.userName+'">http://twitter.com/'+o.userName+'</a>')}$(this).show();$.getScript("http://twitter.com/javascripts/blogger.js");$.getScript("http://twitter.com/statuses/user_timeline/"+o.userName+".json?callback=twitterCallback2&count="+o.numTweets,function(){$(pl).remove();if(o.slideIn){$("ul#twitter_update_list").slideDown(1000)}else{$("ul#twitter_update_list").show()}$("ul#twitter_update_list li:first").addClass("firstTweet");$("ul#twitter_update_list li:last").addClass("lastTweet")})};$.fn.getTwitter.defaults={userName:null,numTweets:5,preloaderId:"preloader",loaderText:"Loading tweets...",slideIn:false,showHeading:true,headingText:"Latest Tweets",showProfileLink:true}})(jQuery);

// ajax set up
$.ajaxSetup({
	headers: {"X-Requested-With":"Ajax"},
	contentType: "application/x-www-form-urlencoded",
	cache: false,
	data: {}
});

// DC namespace
var DC = DC || {};

// external links
DC.externalLinks = function(){
	var $extlinks = $('a[rel=external]');
	$.each($extlinks, function(){
		$(this).attr('target','_blank').attr('title',$(this).attr('title') + ' (opens in a new window)');
	});
};

// output to screen
DC.say = function(str){
	try{
		window.loadFirebugConsole();
		console.log(str);
	}catch(e){
		alert(str);
	}
};

// twitter stuff
DC.twitter = function(){
	
	// create the twitter markup
	init = function(){
		var $box = $('#twitter');
		
		var a = document.createElement('a');
		$(a).attr('href', 'http://www.twitter.com/dannycallaghan');
		$(a).attr('title', 'Follow me on Twitter');
		$(a).attr('rel', 'external');
		
		var img = document.createElement('img');
		$(img).attr('src', '/_i/twitterbird.png');
		$(img).attr('alt', 'Twitter');
		
		var p = document.createElement('p');
		$(p).attr('class', 'info');
		$(p).text("Yes, I'm on Twitter. Latest tweets...");
		
		var div = document.createElement('div');
		$(div).attr('class', 'tweet');
		
		var clear = document.createElement('div');
		$(clear).attr('class', 'clear');
		
		$(a).append($(img));
		$box.append($(a))
		
		$box.append($(p));
		$box.append($(div));
		
		$box.append($(clear));
	}();
	
	$("#twitter p.noscript").remove();
	
	// twitter set up	
	$("#twitter .tweet").getTwitter({
		userName: "dannycallaghan",
		numTweets: 3,
		loaderText: "Loading tweets...",
		slideIn: false,
		showHeading: false,
		headingText: "Latest Tweets",
		showProfileLink: false
	});
};

// contact form stuff
DC.contactForm = function(){
	
	var $form 	= $('form'),
	$name		= $('#form-name'),
	$email 		= $('#form-email'),
	$message	= $('#form-message'),
	$sum		= $('#form-sum'),
	emsg		= '';
	$nums		= $form.children().find('label[for=form-sum]').children('span'),
	total		= 0;
	
	// override submit event
	addEvent = function(){
		$form.bind('submit', function(e){
			doValidate();
			e.preventDefault();
		});
	};
	
	// get the sum of our two digits
	initSum = function(){
		$.each($nums, function(){
			var ran = parseInt($(this).text());
			total = total+ran;
		});
	};
	
	// get rid of any errors
	clearErrors = function(){
		$form.children('div.error').removeClass('error');
		$form.children('p.error').remove();
	};
	
	// walk through the validating process
	doValidate = function(){
		clearErrors();
		if($name.val().length===0){
			emsg = 'Please let me know your name.';
			showError($name, emsg);
			return false;
		}
		if($email.val().length===0){
			emsg = 'Please let me know your email address.';
			showError($email, emsg);
			return false;
		}else{	
			if(!checkEmail($email.val())){
				emsg = 'Please enter a valid email address.';
				showError($email, emsg);
				return false;
			}
		}
		if($message.val().length===0){
			emsg = 'Please write me a message.';
			showError($message, emsg);
			return false;
		}
		if($sum.val().length===0){
			emsg = 'Please answer my little mathematics problem.';
			showError($sum, emsg);
			return false;
		}else{	
			if(!checkSum($sum.val())){
				emsg = 'Please check your answer to my numbers question.';
				showError($sum, emsg);
				return false;
			}
		}
		doSend();	
	};
	
	// send our form
	doSend = function(){
		var args = "name=" + $name.val() + "&email=" + $email.val() + "&message=" + $message.val();
		
		$.ajax({
			type: "POST",
			url: "/_contact/contact.php",
			data: args,
			error: function(data){
				emsg = "Sorry, you've broken the internet. Please try again later.";
				showError('', emsg);							
				return;
			},
			success: function(data){
				var data = eval('(' + data + ')'); // evil. need to sort this.
				if(data["errorMessage"]||data["errorMessage"]==''){
					emsg = "Sorry, you've broken the internet. Please try again later.";
					showError('', emsg);							
					return;
				}
				if(data["okMessage"]||data["okMessage"]==''){
					emsg = "Thanks for getting in touch.";
					showError('', emsg, true);							
					return;
				}
			}
		});
	}
	
	// output error to user
	showError = function(obj, msg, ok){
		var $obj = $(obj);
		$obj.parent().addClass('error');
		var p = document.createElement('p');
		(ok)? $(p).addClass('ok'):$(p).addClass('error');
		$(p).text(msg);
		$form.prepend($(p));	
		$(p).fadeIn('fast');					
	};
	
	// validate email address
	checkEmail = function(email){
		var at							= "@";
		var dot							= ".";
		var lat							= email.indexOf(at);
		var lstr						= email.length;
		var ldot						= email.indexOf(dot);
		if (email.indexOf(at) == -1) {return false;}
		if (email.indexOf(at) == -1 || email.indexOf(at)==0 || email.indexOf(at)==lstr) {return false;}
		if (email.indexOf(dot) == -1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr) {return false;}
		if (email.indexOf(at,(lat+1)) != -1) {return false;}
		if (email.substring(lat-1,lat) == dot || email.substring(lat+1,lat+2)==dot) {return false;}
		if (email.indexOf(dot,(lat+2)) == -1) {return false;}
		if (email.indexOf(" ")!=-1) {return false;}
		return true;
	};
	
	// validate sum of our two digits
	checkSum = function(sum){
		return(parseInt(sum)===total);
	};
	
	// init
	init = function(){
		addEvent();
		initSum();
	}();

};

// sets up the growing textarea
DC.textareaGrow = function(){
	$('textarea').autogrow({
		maxHeight: 300,
		lineHeight: 22
	});
};

// sets up the back to top links
DC.backToTop = function(){
	$('p.back-to-top a').click(function() {  
		$(document).scrollTo(0,500);
		return false;  
	});
};

// adds scroll effect to "nav"
DC.createAnchorScroll = function(){
	var $anchors = $('a.anchor');
	$.each($anchors, function(){
		$(this).click(function(e){
			var anchor = $(this).attr('href');
			var pos = $(anchor).position();
			if(pos){
				$(document).scrollTo(pos.top,500);
			}
			e.preventDefault();
		});
	});
};

// when we're ready...
$(document).ready(function(){
	
	DC.twitter(); // twitter

	DC.externalLinks(); // external links

	DC.textareaGrow(); // auto grow textarea

	DC.contactForm(); // contact form validator

	DC.backToTop(); // back to top scroll
	
	DC.createAnchorScroll(); // "nav" anchor scroll
	
});