var subnavTimeout;
var subnavTimeoutLength = 100;

var slideshowTimeoutLength = 6000;
var slideshowTimerTimeout;
var slideshowTimerPosition = 0;

var showcaseTimeout;
var showcaseTimeoutLength = 2500;
var numShowcases;
var currentShowcasing = 1;

$(document).ready(function(){
    loadRecentTweets();
	fixSubnavBorder();
	addSubnavAnimations();
	slideshowControls();
	tableStyles();
	showcase();
	subscribeForm();
	
	Cufon.replace('.ColabLight', { fontFamily: 'ColaborateLightRegular' });
	Cufon.replace('.ColabThin', { fontFamily: 'ColaborateThinRegular' });
	
	Cufon.replace('h2', { fontFamily: 'ColaborateThinRegular' });
	Cufon.replace('h3', { fontFamily: 'ColaborateThinRegular' });
	Cufon.replace('.core_service_link', { fontFamily: 'ColaborateThinRegular' });
	Cufon.replace('.sidebox h4', { fontFamily: 'ColaborateLightRegular' });
	Cufon.replace('.subnav dt', { fontFamily: 'ColaborateThinRegular' });
	
	Cufon.replace('.linkbox span', { fontFamily: 'ColaborateThinRegular' });
	
	
});

function subscribeForm() {
	if ($('#subscribebox').size() > 0) {
		$('#subscribebox input[type="input"]').one("click", function(){
			$(this).val("");
		});
	}
}

function showcase() {
	if ($('#showcase').size() > 0) {
		numShowcases = $('.showcase_award').size();
		setTimeout(showcase_next, showcaseTimeoutLength);
	}
}

function showcase_next() {
	$('.showcasing').fadeOut(function(){
		$(this).removeClass('showcasing');
		currentShowcasing = (currentShowcasing >= numShowcases) ? 1 : currentShowcasing+1;
		$('.showcase_award[data-order='+currentShowcasing+']').fadeIn().addClass('showcasing');
		setTimeout(showcase_next, showcaseTimeoutLength);
	});
}


function slideshowControls() {
	if ($('#slideshow').size() > 0) {

		$('#slidecontrols li').mouseover(function(e){
			e.preventDefault();
			$('#slidecontrols li').removeClass("selected");
			$(this).addClass("selected");
			
			var scrollX = -1 * $("#" + $(this).attr("data-slide")).position().left;
			
			$("#slidereel").stop().animate({left: scrollX}, 300, "linear");
		});
		
		$('#slidecontrols li').click(function(e){
			e.preventDefault();
		});
		
		addSlideshowTimer();
	}
}


function addSlideshowTimer() {
	$('#slidecontrols ul').mouseover(function(){
		clearTimeout(slideshowTimerTimeout);
		$('#slideshow_timer').fadeOut();
	});
	moveTimer();
}

function nextSlide() {
	var currentSelected = $('#slidecontrols li.selected').removeClass('selected');
	if (currentSelected.is(':last-child')) {
		$('#slidecontrols li:first-child').addClass('selected');
	} else {
		currentSelected.next().addClass('selected');
	}
	
	var scrollX = -1 * $("#" + $('#slidecontrols li.selected').attr("data-slide")).position().left;
	$("#slidereel").stop().animate({left: scrollX}, 300, "linear");
}

function moveTimer() {
	if (slideshowTimerPosition == 3 ) {
		slideshowTimerPosition = 0;
		nextSlide();
	} else {
		slideshowTimerPosition++
	}
	
	$('#slideshow_timer').css('background-position', '0 '+slideshowTimerPosition*-8+'px');
	
	slideshowTimerTimeout = setTimeout("moveTimer()", slideshowTimeoutLength/4);
}



function tableStyles() {
	$('table').each(function(i){
		if ($(this).find('th').length > 0) {
			$('th:first-child', this).addClass('br_tl').css({'border': '1px solid #0d387d'});
			$('th:last-child', this).addClass('br_tr').css({'border': '1px solid #0d387d'});
			$('tr:even td', this).addClass('altBG');
		} else {
			$('tr:first-child td:first-child', this).addClass('br_tl').css({'border-top': '1px solid #DDD'});
			$('tr:first-child td:last-child', this).addClass('br_tr').css({'border-top': '1px solid #DDD'});
			$('tr:odd td', this).addClass('altBG');
		}
	});
	$('.mainbox table td:first-child').css({'border-left': '1px solid #DDD'});
	$('.mainbox table td:last-child').css({'border-right': '1px solid #DDD'});
	$('.mainbox table tr:last-child td:first-child').addClass('br_bl').css({'border-bottom': '1px solid #DDD'});
	$('.mainbox table tr:last-child td:last-child').addClass('br_br').css({'border-bottom': '1px solid #DDD'});
}

function fixSubnavBorder() {
	$('.subnav dl').css({
		'border-left': '1px solid #fff',
		'border-right': '1px solid #e6e6e6'
	}).filter(':last-child').css('border-left', '0').end().filter(':first-child').css('border-right', '0').end();
}

function addSubnavAnimations() {

	$('#nav a').mouseover(function(){
		clearTimeout(subnavTimeout);
		
		if (!$(this).hasClass('selected')) { // If already selected, do nothing
			
			hideSubnav();
			$(this).addClass('selected');
			$('#wrapper_header').addClass('selected'); 
			 
			var thisSubnav = $('#sub' + $(this).prop('id'));
			var thisHeight;
			switch(thisSubnav.prop('id')) {
				case "subnav_mediaroom":
				case "subnav_industrysolutions":
					thisHeight = 53;
					break;
				default:
					thisHeight = 140;
			}
			
			thisSubnav.stop().addClass("selected").css({
				display: "block",
				height: 0
			}).animate({ height: thisHeight}, 400);
				
		}
	});
	
	/**
	$('#nav').mouseout(function(e){
		subnavTimeout = setTimeout(removeSubnav, subnavTimeoutLength);
		console.log('#nav mouseout set timeout');
	});/**/
	
	/**/
	$('#nav').hover(function(){
		clearTimeout(subnavTimeout);
	}, function(){
		subnavTimeout = setTimeout(removeSubnav, subnavTimeoutLength);
	});/**/
	
	$('#wrapper_subnav').hover (function(){
		clearTimeout(subnavTimeout);
	}, function(){
		subnavTimeout = setTimeout(removeSubnav, subnavTimeoutLength);
	});
	
}

function removeSubnav() {
	$('#wrapper_header').removeClass('selected'); 
	hideSubnav();
}

function hideSubnav() {
	$('#nav a').removeClass('selected');
	$('#wrapper_header').removeClass('selected'); 
	$('.subnav.selected').stop().removeClass('selected').animate(
		{ height: 0 },
		400,
		function(){
			$(this).css("display", "none");
		}
	);
}

function loadRecentTweets() {
	var html = "";
	$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?count=5&screen_name=DapasoftInc&include_rts=true&include_entities=true&callback=?', function(tweets) {
		for (var i in tweets) {
			html +=
			'<div class="tweet">' +
				'<div class="message">' + linkify(tweets[i].text) + '</div>' +
				'<div class="time">' + 
					'<span class="time_ago"><a rel="nofollow" href="http://twitter.com/#!/DapasoftInc/status/' + tweets[i].id_str + '" target="_blank">' + parseTweetTime(tweets[i].created_at) + '</a></span>' +
					'<span class="time_created">' + formatTweetTime(tweets[i].created_at) + '</span>' +
				'</div>' +
			'</div>';
		}
		$('#tweets').html(html);
	});
}

function universalParseDate(timestamp) {
  var v = timestamp.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
}

function parseTweetTime(timestamp) {
	var timeTweeted = universalParseDate(timestamp);
	
	var timeNow = new Date();
	
	var timeBetween = timeNow.valueOf() - timeTweeted.valueOf();
	var timeAgo = "";
	
	if (timeBetween > 1000*60*60*24) { // More than 24 hours ago
    	dayNow = new Date(timeNow.toLocaleDateString()); // Take very beginning of each day
    	dayTweeted = new Date(timeTweeted.toLocaleDateString());
        var daysAgo = Math.ceil((dayNow - dayTweeted) / (1000*60*60*24));
        if (daysAgo > 1) timeAgo = daysAgo + " days ago";
        else timeAgo = daysAgo + " day ago";
    } else if (timeBetween > 1000*60*60) { // More than 60 minutes ago
        var hoursAgo = Math.round(timeBetween / (1000*60*60)); // Hours taken at half-hour mark
        if (hoursAgo > 1) timeAgo = hoursAgo + " hours ago";
        else timeAgo = hoursAgo + " hour ago";
    } else if (timeBetween > 1000*60) { // More than a minute ago
        var minutesAgo = Math.floor(timeBetween / (1000*60)); // Minutes rounded down
        if (minutesAgo > 1 ) timeAgo = minutesAgo + " minutes ago";
        else timeAgo = minutesAgo + " minute ago";
    } else {
        timeAgo = "Just now";
    }
	
	return timeAgo;
}

function formatTweetTime(timestamp) {
	return universalParseDate(timestamp).toDateString();
}

function linkify(inputText) {
    var replaceText, replacePattern1, replacePattern2, replacePattern3, replacePattern4;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank" rel="nofollow">$1</a>');

    //URLs starting with www. (without // before it, or it'd re-link the ones done above)
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" rel="nofollow">$2</a>');

    //Change email addresses to mailto:: links
    replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}
