String.prototype.ucfirst = function()
{
	return this[0].toUpperCase() + this.substr(1, this.length);
};

var Cycler = function(cycler, options)
{
	var $cycler = $(cycler);
	var cyclerHeight = 0;
	var settings = $.extend({}, $.fn.cyclerDefaults, options);
	var vars = {
		currentInstance: 0,
		counter: 0,
		instances: [],
		numInstances: 0,
		timer: 0
	};

	vars.instances = $('.instance', $cycler).clone();
	vars.numInstances = vars.instances.length;
	
	if(vars.numInstances < 2)
	{
		return;
	}
	
	$('.instance', $cycler).each(function(i, instance)
	{
		if($(instance).height() > cyclerHeight)
		{
			cyclerHeight = $(instance).height();
		}
	});
	
	$('.instance', $cycler).remove();
	$(cycler).height(cyclerHeight);

	var cycle = function($cycler)
	{
		var isFirst = $('.instance', $cycler).length == 0;
		
		if(settings.crossFade)
		{
			$($('.instance', $cycler)[0]).fadeOut(settings.fadeDuration, settings.easing, function() { $(this).remove(); });
		}

		$instance = $(vars.instances[vars.currentInstance]);
		$(cycler).append($instance);
		
		if(!isFirst)
		{
			$instance.hide();
			$instance.fadeIn(settings.fadeDuration, settings.easing, function()
			{
				$(this).siblings().remove();
				lab1111.initFancybox();
			});
		}

		vars.currentInstance++;
		
		if(vars.currentInstance == vars.numInstances)
		{
			vars.currentInstance = 0;
		}
	};
	
	vars.timer = setInterval(function() { cycle($cycler) }, settings.interval);
	$cycler.data('cycler.vars', vars);
	cycle($cycler);
};
	
$.fn.cyclerDefaults = {
	crossFade: false,
	easing: 'swing',
	fadeDuration: 1000,
	interval: 2000
};
		
jQuery.fn.extend(
{
	blankify: function()
	{
		return this.each(function()
		{
			if(($(this).attr('href').indexOf('http://lab1111.com/') == -1) && ($(this).attr('href').indexOf('localhost') == -1))
			{
				$(this).attr('target', '_blank');
			}
		});
	},
	
	cyclify: function(options)
	{
        return this.each(function()
        {
        	var cycler;
			
            if(cycler = $(this).data('cycler'))
            {
            	return cycler;
            }
            
            cycler = new Cycler(this, options);
            $(this).data('cycler', cycler);
        });
	},
	
	linkify: function()
	{
		return this.each(function()
		{
			var text = $(this).text();
			text = text.replace(/(https?:\/\/\S+)/g, '<a href="$1">$1</a>');
			text = text.replace(/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/#!/$2">@$2</a>');
			text = text.replace(/(^|\s)#(\w+)/g, '$1<a class="dark" href="http://search.twitter.com/search?q=%23$2">#$2</a>');
			$(this).html(text);
		});
	},
	
	scrollify: function()
	{
		return this.each(function()
		{
			var $scroller = $(this);
			var itemWidth = $('li:last-child', $scroller).outerWidth(true);
			var itemsPerView = Math.ceil($(this).width() / itemWidth);
			var numItems = $('li', $scroller).length;
			var numViews = Math.ceil(numItems / itemsPerView);

			$('.scroller-inner', $scroller).width(numItems * itemWidth);
			
			if(numViews > 1)
			{
				var $nav = $('<ul class="scroller-nav" />');
				var $bullet;
			
				for(var i = 0; i < numViews; i++)
				{
					var scrollBy = i * -(itemsPerView * itemWidth);
				
					if((i + 1) * itemsPerView > numItems)
					{
						scrollBy -= (numItems - ((i + 1) * itemsPerView)) * itemWidth;
					}
				
					$bullet = $('<li><a data-scroll-to="' + scrollBy + '" href="#">' + i + '</a></li>');
					
					$('a', $bullet).click(function(e)
					{
						e.preventDefault();
						var scrollTo = $(this).attr('data-scroll-to');
						$scrollerInner = $('.scroller-inner', $scroller);
						var left = parseInt($scrollerInner.css('left'));
						$scrollerInner.animate({left: scrollTo}, Math.abs(left - scrollTo), 'easeOutExpo');
						$('.scroller-nav a.active', $scroller).removeClass('active');
						$(this).addClass('active');
					});
					
					$nav.append($bullet);
				}
				
				$('li:first-child a', $nav).addClass('active');
				$(this).append($nav);
				$nav.css('left', ($scroller.width() - $nav.width()) * 0.5);
			}
		});
	}
});

/* lab1111 */

var lab1111 =
{
	init: function()
	{
		lab1111.initNav();
		lab1111.initFancybox();
		lab1111.cam.init();
		lab1111.twitter.getLatest();
		
		$('a[href^="http://"]').blankify();
		$('#product-screens').cyclify({fadeDuration: 500, easing: 'easeInOutQuad', interval: 4000});
		$('#iphone-small .cycler').cyclify({fadeDuration: 500, easing: 'easeInOutQuad', interval: 4000});
		$('#quotes').cyclify({crossFade: true, easing: 'easeOutQuad', interval: 6000});
		$('.scroller').scrollify();
	},
	
	initFancybox: function()
	{
		$('.videobox').click(function(e)
		{
			e.preventDefault();
		
			$.fancybox({
				autoScale: false,
				height: 480,
				href: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				margin: 16,
				overlayColor: '#000',
				overlayOpacity: 0.75,
				padding: 3,
				speedIn: 250,
				speedOut: 250,
				swf: {allowfullscreen: 'true', wmode: 'transparent'},
				titleShow: false,
				type: 'swf',
				transitionIn: 'elastic',
				transitionOut: 'fade',
				width: 853
			});
		});
		$('.youtube').click(function(e)
		{
			e.preventDefault();
		
			$.fancybox({
				autoScale: false,
				height: 480,
				href: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				margin: 16,
				overlayColor: '#000',
				overlayOpacity: 0.75,
				padding: 3,
				speedIn: 250,
				speedOut: 250,
				swf: {allowfullscreen: 'true', wmode: 'transparent'},
				titleShow: false,
				type: 'swf',
				transitionIn: 'elastic',
				transitionOut: 'fade',
				width: 853
			});
		});
		$('.vimeo').click(function(e)
		{
			e.preventDefault();
			$.fancybox({
				autoScale: false,
				height: 480,
				href: this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
				margin: 16,
				overlayColor: '#000',
				overlayOpacity: 0.75,
				padding: 3,
				speedIn: 250,
				speedOut: 250,
				swf: {allowfullscreen: 'true', wmode: 'transparent'},
				titleShow: false,
				type: 'swf',
				transitionIn: 'elastic',
				transitionOut: 'fade',
				width: 853
			});
		});
		
		$('a[rel="product-media"]').fancybox({
			changeSpeed: 250,
			easingIn: 'easeOutQuad',
			easingOut: 'easeOutQuad',
			margin: 16,
			overlayColor: '#000',
			overlayOpacity: 0.75,
			padding: 3,
			speedIn: 250,
			speedOut: 250,
			titleShow: false,
			transitionIn: 'elastic',
			transitionOut: 'elastic'
		});
        return false;

	},
	
	initNav: function()
	{
		$('#top nav > ul > li').hover(function()
		{
			$('.sub', $(this)).slideDown(250);
		},
		function()
		{
			$('.sub', $(this)).hide();
		});
	}
};

lab1111.cam =
{
	activeCam: null,
	activeCamURL: null,
	cams: [],
	cycle: 15000,
	disabled: false,
	intervalCycle: null,
	intervalTime: null,
	menuOpen: false,
	numCams: 0,
	refresh: 3000,
	timeoutCam: null,
	valueNone: 'Geen camera',

	init: function()
	{
		lab1111.cam.blink();
		
		$('#viewers').load('http://lab1111.com/get/active_visitors');
		
		// Cam is disabled by default when viewing a product
		if(lab1111.cam.disabled)
		{
			// Add product title to cam menu for reverting to product visual
			$li = $('<li><a data-cam="' + lab1111.cam.valueNone + '">' + lab1111.cam.valueNone + '</a></li>');
			$('#cam-list').append($li);
			lab1111.cam.view(lab1111.cam.valueNone);
		}
		
		// Get online cams
		$.getJSON('http://lab1111.com/cams/get/?jsoncallback=?', {}, function(data)
		{
			lab1111.cam.cams = data.cams;
			lab1111.cam.numCams = data.cams.length;
			var $li;
			
			// Add cams to menu
			$.each(data.cams, function(i, c)
			{
				// Add live-indicator to team nav item
				$('[data-cam="' + c.name + '"]').addClass('live');
				
				$li = $('<li><a data-cam="' + c.name + '">' + c.name.ucfirst() + '</a></li>');
				$('#cam-list').append($li);
			});
			
			if(!lab1111.cam.disabled)
			{
				if(lab1111.cam.activeCam)
				{
					// Cam specified
					lab1111.cam.view(lab1111.cam.activeCam);
				}
				else
				{
					// No cam specified: let's cycle!
					lab1111.cam.view(data.cams[Math.floor(Math.random() * lab1111.cam.numCams)].name);
					lab1111.cam.intervalCycle = setInterval(lab1111.cam.viewRandom, lab1111.cam.cycle);
				}
			}
		});
		
		$('#cam').click(lab1111.cam.toggleMenu);
		
		lab1111.cam.updateTime();
		lab1111.cam.intervalTime = setInterval(lab1111.cam.updateTime, 1000);
	},
	
	blink: function()
	{
		$('#live').fadeTo(500, 0).fadeTo(500, 1, lab1111.cam.blink);
	},
	
	toggleMenu: function(e)
	{
		e.preventDefault();
		e.stopPropagation();
	
		if(!lab1111.cam.menuOpen)
		{
			$('#cam').addClass('open');
			$('#cam ul').slideDown(200);
			$(document).bind('click', lab1111.cam.toggleMenu);
		}
		else
		{
			console.log('toggle');
		
			$selectedCam = $(e.target);
			$(document).unbind('click');
			
			if($selectedCam.attr('data-cam'))
			{
				if(lab1111.cam.intervalCycle)
				{
					clearInterval(lab1111.cam.intervalCycle);
				}
			
				lab1111.cam.view($selectedCam.attr('data-cam'));
			}
		
			$('#cam ul').slideUp(100, function()
			{
				$('#cam').removeClass('open');			
			});
		}
	
		lab1111.cam.menuOpen = !lab1111.cam.menuOpen;
	},
	
	update: function()
	{
		if(lab1111.cam.activeCamURL)
		{
			var src = lab1111.cam.activeCamURL + '?ac=' + new Date().getTime();
			var $img = $('<img alt="" class="cam">');
			
			$img.load(function()
			{
				if($('#visual').children().length)
				{
					$(this).hide().appendTo('#visual').fadeIn(250, 'easeOutQuad', function()
					{
						$('.cam:not(:last-child)').remove();	
					});
				}
				else
				{
					$(this).appendTo('#visual');
					$('.cam:not(:last-child)').remove();
				}
			}).attr('src', src);
		}
		
		lab1111.cam.timeoutCam = setTimeout(lab1111.cam.update, lab1111.cam.refresh);
	},
	
	updateTime: function()
	{
		var now = new Date();
		var h = String('00' + now.getHours());
		h = h.substr(h.length - 2);
		
		var m = String('00' + now.getMinutes());
		m = m.substr(m.length - 2);
		
		var s = String('00' + now.getSeconds());
		s = s.substr(s.length - 2);
		
		$('#current-time').text(h + ':' + m + ':' + s);
		if((now.getSeconds() % 15) == 0)
		{
			$('#viewers').load('http://lab1111.com/get/active_visitors');
		}		
	},
	
	view: function(cam)
	{
		// Clear timeout
		if(lab1111.cam.timeoutCam)
		{
			clearTimeout(lab1111.cam.timeoutCam);
		}
	
		$('#cam-select').html(cam.ucfirst());
		
		if(cam == lab1111.cam.valueNone)
		{
			// Revert to visual
			$('.cam').fadeOut(1000, 'easeOutQuad', function() { $(this).remove(); });
			lab1111.cam.activeCam = null;
			lab1111.cam.activeCamURL = null;		
		}
		else
		{
			// Set selected cam if available
			$.each(lab1111.cam.cams, function(i, c)
			{
				if(c.name == cam)
				{
					$('#cam-select').attr('data-cam', cam);
					lab1111.cam.activeCam = cam;
					lab1111.cam.activeCamURL = c.url;
					lab1111.cam.update();
				}
			});
		}
	},
	
	viewRandom: function()
	{
		var randomCam = lab1111.cam.cams[Math.floor(Math.random() * lab1111.cam.numCams)].name;
	
		while(randomCam === lab1111.cam.activeCam)
		{
			randomCam = lab1111.cam.cams[Math.floor(Math.random() * lab1111.cam.numCams)].name;
		}
	
		lab1111.cam.view(randomCam);
	}
};

lab1111.twitter =
{
	users: Array(
		'jeroedeb',
		'meinmotion',
		'oscaralexander',
		'parragraaff'
	),
		
	getLatest: function()
	{

		var url = 'http://search.twitter.com/search.json?q=';
		
		if($('#tweets').attr('data-for'))
		{
			url += 'from%3A' + $('#tweets').attr('data-for');
		}
		else
		{
			if($('#tweets').attr('data-hashtag'))
			{
				url += $('#tweets').attr('data-hashtag') + '%20AND%20';
			}
		
			for(i = 0; i < lab1111.twitter.users.length; i++)
			{
				url += 'from%3A' + lab1111.twitter.users[i] + '%20OR%20';
			}
			
			url = url.substr(0, url.length - 8);
		}
	
		url += '&result_type=recent&rpp=10&callback=?';
	
		$.getJSON(url, function(json)
		{
			var $li;
			var count = 1;
			var createdAt;
			
			$.each(json.results, function(index, tweet)
			{
				if(count < 4)
				{
					if(tweet.to_user_id == null)
					{
						createdAt = lab1111.utils.parseDate(new Date(tweet.created_at), true);
						$li = $('<li class="clear" />');
						$li.append('<img alt="' + tweet.from_user + '" src="' + tweet.profile_image_url + '">');
						$li.append('<div><h5><a href="http://twitter.com/#!/' + tweet.from_user + '">' + tweet.from_user + '</a></h5><p class="tweet-text">' + tweet.text + '</p><p class="dark">' + createdAt + '</p></div>');
						$('#tweets').append($li);
						count++;
					}
				}
				
				$('.tweet-text').linkify();
				$('a[href^="http://"]').blankify();
			});
		});
	}
};

lab1111.utils =
{
	parseDate: function(date, withTime)
	{
		var months = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'];
		var ret = '';
		ret += date.getDate() + ' ';
		ret += months[date.getMonth()] + ' ';
		ret += date.getFullYear();
		
		if(withTime)
		{
			var h = String('00' + date.getHours());
			h = h.substr(h.length - 2);
			var m = String('00' + date.getMinutes());
			m = m.substr(m.length - 2);
			ret += ' (' + h + ':' + m + ')';
		}
		
		return ret;
	}
};

lab1111.user =
{
	init: function(user)
	{
		$.getJSON('http://lab1111.com/facebook/get.php', {u: user}, function(data, textStatus, jqXHR)
		{
			if(data.checkin.id)
			{
				var c = data.checkin;
				var center = c.latitude + ',' + c.longitude;
				
				$('<img />')
    				.load(function()
    				{
						$('.team-checkin-map').append($(this));
						$(this).fadeIn();
					})
					.hide()
					.attr('src', 'http://maps.google.com/maps/api/staticmap?center=' + center + '&zoom=12&size=224x168&maptype=roadmap&language=nl&markers=color:red%7C' + center + '&sensor=false');

				$('#checkin h4').html('<a href="http://www.facebook.com/' + c.id + '" target="_blank">' + c.name + '</a>');
				$('#checkin p').html(c.street + ', ' + c.city + '<br><span class="dark">' + c.created_time + '</span>');
			}
			else
			{
				$('#checkin .loader').addClass('none');
				$('#checkin h4').addClass('dark').html('Geen check-in gevonden');
			}
			
			$like_list = $('.team-likes li');
			var like;
			
			for(var i = 0; i < data.likes.length; i++)
			{
				like = data.likes[i];
				$li = $($like_list[i]);
				$li.hide().html(
					'<h5>' + like.category + '</h5>' +
					'<a class="medium" href="http://www.facebook.com/' + like.id + '" target="_blank">' + like.name + '</a><br>' +
					'<span class="dark">' + like.created_time + '</span>').fadeIn();
			}
		});
	}
};

$(document).ready(lab1111.init);
