
/**
 * Date Time processor for parsing dates in the form of:
 * Mon, 25 Feb 2008 03:09:22 GMT
 *
 * By default, if a timestamp is within a month, time will be displayed as
 * x days, x months ago. If the timestamp flag is used, it will be either
 * today, tomorrow or a timestamp
 *
 * Possible classes:
 * timestamp  	-  show a timestamp, regardless of when the time was
 * abbr       	-  abbreviates time unit names
 * descr		  	-  append either "ago" or "remaining"
 * notime    	-  ommits time from the display, supported with timestamp
 * timeonly  	-  shows only the time, only works with timestamp
 * printable 	-  adds a span.print version of the time for printable formats
 */
(function() {

	// the units we are using to calculate time differences
	var units = {
		year: 60 * 60 * 24 * 365,
		month: 60 * 60 * 24 * 30,
		week: 60 * 60 * 24 * 7,
		day: 60 * 60 * 24,
		hour: 60 * 60,
		minute: 60,
		second: 1
	};

	// define some abbreviations
	var abbrs = {
		year:'yr', month:'mth', hour:'hr',
		minute:'min', second:'sec'
	};

	// finds the biggest unit possible in the seconds, returns a tuple with
	// the unit, the quantity and the number of seconds to decrement by
	var findBiggestUnit = function(seconds) {
		for (var key in units) {
			var qty = Math.floor(seconds / units[key]);
			if(qty != 0) return [key,qty,units[key] * qty];
		}
	}

	// calculates the time difference between two times
	var timeDifference = function(time1, time2) {
		var elapsed = Math.abs((time2.getTime() - time1.getTime()) / 1000);
		var tokens = [];

		// break into chunks of time, in descending order
		while(!isNaN(elapsed) && (chunk = findBiggestUnit(elapsed))) {
			suffix = chunk[1] > 1 ? 's' : '';
			tokens.push(chunk[1] + ' ' + chunk[0] + suffix);
			elapsed -= chunk[2];
		}

		return tokens;
	}

	// returns true if an element has a particular class
	var hasClass = function(element, className) {
		return (
			element.className &&
			element.className.match( new RegExp( "\\b"+className+"\\b" ) )
			) ? true : false;
	}

	// gets the first text node that is a direct child of the span
	var findSpanTextNode = function(element) {
		for(var i=0; i<element.childNodes.length; i++) {
			if(element.childNodes[i].nodeType == 3) {
				return element.childNodes[i];
			}
		}
	}

	// calculates the difference in two dates in days
	var getDifferenceInDays = function(date1, date2) {
		var date2 = !date2 ? new Date() : date2;
		return (date1.getTime()-date2.getTime()) / (1000 * 60 * 60 * 24);
	}

	// formats the timestamp, optionally uses the dateformat library
	var formatTimestamp = function(time,config) {
		var now = new Date();
		var today = new Date(now.getFullYear(), now.getMonth(),
			now.getDate());
		var yesterday = new Date(now.getFullYear(), now.getMonth(),
			now.getDate()-1);
		var tomorrow = new Date(today.getTime() + 24*3600000);

		// calculate time
		var timetext = ', ' + time.getHours() + ':' +
			((time.getMinutes()>10) ? time.getMinutes() : '0' + time.getMinutes());

		if (!config.formatDate) {
			// display a short time if we can
			if(time.getTime() >= (tomorrow.getTime()+24*3600000)) {
				// do nothing for future times
			} else if(time.getTime() >= tomorrow.getTime()) {
				return 'tomorrow' + (config.notime ? '' : timetext);
			} else if(time.getTime() >= today.getTime()) {
				return 'today' + (config.notime ? '' : timetext);
			} else if(time.getTime() >= yesterday.getTime()) {
				return 'yesterday' + (config.notime ? '' : timetext);
			}
		}

		// fall back to a date string
		if(typeof(dateFormat) == 'function') {
			if(config.notime) {
				var monthMask = config.abbreviate ? 'mmm' : 'mmmm';
				var mask = monthMask + ' d, yyyy';
			} else if(config.timeonly) {
				var mask = 'h:MM tt';
			} else if (config.formatDate) {
				var mask = 'h:MM tt ddd d mmm';
			} else {
				var monthMask = config.abbreviate ? 'mmm' : 'mmmm';
				var mask = monthMask + ' d, yyyy h:MM tt';
			}
			return dateFormat(time, mask);
		} else {
			return time.toLocaleString();
		}
	}

	// gets a date object parsed from the span
	var getSpanDate = function(span) {
		var node = findSpanTextNode(span);
		if(!node) return false;
		return span.gmttime ? span.gmttime : new Date(Date.parse(node.nodeValue));
	}

	// process a span with a class of gmttime
	var formatSpan = function(span) {
		var dateString = '';
		var date = getSpanDate(span);
		if(!date) return false;

		var dayDiff = getDifferenceInDays(date);
		var since = dayDiff < 0;

		var config = {
			relative: !hasClass(span, 'timestamp'),
			abbreviate: !hasClass(span, 'timestamp') && hasClass(span,'abbr'),
			timeonly: hasClass(span, 'timeonly'),
			describe: hasClass(span, 'descr') || hasClass(span, 'desc'),
			notime: hasClass(span, 'notime'),
			print: hasClass(span, 'printable'),
			noSeconds: hasClass(span, 'noseconds'),
			formatDate: hasClass(span, 'formatdate'),
			withTitle: hasClass(span, 'withTitle'),
			noTitle: hasClass(span, 'notitle')
		}


		// override relative if the date is more than 28 days old
		if(Math.abs(dayDiff) > 28) config.relative = false;

		// don't show seconds unit
		if (config.noSeconds) {
			delete units.second;
		}

		if(!config.relative) {
			dateString = formatTimestamp(date, config);
		} else if(config.relative && since) {
			dateString = timeDifference(date, new Date())
				.slice(0,2).join(', ');
		} else {
			dateString = timeDifference(date, new Date())
				.slice(0,2).join(', ');
		}

		if(!dateString) {
			dateString = formatTimestamp(date, config);
		} else if(config.describe && config.relative) {
			dateString += since ? ' ago' : ' remaining';
		}

		// optionally use abbreviations
		if(config.abbreviate) {
			for(var a in abbrs) dateString = dateString.replace(a, abbrs[a]);
		}

		// set the title
		if (config.noTitle === false) {
			if (config.withTitle) {
				span.title = dateString;
			}
			else {
				span.title = date.toLocaleString();
			}
		}

		span.gmttime = date;

		// replace the value with the formatted time
		var textNode = findSpanTextNode(span);

		screenSpan = document.createElement('span');
		screenSpan.className = 'screen';
		screenSpan.appendChild(document.createTextNode(dateString));
		span.replaceChild(screenSpan,textNode);

		// optionally, add a print only version
		if(config.print) {
			printSpan = document.createElement('span');
			printSpan.className = 'print';
			printSpan.appendChild(document.createTextNode(date.toLocaleString()));
			span.insertBefore(printSpan,screenSpan);
		}
	}

	// function that sets up a span
	var initializeSpan = function(span) {
		// bind some functions to the span
		span.getDate = function() {return getSpanDate(this);}
		span.format = function() {return formatSpan(this);}

		// process the span
		span.format();
	}

	// process span.gmttime
	if(window.jQuery) {

		// add a jQuery plugin
		jQuery.fn.dateTime = function() {
			return this.each(function(){
				initializeSpan(this);
			});
		};

		// process each span
		jQuery('span.gmttime').dateTime();

	// otherwise, do it the old fashioned way
	} else {
		var spans = document.getElementsByTagName('span');
		for(i=0; i<spans.length; i++) {
			if(hasClass(spans[i], 'gmttime')) initializeSpan(spans[i]);
		}
	}

}());

/**
 * Base library for web services
 */

var Service = Service || {};
Service.Base = {};

(function(Base) {

	Base.ServiceException = function(content) {
		this.message = content.errormessage;
		this.errorcode = content.errorcode;
	};

	/**
	 * Gets the url for a method call
	 */
	Base.urlFor = function(service, version, method) {
		return '/api/'+version+'/rest?service='+
			service+'&format=json&method='+method;
	};

	Base.parseResponse = function(text) {
		// TODO: Remove this function
		if (typeof(text) == 'object') return text;

		var json = eval("("+text+")");
		return json;
	};

	/**
	 * Make a call to the service
	 */
	Base.serviceCall = function(url, params, callback) {
		if(callback) {
			jQuery.post(url,params,function(data){
				callback(Base.parseResponse(data));
			});
		} else {
			var json;
			if (params)
			{
				json = Base.parseResponse(
				jQuery.ajax({type:'POST',url:url,async:false,data:params,dataType:'json'}));
			}
			else
			{
				json = Base.parseResponse(
				jQuery.ajax({type:'POST',url:url,async:false,dataType:'json'}));
			}
			// handle failure
			if(json.status == 'fail') {
				throw new Base.ServiceException(json);
			}

			return json.content;
		}
		return undefined;
	};

	Base.call = function (service, version, method, params, callback) {
		var url = Base.urlFor(service, version, method);
		return Base.serviceCall(url, params, callback);
	};

}(Service.Base));
Service.User = {

	getActiveUser: function (context, callback) {
		if (!context) context = 'default';
		this._call('getActiveUser', { context: context }, function (response) {
			callback(response.content);
		});
	},

	sendPrivateMessage: function (message, recipientid, callback) {
		this._call('sendPrivateMessage', { message: message, recipientid: recipientid }, function (response) {
			callback(response.content);
		});
	},

	sendActivationEmail: function (callback) {
		this._call('sendActivationEmail', { }, function (response) {
			callback(response.content);
		});
	},

	getLaunchCapabilities: function (callback) {
		this._call('getLaunchCapabilities', { }, function (response) {
			callback(response.content);
		});
	},

	getAvatarDisplay: function (size, avatarClass, callback) {
		this._call('getAvatarDisplay', { size: size, avatarClass: avatarClass }, function (response) {
			callback(response.content);
		});
	},

	_call: function (method, params, callback) {
		if (!callback) callback = function(){}; // prevent synchronous Service.Base.call
		return Service.Base.call('user', 'v1', method, params, callback);
	}

};var UserBar = {
	isLoaded: false,
	isLoggedIn: undefined,
	callbacks: [],
	ajaxData: undefined,
	navId: undefined,
	type: undefined,
	users: {},
	seenNotifications: false
};

// reset the userbar callbacks and logged in status
UserBar.reset = function () {
	this.isLoaded = false;
	this.isLoggedIn = undefined;
//	this.callbacks = [];
	this.ajaxData = undefined;
	this.navId = undefined;
	this.type = undefined;
	this.seenNotifications = false;
	return this;
};

// loads a userbar element, needs a data-url attribute
UserBar.load = function (element) {
	if(UserBar.isLoaded)
		UserBar.reset();

	if(this._hasLoginCookie()) {
		var loginBar = $(element);
		var loginStatus = $('<li class="nav-item"><em>Checking Login...</em></li>');
		loginBar.find('.loading').prepend(loginStatus);
		loginBar.load(loginBar.attr('data-url'), function() {
			UserBar.navId = $(this).find(' > ul').attr('id');
			UserBar.type = $('#' + UserBar.navId).data('type');
			UserBar._triggerCallbacks(loginBar.find('#' + UserBar.navId).hasClass('loggedin'));
			UserBar._injectUsers();
		});
	} else {
		UserBar._triggerCallbacks(false);
	}

	return this;
};

UserBar.addUser = function (userid, displayname) {
	UserBar.users[userid] = displayname;
	if(UserBar.isLoaded) UserBar._injectUsers();
};

// callbacks triggered after UserBar.load(), or immediately if already loaded.
UserBar.addCallback = function (callback, forceQueue) {
	if (!forceQueue && UserBar.isLoaded) {
		callback(UserBar.isLoggedIn);
	} else {
		UserBar.callbacks.push(callback);
	}
};

UserBar._injectUsers = function () {
	if(UserBar.type === 'contests') {
		UserBar._injectUserIntoList($('#changable-user-list'));
	}
	else if(UserBar.type === 'stock') {
		UserBar._injectUserIntoSelect($('#become-user-userid'));
	}
};

UserBar._injectUserIntoSelect = function(selectElement) {
	var tmpSelect = selectElement.clone();

	for(userid in UserBar.users) {
		if(tmpSelect.has('option[value='+userid+']').length == 0) {
			tmpSelect.append($('<option value="'+userid+'">'+UserBar.users[userid]+'</option>'));
		}
	}
};

UserBar._injectUserIntoList = function(listElement) {

	for(userid in UserBar.users) {
		if(listElement.has('a[data-user-id='+userid+']').length == 0) {
			listElement.append($('<li><a href="#" data-user-id="'+userid+'">'+UserBar.users[userid]+'</a></li>'));
		}
	}

	var tmp = $('li', listElement).sort(function(a, b) {
		return $(a).text().toLowerCase() > $(b).text().toLowerCase() ? 1 : -1;
	});

	listElement.children().remove();
	listElement.append(tmp);
	listElement.find('a[data-user-id]').click(function() {
		var $elem = $(this);
		var $form = $('#become-user-form');

		$form.find('#become-user-userid').val($elem.data('user-id'));
		$form.submit();
	});
};

UserBar._triggerCallbacks = function (isLoggedIn) {
	UserBar.isLoaded = true;
	UserBar.isLoggedIn = isLoggedIn;
	var callback;
	for (var key in UserBar.callbacks) {
		UserBar.callbacks[key](UserBar.isLoggedIn);
	}
};

UserBar._hasLoginCookie = function () {
	return true;
	return Cookie.get('sessionid') || Cookie.get('usertokens');
};

UserBar.addCallback(function(isLoggedIn) {
	if(!isLoggedIn) return;

	$('#' + UserBar.navId).removeClass('loggedout').addClass('loggedin');
});

UserBar.addCallback(function(isLoggedIn) {
	if(!isLoggedIn || UserBar.type === 'stock' || UserBar.ajaxData === undefined) return;

	if(UserBar.ajaxData.savedSearches !== undefined && (UserBar.ajaxData.savedSearches.count > 0 || UserBar.ajaxData.visitorType == 'designer')) {
		$('#' + UserBar.navId).find('.nav-saved-searches').show();
	}
});

UserBar.update = function(data) {
	if(data === undefined) return;

	var $userbar = $('#' + UserBar.navId);

	if(data.messages !== undefined && data.messages.count > 0) {
		var $inbox = $userbar.find('.nav-item.inbox');
		$inbox.addClass('has-new');
		$inbox.find('a:first').attr('title', data.messages.desc).find('em').html(data.messages.count);
	}

	if(data.notifications !== undefined) {

		if(data.notifications.count > 0) {
			var $notifications = $userbar.find('.nav-item.notifications');
			$notifications.addClass('has-new');
			$notifications.find('a:first').attr('title', data.notifications.desc).find('em').html(data.notifications.count);
		} else {
			UserBar.notificationsRead();
		}
	}

	if(data.savedSearches !== undefined && data.savedSearches.count > 0) {
		var $search = $userbar.find('.nav-item.nav-saved-searches');
		$search.find('a:first').attr('title', data.savedSearches.desc);
	}
};

UserBar.updateScore = function(data) {
	if (!data) return;

	var $userbar = $('#' + UserBar.navId);

	$('.score .points', $userbar).text(data.labeled_points);
	$('.score .currentlevel', $userbar).text(data.level.name);
	$('.score .current.level', $userbar).text(data.level.name);
	$('.score .next.level', $userbar).text(data.next_level.name);
	$('.score .progress .remaining', $userbar).text(data.labeled_remaining + ' to go');
	$('.score .progress .inner', $userbar).css({'width': ''+data.percent+'%'});

	if (data.percent < 50)
	{
		$('.score .progress .remaining', $userbar).addClass('leading');
	}
	else
	{
		$('.score .progress .remaining', $userbar).addClass('trailing');
	}

};

UserBar.notificationsRead = function() {
	$('#' + UserBar.navId)
		.find('.notifications')
		.find('em')
		.text('0')
		.closest('li')
		.removeClass('has-new');
};

UserBar.addCallback(function() {
	var urlFragment = window.location.toString().replace(/^((https?:\/\/)?[^\/]*)/,'');
	$('#become-user-form').find('input[name=from]').val(urlFragment);
});

UserBar.addCallback(function() {
	var loginLink = $('#' + UserBar.navId).find('.login');

	if(loginLink.length === 0) return;

	var urlFragment = window.location.toString().replace(/^((https?:\/\/)?[^\/]*)/,'');
	loginLink.attr('href', loginLink.attr('href') + encodeURIComponent(urlFragment));
});

UserBar.addCallback(function() {
	var registerLink = $('#' + UserBar.navId).find('.register');

	if(registerLink.length === 0) return;

	var urlFragment = window.location.toString().replace(/^((https?:\/\/)?[^\/]*)/,'');
	registerLink.attr('href', registerLink.attr('href') + encodeURIComponent(urlFragment));
});

UserBar.addCallback(function() {
	var updating = false;
	var updated = false;
	var updateScore = function() {
		if (updating || updated) { return; }
		updating = true;
		$.ajax({
			url: '/userbar/userscore',
			type: 'GET',
			success: function(data) {
				UserBar.updateScore(data);
				updated = true;
			},
			complete: function() {
				updating = false;
			}
		});
	};

	$('#' + UserBar.navId).find('.active-area').parent().click(function(event) {
		updateScore();
		$(this).closest('.nav-item').toggleClass('active').siblings().removeClass('active');
		event.preventDefault();
		event.stopPropagation();
	});

	$('#' + UserBar.navId).find('.trigger').find('.active-area').delegate('a', 'click', function(event) {
		event.stopPropagation();
	});

	$('body, html').click(function() {
		$('#' + UserBar.navId).find('.active').removeClass('active');
	});
});

UserBar.addCallback(function() {
	$('#nav-account .notifications').click(function() {
		var $elem = $(this);

		$('#notifications-list')
			.load('/userbar/notifications', function() {
				$elem.find('em').text('0').closest('li').removeClass('has-new').find('span.gmttime').dateTime();
				if(UserBar.seenNotifications === false) {
					setTimeout('sendLastNotified()', '2000');
					UserBar.seenNotifications = true;
				}
			});

		return false;
	});
});

UserBar.addCallback(function(isLoggedIn) {
	$('#' + UserBar.navId).show();
});

jQuery.fn.userBar = function() {
	return this.each(function(){
		UserBar.load(this);
	});
};

$(document).ready(function() {
	$('#userbar').userBar();
	$('a[rel=user][data-userid]').each(function() {
		UserBar.addUser($(this).attr('data-userid'), $(this).text());
	});
});



function sendLastNotified() {
	$.ajax({
		url: '/userbar/notifications/lastnotified',
		type: 'GET',
		success: function() {
			UserBar.notificationsRead();
			$('#notifications-list').find('.unread').removeClass('unread');
		}
	});
};

(function (jQuery) {

	var Carousel = function (list, delay, autorotate) {
		this.list = jQuery(list);
		this.listItems = this.list.find('li').get();
		this.itemWidth = jQuery(this.listItems).width();
		this.animating = false;
		this.autorotate = autorotate == undefined ? true : autorotate;
		this.delay = delay == undefined ? 6000 : delay;
		this.position = 0;

		var carousel = this;
		jQuery(this.listItems).each(function (index, element) {
			jQuery(element).css({
				left: index*carousel.itemWidth,
				display: 'block'
			});
		});

		if (this.autorotate)
		{
			this.autoRotater = setInterval(function () {
				carousel.slideLeft();
			}, this.delay);
		}

		this.list.bind('next', function () {
			carousel.slideLeft();
		});

		this.list.bind('previous', function () {
			carousel.slideRight();
		});
	};

	Carousel.prototype = {
		slideLeft : function () {
			if (!this.animating)
			{
				var carousel = this;
				if (this.autorotate)
				{
					clearInterval(this.autoRotater);
					this.autoRotater = setInterval(function () {
						carousel.slideLeft();
					}, this.delay);
				}
				this.animating = true;
				var position = this.list.position();
				var newPosition = position.left - this.itemWidth;

				var nextItem = jQuery(this.getNextItem());
				var currentItem = jQuery(this.listItems[this.position]);
				nextItem.css('left', currentItem.position().left + this.itemWidth);

				this.list.animate({
					left: newPosition
				}, 1500, 'swing', function () {
					carousel.animating=false;
				});
				this.position = this.getNextPosition();
			}
		},

		slideRight : function () {
			if (!this.animating)
			{
				var carousel = this;
				if (this.autorotate)
				{
					clearInterval(this.autoRotater);
					this.autoRotater = setInterval(function () {
						carousel.slideLeft();
					}, this.delay);
				}
				this.animating = true;
				var position = this.list.position();
				var newPosition = position.left + this.itemWidth;

				var previousItem = jQuery(this.getPreviousItem());
				var currentItem = jQuery(this.listItems[this.position]);
				previousItem.css('left', currentItem.position().left - this.itemWidth);

				this.list.animate({
					left: newPosition
				}, 1500, 'swing', function () {
					carousel.animating=false;
				});
				this.position = this.getPreviousPosition();
			}
		},

		getNextItem : function () {
			return this.listItems[this.getNextPosition()];
		},

		getPreviousItem : function () {
			return this.listItems[this.getPreviousPosition()];
		},

		getNextPosition : function () {
			var nextPosition = this.position + 1;
			return nextPosition % this.listItems.length;
		},

		getPreviousPosition : function () {
			var previousPosition = this.position - 1;
			if (previousPosition < 0)
			{
				previousPosition = this.listItems.length - 1;
			}
			return previousPosition;
		}
	};

	var VerticalCarousel = function (list, delay, autorotate) {
		this.list = jQuery(list);
		this.listItems = this.list.find('li').get();
		this.itemHeight = jQuery(this.listItems).height();
		this.animating = false;
		this.autorotate = autorotate == undefined ? true : autorotate;
		this.delay = delay == undefined ? 6000 : delay;

		var carousel = this;
		jQuery(this.listItems).each(function (index, element) {
			jQuery(element).css({
				top: index*carousel.itemHeight,
				display: 'block'
			});
		});
		this.listItems.unshift(this.listItems.pop());

		if (this.autorotate)
		{
			this.autoRotater = setInterval(function () {
				carousel.slideUp();
			}, this.delay);
		}

		this.list.bind('next', function () {
			carousel.slideUp();
		});

		this.list.bind('previous', function () {
			carousel.slideDown();
		});
	};

	VerticalCarousel.prototype = {
		slideUp : function () {
			if (!this.animating)
			{
				clearInterval(this.autoRotater);
				var carousel = this;
				this.autoRotater = setInterval(function () {
					carousel.slideUp();
				}, this.delay);
				this.animating = true;
				var position = this.list.position();
				var newPosition = position.top - this.itemHeight -1;
				var carousel = this;

				var item = this.listItems.shift();
				jQuery(item).css('top', jQuery(this.listItems[this.listItems.length-1]).position().top + this.itemHeight);
				this.listItems.push(item);

				this.list.animate({
					top: newPosition
				}, 1500, 'swing', function () {
					carousel.animating=false;
				});
			}
		},

		slideDown : function () {
			if (!this.animating)
			{
				clearInterval(this.autoRotater);
				var carousel = this;
				this.autoRotater = setInterval(function () {
					carousel.slideDown();
				}, this.delay);
				this.animating = true;
				var position = this.list.position();
				var newPosition = position.top + this.itemHeight -1;
				var carousel = this;

				var item = this.listItems.pop();
				jQuery(item).css('top', jQuery(this.listItems[0]).position().top - this.itemHeight);
				this.listItems.unshift(item);

				this.list.animate({
					top: newPosition
				}, 1500, 'swing', function () {
					carousel.animating=false;
				});
			}
		}
	};

	jQuery.fn.extend({
		carousel : function (delay, autorotate)
		{
			var carousel = new Carousel(this, delay, autorotate);
			return carousel;
		},
		verticalCarousel : function (delay, autorotate)
		{
			var carousel = new VerticalCarousel(this, delay, autorotate);
			return carousel;
		}
	});
}(jQuery));// load user login bar via Ajax.
//UserBar.load();

(function ($) {

	window.fbAsyncInit = function() {
		FB.Event.subscribe('edge.create', function(response) {
			if (typeof(_vis_opt_top_initialize) == "function") { _vis_opt_register_conversion(201); }
		});
	};

	var log = function(target) {
		if (window.console)
			console.debug(target);
	};

	var track = function(action, value) {
		value = Math.round(value);
		Analytics.trackEvent('Homepage Video', action, '/video-homepage', value);
	};

	var cuePoints = $.map([1,2,3,4,5,6,7,8,9,10,11,12], function(e){
		return e * 10000;
	});

	$('#cta-section .has-dropdown').click(function(e) {
		$(this).toggleClass('active');
		$('#cta-section .dropdown').slideToggle('slow', function() {});

		e.preventDefault();
	});

	$('.video-player').each(function(i) {

		var playerContainer = $(this)
			.attr('id', 'video-player-'+i);

		var clipUrl = $('.video-clip', playerContainer).remove().attr('href');
		var playCount = 0;
		var player = flowplayer('video-player-'+i, playerFlashPath, {
			onLoad: function(){
				log('flash loaded');
			},
			clip: {
				url: clipUrl,
				autoBuffering: true,
				autoPlay: true,
				onBegin: function() {
					log('streaming has started');
				},
				onFinish: function() {
					log('playback has finished');
					track('finished', this.getTime());
					playCount++;

					if (typeof(_vis_opt_top_initialize) == "function") { _vis_opt_register_conversion(200); }
					$('#facebook-container.variation-2').show();
				},
				onPause: function() {
					log('playback has paused');
					track('pause', this.getTime());
				},
				onResume: function() {
					log('playback has resumed');
					track('play', this.getTime());
				},
				onSeek: function() {
					log('seek occurred');
				},
				onStart: function() {
					log('playback has started');
					if (playCount)
						track('replay', this.getTime());
					else
						track('play', this.getTime());
				},
				onStop: function() {
					log('playback has stopped');
					track('stop', this.getTime());
				},
				onBufferEmpty: function() {
					if (this.isPlaying()) {
						log('buffer empty');
						track('bufferempty', this.getTime());
					}
				},
				onCuepoint: [
					cuePoints,
					function() {
						log('cuepoint reached');
						track(Math.round(value)+'seconds', this.getTime());
					}
				]
			},
			canvas: {
				background: 'none',
				backgroundGradient: 'none'
			},
			plugins: {
				controls: {
					backgroundColor: "rgba(0,0,0,0.6)",
					backgroundGradient: "none",
					sliderColor: '#FFFFFF',
					volumeSliderColor: '#FFFFFF',
					tooltipColor: 'rgba(0,0,0,0.6)',
					tooltipTextColor: '#FFFFFF',
					scrubberHeightRatio: 1,
					volumeSliderHeightRatio: 1,
					time: false,
					autoHide: {
						enabled: true,
						fullscreenOnly: false,
						hideStyle: 'move'
					}
				}
			}
		}).ipad();
	});


	$('#choosecountry .arrow').click(function(e) {
		e.preventDefault();
		$('#choosecountry').toggleClass('click');
	});

	$('#choosecountry[class!="click"] .option').live('click', function(e) {
		e.preventDefault();
		$('#choosecountry').toggleClass('click');
	});

	$('#choosecountry.click .option').live('click', function(e) {
		$('#choosecountry .option').hide();
		jQuery(this).show();
		$('#choosecountry').removeClass('click');
		$('#choosecountry').unbind();
		$('#choosecountry').die();
	});

	$('*').live('click', function(e) {
		if (!$('#choosecountry').hasClass('click')) return;

		// clicking outside dropdown closes it
		if (jQuery.contains($('#choosecountry')[0], this)) {
			e.stopImmediatePropagation();
		} else {
			$('#choosecountry').removeClass('click');
		}
	});

})(jQuery);

