jQuery.exists = function(selector) {return ($(selector).length > 0);}
var emailRegEx = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i; 
var subscriptions = [];

google.setOnLoadCallback(function()
{
	$(document).ready(function(){
		if(loggedIn)
		{
			subscriptions = jQuery.secureEvalJSON(getCookie("roomSubscriptions"));
			if(subscriptions == null)
			{
				subscriptions = [];
			}

			$.get(contextPath + '/user/getmyid', function(feedback) {
				userId = parseInt($(feedback).find('loggedInUserId').text());

				if(userId != Number.NaN)
				{
					serverTime = new Date(Date.parse($(feedback).find('now').text()));
					localTime = new Date();
					timeCorrection = Math.round((serverTime.getTime() + serverTime.getTimezoneOffset() - localTime.getTime() + localTime.getTimezoneOffset()) / 1000);

					/**
					 * Messages
					 */
					setTimeout(function() {checkForNewMessages(userId);}, 1000);

					/**
					 * Achievements
					 */
					setTimeout(function() {checkForNewAchievements(userId);}, 2000);

					/**
					 * Room subscriptions
					 */
					setTimeout(function() {checkRoomSubscriptions(userId, timeCorrection);}, 500);
				}
			});
		}
	});
});

function getCookie(cookie_name)
{
	results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

	if (results)
	{
		return unescape(results[2]);
	}
	else
	{
		return null;
	}
}

function setCookie(name, value, exp_y, exp_m, exp_d, path, domain, secure)
{
	cookie_string = name + "=" + escape(value);

	if (exp_y)
	{
		expires = new Date(exp_y, exp_m, exp_d);
		cookie_string += "; expires=" + expires.toGMTString();
	}

	if (path)
	{
		cookie_string += "; path=" + escape(path);
	}

	if (domain)
	{
		cookie_string += "; domain=" + escape(domain);
	}

	if (secure)
	{
		cookie_string += "; secure";
	}

	document.cookie = cookie_string;
}

function checkForNewAchievements(userId)
{
	$.get(contextPath + '/user/' + userId + '/achievements/anynew', function(feedback) {
		now = $(feedback).find('now').text();
		if(getCookie("achievementsDate") != now)
		{
			setCookie("achievementsDate", now, null, null, null, contextPath + "/");

			anyNew = parseInt($(feedback).find('anyNew').text());
			if(anyNew == 1)
		  	{
		  		newAchievementsAlert(userId);
			}
		}
		
		setTimeout(function() {checkForNewAchievements(userId);}, 600000);
	});
}

function newAchievementsAlert(userId)
{
	if(!$('.newAchievementPopup').length)
	{   
		// create html
		newAchievementImage = $('<img>').attr('src', templateRootPath + '/images/achievements/layout/newAchievement.png');
		newAchievementA = $('<a>').attr('href', contextPath + '/user/' + userId + '/messages/list').html(newAchievementImage);
		newAchievementDiv = $('<div>').addClass('newAchievementPopup').append(newAchievementA);
		$('body').append(newAchievementDiv);
	}
  	
  	// display animation
  	$('.newAchievementPopup img').animate(
		{right: ['0','easeOutBounce']},
		1500,
		function() {
			// when done => wait & disappear
	  		$('.newAchievementPopup img').delay(15000).animate({right: '-500'}, 1000, function() {});
  		}
	);
}

function checkForNewMessages(userId)
{
	$.get(contextPath + '/user/' + userId + '/messages/anynew', function(feedback) {
		newMessageCount = parseInt($(feedback).find('newMessageCount').text());
		if(newMessageCount > 0)
	  	{
	  		setInterval(newMessageAlert, 1000);
		}
		
		setTimeout(function() {checkForNewMessages(userId);}, 600000);
	});
}

function newMessageAlert()
{
	messageIcon = $("#messageNotification");
	if(messageIcon.attr("src") == messageIcon.attr("src").replace('-normal.png', "-new.png"))
	{
		messageIcon.attr("src", messageIcon.attr("src").replace('-new.png', "-normal.png"));
	}
	else
	{
		messageIcon.attr("src", messageIcon.attr("src").replace('-normal.png', "-new.png"));
	}
}

(function (Date, undefined) {
	var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
	Date.parse = function (date) {
		var timestamp, struct, minutesOffset = 0;

		if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
			for (var i = 0, k; (k = numericKeys[i]); ++i) {
				struct[k] = +struct[k] || 0;
			}

			struct[2] = (+struct[2] || 1) - 1;
			struct[3] = +struct[3] || 1;

			if (struct[8] !== 'Z' && struct[9] !== undefined) {
				minutesOffset = struct[10] * 60 + struct[11];

				if (struct[9] === '+') {
					minutesOffset = 0 - minutesOffset;
				}
			}

			timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
		}
		else {
			timestamp = origParse ? origParse(date) : NaN;
		}

		return timestamp;
	};
}(Date));

function checkRoomSubscriptions(userId, timeCorrection)
{
	now = new Date();
	now.setSeconds(now.getSeconds() + timeCorrection);

	firstSubscription = null;
	for(i in subscriptions)
	{
		subscription = subscriptions[i];
		startTime = new Date(Date.parse(subscription.startTime.replace(/\+([0-9]{2})([0-9]{2})$/, "+\$1:\$2")));

		if(now > startTime)
		{
			unsubscribeFromRoom(subscription.roomId, userId);

			if(subscription.userId == userId)
			{
				roomField = $("<input>").attr("name", "roomId").attr("type", "hidden").val(subscription.roomId);
				form = $("<form>").attr("method", "post").attr("action", contextPath + "/game/afvalrace/play").append(roomField);
				
				loaderImage = $("<img>").attr("style", "top: 45%; position: relative;").attr("src", templateRootPath + "/images/loading.gif");
				loader = $("<div>").attr("style", "width: 100%; height: 100%; background-color: grey; position: absolute; left: 0; top: 0; opacity:0.4; filter:alpha(opacity=40); text-align: center;").append(loaderImage);
				$("body").append(loader);

				joinDelay = 4000 + Math.round(Math.random() * 16000);
				setTimeout(function()
				{
					$("body").append(form);
					form.submit();
				}, joinDelay);
			}
		}
		else if(firstSubscription == null || startTime < new Date(Date.parse(firstSubscription.replace(/\+([0-9]{2})([0-9]{2})$/, "+\$1:\$2"))))
		{
			firstSubscription = subscription.startTime;
		}
	}

	if(firstSubscription != null)
	{
		if($("#lastManStandingTimer").html() == "" || firstSubscription != $("#lastManStandingTimer").attr("startTime"))
		{
			showLastManStandingTimer(firstSubscription, timeCorrection);
		}
	}
	else
	{
		$("#lastManStandingTimer").remove();
	}

	setTimeout(function() {checkRoomSubscriptions(userId, timeCorrection);}, 3000);
}

function showLastManStandingTimer(time, timeCorrection)
{
	function onFlashPlaced(e) {
		flashMovie = e.ref;
	}

	var flashvars = {
		startTime: time,
		timeCorrection: timeCorrection
	};

	var params = {
		play: "false",
		loop: "false",
		menu: "false",
		scale: "noscale",
		wmode: "transparent",
		seamlesstabbing: "true",
		allowfullscreen: "true",
		allowscriptaccess: "always",
		allownetworking: "all",
		base: templateRootPath + "/swf/AfvalraceBanner/"
	};

	var attributes = {};
	attributes.id = "lastManStandingTimer";
	
	if($("#lastManStandingTimer").length == 0)
	{
		$("<div>", {id: "lastManStandingTimer"}).prependTo("#container");
	}

	swfobject.embedSWF(templateRootPath + "/swf/AfvalraceBanner/AfvalraceBanner.swf", "lastManStandingTimer", "220", "45", "10.1",templateRootPath + "/swf/expressInstall.swf", flashvars, params, attributes, onFlashPlaced);
	$("#lastManStandingTimer").attr("startTime", time);
}

function subscribeToRoom(roomId, startTime, userId)
{
	if(userId == undefined)
	{
		$.get(contextPath + '/user/getmyid', function(feedback) {
			userId = parseInt($(feedback).find('loggedInUserId').text());

			if(userId != Number.NaN)
			{
				for(subscription in subscriptions)
				{
					if(subscriptions[subscription].roomId == roomId)
					{
						subscriptions.splice(subscription);
					}
				}

				subscriptions.push({"roomId": roomId, "userId": userId, "startTime": startTime});
				setCookie("roomSubscriptions", jQuery.toJSON(subscriptions), null, null, null, contextPath + "/");
			}
		});
	}
	else
	{
		for(subscription in subscriptions)
		{
			if(subscriptions[subscription].roomId == roomId)
			{
				subscriptions.splice(subscription);
			}
		}

		subscriptions.push({"roomId": roomId, "userId": userId, "startTime": startTime});
		setCookie("roomSubscriptions", jQuery.toJSON(subscriptions), null, null, null, contextPath + "/");
	}
}

function unsubscribeFromRoom(roomId, userId)
{
	if(getCookie("roomSubscriptions") != null)
	{
		if(userId == undefined)
		{
			$.get(contextPath + '/user/getmyid', function(feedback) {
				userId = parseInt($(feedback).find('loggedInUserId').text());

				if(userId != Number.NaN)
				{
					for(i in subscriptions)
					{
						if(subscriptions[i].roomId == roomId && subscriptions[i].userId == userId)
						{
							subscriptions.splice(i, 1);
						}
					}

					setCookie("roomSubscriptions", jQuery.toJSON(subscriptions), null, null, null, contextPath + "/");
				}
			});
		}
		else
		{
			for(i in subscriptions)
			{
				if(subscriptions[i].roomId == roomId && subscriptions[i].userId == userId)
				{
					subscriptions.splice(i, 1);
				}
			}

			setCookie("roomSubscriptions", jQuery.toJSON(subscriptions), null, null, null, contextPath + "/");
		}
	}
}

