var errors = false, 
		interval = null, 
		attempts = 0;

$(document).ready(function() {
	if($('#nav').length) {
		$('#nav li').not('li.active').children('ul').hide();
		if($('#nav li.active').length == 0) {
			$('#nav li:first-child').children('ul').show();
		}
		$('#nav span').each(function() {
			var span = $(this);
			span.click(function() {
				$(this).next('ul').slideToggle();
				$(this).parent().toggleClass('active');
			});
		});
	}
	
	if($('#slideshow').length) {
		$('#slideshow li').each(function() {
			var li = $(this);
			li.click(function() {
				goToSlide(li);
				clearInterval(interval);
				return false;
			});
		});
		interval = setInterval("next()", 5000);
	}
	
	if($('#socialbox').length) {
  	$('#socialtabs li').click(function() {
  		var rel = $(this).attr('rel');
  		$('#socialbox .feed').hide();
  		$('#'+rel).show();
  		$('#socialtabs li.active').removeClass('active');
  		$(this).addClass('active');
  	});
  	
  	getTwitters('twitterfeed', { 
			id: 'TCompuMark', 
			count: 3, 
			enableLinks: true,
			ignoreReplies: false,
			clearContents: true,
			template: '%text% <br /><a class="statustime" target="_blank" href="http://twitter.com/%user_screen_name%/status/%id_str%/">%time% From Twitter</a>'
		});
  }
  $('form').submit(function() {
  	errors = false;
  	var form = $(this);
  	form.find('.error').removeClass('error');
  	form.find('.required').each(function() {
  		var field = $(this);
  		var val = field.val();
  		if(val=='') {
  			errors = true;
  			field.addClass('error');
  		}
  	});
  	if(errors) {
  		form.find('.error:first').focus();
  		return false;
  	}
  });
  
});

function next() {
	var next = $('#slideshow li.active').next();
	if(next.length) {
		goToSlide(next);
	} else {
		goToSlide($('#slideshow li:first-child'));
	}
}

function goToSlide(li) {
	var html = li.children('div.hidden').html(),
			href = li.children('a').attr('href'),
			credit = li.children('a').attr('title'),
			newImg = $(document.createElement('img'));
			
	$('#slideshow .img_display img').addClass('old');
	$(".img_display").append(newImg
										.attr('src', href)
										.hide()
										.fadeIn(500, function(){
											$('.old').remove();
										}));
	$('#slide_content').html(html);
	$('#slideshow li.active').removeClass('active');
	$('#photocredit').text(credit);
	li.addClass('active');
}

function loadData() {
	IN.API.Raw("/groups/4135628/posts:(title,summary,creator,type,creation-timestamp,site-group-post-url)?order=recency").result(function(result) {
		var max = 3;
		$('#linkedinfeed').html('');
		$('#linkedinfeed').prepend('<ul></ul>');
		var d = new Date();
		if(result._total == 0) {
			$('#linkedinfeed').prepend('<p style="padding: 10px 0 0;">Loading Linkedin content...</p>');
			attempts++;
			if(attempts < 15) {
				loadData();
			}
		} else {
			for(i in result.values) {
				if(i>=max) {break;}
				$('#linkedinfeed ul').append("<li><span class='title'><a href='" + result.values[i].siteGroupPostUrl + "' target='Li'>" + result.values[i].title + "</a></span>" + result.values[i].summary + "<span class='statustime'>Posted " + time_since((d.getTime() - result.values[i].creationTimestamp)/1000) + " via LinkedIn</span></li>");
			}
		}
	});
}

function time_since(since) {
	var chunks = Array(
	  Array(60 * 60 * 24 * 365 , 'year'),
	  Array(60 * 60 * 24 * 30 , 'month'),
	  Array(60 * 60 * 24 * 7, 'week'),
	  Array(60 * 60 * 24 , 'day'),
	  Array(60 * 60 , 'hour'),
	  Array(60 , 'minute'),
	  Array(1 , 'second')
	);
	
	var seconds = '';
	var name = '';
	var j = 0;
	for (var i = 0, j = chunks.length; i < j; i++) {
	  seconds = chunks[i][0];
	  name = chunks[i][1];
	  if ((count = Math.floor(since / seconds)) != 0) {
	    break;
	  }
	}
	
	var print = (count == 1) ? '1&nbsp;' + name + '&nbsp;ago' : count + "&nbsp;" + name + "s&nbsp;ago";
	return print;
}

function linkTweet(string) {
	string = string.replace(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g, '<a href="$1://$2$3" target="_blank">$1://$2$3</a>');
	string = string.replace(/ ?\#(\w+) ?/ig, ' <a href="http://twitter.com/#!/search/%23$1" target="_blank">#$1</a> ');
	string = string.replace(/ ?\@(\w+) ?/ig, ' <a href="http://twitter.com/#!/$1" target="_blank">@$1</a> ');
	return string;
}
