$(document).ready(function() {
	if($('body.home').length) {
		// switch the header link to the press releases archive to show the most recent press release instead.
		$.ajax({
			type: 'GET', 
			url: '/news/api/get_recent_posts?post_type=hbk_pressrelease',
			dataType: 'jsonp',
			success: function(data){
				var url = data.posts[0].url;
				 $('#main #pr a').attr('href', url);
			}
		})
		
		var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
		
		var $error = $('<p>', {
			'class': 'error',
			text: 'Error loading content.'
		});
		
		var $loader = $('<img>', {
			'class': 'loader',
			src: 'images/ajax-loader.gif'
		});
		
		$loader.insertAfter('.column:not(#work) .content .see');
		
		$('.loader').ajaxStart(function () {
			$(this).css('display', 'block');
		});
		
		$('#culture').ajaxStop(function () {
			$('#culture .content ul li:gt(2)').addClass('desktop');
		});
		
		$('#twitter').ajaxStop(function () {
			$('#twitter .content ul li:gt(2)').addClass('desktop');
		});

		$.ajax({ 
			type: 'GET', 
			url: 'linkedin.php',
			dataType: 'jsonp',
			error: function () {
				$('#jobs .content .loader').remove();
				$('#jobs .content').prepend($error);
			},
			success: function (data) {
				$('#jobs .content .loader').remove();
				var jobs = [];
				$.each(data, function (k, job) {
					jobs.push({
						'link': 'http://linkedin.com/' + job.link,
						'title': job.title,
						'date': liDate(job.date)
					});
				});
				$('#jobsTemplate').tmpl(jobs.slice(0, 5)).appendTo('#jobs .content ul');
			}
		});
		
		$.ajax({ 
			type: 'GET', 
			url: 'http://www.twitter.com/statuses/user_timeline/hbk140.json', 
			dataType: 'jsonp',
			error: function () {
				$('#twitter .content .loader').remove();
				$('#twitter .content').prepend($error);
			}, 
			success: function (data) {
				$('#twitter .content .loader').remove();
				var tweets = [];
				$.each(data, function (k, tweet) {
					tweets.push({
						'text': ify.clean(tweet.text),
						'name': 'hbk140',
						'time': relative_time(tweet.created_at),
						'source': tweet.source
					});
				});
				$('#twitterTemplate').tmpl(tweets.slice(0, 5)).appendTo('#twitter .content ul');
			}
		}); 
		
		/*$.ajax({ 
			type: 'GET', 
			url: 'http://gdata.youtube.com/feeds/api/users/hbkwork/uploads?alt=json',
			dataType: 'jsonp', 
			error: function () {
				$('#work .content .loader').remove();
				$('#work .content').prepend($error);
			}, 
			success: function (data) {
				$('#work .content .loader').remove();
				var videos = [];
				$.each(data.feed.entry, function (k, video) {
					videos.push({
						'link': video.link[0].href,
						'title': video.title.$t,
						'thumb': video.media$group.media$thumbnail[0].url,
						'time': formattedDate(video.published.$t),
						'views': video.yt$statistics.viewCount
					});
				});
				$('#youtubeTemplate').tmpl(videos.slice(0, 3)).appendTo('#work .content ul');
			}
		});*/
		
		$.ajax({ 
			type: 'GET', 
			url: 'http://www.hendersonbaskohn.com/news/api/core/get_recent_posts?post_type=hbk_pressrelease&count=10',
			dataType: 'jsonp', 
			error: function () {
				$('#news .content .loader').remove();
				$('#news .content').prepend($error);
			}, 
			success: function (response) {
				$('#news .content .loader').remove();
				var posts = [];
				$.each(response.posts, function (k, post) {
					posts.push({
						'title': post.title,
						'thumb': post.thumbnail,
						'date': formattedDate(post.date),
						'link': post.url
					});
				});
				$('#newsTemplate').tmpl(posts).appendTo('#news .content ul');
			}
		});

	//	$.ajax({ 
	//		type: 'GET', 
	//		url: 'http://graph.facebook.com/hendersonbaskohn/feed&limit=15',
	//		dataType: 'jsonp', 
	//		error: function () {
	//			$('#culture .content .loader').remove();
	//			$('#culture .content').prepend($error);
	//		}, 
	//		success: function (response) {
	//			$('#culture .content .loader').remove();
	//			var posts = [];
	//			$.each(response.data, function (k, post) {
	//				if(escape(post.from.name) == 'henderson bas kohn') {
	//					if(post.message != null) {
	//						posts.push({
	//							'message': escape(post.message),
	//							'from': escape(post.from.name),
	//							'date': formattedDate(post.updated_time)
	//						});
	//					}
	//				}
	//			});
	//			$('#fbTemplate').tmpl(posts.slice(0, 5)).appendTo('#culture .content ul');
	//		}
	//	});
		
		window.ify = function() {
		  var entities = {
			  '"' : '&quot;',
			  '&' : '&amp;',
			  '<' : '&lt;',
			  '>' : '&gt;'
		  };

		  return {
			'link': function(t) {
			  return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a href="' + m + '" target="_blank">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			  });
			},
			'at': function(t) {
			  return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
				return m1 + '@<a href="http://twitter.com/' + m2 + '" target="_blank">' + m2 + '</a>';
			  });
			},
			'hash': function(t) {
			  return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '" target="_blank">' + m2 + '</a>';
			  });
			},
			'clean': function(tweet) {
			  return this.hash(this.at(this.link(tweet)));
			}
		  };
		}();
		
		function formattedDate(date) {
			var p = (date.indexOf('T') !== -1) ? date.split('T')[0].split('-') : date.split(' ')[0].split('-');
			var d = new Date();
			d.setUTCFullYear(p[0], p[1] - 1, p[2]);
			d.setUTCHours(0, 0, 0, 0);
			return d.getDate() + ' ' + monthDict[d.getMonth()] + ' ' + d.getFullYear();
		}
		
		function liDate(date) {
			var p = date.split(', ');
			var d = p[0].split(' ');
			return d[1] + ' ' + d[0] + ' ' + p[1];
		}
		
		
		/* from Remy Sharp Twitter.js */
		function relative_time(time_value) {
			var values = time_value.split(' '),
				parsed_date = Date.parse(values[1] + ' ' + values[2] + ', ' + values[5] + ' ' + values[3]),
				date = new Date(parsed_date),
				relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
				delta = parseInt((relative_to.getTime() - parsed_date) / 1000),
				r = '';
			
			function formatTime(date) {
				var hour = date.getHours(),
					min = date.getMinutes() + '',
					ampm = 'AM';
				
				if (hour == 0) {
					hour = 12;
				} else if (hour === 12) {
					ampm = 'PM';
				} else if (hour > 12) {
					hour -= 12;
					ampm = 'PM';
				}
				
				if (min.length === 1) {
					min = '0' + min;
				}
				
				return hour + ':' + min + ' ' + ampm;
			}
			
			function formatDate(date) {
				var ds = date.toDateString().split(/ /),
					mon = monthDict[date.getMonth()],
					day = date.getDate() + '',
					dayi = parseInt(day),
					year = date.getFullYear(),
					thisyear = (new Date()).getFullYear(),
					th = 'th';
				
				if ((dayi % 10) === 1 && day.substr(0, 1) !== '1') {
					th = 'st';
				} else if ((dayi % 10) === 2 && day.substr(0, 1) !== '1') {
					th = 'nd';
				} else if ((dayi % 10) === 3 && day.substr(0, 1) !== '1') {
					th = 'rd';
				}
				
				if (day.substr(0, 1) === '0') {
					day = day.substr(1);
				}
				
				return mon + ' ' + day + th + (thisyear !== year ? ', ' + year : '');
			}
			
			delta = delta + (relative_to.getTimezoneOffset() * 60);

			if (delta < 5) {
				r = 'less than 5 seconds ago';
			} else if (delta < 30) {
				r = 'half a minute ago';
			} else if (delta < 60) {
				r = 'less than a minute ago';
			} else if (delta < 120) {
				r = '1 minute ago';
			} else if (delta < (45 * 60)) {
				r = (parseInt(delta / 60)).toString() + ' minutes ago';
			} else if (delta < (2 * 90 * 60)) {
				r = 'about 1 hour ago';
			} else if (delta < (24 * 60 * 60)) {
				r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
			} else {
				if (delta < (48 * 60 * 60)) {
					r = formatTime(date) + ' yesterday';
				} else {
					r = formatTime(date) + ' ' + formatDate(date);
				}
			}

			return r;
		}
		
		if(location.hash != '') {
			if(($(window).height() > $(window).width()) || ($(window).width() <= 480) || (isOldBB == true)) {
				var id = location.hash.replace('#', '');
				$('#' + id + ' .content').css('display', 'block');
				$('#' + id).addClass('active');
			}
		}
	}
});

function doMobileStuff() {
	$('#work .content ul:not(#recent) li:gt(0)').addClass('desktop');
	
	$('.column .header a').click(function() {
		var section_id = $(this).closest('.column').attr('id');
		return(checkIfMobileForHeaderLinks(section_id));
	});
	
	$(window).resize(checkWidth);
};

function checkIfMobileForHeaderLinks(section_id) {
	if(($(window).height() > $(window).width()) || ($(window).width() <= 480) || (isOldBB == true)) {
		if(!$('#' + section_id).hasClass('active')) {
			$('.column.active .content').slideUp('slow');
			$('.column.active').removeClass('active');
			$('#' + section_id).addClass('active');
			$('#' + section_id).find('.content').slideDown('slow');
		} else {
			$('#' + section_id).removeClass('active');
			$('#' + section_id).find('.content').slideUp('slow');
		}
		return false;
	} else if(window.location.pathname.indexOf('/work') != -1) {
		return false;
	}
	else {
		return true;
	}
}

function checkWidth() {
	if(($(window).height() > $(window).width()) || ($(window).width() <= 462)) {
		$('.column:not(.desktop):not(.active) .content').css('display', 'none');
	} else {
		$('.column:not(.mobile) .content').css('display', 'block');
	}
}
