
/******************************** socialBar *********************************/
var socialBar = (function(){

	/* all times are in milliseconds */
	var cycleSpeed = 1500;         // the speed of the transition
	var timeBetweenCycles = 4500;  // the time after one cycle ends but before the next one starts
	var maxFeedItems = 10;         // for Facebook & Twitter

	/*
	 * socialBar uses jQuery.Cookie
	 */

	function init(){
		if (typeof $.cookie == 'undefined'){
			$.ajax({
        url: 'http://' + document.domain + '/js/jquery.cookie-modified.js?',
        dataType: 'script',
        success: init2,
				data: {},
				error: function(){
					alert('cookie failure');
				}
			});
		}
		else{
			init2();
		}
	}
	
	function init2(data){
		jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
		setInitialState();
		setupFeeds();
		setupEvents();
		$('#sb-links a.tab1').click();
		$('#social-bar .tab').css('display', 'block');
		setupScrollers();
	}

	function setInitialState(){
		var opened = $.cookie('sb-state');
		if (opened == 'opened'){
			open();
		}
		else{
			close();
		}
	}

	function setupFeeds() {
		setupFacebookFeed('#facebook-feed .items', 'http://www.facebook.com/feeds/page.php?format=atom10&id=116692805029796', function(){
			setupScroller('#facebook-feed', scrollerFacebook);
		});
		setupTwitterFeed('#twitter-feed .items', 'ninety_five_5', function(){
			setupScroller('#twitter-feed', scrollerTwitter);
		});
	}

	function setupFacebookFeed(container, url, callback){
		var query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20atom%20where%20url%3D%22"+
			encodeURIComponent(url)+
			"%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";//&callback=
//		console.log(query);
		$.ajax({
			url: query,
			dataType: 'jsonp',
			cache: false,
			data: {},
			success: function(data){
//				console.log('data: ',data);
				if(data.query.count){
					var results = data.query.results.entry;
					var items = '';
					var max = data.query.count > maxFeedItems ? maxFeedItems :  data.query.count;
					for (var $i = 0; $i < max; $i++){
						var title = $.trim(results[$i].title).trunc(150);
						if (title.length > 0)
							items += '<div class="item">'+ title +'<a href="'+ results[$i].link.href +'"> (read more)</a></div>';
					}
					$(container).html(items);
					if (typeof callback == 'function'){
						callback.call(this);
					}
				} else {
					$(container).html('Error!');
				}
			},
			error: function(xhr, status, errorThrown) {
				console.log(errorThrown+'\n'+status+'\n'+xhr.statusText);
			}
		});
	}

	function setupTwitterFeed(container, screenName, callback){
		var query = "http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20twitter.user.status%20WHERE%20screen_name%3D%22"+
			screenName+
			"%22%20and%20count%3D%2230%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";//&callback=
		$.ajax({
				url: query,
				dataType: 'jsonp',
				data: {},
				success: function(data){
//					console.log('data: ',data);
					if(data.query.count){
						var results = data.query.results.status;
						var items = '';
						var max = data.query.count > maxFeedItems ? maxFeedItems :  data.query.count;
						for (var $i = 0; $i < max; $i++){
							var title = $.trim(results[$i].text).trunc(150).parseURL();
							if (title.length > 0)
								items += '<div class="item">'+ title +'</div>';
						}
						$(container).html(items);
						if (typeof callback == 'function'){
							callback.call(this);
						}
					} else {
						$(container).html('Error!');
					}
				}
		});
	}

	function setupEvents(){
		$('#sb-open-close a').click(function(){
			var cls = $(this).attr('class');
			$(this).attr('class', '');
			if (cls == 'opened'){ // opened, so close
				close();
				return false;
			}
			else{
				open();
				return false;
			}
		});
		$('#sb-links a').click(function(){
			$('#sb-links a').removeClass('active');
			var cls = $(this).attr('class');
			$(this).addClass('active');
			$('#social-bar .tab').css('zIndex', 1);
			$('#sb-' + cls).css('zIndex', 100);
			return false;
		});
		$('#social-bar a.play-video').click(function(){
			$(this).colorbox({
				iframe: true,
				innerWidth:580,
				innerHeight: 328,
				close: 'close ( X )',
				top: '150px',
				opacity: 0.75
			})
		});
	}

	var scrollerFacebook = {
		current: -1,
		count: 0
	};
	var scrollerTwitter = {
		current: -1,
		count: 0
	};
	var scrollerFiveOnline1 = {
		current: -1,
		count: 0
	};
	var scrollerFiveOnline2 = {
		current: -1,
		count: 0
	};

	function setupScrollers(){
		setupScroller('#five-online-feed1', scrollerFiveOnline1);
		setupScroller('#five-online-feed2', scrollerFiveOnline2);

		window.setTimeout(function(){
			cycleScrollers();
		}, 1500 + cycleSpeed);
	}

	function setupScroller(scrollerId, counter){
		$(scrollerId + ' .items .item').each(function(idx){
			$(this).addClass('item-' + idx);
			counter.count++;
		});
	}

	function cycleScrollers(){
		cycleScroller('#facebook-feed', scrollerFacebook);
		cycleScroller('#twitter-feed', scrollerTwitter);
		cycleScroller('#five-online-feed1', scrollerFiveOnline1);
		cycleScroller('#five-online-feed2', scrollerFiveOnline2);

		window.setTimeout(function(){
			cycleScrollers();
		}, timeBetweenCycles + cycleSpeed);
	}

	function cycleScroller(scrollerId, counter){
//		console.log(scrollerId + ': ' + counter.current +' of '+counter.count);
		$(scrollerId + ' .item-' + counter.current).animate({
			top: '-120px'
		}, cycleSpeed, function(){
			$(this).css('top', '120px');
		});
		counter.current++;
		// reset if this was the last item
		if (counter.current == counter.count)
			counter.current = 0;
		$(scrollerId + ' .item-' + counter.current).animate({
			top: '0'
		}, cycleSpeed);
	}

	function open(){
		$('#sb-max').show();
		$('#sb-open-close a').addClass('opened').attr('title', 'Hide Social Bar');
		Cufon.set('fontFamily', 'Aller').replace('#sb-open-close a');
		$.cookie('sb-state', 'opened', {expires: getCookieExpiration(), path: '/'});
	}

	function close(){
		$('#sb-max').hide();
		$('#sb-open-close a').addClass('closed').attr('title', 'Show Social Bar');
		Cufon.set('fontFamily', 'Aller').replace('#sb-open-close a');
		$.cookie('sb-state', 'closed', {expires: getCookieExpiration(), path: '/'});
	}

	function getCookieExpiration(){
		var minutes = 30;
		var d = new Date();
		d.setMinutes(d.getMinutes() + minutes);
		return d;
	}

	return {
		init: init
	}
})();


/******************************* cufonStyles ********************************/
var cufonStyles = (function(){
	var timeoutCount = 0;

	function init(){
		setStyles();
		//setStylesTimeout();
	}

	function setStyles(){
		Cufon.set('fontFamily', 'Aller');
		Cufon.replace('#social-bar #sb-open-close a');
		Cufon.replace('#marketing .menu p');
		Cufon.replace('#marketing .menu a span');
		Cufon.replace('#marketing .messages .title');
		Cufon.replace('#marketing .messages .description');
		Cufon.replace('#marketing a.blue-button');
	}

	function setStylesTimeout(){
		window.setTimeout(function(){
			Cufon.set('fontFamily', 'Aller');
			timeoutCount++;
			if (timeoutCount < 5)
				setStylesTimeout();
		},500);
	}

	return {
		init: init
	}
})();


/******************************** marketing *********************************/
var marketing = (function(){

	var runInitialAnimations = true;
	var fadeOutSpeed = 1000;
	var fadeInSpeed = 1000;
	var animationSpeed = 1500;

	function init(){
		$('#marketing .messages .title').fadeOut(0);
		$('#marketing .messages .description').fadeOut(0);
		$('#marketing .messages .button').fadeOut(0);

		runAnimations();
		setupEvents();
	}

	function setupEvents(){
		$('#marketing .menu a').click(function(){
			// stop initial animations if they are still running
			runInitialAnimations = false;

			// the cls tells us what elements to show
			var cls = $(this).attr('class');

			// hide, then show the main image
			var imgId = '#marketing .images #img-' + cls;
			var imgLeft = $(imgId).attr('data-left');
			$('#marketing .images img').animate({
				left: '-500px'
			}, animationSpeed);
			$(imgId).animate({
				left: imgLeft + 'px'
			}, animationSpeed);

			//hide, then show the text messages
			var txtId = '#marketing #msg-' + cls;
			$('#marketing .messages .current .title').fadeOut(fadeOutSpeed, function(){
					$('#marketing .messages .current .description').fadeOut(fadeOutSpeed, function(){
						$('#marketing .messages .current .button').fadeOut(fadeOutSpeed, function(){
							$('#marketing .messages .current').removeClass('current');
							$(txtId + ' .title').css('top', 0).fadeIn(fadeInSpeed, function(){
							$(txtId + ' .description').css('left', 0).fadeIn(fadeInSpeed, function(){
								var btnPos = parseInt($(txtId + ' .description').css('top')) + parseInt($(txtId + ' .description').css('height')) + 15;
								$(txtId + ' .button').css('top', btnPos + 'px').fadeIn(fadeInSpeed);
								$(txtId).addClass('current');
							});
						});
					});
					});

				});

			return false;
		});
	}

	function runAnimations(){
		menuAnimations();

	}

	/*
	 * The initial left menu animations
	 */
	function menuAnimations(){
		$('#marketing .heading').animate({
				left: 0
			}, animationSpeed, function(){
				$('#marketing .button-top').animate({
						left: 0
					}, animationSpeed, function(){
						$('#marketing .button-middle').animate({
								left: 0
							}, animationSpeed, function(){
								$('#marketing .button-bottom').animate({
										left: 0
									}, animationSpeed, function(){
										initialTextAnimations();
										initialImageAnimations();
									});
							});
					});
			});
	}

	/*
	 * The initial main image animations
	 */
	function initialImageAnimations(){
		var imgLeft1 = $('#img-default1').attr('data-left');
		var imgLeft2 = $('#img-default2').attr('data-left');
		$('#img-default1').animate({
				left: imgLeft1 + 'px'
			}, animationSpeed, function(){
				window.setTimeout(function(){
					if (runInitialAnimations){
						$('#img-default1').animate({
							left: '-500px'
						}, animationSpeed);
						$('#img-default2').animate({
							left: imgLeft2 + 'px'
						}, animationSpeed);
					}
				},5000);
			});
	}

	/*
	 * The initial main image animations
	 */
	function initialTextAnimations(){
		$('#msg-default .title').css('top', 0).fadeIn(fadeInSpeed, function(){
			$('#msg-default .description').css('left', 0).fadeIn(fadeInSpeed, function(){
				var btnPos = parseInt($('#msg-default .description').css('top')) + parseInt($('#msg-default .description').css('height')) + 15;
				$('#msg-default .button').css('top', btnPos + 'px').fadeIn(fadeInSpeed, function(){
					$('#marketing .arrows img').animate({
						right: 0,
						bottom: 0
					}, animationSpeed);
				});
			});
		});
		$('#msg-default').addClass('current');
	}

	return {
		init: init
	}
})();


String.prototype.trunc =
	function(n,useWordBoundary){
		var toLong = this.length>n,
			s_ = toLong ? this.substr(0,n-1) : this;
		s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
		return  toLong ? s_ +'...' : s_;
	};
String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
		return url.link(url);
	});
};

$(document).ready(function(){
	socialBar.init();
	cufonStyles.init();
});
$(window).load(function(){
	if ($('#marketing').length)
		marketing.init();
});
