Element.implement({
	injectHTML: function(content, where){
		new Element('div').set('html', content).getChildren().inject(this, where);
		return this;
	},
	toggle: function()
	{
		newDisplay = ( this.getStyle('display') == 'none' ) ? 'block' : 'none';
		this.setStyles({
			'display': newDisplay
		});
		return this;
	},
	show: function()
	{
		this.setStyle('display', 'block');
		return this;
	},
	hide: function()
	{
		this.setStyle('display', 'none');
		return this;
	}
});

var $E = function(selector, filter){
	return ($(filter) || document).getElement(selector);
};

var $ES = function(selector, filter){
	return ($(filter) || document).getElements(selector);
};

accentsTidy = function(s){
	var r=s.toLowerCase();
	r = r.replace(new RegExp("\\s", 'g'),"");
	r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
	r = r.replace(new RegExp("æ", 'g'),"ae");
	r = r.replace(new RegExp("ç", 'g'),"c");
	r = r.replace(new RegExp("[èéêë]", 'g'),"e");
	r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
	r = r.replace(new RegExp("ñ", 'g'),"n");                            
	r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
	r = r.replace(new RegExp("œ", 'g'),"oe");
	r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
	r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
	r = r.replace(new RegExp("\\W", 'g'),"");
	return r;
};


if ( window.addEventListener ) {
	var state = 0, konami = [38,38,40,40,37,39,37,39,66,65];
	window.addEventListener("keydown", function(e) {
		if ( e.keyCode == konami[state] ) state++;
		else state = 0;
		if ( state == 10 && !$('konami_kate') )
		{
			var kate = new Element('img', {
				'src' : staticsHost + '/img/iphone/confirm_kate.png',
				'style': 'position: fixed; bottom: 0; left: -165px; z-index: 9999'
			});
			document.getElement('body').adopt(kate);
			var myFx = new Fx.Tween(kate);
			myFx.start('left', 0);
		}
	}, true);
}

function PWSecurity(password, totallyForbiddenValue)
{
	if ( password.toLowerCase() == totallyForbiddenValue.toLowerCase() ) return 0;

	var points = 0;							// total points
	var j = 0;								// counter (points)
	var n = '0123456789';					// numbers
	var a = 'abcdefghijklmnopqrstuvwxyz';	// alpha letters
	var u = 0;								// upper case count
	var l = 0;								// lower case count
	var an = a + n + a.toUpperCase();		// alpha numeric

	// Length of password - 8 characters recomended
	points = points + (password.length * 2.5);
	if(points > 20){points = 20;}

	// Amount of Numbers - 2 recomended, 3 prefered
	j = 0;
	for(var i = 0;i<password.length;i++)
		{if(n.indexOf(password.substring(i,i+1))!=-1){j+=6.67;}}
	if(j>20){j=20;}
	points += j;

	// Non-Repeating characters - 8 recomended
	j = 0;
	for(i=0;i<password.length-1;i++)
		{if(password.substring(i,i+1) != password.substring(i+1, i+2)){j+= 2.86;}}
	if(j>20){j=20;}
	points += j;

	// Pairs of mixed-case - 2 recomended
	for(i=0;i<password.length;i++)
	{
		if(a.indexOf(password.substring(i, i+1)) != -1){l++;}
		if(a.toUpperCase().indexOf(password.substring(i, i+1)) != -1){u++;}
	}
	if(u>l){j=l*10;}else{j=u*10;}
	if(j>20){j=20;}
	points += j;

	// non-alpha-numeric characters - 2 recomended
	j = 0;
	for(i = 0;i<password.length;i++)
		{if(j < 20){if(an.indexOf(password.substring(i,i+1)) == -1){j+=10;}}}
	if(j>20){j=20;}
	points += j;

	return points;
}

var divName = "tooltip"; // div that is to follow the mouse
var offX = -50;         // X offset from mouse position
var offY = 15;         // Y offset from mouse position
var posx = 0;
var posy = 0;
var popupVisible = false;
var lastContent;
var showPopupTimer = false;
var hidePopupTimer = false;

function mtrack(e)
{
	posx = e.page.x;
	posy = e.page.y;

	if ( popupVisible ) reposTooltip();
}

function reposTooltip()
{
	var tmpLeft = (posx - ($("tooltip").offsetWidth / 2) );

	tmpLeft = Math.min((window.getWidth() + window.getScrollLeft()) - $("tooltip").offsetWidth - 25, tmpLeft);

	if ( tmpLeft < 25 ) tmpLeft = 25;

	$("tooltip").setStyle("left", tmpLeft + "px");
	$("tooltip").setStyle("top", (posy + offY) + "px");
}

function popup(msg,width)
{
	hidePopup();
	if ( lastContent != msg )
	{
		lastContent = msg;
		$("tooltip").set('html', msg);

		if ( width > 0 ) $("tooltip").setStyle("width", width + "px");
		else $("tooltip").setStyle("width", "auto");

		if ( hidePopupTimer ) $clear(hidePopupTimer);
		showPopupTimer = showPopup.delay(500);
	}
}

function kill()
{
	if ( showPopupTimer ) $clear(showPopupTimer);
	hidePopupTimer = hidePopup.delay(150);
}

function showPopup()
{
	$("tooltip").setStyle("left", "-1000px");

	$("tooltip").setStyle("display", "inline");
	reposTooltip();
	popupVisible = true;
	showPopupTimer = false;
}

function hidePopup()
{
	$("tooltip").setStyle("display", "none"); //display = "hidden";
	lastContent = "";
	popupVisible = false;
	hidePopupTimer = false;
}

function textCounter(field, maxlimit)
{
	if ( $chk(URBAN.page.textCounterTimer) ) $clear( URBAN.page.textCounterTimer );
	URBAN.page.textCounterTimer = updateTextCounter.delay(500, this, [field, maxlimit]);
}

function updateTextCounter(field, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);

	if ( !$("msgCounter") ) return;

	$("msgCounter").set('html', field.value.length );

	$("msgCounter").setStyle("background-color", "#FFFEC2");
	new Fx.Tween("msgCounter", {duration:400}).start("#ff0").chain(
		function() {
			this.start("background-color", "#FFFEC2");
			}
	).chain(
		function() {
			if ( $("msgCounter") ) $("msgCounter").setStyle("background-color", "");
		}
	);
}

function insertAtCursor(fieldName, myValue) {
	var myField = $(fieldName);
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
		} else {
		myField.value += myValue;
	}
}

function insertAtCursor2(fieldName, myValue) {
	if(window.tinyMCE) {
		tinyMCE.execInstanceCommand(fieldName,'mceInsertContent',true,myValue);
	} else {
		var myField = $(fieldName);
		//IE support
		if (document.selection) {
			myField.focus();
			sel = document.selection.createRange();
			sel.text = myValue;
		}
		//MOZILLA/NETSCAPE support
		else if (myField.selectionStart || myField.selectionStart == '0') {
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
			} else {
			myField.value += myValue;
		}
	}
}

function openSearchDiv()
{
	$('clickToSearchDiv').style.display='none';
	$('searchDiv').style.display='inline';
	$('searchPseudo').focus();
	$('searchPseudo').select();
}

function startSearch(mode)
{
	if ( mode === undefined ) document.location = '/community/search.php?terms=' + escape($('searchPseudo').value) + '&option=nick';
	else if ( mode == "elo") document.location = '/game/rankings/elo.php?pseudo=' + escape($('searchPseudo').value);
}

function handleSearchKeyPress(e,mode)
{
	var key = window.event ? e.keyCode : e.which;
	if ( key == 13) startSearch(mode);
}

var now = new Date();

function getRemainingTime(date, totalTimeInSeconds)
{
	var myTimestamp = 0;
	var myRegexp, array_date, year, month, day;

	if ( date.test(' ') && !date.test("00:00:00") ) // Case: format = "1978-03-29 11:02:23"
	{
		myRegexp = /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
		array_date = myRegexp.exec(date);

		year = array_date[1];
		month = array_date[2];
		day = array_date[3];
		var hour = array_date[4];
		var minute = array_date[5];
		var second = array_date[6];

		myTimestamp = new Date(year, month - 1, day, hour, minute, second);
	}
	else if ( date.test("00-00-00") ) // Case: format = "1978-03-29"
	{
		myRegexp = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
		array_date = myRegexp.exec(date);

		year = array_date[1];
		month = array_date[2];
		day = array_date[3];

		myTimestamp = new Date(year, month - 1, day);
	}
	else
	{
		// MUST BE millisec
		myTimestamp = new Date(date);
	}

	var remainingTime = (myTimestamp.getTime() + (totalTimeInSeconds * 1000)) - now.getTime() - (now.getTimezoneOffset() - (serverGMTOffset / 100 * 60) * 1000);

	if ( remainingTime < 0 ) return '0h, 0min';

	remainingTime /= 1000; // Convert from milliseconds to seconds

	var hours = Math.floor(remainingTime / (60 * 60));
	var minutes = Math.floor((remainingTime - (hours * 60 * 60)) / 60);
	var seconds = Math.floor(remainingTime - (hours * 60 * 60) - (minutes * 60));

	return hours + 'h, ' + minutes + 'min'; //' '.seconds.'s';
}

function getFormattedNumber(number)
{
	var numberBeautifull = new Array();
	if ( number >= 1000000 )
	{
		myRegexp = /^([0-9]+)([0-9]{3})([0-9]{3})$/;
		numberBeautifull = myRegexp.exec(number);
	}
	else if ( number >= 1000 )
	{
		myRegexp = /^([0-9]+)([0-9]{3})$/;
		numberBeautifull = myRegexp.exec(number);
	}
	else
	{
		numberBeautifull[0] = number;
		numberBeautifull[1] = number;
	}

	output = '';
	for (var i = 1; i < numberBeautifull.length; ++i)
	{
		if ( i != 1) output += ' ';
		output += numberBeautifull[i];
	}

	return output.trim();
}

var enableCache = true;
var jsCache = new Array();

function ajax_loadContent(divId,url)
{
	if(enableCache && jsCache[url]){
		$(divId).innerHTML = jsCache[url];
		return;
	}

	new Request.HTML( {
		'url': url,
		'method': 'get',
		'update': $(divId),
		'evalScripts': true,
		'onRequest': function () {
			$(divId).set('html',  '<img src=/img/loading.gif />' );
		}
	}).send();
}

function switchDivVisibility(divId)
{
	var myDiv = $(divId);
	myDiv.style.display = ((myDiv.style.display == '' || myDiv.style.display == 'none')?'block':'none');
}

function setPlayerPref(pref, val)
{
	new Request({
		'url': '/ajax/set_preference.php',
		'data': {'pref': pref, 'val': val}
	}).send();
}

function changeSitePref(prefKey,prefValue)
{
	var url = "/ajax/change_site_pref.php?prefKey=" + prefKey + "&prefValue=" + prefValue;

	new Request({
		'url': url,
		'method': 'get',
		'onComplete': reloadCurrentPage
	}).send();
}

function reloadCurrentPageURLOnly(arg)
{
	var url = location.protocol + '//' + location.host + location.pathname;
	if ( arg ) url += "?" + arg;
	location.replace( url );
}

function reloadCurrentPage()
{
	location.replace( location.protocol + '//' + location.host + location.pathname + location.search );
}

function getPictureURL(playerID)
{
	return new String(pictureURLStaticDefault).replace('\/0\/', '/' + Math.floor(playerID / 1000) + '/' ).replace('0.jpg', playerID + '.jpg' );
}

function trim(str)
{
	return str.trim();
}

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]';
}

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.substr(1);
};

String.implement({
	count: function(s1) {
		return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
	},

	parseQueryString: function() {
		var vars = this.split(/[&;]/);
		var rs = {};
		if (vars.length) vars.each(function(val) {
			var keys = val.split('=');
			if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
		});
		return rs;
	},

	parseUri: function(){
		var bits = this.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/);
		return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null;
	}
});

/* TABS */
function toggleMenuList( element, selector )
{
	var filter = (selector) ? selector : '.menu_list';
	var menuList = element.getElement( filter );

	if( menuList )
	{
		menuList.toggle();
	}
}

function initDom()
{
	if ( !window.isTouchDevice )
	{
		// Placeholder (disabled for iPhone/iPod Touch)
		if( !Browser.Platform.ipod ){"placeholder"in document.createElement("input")||$$("input").each(function(a){var b=a.get("placeholder"),d=a.getStyle("color");if(b){a.setStyle("color","#aaa").set("value",b).addEvent("focus",function(){if(a.value==""||a.value==b)a.setStyle("color",d).set("value","");}).addEvent("blur",function(){if(a.value==""||a.value==b)a.setStyle("color","#aaa").set("value",b);});var c=a.getParent("form");c&&c.addEvent("submit",function(){a.value==b&&a.set("value","");});}});};

		if ( $('tabsContainerDiv') ) allTabs = $('tabsContainerDiv').getChildren();

		$(document.body).addEvent('mousemove', mtrack.bindWithEvent());

		var assetsToLoad = [
			staticsHost + '/img/v2/ui/tabs/tabs_bgs.jpg'
		];

		// Preload ui images
		new Asset.images(assetsToLoad);

		addPlayerPopup();

		if ( window.playerIsLogged )
		{
			URBAN.roar = new Roar({
				position: 'upperRight',
				duration: 7500 // 5 seconds until message fades out
			});

			if ( !disablePlayerRoarNotification  )
			{

			//window.isForeground = true;
				window.myID = 'Window-' + Math.random();
				URBAN.page.toolbox.setEnv('lastWindow', window.myID);

				planUrbanFeedCheck(false, true);

				window.addEvent('focus', function(e) {
					if ( URBAN.page.toolbox.getEnv('lastWindow') != window.myID )
					{
						URBAN.page.toolbox.setEnv('lastWindow', window.myID);
						planUrbanFeedCheck(false, true);
					}
				});
			}
		}

		if( $('top_form') )
		{
			if ( $('top_search') )
			{
				$('top_form').addEvent('submit', function(evt){
					if( $('top_search', this).value && trim( $('top_search', this).value ) != '' )
					{// Anonymous function cannot return anything
			
					}
					else
					{
						evt.stop();
					}
				});
			}
			
			if( $('top_form').getElement('.flag') )
			{
				$('top_form').getElement('.flag').addEvent('click', function(){
					document.location.href = '/player/edit.php';
				});
			}
		}

		if( document.getElements('.menu') )
		{
			document.getElements('.menu').forEach(function(item, index){
				item.addEvents({
					'mouseenter': function(){
						//toggleMenuList(this);
						var menuList = this.getElement( '.menu_list' );
						if( menuList )
						{
							menuList.show();
						}
					},
					'mouseleave': function(){
						//toggleMenuList(this);
						var menuList = this.getElement( '.menu_list' );
						if( menuList )
						{
							menuList.hide();
						}
					}
				});
			});
		}

		if( document.getElements('.signoff') )
		{
			document.getElements('.signoff').forEach(function(item, index){
				item.addEvent('click', function(evt){
					evt.stop();
					confirmDisconnect(this);
				});
			});
		}

		if( $('locale_selector') )
		{
			var links = document.getElements('#available_locales li a');
			if( links )
			{
				links.forEach(function(item, index){
					item.addEvent('click', function(evt){
						evt.stop();
						var newLocale = item.getProperty('rel');
						var fiveYears = 60 * 60 * 24 * 365 * 5;
						URBAN.page.toolbox.setEnv('locale', newLocale, fiveYears);
						reloadCurrentPage();
					});
				});
			}
		}

		if( $('dropdown') )
		{
			$('dropdown').addEvent('click', function(evt){
				$('top_search_scope').toggle();
			});
			$('drop').addEvent('click', function(evt){
				$('top_search_scope').toggle();
			});

			$('top_search_scope').getElements('a').forEach(function(item, index){
				item.addEvent('click', function(evt){
					evt.stop();
					//$('dropdown').set('text', item.get('text'));
					$('dropdown').setProperty('value', item.get('text'));
					$('search_options').setProperty('value', item.getProperty('rel'));
					$('top_search_scope').toggle();
				});
			});
		}

		if( window.changeTimeZone )
		{
			var ajax = new Request({
				'url': '/ajax/player/index.php',
				'method': 'post',
				'data': {
					'action': 'setTimeZone',
					'id_player': window.playerIsLogged,
					'timeZone': window.timeZone
				}
			}).send();
		}
	}
}

//var roarInitAlreadyDone = false;

function planUrbanFeedCheck(lastRequestHadMessages, windowGotFocus)
{
	$clear(window.feedTimer);

	var feedDelay = Math.round(URBAN.page.toolbox.getEnv('feedDelay'));

	if ( !feedDelay ) feedDelay = 45000;
	else if ( !windowGotFocus )
	{
		feedDelay = (lastRequestHadMessages ? 45000 : feedDelay + 15000);
		if ( feedDelay > 240000 ) feedDelay = 240000;
	}

	URBAN.page.toolbox.setEnv('feedDelay', feedDelay);

	if ( window.myID == URBAN.page.toolbox.getEnv('lastWindow') )
	{
		window.feedTimer = checkUrbanFeed.delay( feedDelay );
	}
}

function checkUrbanFeed()
{
	if ( window.myID != URBAN.page.toolbox.getEnv('lastWindow') ) return;

	//var mustInit = ( !roarInitAlreadyDone && window.roarInit );

	new Request( {
		'url': '/ajax/feed/',
		'method': 'post',
		'data': {'action': 'getFeedForRoar'}, //, 'init': (mustInit ? 1 : 0) },
		'onComplete': function (responseText)
		{
			//roarInitAlreadyDone = true;

			var response = JSON.decode(responseText);
			var previousAlert = false;

			if ( response.feed )
			{
				response.feed = response.feed.reverse();

				response.feed.forEach( function( item ) {

					var imgHtml = ( item['icon'].match('^<img') ? item['icon'] : '<img src="' + item['icon'] + '" align="left" style="margin-right: 10px;"/>');

					if ( !previousAlert )
					{
						URBAN.roar.alert( _("New activity from %s").sprintf(item.player.name), imgHtml + item['text'].join("<br/>") + '<br clear="all"/>' );
						URBAN.roar.items.getLast().getElements('a').setProperty('target', '_blank');

						previousAlert = true;
					}
					else
					{
						URBAN.roar.chain( function() {
							URBAN.roar.alert( _("New activity from %s").sprintf(item.player.name), imgHtml + item['text'].join("<br/>") + '<br clear="all"/>' );
							URBAN.roar.items.getLast().getElements('a').setProperty('target', '_blank');
						});
					}
				});
			}

			planUrbanFeedCheck( $chk(response.feed) );
		}
	}).send();
}

function darkenPopup(callBack, minHeight, anOpacity, aColor)
{
	var opacity = $chk(anOpacity) ? anOpacity : 0.5;
	var color = $chk(aColor) ? aColor : '#000';

	if( !$chk( $('darkPopup') ) )
	{
		var mask = new Element('div').setProperty('id', 'darkPopup').setStyles({
			'position': 'fixed',
			'display': 'none',
			'z-index': 999,
			'top': '0px',
			'left': '0px',
			'right': '0px',
			'bottom': '0px',
			'text-align': 'center'
		}).injectInside( document.getElement('body') );

		if( Browser.Engine.trident4 )
		{
			mask.setStyles({
				'position': 'absolute'
			});
		}
	}

	window.fireEvent('darkPopupWillShow');
	var myFx = new Fx.Tween("darkPopup", {
		duration: 300,
		fps: 15,
		onStart: function()
		{
			$('darkPopup').setStyles(
				{
					display: "block",
					opacity: 0,
					backgroundColor: color,
					padding: 0,
					margin: 0
				}
			);
		},
		onComplete: function()
		{
			window.fireEvent('darkPopupHasShown');
			if ( $chk(callBack) )
			{
				callBack();
			}
			window.fireEvent('darkPopupCallbackCalled');
		}
	});
	myFx.start( "opacity", 0, opacity );
}

function undarkenPopup(callBack)
{
	window.fireEvent('darkPopupWillHide');
	var myFx = new Fx.Tween("darkPopup", {
		duration: 300,
		fps: 15,
		onComplete: function (element) {
			element.setStyle("display", "none");
			if ( $chk(callBack) ) callBack();
			window.fireEvent('darkPopupHasHidden');
		}
	});

	myFx.start( "opacity", 0 );
}

function getDarkDiv()
{
	return $('darkPopup');
}

function setTableGradient(tableID)
{
	var myTable = $(tableID);
	var tableRows = myTable.getElements('tr');

	var tableHeaderCells = myTable.getElements('th');
	var headerColor;
	for ( var i = 0; i < tableHeaderCells.length; ++i )
	{
		if ( tableHeaderCells[i].innerHTML != '' )
		{
			headerColor = new Color(tableHeaderCells[i].getStyle('background-color'));
			break;
		}
	}

	setElementsGradient(tableRows, headerColor, new Color('#fff'), 1);
}

function setElementsGradient(elements, fgColor, bgColor, offset)
{
	if ( !$chk(offset) ) offset = 0;

	for ( var i = offset; i < elements.length; ++i )
	{
		var tmpColor = fgColor.mix(bgColor, 100 * i / (elements.length - offset + 1));
		elements[i].setStyle('background-color', tmpColor);
	}
}

// Illustration rotater
var divIllustrationId;
var arrayIllustrations;
var currentPicture;

function preloadIllustrations(myArrayIllustrations, myDivIllustrationId)
{
	arrayIllustrations = myArrayIllustrations;
	divIllustrationId = myDivIllustrationId;
	currentPicture = 0;

	preloadIllustrationImg( [arrayIllustrations[currentPicture + 1]], function() { URBAN.page.disappearAnimTimer = pictureDisappear.delay(5000); } );
}

function preloadIllustrationImg(src, callback)
{
	// Preload ui images
	new Asset.images( src, { onComplete: callback });
}

function onDailymotionPlayerReady (playerid)
{
	if (playerid == 'trailerdm')
	{
		URBAN.page.dmPlayerLoaded = true;

		$('trailerdm').addEventListener('onStateChange', 'onDailymotionPlayerStateChange');
		replayDailymotionVideo();

		if ( URBAN.page.blockImageRotator )
		{
			$('trailerdm').pauseVideo();
		}
	}
}

function onDailymotionPlayerStateChange (playerstate)
{
	switch(playerstate)
	{
		// Ended
		case 0:
			var replayVideo = function() {
				replayDailymotionVideo();
			};
			replayVideo.delay(60000);
		break;
		
		// Paused
		case 2:
			URBAN.page.dmPlayerPaused = true;
		break;
		
		// Play
		case 1:
			URBAN.page.dmPlayerPaused = false;		
		break;

		// Ready to play
		case 5:
			if ( !URBAN.page.dmPlayerNotFirstTime )
			{
				URBAN.page.dmPlayerNotFirstTime = true;
				URBAN.page.dmPlayerMuted = true;
				$('trailerdm').mute();
			}

			if ( URBAN.page.blockImageRotator ) $('trailerdm').pauseVideo();
		break;
	}
}

function pauseDailymotionVideo () {
	if ( !URBAN.page.dmPlayerPaused && URBAN.page.dmPlayerLoaded ) $("trailerdm").pauseVideo();
}

function switchDailymotionSound()
{
	if ( !URBAN.page.dmPlayerLoaded ) return;

	if ( URBAN.page.dmPlayerMuted ) $('trailerdm').unMute();
	else $('trailerdm').mute();
	
	if ( URBAN.page.dmPlayerMuted )	$('dmTrailerSoundImg').setProperty('src', staticsHost + '/img/v2/icons/speaker.png');
	else $('dmTrailerSoundImg').setProperty('src', staticsHost + '/img/v2/icons/speaker_mute.png');
	
	URBAN.page.dmPlayerMuted = !URBAN.page.dmPlayerMuted;
}

function replayDailymotionVideo ()
{
	if ( !URBAN.page.dmPlayerLoaded ) return;

	var dmTrailerVideoID = 'xd6x6s';
	$('trailerdm').loadVideoById(dmTrailerVideoID);
}

function setImageRotatorBlocked( block )
{
	$clear(URBAN.page.disappearAnimTimer);
	URBAN.page.disappearAnimTimer = undefined;

	if ( block )
	{
		if ( URBAN.page.dmPlayerLoaded )
		{
			$('trailerdm').pauseVideo();
		}
		URBAN.page.blockImageRotator = true;
	}
	else
	{
		if ( URBAN.page.dmPlayerLoaded )
		{
			$('trailerdm').playVideo();
		}
		URBAN.page.blockImageRotator = false;
		pictureDisappear();
	}
}

function pictureDisappear()
{
	if ( URBAN.page.blockImageRotator || !$(divIllustrationId) )
	{
		return;
	}

	if ( typeof($(divIllustrationId).fxDis) == "undefined" )
	{
		$(divIllustrationId).fxDis = new Fx.Tween(divIllustrationId, { duration: 1000, onComplete: pictureAppear } );
	}
	$(divIllustrationId).fxDis.start( "opacity", 1, 0 );
}
function pictureAppear()
{
	++currentPicture;
	if ( currentPicture == arrayIllustrations.length ) currentPicture = 0;
	$(divIllustrationId).setProperty("src", arrayIllustrations[currentPicture]);

	if ( typeof( $(divIllustrationId).fxApp ) == "undefined" )
	{
		$(divIllustrationId).fxApp = new Fx.Tween(divIllustrationId, { duration: 1000, onComplete:
			function ()
			{
				if ( !URBAN.page.blockImageRotator )
				{
					if ( (currentPicture + 1) == arrayIllustrations.length ) URBAN.page.disappearAnimTimer = pictureDisappear.delay(5000);
					else preloadIllustrationImg([arrayIllustrations[currentPicture + 1]], function() { URBAN.page.disappearAnimTimer = pictureDisappear.delay(5000); } );
				}
			}
		} );
	}
	$(divIllustrationId).fxApp.start( "opacity", 0, 1 );
}

function getPersoImgURL( name, famille, level, type, size )
{
	var regExp = new RegExp(" ","g");
	name = name.replace(regExp,"");
	famille = famille.replace(regExp,"");
	return staticsHost + '/urimages/perso/' + (famille + '/' + famille + '_' + name +  '_N' + level + '_' + type + '_' + size).toUpperCase() + '.gif';
}

function getStatusIcon(my_status, size)
{
	size = size ? size : 16;
	return '<img src="' + staticsHost + '/img/status/' + size.toString() + '/' + my_status + '.png" class="onlineStatusBubble iepng" alt="onlineStatus" align="absmiddle"/>';
}

function getClanImgURL( famille, size )
{
	var regExp = new RegExp(" ","g");
	famille = famille.replace(regExp,"");
	return staticsHost + '/urimages/clan/' + (famille + '_' + size).toUpperCase() + '.png';
}

function getFlagImgURL( country, size )
{
	return staticsHost + '/urimages/ranking/' + country.toLowerCase() + '_' + size + '.gif';
}

function getFlagSprite(country, format, extra_styles, extra_classes, id)
{
	if ( country == 'en' ) country = 'us';

	var classes = Array('flag', 'flag_'+format, 'flag_'+format+'_'+country.toLowerCase());
	if(extra_classes)
	{
		classes = classes.concat(extra_classes);
	}

	var img = new Element('img', {'src': staticsHost + '/img/p.gif'});

	if(id)
	{
		img.setProperty('id', id);
	}
	if(extra_styles)
	{
		img.setStyles(extra_styles);
	}
	img.addClass('iepng');
	for(var i = 0; i < classes.length; i++)
	{
		img.addClass(classes[i]);
	}
	return img;
}

function getFlagSpriteTag(country, format, extra_styles, extra_classes, id)
{
	var dummy = new Element('div').adopt( getFlagSprite(country, format, extra_styles, extra_classes, id) );
	return dummy.innerHTML;
}

function linkToObjectByName(objName, obj)
{
	if ( objName == 'player' )
	{
		return '<a href=/player/?id_player=' + obj.id + ' class="playerLink">' + obj.name + '</a>';
	}
	else if ( objName == 'guild' )
	{
		return '<a href=/guild/?id_guild=' + obj.id + ' class="guildLink">' + obj.name + '</a>';
	}
	else if ( objName == 'event' )
	{
		return '<a href=/events/?id_event=' + obj.id + ' class="eventLink">' + obj.name + '</a>';
	}
}

var characterInPreview;
var characterInPreviewTimer;

function setCharacterInPreview(character)
{
	if ( characterInPreview == character )
	{
		return;
	}

	characterInPreview = character;

	if ( characterInPreviewTimer ) $clear(characterInPreviewTimer);

	characterInPreviewTimer = updateCardPreview.delay(400);
}

function updateCardPreview()
{
	if ( $('cardPreviewDiv').model == characterInPreview ) return;

	$('cardPreviewDiv').setStyle("display", "block");

	$('cardPreviewDiv').model = characterInPreview;

	var fullCard = characterInPreview.getFullCard(true);
	fullCard.setStyles({top: '11px', left: '11px'});

	if ( !$('cardPreviewDiv').getFirst() )
	{
		$('cardPreviewDiv').adopt( fullCard );
	}
	else
	{
		fullCard.replaces( $('cardPreviewDiv').getFirst() );
	}
}

// Mission completed - called from flash
function notifyMissionCompleted(missionOfPlayer)
{
}

// Update the XP Bar - called from flash
function updatePlayerXP(level, currentXP, maxXP, clintz)
{
	level = parseInt(Number(level), 10).toString();
	currentXP = parseInt(currentXP, 10);
	maxXP = parseInt(maxXP, 10);
	clintz = parseInt(Number(clintz), 10);

	if( clintz )
	{
		$('playerInfoClintz').set('text', getFormattedNumber(clintz) );
	}

	if(currentXP > maxXP)
	{
		return;
	}


	if( !window.previous_level || window.previous_level < parseInt(Number(level), 10) )
	{
		$('playerMenuLevel').getChildren().forEach(function(el, i){
			if( level.charAt(i).toString() != el.getProperty('alt') )
			{
				if( i == 0 && level.charAt(i).toString() == '' )
				{
					el.destroy();
				}
				else
				{
					var new_src = staticsHost + '/img/v2/ui/player/xpnumbers-orange-black/' + level.charAt(i) + '.gif';
					new Asset.images(new_src);

					new Fx.Tween(el, {'property': 'opacity', 'duration': 200, 'transition': Fx.Transitions.linear, 'onComplete': function(){
						var new_img = new Element('img').setProperties({
													'src': new_src,
													'alt': level.charAt(i),
													'class': 'middle'
												}).injectInside( $('playerMenuLevel') );
						new_img.replaces( el );
					}}).start(1, 0);
				}
			}
		});

		$('playerMenuXP').setProperty('title', getFormattedNumber(currentXP) + ' / ' + getFormattedNumber(maxXP));

		window.previous_level = level;
	}

	newWidth = Math.floor((currentXP*137)/maxXP) + 'px';
	var fx = new Fx.Morph( $('playerMenuXP').getFirst(),
							{
								duration:500,
								transition: Fx.Transitions.Back.easeOut
							}).start({'width': newWidth});
}

function joinChat(channel,newwindow)
{
	urconfirm( _("Clint: Urban Rivals staff do not monitor chat rooms. Users enter at their own risk and hold all responsibilities for what they experience in chat rooms. Clint: Urban Rivals and Clint: Urban Rivals staff are not responsible for what users say and hear in chat rooms.\nUsers under the age of 16 are not allowed in the chat room\n\nNEVER GIVE OUT YOUR PHONE NUMBER, MAIL OR ANY OTHER PERSONNAL INFORMATION ON THE CHAT.\n\nNEVER give out your password to another player. Staff members will NEVER ask for your password."), function() {
		if ( newwindow )
		{
			 window.open('/community/chat/?channel=' + channel, 'urbanchat');
		}
		else
		{
			 window.location = '/community/chat/?channel=' + channel;
		}
	});
}

function confirmDisconnect(element)
{
	urconfirm( _("Are you sure you want to logout ?"), function() {
		window.location = "/?action=signoff";
	} );
}

function getMarketPricesPopup(id_perso, niveau)
{
	if ( !window.minPrices ) return;
	
	var min_price = minPrices[id_perso];
	var avg_price = avgPrices[id_perso];
	var max_price = maxPrices[id_perso];

	var min_price_niveau = minLevelPrices[id_perso + "-" + niveau];
	var avg_price_niveau = avgLevelPrices[id_perso + "-" + niveau];
	var max_price_niveau = maxLevelPrices[id_perso + "-" + niveau];

	var marketPopupTxt = '<span class=boldText>' + _("Value on the Market") + '</span><span class=smallText><br/>' + _("(min/avg/max)") + '<br/><br/>';
	marketPopupTxt += getString(_("At level @0@:"), [niveau]) + "<br/>";

	if ( min_price_niveau ) marketPopupTxt += getFormattedNumber(min_price_niveau) + " Ctz / " + getFormattedNumber(avg_price_niveau) + " Ctz / " + getFormattedNumber(max_price_niveau) + " Ctz";
	else marketPopupTxt += _("Not available on the Market");

	marketPopupTxt += "<br/>";
	marketPopupTxt += _("Any level:") + '<br/>';

	if ( min_price ) marketPopupTxt += getFormattedNumber(min_price) + " Ctz min."; //"/ " + getFormattedNumber(avg_price) + " Ctz / " + getFormattedNumber(max_price) + " Ctz";
	else marketPopupTxt += _("Not available on the Market");
	marketPopupTxt += "</span>";

	return marketPopupTxt;
}

function uploadImage(kind, id, maxSmall, maxNormal)
{
	var url = '/contents/upload_box.php?kind=' + kind + '&id=' + id;

	if ( $chk(maxSmall) ) url += '&maxSmall=' + maxSmall;
	if ( $chk(maxNormal) ) url += '&maxNormal=' + maxNormal;

	window.open(url, 'upload_' + kind + '_' + id, "width=450, height=300, location=no, menubar=no, resizable=no, status=no, scrollbars=no, toolbar=no");
}

function deleteUploadedImage(kind, id)
{
	URBAN.page.popup = new URPopup( _("Are you sure you want to delete the image ?"), {
		type: 'confirm',
		chainable: true,
		onValidate: function() {
			new Request({
				'url': '/ajax/media/',
				'data': {'kind': kind, 'id': id},
				'onComplete': function (responseText) {
					var response = JSON.decode(responseText);
					if ( response.deleted )
					{
						URBAN.page.popup.refresh( _("Image deleted successfully."), {
							onValidate: function() {
								reloadCurrentPage();
							}
						} );
					}
					else
					{
						URBAN.page.popup.refresh( _("There was an error while deleting the image.") );
					}
				}
			}).send();
		}
	} );
}

function setPlayerPopupContent(link, details)
{
	var content = '<a href="#" class="close boldText" title="' + _("Close") + '" style="position: absolute; top: -12px; right: 10px;">x</a>';

	content += '<img src="' + details.pictureURL + '" style="float: left; width: 48px; height: 48px; border: 1px solid #666;"/>';

	content += '<div style="margin-left: 55px; min-height: 50px; overflow: visible;">';
	content += '<div class="boldText" style="height: auto;">';

	my_status = ( details.is_online ) ? 'available' : 'offline';
	content += getStatusIcon(my_status);

	content += linkToObjectByName('player', details);

	content += '<br />';

	content += getFlagSpriteTag(details.country, 16);
	content += ' ';

	content += details.grade;
	content += ' ';
	content += _("Level %s").sprintf(details.level);

	if ( details.stars )
	{
		content += ' ';
		for(var i = 0; i < details.stars; ++i)
		{
			content += '<img src="' + staticsHost + '/img/star.gif"/>';
		}
	}

	content += '</div>';

	if ( details.guild )
	{
		content += '<div class="smallText boldText" style="height: auto;">';
		//content += '<img src="' + staticsHost + '/img/v2/icons/guild.gif" style="vertical-align: middle;"/>';
		content += linkToObjectByName('guild', details.guild);
		content += '</div>';
	}


	content += '<div class="smallText" style="padding-top: 4px; height: auto;">';
	content += '<a href="/player/?id_player=' + details.id + '">' + _("View %s's profile").sprintf(details.name) + '</a>';
	content += '<br />';

	if ( $defined(details.is_friend) )
	{
		content += '<a href="#" class="goToPrivateMsg">' + _("Send a private message") + '</a>';
		content += '<br />';

		if ( details.can_initiate_chat )
		{
			content += '<a href="#" class="startLiveChat">' + _("Start a live chat") + '</a>';
			content += '<br />';
		}

		if ( details.is_friend )
		{
			content += '<a href="#" class="removeFromFriends">' + _("Remove from my Friends List").sprintf(details.name) + '</a>';
		}
		else
		{
			content += '<a href="#" class="addToFriends">' + _("Add to my Friends List").sprintf(details.name) + '</a>';
		}
		content += '<br />';
		if ( details.is_blacklist )
		{
			content += '<a href="#" class="removeFromPersonnalBlacklist">' + _("Remove from my Blacklist").sprintf(details.name) + '</a>';
		}
		else
		{
			content += '<a href="#" class="addToPersonnalBlacklist">' + _("Add to my Blacklist").sprintf(details.name) + '</a>';
		}
	}

	content += '</div>';


	content += '</div>';

	link.updateTooltipContent( content );

	link.tooltip.getElements('.goToPrivateMsg').addEvent('click', function(event) {
		new Event(event).stop();
		var content = _("Enter your message to %s").sprintf(linkToObjectByName('player', details)) + ':';
		content += '<br/>';
		content += '<label><textarea class="body smallText" style="margin-top: 2px; margin-bottom: 2px; border: 1px solid #666; width: 95%; height: 50px;"></textarea></label>';
		content += '<br/>';
		content += '<a href="#" class="send">' + _("Send your message") + '</a>';
		content += ' - ';
		content += '<a href="#" class="cancel">' + _("Cancel") + '</a>';
		link.updateTooltipContent( content );

		link.tooltip.getElement('.body').focus();

		link.tooltip.getElements('.send').addEvent('click', function(event) {
			new Event(event).stop();
			new Request({
				'url': '/ajax/send_private_message.php',
				'data': {
					'action': 'sendPrivateMessage',
					'dest_id': details.id,
					'type': 'normal',
					'message': link.tooltip.getElement('.body').value.trim()
					},
				'onRequest': function()
				{
					link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
				},
				'onComplete': function(responseText) {
					var response = JSON.decode(responseText);
					if ( responseText == -1 )
					{
						link.updateTooltipContent( _("There was an error while sending your message.") );
					}
					else
					{
						link.updateTooltipContent(_("Your message has been sent."));
					}

					(function() {
						setPlayerPopupContent(link, details);
					}).delay(1000);
				}
			}).send();
		});

		link.tooltip.getElements('.cancel').addEvent('click', function(event) {
			new Event(event).stop();
			setPlayerPopupContent(link, details);
		});

	});

	link.tooltip.getElements('.addToFriends').addEvent('click', function(event) {
		new Event(event).stop();
		new Request({
			'url': '/ajax/player/',
			'data': {
				'action': 'addToFriends',
				'id_player': details.id
				},
			'onRequest': function()
			{
				link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
			},
			'onComplete': function(responseText) {
				var response = JSON.decode(responseText);
				if ( response.added )
				{
					link.updateTooltipContent(_("%s has been added to your Contact List!").sprintf(details.name));
					(function() {
						link.fireEvent('tooltiphasshow');
					}).delay(1000);
				}
			}
		}).send();
	});
	link.tooltip.getElements('.removeFromFriends').addEvent('click', function(event) {
		new Event(event).stop();
		new Request({
			'url': '/ajax/player/',
			'data': {
				'action': 'removeFromFriends',
				'id_player': details.id
				},
			'onRequest': function()
			{
				link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
			},
			'onComplete': function(responseText) {
				var response = JSON.decode(responseText);
				if ( response.removed )
				{
					link.updateTooltipContent(_("%s has been removed from your Contact List!").sprintf(details.name));
					(function() {
						link.fireEvent('tooltiphasshow');
					}).delay(1000);

				}
			}
		}).send();
	});

	link.tooltip.getElements('.addToPersonnalBlacklist').addEvent('click', function(event) {
		new Event(event).stop();
		new Request({
			'url': '/ajax/player/',
			'data': {
				'action': 'addToPersonnalBlacklist',
				'id_player': details.id
				},
			'onRequest': function()
			{
				link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
			},
			'onComplete': function(responseText) {
				var response = JSON.decode(responseText);
				if ( response.added )
				{
					link.updateTooltipContent(_("%s has been added to your personnal blacklist.").sprintf(details.name));
				}
				(function() {
					link.fireEvent('tooltiphasshow');
				}).delay(1000);
			}
		}).send();
	});
	link.tooltip.getElements('.removeFromPersonnalBlacklist').addEvent('click', function(event) {
		new Event(event).stop();
		new Request({
			'url': '/ajax/player/',
			'data': {
				'action': 'removeFromPersonnalBlacklist',
				'id_player': details.id
				},
			'onRequest': function()
			{
				link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
			},
			'onComplete': function(responseText) {
				var response = JSON.decode(responseText);
				if ( response.removed )
				{
					link.updateTooltipContent(_("%s has been removed from your personnal blacklist.").sprintf(details.name));
				}
				(function() {
					link.fireEvent('tooltiphasshow');
				}).delay(1000);
			}
		}).send();
	});

	link.tooltip.getElements('.startLiveChat').addEvent('click', function(event) {
		new Event(event).stop();
		up_launchWM( playerIsLogged, details.id, details.name );
	});

	link.tooltip.getElements('.close').addEvent('click', function(event) {
		new Event(event).stop();
		link.hideTooltip();
	});
}

function addPlayerPopup(parent)
{
	if ( window.disablePlayerMiniMenu != undefined && window.disablePlayerMiniMenu ) return;

	var playerLinks = ($(parent) || document).getElements('.playerLink');
	if ( playerLinks )
	{
		var idRegExp = new RegExp('id_player=([0-9]+)');

		playerLinks.forEach( function(link){
			var matches = link.getProperty('href').match( idRegExp );
			if ( matches )
			{
				var id_player = matches[1];

				link.addEvent('tooltipwillshow', function() {
					if ( window.currentPlayerPopup ) window.currentPlayerPopup.hideTooltip();
					window.currentPlayerPopup = link;
				});

				link.addEvent('tooltiphashide', function() {
					if ( window.currentPlayerPopup == link ) window.currentPlayerPopup = undefined;
					link.updateTooltipContent( '<center><img src="' + staticsHost + '/img/loading.gif"/></center>' );
				});

				link.addEvent('tooltiphasshow', function() {
					new Request({
						'url': '/ajax/player/',
						'method': 'post',
						'data': {
							'action': 'getDetails',
							'id_player': id_player
							},
						'onComplete': function(responseText) {
							var response = JSON.decode(responseText);
							if ( response.details )
							{
								var details = response.details;

								setPlayerPopupContent( link, details );
							}
						}
					}).send();
				});

				link.attachTooltip({
					'tooltip': 'bubble',
					'position': 'top leftSide',
					'content': '<center><img src="' + staticsHost + '/img/loading.gif"/></center>',
					'appearEvent': false,
					'disappearEvent': false,
					'width': 275
					});

				link.removeEvents('click').addEvent('click', function (e) {
					var event = new Event(e);

					if ( event.shift || event.control || event.alt || event.meta )
					{
						return;
					}
					else
					{
						event.stop();
						if ( window.currentPlayerPopup == link ) return;
						link.showTooltip();
					}
				});
			}
		});
	}
}

var URBAN = new Object();
URBAN.page = new Object();

window.addEvent('domready', initDom );