function autolink(s){
	var hlink = /\s(ht|f)tp:\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
	return (s.replace (hlink, function ($0,$1,$2) { 
		s = $0.substring(1,$0.length);
		// remove trailing dots, if any
		while (s.length>0 && s.charAt(s.length-1)=='.')
			s=s.substring(0,s.length-1);
			// add hlink
			return " " + s.link(s);
	}));
}

function doautolink(t)
{
 	return autolink(t);
}
$(function(){

	/* Get elements for home page via Ajax to speed up initial load */
	if(location.pathname == '/home' || location.pathname == '/home/' || location.pathname == '/' || location.pathname == '/philsbury/'){
		$('ul.work a').attr('href', 'work/');
		$.ajax({
		
			type: "GET",
			url: "webservice/home",
			dataType: 'JSON',
			success: function(json){
			
				var home = eval('(' + json + ')');
				if(typeof home.twitter == 'string'){
					$('li#twitter blockquote').html(doautolink(home.twitter)).hide().fadeIn();
				}
				
				var music = home.music;
				var musicList = '<ul class="smList">';
				for(i = 0; i < music.length; i++){
				
					if(typeof music[i].artwork == 'object'){
						musicList = musicList + '<li><a class="songInfo" href="'+ music[i].url[0] +'" title="'+music[i].artist+', '+music[i].song+'"><img src="' + music[i].artwork[0] + '" alt="" width="120" height="120" /></a></li>';
					
					} else {
					
						musicList = musicList + '<li><a class="songInfo" href="'+ music[i].url[0] +'" title="'+music[i].artist+', '+music[i].song+'"><img src="' + music[i].artwork + '" alt="" width="120" height="120" /></a></li>';
					
					}
				
				}
				musicList = musicList + '</ul>';
				$('li#lastfm .info').html(musicList).hide().fadeIn();
				
				var flickr = '<ul class="smList">';
					for(i = 0; i < home.flickr.length; i++){
						flickr = flickr + '<li><a href="http://www.flickr.com/photos/52426878@N02/" title=""><img src="'+home.flickr[i]+'" alt="" /></a>';
					}
				flickr = flickr + '</ul>';		
				$('li#flickr .info').html(flickr).hide().fadeIn();
			},
			error: function(){},
			complete: function(){
				$('#sub').css('min-height', ($('#main').innerHeight() - 16));
			
			}
		
		
		});
	
	} else {
	
		$('#sub').css('min-height', ($('#main').innerHeight() - 16));
	
	}
	$('#sub').css('min-height', ($('#main').innerHeight() - 16));
	$('#sub .formbox, #sub #search').populate();
	$('#slider').nivoSlider();
	$('a.external').attr('target', '_blank');
	$('#globalNav').flipNav();
	$('#sub .socialMedia li.search img').click(function(e){
		
		e.preventDefault();
		$('#content').fadeOut();
		if($('#searchResults').length == 0){
			$('#main').append('<div id="searchResults"><span class="removeResults">Remove search results</span><h2>Searching</h2><img src="images/icons/ajax-loader-2.gif" alt="" class="loader" /></div>');
		} else {
			$('#searchResults').html('<span class="removeResults">Remove search results</span><h2>Searching</h2><img src="images/icons/ajax-loader-2.gif" alt="" class="loader" />');
		}
		$.ajax({
			type: "POST",
			url: "webservice/search",
			dataType: 'JSON',
			data:{ searchTerm: $('#search').val()},
			
			success: function(JSON){
				var search = eval("(" + JSON + ")");
				$('#searchResults h2').text(search.header);
				if(search.status == 0){
					$('.loader').fadeOut(500, function(){					
						
						$('#searchResults h2').after(search.html.message);
					
					});
					
				
				} else {
					
					$('.loader').fadeOut(500, function(){					
						
						var results = '<ul class="blogroll">';
						for($i = 0; $i < search.results.length; $i++){
							
							results = results + '<li>\
							<a href="blog/'+search.results[$i].url+'/" title=""><img src="image/crop/120/90/blog/'+search.results[$i].image+'" alt="" /></a>\
							<p class="postDate">'+search.results[$i].date+'</p>\
							<h3><a href="blog/'+search.results[$i].url+'/" title="">'+search.results[$i].headline+'</a></h3>\
							<p>'+search.results[$i].desc+'&hellip;<a href="blog/'+search.results[$i].url+'/" title="Read more" class="readMore">[more]</a></p>\
							</li>';
						
						}
						results = results + '</ul>';					
						$('#searchResults h2').after(results);
					
					});
				
				}
			
			},
			error: function(){
			
				window.location = "search/"+$('#search').val();
			
			},
			complete: function(){}
		
		});
		
	});
	$('#searchForm').submit(function(e){
		e.preventDefault();
		$('#content').fadeOut();
		if($('#searchResults').length == 0){
			$('#main').append('<div id="searchResults"><span class="removeResults">Remove search results</span><h2>Searching</h2><img src="images/icons/ajax-loader-2.gif" alt="" class="loader" /></div>');
		} else {
			$('#searchResults').html('<span class="removeResults">Remove search results</span><h2>Searching</h2><img src="images/icons/ajax-loader-2.gif" alt="" class="loader" />');
		}
		$.ajax({
			type: "POST",
			url: "webservice/search",
			dataType: 'JSON',
			data:{ searchTerm: $('#search').val()},
			
			success: function(JSON){
				var search = eval("(" + JSON + ")");
				$('#searchResults h2').text(search.header);
				if(search.status == 0){
					$('.loader').fadeOut(500, function(){					
						
						$('#searchResults h2').after(search.html.message);
					
					});
					
				
				} else {
					
					$('.loader').fadeOut(500, function(){					
						
						var results = '<ul class="blogroll">';
						for($i = 0; $i < search.results.length; $i++){
							
							results = results + '<li>\
							<a href="blog/'+search.results[$i].url+'/" title=""><img src="image/crop/120/90/blog/'+search.results[$i].image+'" alt="" /></a>\
							<p class="postDate">'+search.results[$i].date+'</p>\
							<h3><a href="blog/'+search.results[$i].url+'/" title="">'+search.results[$i].headline+'</a></h3>\
							<p>'+search.results[$i].desc+'&hellip;<a href="blog/'+search.results[$i].url+'/" title="Read more" class="readMore">[more]</a></p>\
							</li>';
						
						}
						results = results + '</ul>';					
						$('#searchResults h2').after(results);
					
					});
				
				}
			
			},
			error: function(){
			
				window.location = "search/"+$('#search').val();
			
			},
			complete: function(){}
		
		});
		
	});
	$('.removeResults').live("click", function(){
		
		$('#searchResults').fadeOut(500, function(){
			$(this).remove();
			$('#content').fadeIn();
		});
		
	});
	$('.socialMedia li.search').hover(
		function(){
			
			$(this).children('form').children('img').attr('src', 'images/icons/ico-search-active.gif');
		
		},
	
		function(){
			if($(this).hasClass('active') == false){
				$(this).children('form').children('img').attr('src', 'images/icons/ico-search.gif');
			}
		}
	);
	
	$('#search').focus(function(){
	
		$(this).parent('form').parent('li').addClass('active');
		$(this).siblings('img').attr('src', 'images/icons/ico-search-active.gif');
	});
	$('#search').blur(function(){
	
		$(this).parent('form').parent('li').removeClass('active');
		$(this).siblings('img').attr('src', 'images/icons/ico-search.gif');
	});
	
	$('a[href="#reloadForm"]').live("click", function(){
		
		$('#sub #contact p').fadeOut(500, function(){
			$(this).remove();
			$('#subContact').show().fadeTo(500, 1);
		});
		return false;
	});
	
	$('#subContact').submit(function(e){
		
		e.preventDefault();
		$('#subContact').fadeTo(500, 0.5);
		$('#sub #contact').append('<img src="images/icons/ajax-loader-2.gif" class="loader" alt="Processing" />');
		$('.error').remove();
		$.ajax({
			type: 'POST',
			dataType: 'JSON',
			url: 'webservice/contactform',
			data: $("#subContact").serializeArray(),
			success: function(JSON){
				
				var contact = eval("(" + JSON + ")");
				
				if(contact.status == 0){
				
					$('input#name').after(contact.messages.name);
					$('input#email').after(contact.messages.email);
					$('textarea#message').after(contact.messages.message);
					$('#subContact').fadeTo(500, 1);
					$('#sub #contact .loader').fadeTo(500, 0, function(){
						$(this).remove();
					});

				} else if(contact.status == 1) {
					$('#sub #contact .loader').fadeTo(500, 0, function(){
						$(this).remove();
					});
					$('#subContact').fadeTo(500, 0).hide(100, function(){
						$('#subContact #message').val('Message');
						$('#subContact #name').val('Name');
						$('#subContact #email').val('Email');
						$('#sub #contact').append('<p class="thanks">Thank you, your message has been sent.</p><p><a href="#reloadForm" title="">Reload the form</a></p>');
						$('#sub #contact p').hide().fadeIn();
					});
					
				}
				
				
			},
			error: function(){
			
			
			},
			complete: function(){
				
				$('.error').css('display', 'block');
			
			}
			
		});
	
	});
	
	$('.portfolio li a').click(function(){
		
		var img = $(this).children('img').attr('src');
		var url = $(this).attr('href');
		var pos = $(this).position();
		
		var loadImg = new Image();
		  
	  // wrap our new image in jQuery, then:
	  $(loadImg)
	    // once the image has loaded, execute this code
	    .load(function () {
	      // set the image hidden by default    
	      $(this).hide();
			$('#content').append('<div class="folioInfo" />');
		
		$('.folioInfo').css({
		
			background: '#ededed',
			position: 'absolute',
			top: 0,
			left: 0,
			width: '630px',
			height: '99%'
		
		}).hide();
		
		$.ajax({
			type: "POST",
			dataType: "JSON",
			data: {
				project: url,
				pos: pos
			},
			url: 'webservice/portfolio',
			success: function(JSON){
				
				var project = eval("(" + JSON + ")");
				// ADD IMAGE LOADER
				$('.folioInfo').html('<h2>Portfolio</h2><h3 style="display: none;">'+project.title+' ('+project.year+')<a href="#close" class="removeFolio" title="" rel="'+pos.top+'" rev="'+pos.left+'">Close project</a></h3><img src="'+img+'" id="slideImg" style="position: absolute; top: '+pos.top+'px; left: '+pos.left+'px" /><div class="info" style="display: none;">'+project.description+'</div>').fadeIn(500, function(){
					
					$('#slideImg').animate({
						
						top: '72.89999389648438px'
					
					}, 500, function(){
					
						$('#slideImg').animate({
						
							left: 0
						
						}, 500, function(){
							$('.folioInfo h3, .folioInfo .info').fadeIn(500);
						
						});
					
					});
				
				});
				
			},
			error: function(){
				
				window.location.href = url;
			
			},
			complete: function(){
				
				
			
			}		
		
		});
	    })
	    
	    // if there was an error loading the image, react accordingly
	    .error(function () {
	      // notify the user that the image could not be loaded
	    })
	    
	    // *finally*, set the src attribute of the new image to our image
	    .attr('src', img);
		
		
		
		
		return false;
	});
	
	$('.removeFolio').live("click", function(){
		var left = $(this).attr('rev');
		var top = $(this).attr('rel');
		$('.folioInfo h3, .folioInfo .info').fadeOut(500, function(){
			
			$('#slideImg').animate({
				
				left: left
			
			}, 500, function(){
			
				$('#slideImg').animate({
					top: top
				}, 500, function(){
				
					$('.folioInfo').fadeOut(500, function(){
						
						$('.folioInfo').remove();
						
					});
				
				});
			
			});
			
		
		});
		return false;
	});
	
});

jQuery.fn.populate = function() {
	this.each(function(){
		this.value = jQuery(this).siblings('label').html();
		jQuery(this).siblings('label').hide();
	});	
	return this.focus(function() {
	
	if( this.value == jQuery(this).siblings('label').html() ) {
		this.value = "";
	}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = jQuery(this).siblings('label').html();
	}
	});
	
	
};

