﻿{ /***************Craft********************/
	var g_cm = {
		skills: {},
		currentSkill: 0,
		highestSkill: 0,
		numCraftedItems: 0,
		LoadFirstSkills: function(){
			g_unloadFunction2 = this.Reset.bind(this);
			for (var i in this.skills)
			{
				this.skills[i].Load( true);
			}
		},
		Load: function( p_limited, p_limitedItems){
			this.loaded = true;
			g_mainChar.LoadSkills();
			this.usableSkill = p_limited;
			g_unloadFunction2 = this.Reset.bind(this);
			
			if ($('RecipeListIn'))
			{
				$('RecipeListIn').update();
			}
			
			this.LoadFriendList();
			if ( ! p_limited)
			{
				var l_newcurrent = 0;
				for (var i in this.skills)
				{
					this.skills[i].Load( false, true);
					if (this.skills[i].current){l_newcurrent = i;}
				}
				if (l_newcurrent == 0)
				{
					for (var i in this.skills)
					{
						if (this.skills[i].currentLevel > 0 && this.skills[i].type != 1){l_newcurrent = i;}
					}
				}
				if (l_newcurrent != 0)
				{
					this.skills[l_newcurrent].SetCurrent();
				}
				$('Tab_SkillsOpener').onclick = function(){$('Tab_Skills').show();$('RecipeList').hide()};
			}
			else
			{
				this.skills[p_limited].Load();
				this.skills[p_limited].SetCurrent( p_limitedItems);
			}
		},
		Reset: function(){
			this.handler_id = false;
			this.percent = 0;
			this.selectedItemId = 0;
			this.usableSkill = false;
			this.recipes = {};
			this.loaded = false;
			this.confirmedFriend = 0;
		},
		SetBuyableSkills: function( p_skills){
			this.buyableSkills = p_skills;
		},
		GetMaxXpForLevel: function( p_level){
			return 8 + 2 * p_level;
		},
		Finish: function(){
			
			$('button_build').hide();
			++ this.numCraftedItems;
			this.handler_id = false;
			$('send_item', 'store_item', 'sell_item').invoke('show');
		},
		StartProgressBar: function(){
			if ( ! this.handler_id)
			{
				$('Bar_On').setStyle({left:-320 *g_map.allScale +  'px'});
				this.handler_id = new Effect.Move('Bar_On',{transition:Effect.Transitions.linear,duration:3.0,x:320*g_map.allScale,mode:'relative',afterFinish:this.Finish.bind(this)});
				$('SpanPub').hide();
				UpdateEncartPub();
			}
		},
		SellItem: function(){
			if (this.selectedItemId != 0)
			{
				new Ajax.Request( '/callback/craft_item.php', { method: 'post', parameters: {item : this.selectedItemId, action : 'sell'}} );
			}
			this.selectedItemId = 0;
			$('SpanPub').show();
			$( 'Build').hide();
		},
		StoreItem: function(){
			if (this.selectedItemId > 0)
			{
				new Ajax.Request( '/callback/craft_item.php', { method: 'post', parameters: {item : this.selectedItemId, action : 'store'}} );
			}
			this.selectedItemId = 0;
			$('SpanPub').show();
			$( 'Build').hide();
		},
		SendTo: function(){
			new Ajax.Request( '/callback/craft_item.php', { method: 'post', parameters: {item : this.selectedItemId, action : 'send', targetid: this.confirmedFriend}, onSuccess: function(p_ans){
				this.selectedItemId = 0;
			}} );
			
			$('FilterFriendList').value = '';
			TableFilter( '','table_', 1);
			$('ListMain').show();
			$('SpanPub').show();
			$('ListMain_friends', 'Build').invoke('hide');
		},
		PreSendTo: function(p_id){
			this.confirmedFriend = p_id;
			g_confirm.Show( g_text.craft['confirm'],'_contents',this.SendTo.bind(this));
		},
		UpdateSkill: function( p_level, p_xp){
			if ($('CurrentSkillXP'))
			{
				$('CurrentSkillXP').update( p_xp + ' / ' +  (8 + p_level*2));
				$('CurrentSkillLevel').update( p_level);
			}
			if (this.skills[this.currentSkill])
			{
				this.skills[this.currentSkill].Update( p_level, p_xp);
			}
		},
		ShowFriendList: function(){
			$( 'ListMain').hide();
			$( 'ListMain_friends').show();
		},
		LoadFriendList: function(){
			new Ajax.Updater( 'ListMain_friends', '/callback/get_friend_list.php', {evalScripts:true, method: 'post'});
		}
	};g_cm.Reset();
	var Skill = new Class.create({
		initialize: function( p_id, p_price, p_minPopu, p_minSkill, p_background, p_type){
			this.id = p_id;
			this.type = p_type;
			this.price = p_price;
			this.minPopu = p_minPopu;
			this.minSkill = p_minSkill;
			this.background = p_background;
			this.tiers = {};
			this.recipes = {};
			this.currentLevel = 0;
			this.currentXp = 0;
			this.current = false;
			this.currentTier = 0;
			g_cm.skills[this.id] = this;
		},
		Update: function( p_level, p_xp){
			this.currentXp = p_xp;
			if (p_level > this.currentLevel)
			{
				this.currentLevel = p_level;
				for (var i in this.tiers)
				{
					if (this.tiers[i].CorrectTierFor(this.currentLevel))
					{
						this.currentTier = i;
						break;
					}
				}
				if (this.tiers[this.currentTier])
				{
					this.tiers[this.currentTier].LoadOnList( this.currentLevel, this.currentXp, false);
				}
				this.SetCurrent();
			}
		},
		Load: function( p_firstSkills, p_limitedList){
			if (this.currentLevel == 0){return;}
			if (p_firstSkills && this.type != 1){return;}
//			if (p_limitedList && this.type == 1 && this.currentLevel > 0){return;}
//			if (this.currentLevel == 0 && g_cm.buyableSkills && ! g_cm.buyableSkills[this.id]){return;}
			for (var i in this.tiers)
			{
				if (this.tiers[i].CorrectTierFor(this.currentLevel))
				{
					this.currentTier = i;
					break;
				}
			}
			if (this.tiers[this.currentTier])
			{
				this.tiers[this.currentTier].LoadOnList( this.currentLevel, this.currentXp, p_firstSkills);
			}

			if ( ! p_firstSkills)
			{
				if (g_cm.currentSkill == this.id)
				{
					this.SetCurrent();
				}
			}
		},
		SetActive: function( p_level, p_xp, p_current){
			if (p_current == 1)
			{
				g_cm.currentSkill = this.id;
			}
			
			this.currentLevel = p_level;
			this.currentXp = p_xp;
			
			if (this.currentLevel > 0 && this.price == 0)
			{
				g_mainChar.numBaseSkills ++;
			}
			
			if (this.currentLevel > g_cm.highestSkill)
			{
				g_cm.highestSkill = this.currentLevel;
			}
		},
		MouseOver: function(){
			if (this.currentLevel > 0)
			{
				var l_descr = '<h3>' + this.tiers[this.currentTier].name + '</h3>'+(g_text.gen['level'])+' : ' + this.currentLevel + ' (Xp : ' + this.currentXp + ' / ' + g_cm.GetMaxXpForLevel( this.currentLevel) + ')';
				tooltip.show( l_descr);
			}
			else
			{
				var l_descr = '<h3>' + this.tiers[this.currentTier].name + '</h3><hr class="grey"/>'+this.tiers[this.currentTier].desc+'<br/>';
				if (this.price > 0)
				{
					l_descr += AddTagIf( '<strong>', this.price + ' '+g_text.gen['kaz'], g_mainChar.credits < this.price, '</strong>') + '<br />';
				}
				else
				{
					l_descr += AddTagIf( '<strong>', g_mainChar.numBaseSkills * 500 + ' '+g_text.gen['kaz'], g_mainChar.credits < g_mainChar.numBaseSkills * 500, '</strong>') + '<br />';
				}
				
				if (this.minPopu > 0)
				{
					l_descr += AddTagIf( '<strong>', this.minPopu + ' '+g_text.gen['popu_short'], g_mainChar.popu < this.minPopu, '</strong>') + '<br />';
				}
				tooltip.show( l_descr);
			}
		},
		SetCurrent: function( p_limitedItems){
			$('RecipeListIn').update();
			$('RecipeList').show();
			$('Build').hide();
			var linkItems = true;
			if (this.type == 1 || this.type == 2)
			{
				if (this.id != g_cm.usableSkill)
				{
					linkItems = false;
				}
				var tierImg = '';
				for (var i in this.tiers)
				{
					tierImg = this.tiers[i].icon;
					break;
				}
				$('SpanInfoGather').show();
				$('SpanInfoGatherIn').update('<img src="/i/s/'+g_mainChar.language+'/r/'+tierImg+'"style="width:100%">');
			}
			else
			{
				$('RecipeList').show();
				$('SpanInfoGather').hide();
			}
			this.tiers[this.currentTier].LoadAsActive( this.currentLevel, this.currentXp);
			for (var i in this.recipes)
			{
				if (p_limitedItems && !p_limitedItems[i]){continue;}
				this.recipes[i].Load( this.currentLevel, linkItems);
			}
			g_cm.currentSkill = this.id;
		},
		Click: function(){
			$('Tab_Skills').hide();
			if (this.currentLevel > 0 && g_cm.currentSkill != this.id)
			{
				this.SetCurrent();
				new Ajax.Request( '/callback/skills.php', { method:'post',parameters:{a:'chsk',id:this.id},evalScripts:true});
			}
			else if (this.currentLevel == 0)
			{
				if (confirm( g_text.craft['skill_click']))
				{
					new Ajax.Request( '/callback/skills.php', { method:'post',parameters:{a:'buysk',id:this.id},evalScripts:true});
				}
			}
			return false;
		}
	});
	var SkillTier = new Class.create({
		initialize: function( p_id, p_refSkill, p_minLevel, p_maxLevel, p_icon, p_name, p_desc, p_minTier){
			if (!g_cm.skills[p_refSkill]){return;}
			this.id = p_id;
			this.minLevel = p_minLevel;
			this.maxLevel = p_maxLevel;
			this.icon = p_icon;
			this.name = p_name;
			this.desc = p_desc;
			this.minTier = p_minTier;
			this.refSkill = p_refSkill;
			g_cm.skills[p_refSkill].tiers[this.id] = this;
		},
		LoadAsActive: function( p_level, p_xp){
			$('CurrentSkillName').update( this.name);
			$('CurrentSkillLevel').update( p_level);
			$('CurrentSkillXP').update( p_xp + ' / ' + g_cm.GetMaxXpForLevel( p_level));
			$('CurrentSkillIcon').src='/i/s/' + g_mainChar.language +'/'+ this.icon;
		},
		LoadOnList: function( p_level, p_xp, p_firstSkill){
			if (p_level == 0 && this.minTier > g_mainChar.tier){return;}
			var div = new Element( 'span', {'class':'base i64'});
			var ele = new Element( 'a', {href:'javascript:;'});
			
			div.onmouseover = g_cm.skills[this.refSkill].MouseOver.bind( g_cm.skills[this.refSkill]);
			div.onmouseout = tooltip.hide.bind(tooltip);

			ele.onclick = g_cm.skills[this.refSkill].Click.bind( g_cm.skills[this.refSkill]);
			ele.update( '<img class="i64" src="' + '/i/s/' + g_mainChar.language + '/'+ this.icon + '">');

			if (p_level == 0 && ! p_firstSkill)
			{
				ele.insert( '<img class="i64 top_left0"src="/i/nometier.png"/>');
			}

			div.update( ele);

			$('SkillList').insert( div);
		},
		CorrectTierFor: function( p_level){
			return this.minLevel <= p_level && p_level <= this.maxLevel;
		}
	});
	var SkillRecipe = Class.create({
		initialize: function( p_id){
			this.o = g_itemManager.items[p_id];
			if ( ! g_cm.skills[this.o.refSkill]){return;}
			this.id = p_id;
			g_cm.skills[this.o.refSkill].recipes[this.id] = this;
			this.unavailable = true;
			this.recipeItems = [];
			g_cm.recipes[this.id] = this;
		},
		AddRqI: function(p_itemId, p_num){
			this.recipeItems.push({i:p_itemId,n:p_num});
		},
		Load: function( p_level, p_useLink){
			var div = new Element( 'span', {'class':'base i64'});
			var ele = new Element( 'a', {href:'javascript:;'});
			ele.update( '<img class="i64" src="' + this.o.icon + '">');

			div.onmouseover = this.MouseOver.bind( this);
			div.onmouseout = tooltip.hide.bind(tooltip);
			
			if (p_level == 0 || this.o.minSkill > p_level)
			{
				this.unavailable = true;
				ele.insert( '<img class="i64 top_left0"src="/i/defisnofait.png"/>');
			}
			else
			{
				this.unavailable = false;
				if (p_useLink)
				{
					ele.onclick = this.Click.bind(this);
				}
				else
				{
					ele.onclick = this.Click2.bind(this);
				}
			}
			
			div.update( ele);

			$('RecipeListIn').insert( div);
		},
		MouseOver: function(){
			tooltip.show( '<h3>' + this.o.name + '</h3>' + this.o.value + ' '+g_text.gen['kaz'] + (this.unavailable?'<br />'+g_text.gen['level']+' ' + this.o.minSkill:''));
		},
		Click2: function(){
			new Effect.Pulsate('SpanInfoGather');
		},
		Click: function(){
			g_cm.selectedItemId = this.id;
			g_cm.percent = 0;
			$('SpanPub').hide();
			$('Bar_On').setStyle({left:-320 *g_map.allScale +  'px'});
			$('ItemRecipeDetails').update();
			$('SpanInfoGather').hide();
			
			var l_craft = false;
			for (var i = 0 ; i < this.recipeItems.length; i++)
			{
				if (l_craft)
				{
					$('ItemRecipeDetails').insert( ' + ');
				}
				l_craft = true;
				var l_i = g_itemManager.items[this.recipeItems[i].i];
				var l_num = this.recipeItems[i].n;
				$('ItemRecipeDetails').insert('<img src="'+l_i.icon+'"class="i32m" onmouseover="tooltip.show(\''+l_i.name+' x '+l_num+'\')" onmouseout="tooltip.hide()"> x '+l_num);
			}
			
			if (l_craft)
			{
				$('ItemRecipeDetails').insert(' => ');
			}
			
			
			$('ItemPic').src = this.o.icon;
			$('ItemName').update( this.o.name);
			$('send_item', 'sell_item', 'store_item', 'SpanPub').invoke('hide');
			$('button_build', 'Build').invoke('show');
		}
	});
}
{ /***************Shop*********************/
	var g_shop = {
		persoTxt: {},
		items: {},
		fadingConfirm: false,
		confirmBuy: false,
		Load: function( p_shopId){
			this.items = {};
			UpdateEncartPub();
			this.loaded = true;
			g_unloadFunction2 = this.Reset.bind(this);
			for (var i in g_itemManager.items)
			{
				var item = g_itemManager.items[i];
				if (item.actions.b && item.tier <= g_mainChar.tier && item.shops[p_shopId]){new ShopItem(item.id);}
			}

			for (var i in this.items)
			{
				this.items[i].Load();
			}
		},
		Reset: function(){
			this.selectedItem = 0;
			this.loaded = false;
			if (this.fadingConfirm)
			{
				this.fadingConfirm.cancel();
				this.fadingConfirm = false;
			}
		},
		BuyItem: function(){
			$('PerChooseAction').hide();
			var l_item = this.items[this.selectedPersoItem];
			if ( ! l_item)
			{
				return;
			}
			new Ajax.Request( '/callback/perso.php', { method:'post',parameters:{a:'buyitem','id':l_item.id}});
		},
		Confirm: function(p_storing){
			var l_item = this.items[this.selectedPersoItem];
			if ( ! l_item)
			{
				return;
			}
			g_confirm.Show(this.persoTxt.c + l_item.o.value+' Kaz ?','_contents',p_storing?this.StoreItem.bind(this):this.BuyItem.bind(this));
		},
		StoreItem: function(){
			$('PerChooseAction').hide();
			var l_item = this.items[this.selectedPersoItem];
			if ( ! l_item)
			{
				return;
			}
			new Ajax.Request( '/callback/perso.php', { method:'post',parameters:{a:'storeitem','id':l_item.id}});
		},
		ShowConfirmed: function(p_img, p_itemId){
			$('Perso_InfoDiv').update( this.persoTxt.e + '<img src="/i/r/'+p_img+'" class="i24m"/>');
			$('Perso_InfoDiv').show();
			this.fadingConfirm = new Effect.Fade('Perso_InfoDiv',{duration:5,delay:3});
			if (this.confirmBuy)
			{
				this.confirmBuy( p_itemId);
			}
		}
	};g_shop.Reset();
	var ShopItem = Class.create({
		initialize : function( p_id){
			this.o = g_itemManager.items[p_id];
			this.id = p_id;
			this.tooltip = '';
			g_shop.items[this.id] = this;
		},
		Load: function(){
			$('Perso_Shop_'+this.o.rank).insert( '<span class="base" id="PersoItem_'+this.id+'"><a href="" onmouseover="g_shop.items['+this.id+'].Tooltip()" onmouseout="tooltip.hide()" onclick="return g_shop.items['+this.id+'].Select()"><img class="KazuTama_Item" src="'+this.o.icon+'"/></a></span>');
		},
		Select: function(){
			var l_div = $('PerChooseAction');
			if (!l_div){return;}
			g_shop.selectedPersoItem = this.id;
			l_div.show();
//			$('PersoItem_'+this.id).appendChild( l_div);
			return false;
		},
		Tooltip: function(){
			if (this.tooltip.length == 0)
			{
				this.tooltip = '<h3>'+this.o.name+' ('+this.o.value+' Kaz)</h3><ul>';
				if (this.o.stats.h > 0){this.tooltip += '<li>'+g_shop.persoTxt.h+' : +'+this.o.stats.h+'</li>';}
				if (this.o.stats.s > 0){this.tooltip += '<li>'+g_shop.persoTxt.s+' : +'+this.o.stats.s+'</li>';}
				if (this.o.stats.f > 0){this.tooltip += '<li>'+g_shop.persoTxt.u+' : +'+this.o.stats.f+'</li>';}
				if (this.o.stats.b > 0.0){this.tooltip += '<li>'+g_shop.persoTxt.b + ' : +'+(this.o.stats.b * 100.0)+' %</li>';}
				this.tooltip +='</ul>';
			}
			tooltip.show(this.tooltip);
		}
	});
}
{ /***************Inventaire***************/
	var g_inv = {
		Load: function(){
			this.loaded = true;
			g_unloadFunction2 = this.Reset.bind( this);
		},
		Reset: function(){
			this.items = {};
			this.currentInventoryAction = 0;
			this.selectedId = 0;
			this.loaded = false;
		},
		Finalise: function(){
			for (var i in this.items)
			{
				this.items[i].Finalise();
			}
		},
		SetLanguage: function( p_del, p_sell, p_store){
			this.deleteText = p_del;
			this.sellText = p_sell;
			this.storeText = p_store;
		},
		DetailsInit: function( p_item){
			p_item.setStyle({left:0,top:0});
			$('InvConfNumInput').value='1';
			$('InventoryConfirmItemId').value = p_item.instanceId;
			$('InventoryConfirmImg2').src=this.items[p_item.instanceId].o.icon;
			$('InventoryConfirmNum').show();
			$('InvConfNumInput').focus();
			this.selectedId = p_item.instanceId;
		},
		DeleteItem: function( p_item){
			if ( ! p_item || ! p_item.instanceId || ! this.items[p_item.instanceId]) {return;}
			this.currentInventoryAction = 'delete';
			$('InventoryConfirmImg').src='/i/trash.png';
			$('InventoryConfirmText').update( this.deleteText);
			this.DetailsInit( p_item);
		},
		SellItem: function( p_item){
			if ( ! p_item || ! p_item.instanceId || ! this.items[p_item.instanceId]) {return;}
			this.currentInventoryAction = 'sell';
			$('InventoryConfirmImg').src='/i/market.png';
			$('InventoryConfirmText').update( this.sellText);
			this.DetailsInit( p_item);
		},
		HighlightUsed: function( p_id){
			new Effect.Highlight( p_id, { startcolor: '#BBBBBB', endcolor: '#ffffff'});
		},
		StoreItem: function( p_item){
			this.HighlightUsed( 'Shelves');
			p_item.setStyle({left:0,top:0});
			new Ajax.Request( '/callback/inventory.php', { method:'post',parameters:{action:'store',item:p_item.instanceId},evalScripts:true});
		},
		UseItem: function( p_item){
			if (!p_item || !p_item.instanceId || ! this.items[p_item.instanceId]){return;}
			this.currentInventoryAction = 'use';
			$('InventoryConfirmImg').src= $('Inv_Yourself').src;
			$('InventoryConfirmText').update( this.storeText);
			this.DetailsInit( p_item);
		},
		Confirm: function(){
			if ($('InventoryConfirmItemId').value == '0')
			{
				return this.Cancel();
			}
			
			if (this.currentInventoryAction == 'sell')
			{
				this.HighlightUsed( 'Shop');
				new Ajax.Request( '/callback/inventory.php', { method: 'post', parameters: {action:'sell',item : $('InventoryConfirmItemId').value, num:$('InvConfNumInput').value},evalScripts:true});
			}
			else if (this.currentInventoryAction == 'delete')
			{
				this.HighlightUsed( 'Trash');
				new Ajax.Request( '/callback/inventory.php', { method: 'post', parameters: {action:'delete',item : $('InventoryConfirmItemId').value, num:$('InvConfNumInput').value},evalScripts:true});
			}
			else if (this.currentInventoryAction == 'use')
			{
				this.HighlightUsed( 'Inv_Yourself');
				new Ajax.Request( '/callback/inventory.php', { method: 'post', parameters: {action:'use',item : $('InventoryConfirmItemId').value, num:$('InvConfNumInput').value},evalScripts:true});
			}
			
			return this.Cancel();
		},
		Cancel: function(){
			this.currentInventoryAction = '';
			$('InventoryConfirmItemId').value = '0';
			$('InventoryConfirmNum').hide();
			return false;
		},
		RemoveNItems: function( p_item, p_num){
			if (this.items[p_item])
			{
				this.items[p_item].RemoveN( p_num);
			}
		}
	};g_inv.Reset();
	var InvItem = Class.create({
		initialize: function( p_id, p_num){
			this.id = p_id;
			this.o = g_itemManager.items[p_id];
			this.num = p_num;
			this.draggable = null;
			this.tooltip = '';
			
			var l_cont = new Element('span',{id:'InventItem_'+this.id,'class':'base '+(this.o.actions.q?'':' deletable storable ')+(this.o.actions.u?' usable ':'')+(this.o.actions.s?' sellable ':'')});
			l_cont.setStyle({margin:'0.125em'});
			l_cont.onmouseover = this.MouseOver.bind(this);
			l_cont.onmouseout = tooltip.hide.bind(tooltip);
			
			l_cont.update('<img class="h48" src="'+this.o.icon+'"/>');
			if (this.o.actions.q)
			{
				l_cont.insert( '<div class="bottom_left" id="InventItem_Num_' + this.id + '" style="color:red"><strong>Q</strong></div>');
			}
			if (this.num > 1)
			{
				l_cont.insert( '<div class="bottom_right0" id="InventItem_Num_' + this.id + '" style="width:1.125em;height:1em;margin-right:0;background:url(\'/i/iconeenvelope.png\');text-align:right;">'+this.num+'</div>');
			}
			$('InventoryMain').insert( l_cont);
			g_inv.items[this.id] = this;
		},
		MouseOver: function(){
			if (this.tooltip.length == 0)
			{
				this.tooltip = '<h3>'+this.o.name+(this.o.actions.s?' ('+this.o.value+' '+g_text.gen['kaz']+')':'')+'</h3>';
				if (this.o.actions.u)
				{
					this.tooltip += '<hr/>'+g_text.craft['kaz']+' :<br/><ul>';
					if (this.o.stats.h > 0){this.tooltip += '<li>'+g_shop.persoTxt.h+' : +'+this.o.stats.h+'</li>';}
					if (this.o.stats.s > 0){this.tooltip += '<li>'+g_shop.persoTxt.s+' : +'+this.o.stats.s+'</li>';}
					if (this.o.stats.f > 0){this.tooltip += '<li>'+g_shop.persoTxt.u+' : +'+this.o.stats.f+'</li>';}
					if (this.o.stats.b > 0.0){this.tooltip += '<li>'+g_shop.persoTxt.b + ' : +'+(this.o.stats.b * 100.0)+' %</li>';}
					this.tooltip +='</ul>';
				}
				if (this.o.actions.q)
				{
					this.tooltip += '<hr/><font color=red>'+g_text.craft['quest']+'</font><br/>';
				}
			}

			tooltip.show( this.tooltip);
		},
		UpdateN: function( p_amount){
			$('InventItem_'+this.id).setStyle({left:0,top:0});
			if (this.num <= 0)
			{
				this.draggable.destroy();
				delete g_inv.items[this.id];
				new Effect.Fade('InventItem_'+this.id);
			}
			else
			{
				if (this.num > 1)
				{
					$('InventItem_Num_' + this.id).update( this.num);
				}
				else
				{
					$('InventItem_Num_' + this.id).hide();
				}
			}
		},
		RemoveN: function( p_amount){
			this.num -= p_amount;
			this.UpdateN();
		},
		Finalise: function(){
			if (this.quest){return;}
			this.draggable = new Draggable( 'InventItem_' + this.id, { revert:'failure'});
			$('InventItem_' + this.id).instanceId = this.id;
		}
	});
}
{ /***************Postbox******************/
	var g_pb = {
		numMailsPerPage: 6,
		Load: function(){
			this.loaded = true;
			g_unloadFunction2 = this.Reset.bind(this);
		},
		Reset: function(){
			this.mails = {};
			this.loaded = false;
			this.sortedMails = [];
			this.deleting = 0;
		},
		RedrawList: function(){
			g_mainChar.SetGifts( this.sortedMails.length);
			for (var i = 0; i < this.sortedMails.length ; ++ i)
			{
				if (i >= this.numMailsPerPage){return;}
				this.mails[this.sortedMails[i]].Show();
			}
		},
		PreDelete: function(p_elem, p_confirm){
			if (p_elem.elemId && this.mails[p_elem.elemId])
			{
				this.deleting = p_elem.elemId;
				l_e = this.mails[p_elem.elemId];
			}
			else
			{
				return false;
			}
			
			g_confirm.Show(p_confirm,'_contents',this.Delete.bind(this));
			return false;
		},
		Delete: function(p_ele){
			var l_e;
			this.deleting = p_ele.elemId;
			l_e = this.mails[this.deleting];
			if (l_e)
			{
				l_e.Delete();
			}
			this.RedrawList();
			return true;
		},
		Accept: function( p_elem){
			var l_e;
			if (p_elem.elemId && this.mails[p_elem.elemId])
			{
				l_e = this.mails[p_elem.elemId];
			}
			else
			{
				return;
			}
			l_e.Accept();
			this.RedrawList();
		},
		DeleteOne: function( p_type, p_id){
			var l_temp = $( p_type + p_id);
			l_temp.parentNode.removeChild( l_temp);
			delete this.mails[p_id];
			
			for (var i = 0; i < this.sortedMails.length ; ++ i)
			{
				if (i >= this.numMailsPerPage){return;}
				if (this.sortedMails[i] == p_id)
				{
					this.sortedMails.splice(i,1);
					return;
				}
			}
		}
	};g_pb.Reset();
	var Gift = Class.create({
		initialize: function( p_id, p_icon, p_desc){
			this.id = p_id;
			this.icon = p_icon;
			this.desc = p_desc;
			this.shown = false;
			g_pb.mails[this.id] = this;
			g_pb.sortedMails.push(this.id);
		},
		Delete: function(){
			new Ajax.Request( '/callback/mail.php', { method:'post',parameters:{a:'1',t:'2',id:this.id},evalScripts:true});
			g_pb.DeleteOne( 'gift_', this.id);
		},
		Accept: function(){
			new Ajax.Request( '/callback/mail.php', { method:'post',parameters:{a:'2',t:'2',id:this.id},evalScripts:true});
			g_pb.DeleteOne( 'gift_', this.id);
		},
		Show: function(){
			if (this.shown){return;}
			this.shown = true;
			
			var l_temp = new Element('span', {id: 'gift_' + this.id, 'class': 'base trashable storable i64'});
			l_temp.setStyle({background:'url(\'/i/cadeau02.png\')'});
			l_temp.update( '<img src="/i/r/'+this.icon+'" class="i32"style="margin:1.6em 0.5em 0.4em 1.5em;" onmouseover="tooltip.show(\''+addslashes(this.desc)+'\')" onmouseout="tooltip.hide();">');
			$( 'PostBox_Base').insert( l_temp);
			l_temp.elemId = this.id;
			this.draggable = new Draggable( 'gift_' + this.id, {revert:'failure'});
		}
	});
	var Mail = Class.create({
		initialize: function(p_id, p_icon, p_title, p_text){
			this.id = p_id;
			this.icon = p_icon;
			this.shown = false;
			this.title = p_title;
			this.text = p_text;
			g_pb.mails[this.id] = this;
			g_pb.sortedMails.push(this.id);
		},
		Delete: function(){
			new Ajax.Request( '/callback/mail.php', { method:'post',parameters:{a:'1',t:'1',id:this.id},evalScripts:true});
			g_pb.DeleteOne( 'mail_', this.id);
		},
		Accept: function(){
			$('MailText_Title').update( this.title);
			$('MailText_Text').update( this.text);
			$('mail_'+this.id).style.top=$('mail_'+this.id).style.left='0';
			$('MailText').show();
		},
		Show: function(){
			if (this.shown){return;}
			this.shown = true;
			var l_temp = new Element('span', {id: 'mail_' + this.id, 'class': 'base trashable storable i64'});
			l_temp.setStyle(
			{
				background:	'url(\'/i/lettre03.png\')'
			});
			l_temp.ondblclick = this.Accept.bind(this);
			l_temp.update( '<img src="/i/'+this.icon+'" class="i32"style="margin:1em 0.75em 1em 1.25em" onmouseover="tooltip.show(\''+addslashes(this.title)+'<br/><br/>'+g_text.mail['read']+'\')" onmouseout="tooltip.hide();">');
			$( 'PostBox_Base').insert( l_temp);
			l_temp.elemId = this.id;
			this.draggable = new Draggable( 'mail_' + this.id, {revert:'failure'});
		}
	});
}
{ /***************Dresses******************/
	var g_dm = {
		slots: {},
		dresses: {},
		Load: function( p_sex, p_baseSize, p_shopId,p_un){
			g_unloadFunction2 = this.Reset.bind(this);
			this.baseSize = p_baseSize || 256;
			this.factor = this.baseSize / 256;
			this.sex = p_sex;
			this.unava = p_un;
			this.shopId = p_shopId;
			this.loaded = true;
			this.sTimer = 0;
			for (var i in this.slots)
			{
				this.slots[i].Load( this.sex);
			}
		},
		Reset: function(){
			this.loaded = false;
			this.sex = 0;
			this.finished = false;
			this.baseSize = 256;
			this.filter = 0;
			this.totalPrice = 0;
			this.highestPopu = 0;
			this.currentSlotShown = 0;
			this.changed = false;
			for (var i in this.slots)
			{
				this.slots[i].loaded = false;
			}
		},
		Finalise: function(){
//			this.RecalcPrice();
			for (var i in this.slots)
			{
				this.slots[i].Finalise();
			}
			this.finished = true;
		},
		SelectDress: function( p_id){
//		return false;
			if(!this.dresses[p_id]){return false;}
			this.dresses[p_id].Select();
			
			return false;
		},
		AddColor: function( p_refDress, p_idCol, p_img){
			if (this.dresses[p_refDress])
			{
				this.dresses[p_refDress].subs[p_idCol] = p_img;
				++this.dresses[p_refDress].numSubs;
			}
		},
		SelectColor: function( p_dress, p_id, p_ch){
//		return false;
			if (!this.dresses[p_dress]){return false;}
			this.dresses[p_dress].SelectSub(p_id, p_ch);
			return false;
		},
		RecalcPrice: function(){
			var i;
			var l_price = 0;
			var l_highestPopu = 0;
			for (var i in this.slots)
			{
				l_price += this.slots[i].GetPrice();
				l_highestPopu = Math.max(l_highestPopu, this.slots[i].GetPopu());
			}

			this.totalPrice = l_price;
			this.highestPopu = l_highestPopu;
		},
		Randomize: function(){
			var l_slots = [];
			
			var l_maxCredits = g_mainChar.credits;

			for (var i in this.slots)
			{
				this.slots[i].SetNull();
				if (this.slots[i].numDresses > 0)
				{
					l_slots.push(i);
				}
			}
			
			l_slots.shuffle();

			for (var i = 0;i<l_slots.length;i++)
			{
				l_maxCredits -= this.slots[l_slots[i]].Randomize( l_maxCredits);
			}
			
			$('ListeMeublesInCat').update();
			
			return false;
		},
		postSaveDresses: function( p_ans){
		},
		Save: function( p_un){
//			if (!this.changed){return;}
			var l_dresses = '';
			for (var i in this.slots)
			{
				l_dresses += this.slots[i].Save();
			}
			if (p_un)
			{
				new Ajax.Request('/callback/saveavatar.php',{evalScripts:true, method: 'post',parameters:{verif:1, a:'save', g:this.sex,dresses:l_dresses},onSuccess:PostSaveDresses});
				return;
			}
//			$('DressLoading').show();
			
			$('LoadingMsg').update( g_text.dm['load']);
			$('LoadingImg').show();
			return _openUrl2( 'avatar', {verif:1, a:'save', g:this.sex,dresses:l_dresses,id:this.shopId});
		},
		AskSave: function(){
			this.RecalcPrice();
			if (this.totalPrice > g_mainChar.credits)
			{
				g_confirm.Show( g_text.dm['conf_nokaz'], '_contents', function(){_openUrl2('howkaz');});
			}
			else if (this.highestPopu > g_mainChar.popu)
			{
				g_confirm.Show( g_text.dm['conf_nopopu'], '_contents', function(){},UnloadCurrentInline);
			}
			else
			{
				g_confirm.Show( g_text.dm['conf_save'] ,'_contents',this.Save.bind(this));
			}
		},
		MouseOverSave: function(){
			tooltip.show( this.totalTxt + this.totalPrice + ' kaz !');
		},
		PreSave: function(){
			this.Save();
			return;
			this.RecalcPrice();
			if (this.totalPrice > 0)
			{
				$('Saving').hide();
				$('PriceItems').show();
			}
			else
			{
				this.Save();
			}
		},
		SetOwned: function(){
			for (var i = 0 ; i < arguments.length;++i)
			{
				if(g_dm.dresses[arguments[i]])
				{
					g_dm.dresses[arguments[i]].price = 0;
				}
			}
		},
		ReDisplayList:function(){
			if (this.unava)
			{
				new Pager('ListeMeublesInCat',{vertical:true});
			}
			else
			{
				new Pager('ListeMeublesInCat');
			}
			
			// if (this.sTimer != 0)
			// {
				// clearTimeout( this.sTimer);
			// }
			//this.sTimer = setTimeout( "g_dm.EndSTimer();new Pager('ListeMeublesInCat');",50);
		},
		EndSTimer: function(){
			this.sTimer = 0;
		}
	};g_dm.Reset();
	var Slot = Class.create({
		initialize: function( p_id, p_sex, p_name, p_offsetX, p_offsetY, p_sizeX, p_sizeY, p_img, p_layer, p_nullable){
			p_layer = parseInt(p_layer);
			this.id = p_id;
			this.sex = p_sex;
			this.dresses = {};
			this.numDresses = 0;
			this.img = p_img;
			this.name = p_name;
			this.loaded = false;
			this.nullable = p_nullable;
			this.dims = {l:p_offsetX,t:p_offsetY,w:p_sizeX,h:p_sizeY,z:p_layer+300};
			this.currDress = 0;
			g_dm.slots[this.id]=this;
		},
		Load: function( p_sex){
			this.currDress = 0;
			if (this.sex != p_sex){this.loaded = false;return;}
			this.loaded = true;
			$('Dressit_MenuLeft').insert( '<a href="" id="Slot_'+this.id+'"onclick="return g_dm.slots['+this.id+'].Show()"><img src="/i/j/s/'+this.img+'"class="h32" style="margin:2px"onmouseover="tooltip.show(\''+addslashes(this.name)+'\')"onmouseout="tooltip.hide()"/></a>');
			$('Dressit_Main').insert( '<img id="DressIsImg_'+this.id+'"style="position:absolute;width:'+(this.dims.w * g_dm.factor)/16+'em;height:'+(this.dims.h * g_dm.factor)/16+'em;left:'+(this.dims.l * g_dm.factor)/16+'em;top:'+(this.dims.t * g_dm.factor)/16+'em;z-index:'+this.dims.z+';">');
		},
		GetPrice: function(){
			if (this.dresses[this.currDress])
			{
				return this.dresses[this.currDress].price;
			}
			return 0;
		},
		GetPopu: function(){
			if (this.dresses[this.currDress])
			{
				return this.dresses[this.currDress].min_popu;
			}
			return 0;
		},
		SetNull: function(){
			if(!this.loaded){return;}
//			$('Dressit_CenterBottom').update();
			$('DressIsImg_' + this.id).hide();
			this.currDress = 0;
			g_dm.RecalcPrice();
			return false;
		},
		Save: function(){
			if (this.currDress != 0)
			{
				return this.id + '!' + this.currDress + '!' + this.dresses[this.currDress].currentSub + ',';
			}
			return '';
		},
		Show: function(){
			g_dm.currentSlotShown = this.id;
			$('ListeMeublesInCat').update();
			if (this.nullable)
			{
				$('ListeMeublesInCat').insert( '<img src="/i/j/None.png" class="i64"style="width:64px;height:64px;" tooltip="Rien"onclick="return g_dm.slots['+this.id+'].SetNull();"/>');
			}
			for (var i in this.dresses)
			{
				this.dresses[i].AddToList();
			}
			g_dm.ReDisplayList();
			return false;
		},
		Finalise: function(){
			if(!this.loaded){return;}
			if (this.numDresses == 0)
			{
				$('Slot_'+this.id).hide();
			}
		},
		Randomize: function( p_maxCredits){
			if(!this.loaded){return 0;}
			var l_dresses = [];

			for (var i in this.dresses)
			{
				var l_dr = this.dresses[i];
				if (l_dr.price <= p_maxCredits && l_dr.min_popu <= g_mainChar.popu)
				{
					l_dresses.push(i);
				}
			}
			if (l_dresses.length == 0){return 0;}
			var l_dress = g_dm.dresses[l_dresses[parseInt(Math.random()*l_dresses.length)]];
			g_dm.SelectDress( l_dress.id);
			if (l_dress.numSubs > 1)
			{
				var l_subs = [];
				for (var i in l_dress.subs)
				{
					l_subs.push( i);
				}
				var rselect = l_subs[parseInt(Math.random()*l_subs.length)];
				g_dm.SelectColor( l_dress.id, rselect);
			}
			
			return l_dress.price;
		}
	});
	var Dress = Class.create({
		initialize: function( p_id, p_image, p_name, p_slot, p_price, p_minPopu){
			if ( ! g_dm.slots[p_slot]){return;}
			
			this.img = '/i/j/'+p_image;
			this.icone = '/i/j/x'+p_image.replace('.png','.jpg');
			this.subs = {};
			this.numSubs = 0;
			this.name = p_name;
			this.descr = this.name;
			
			if (p_price > 0)
			{
				this.descr += ' - ' + p_price + ' '+g_text.gen['kaz']+'<br />';
				if (p_minPopu > 0)
				{
					this.descr += + p_minPopu + ' '+g_text.gen['popu_short'];
				}
			}
			
			this.id = p_id;
			this.currentSub = 0;
			this.price = p_price;
			this.min_popu = p_minPopu;
			this.slot = p_slot;
			g_dm.slots[p_slot].dresses[this.id] = this;
			++ g_dm.slots[p_slot].numDresses;
			g_dm.dresses[this.id] = this;
		},
		SelectSub: function(p_id,p_ch){
			if (this.subs[p_id])
			{
				g_dm.slots[this.slot].currDress = this.id;
				this.currentSub = p_id;
				$('DressIsImg_'+this.slot).show();
				$('DressIsImg_'+this.slot).src='/i/j/'+this.subs[p_id];
				g_dm.RecalcPrice();
				if (p_ch && p_ch == 1)
				{
					g_dm.changed = true;
				}
			}
		},
		Select: function(){
			if (this.numSubs > 1)
			{
				tooltip.hide();
				if (!g_dm.finished)
				{
					return;
				}
				$('ListeMeublesInCat').update('<span class="base i64"><img src="/i/map/mid/dezoom.png"onclick="return g_dm.slots['+this.slot+'].Show()"class="i64"></span>');
				for (var i in this.subs)
				{
					$('ListeMeublesInCat').insert( '<span class="base i64"><img onclick="return g_dm.SelectColor('+this.id+','+i+',1);"class="i64" src="/i/j/x'+this.subs[i].replace('.png','.jpg')+'"/></span>');
				}
				g_dm.ReDisplayList();
			}
			else
			{
				for (var i in this.subs)
				{
					this.SelectSub( i);break;
				}
			}
			
		//	$('DressIsImg_'+this.id).src=this.dresses[p_id].img;
		},
		AddToList: function(){
			if (!g_dm.finished){return;}
			if (this.price <= 0 || g_dm.shopId > 0)
			{
				$('ListeMeublesInCat').insert( '<img src="'+this.icone+'"class="i64"onclick="return g_dm.SelectDress('+this.id+')" onmouseover="tooltip.show(\''+addslashes(this.descr)+'\')"onmouseout="tooltip.hide()"/>');
			}
		}
	});
}
{ /***************Character****************/
	var g_mainChar = {
		id: 0,
		name: "",
		credits: 5000,
		popu: 0,
		numGifts: 0,
		language: 'EN',
		x: 0,
		y: 0,
		rid: 0,
		level: 1,
		tier: 0,
		rank: 0,
		sex:0,
		tokens:0,
		noreload: false,
		questDone: {},
		currentQuests: {},
		barText: {u:'',h:'',s:''},
		stats: {u:10000,h:10000,s:10000},
		status: 0,
		onQuest: 0,
		needLevel: false,
		skills: {},
		npcTarget: false,
		onQuestFail: 0,
		specialDressCode: false,
		ShowXp: function(){
			if ($('TPopu').visible())
			{
				$('TPopu').hide();
			}
			else
			{
				var l_prev = this.popu - this.offsetLevel;
				var l_diff = this.XpForLevel(this.level+1);
				this.xpPercent = l_prev / l_diff;
				$('TestInBar').setStyle({width:(this.xpPercent * 280)+'px'});
				$('PrevLvl').update(g_mainChar.NumFormatImg(this.level,true));
				$('CurrXp').update(g_mainChar.NumFormatImg(l_prev,false));
				$('NextXp').update(g_mainChar.NumFormatImg(l_diff,false));
				$('NextLvl').update(g_mainChar.NumFormatImg(this.level + 1,true));
				$('TPopu').show();
			}
		},
		LevelUp: function(){
			g_win.Add('<h2>'+g_text.gchar['levelup1']+'</h2><br/><span class="base">'+this.NumFormatImg(this.level,4)+'</span><img src="/i/Popu2.png"class="i64"><br/><h3>'+g_text.gchar['levelup2']+'<br/><img src="/i/kaz.png"class="i48"><br/>500 Kaz<br/><a href="javascript:;"onclick="facebook.PublishPre(31);return false;"><img src="/i/'+g_mainChar.language+'/menu/t/partager.png"></a></h3>');
		},
		SetBarText: function(p_hunger, p_health, p_sleep){
			this.barText = {u:p_hunger,h:p_health,s:p_sleep};
		},
		MouseOverBar: function( p_which){
			switch (p_which)
			{
				case 'hp':tooltip.show( '<img src="/i/icone_jauge_sante.png" class="i24m"/>'+g_text.gen['health']+': ' + parseInt(this.stats.h * 0.01) + '%');break;
				case 'xp':
				{
					tooltip.show( '<img src="/i/Popu.png" class="i24m"/>'+g_text.gen['level']+' : ' + this.level);
					break;
				}
			}
		},
		SetQuestsDone: function( p_questList){
			this.questDone = {};
			for (var i =0; i < p_questList.length ; ++ i)
			{
				this.questDone[p_questList[i]] = true;
			}
		},
		StartQuest: function(p_id){
			g_qm.StartQuest(p_id);
//			this.currentQuests[p_id] = true;
		},
		EndQuest: function(p_id){
			if (this.onQuest){g_diM.OpenDiscussion(this.onQuest);this.onQuest = 0;}
			g_qm.EndQuest(p_id);
		},
		FailQuest: function(p_id){
			if (this.onQuestFail){g_diM.OpenDiscussion(this.onQuestFail);this.onQuestFail = 0;}
		},
		_chk: function( p_cond){
			if (typeof p_cond != 'string'){return true;}
			if ( ! p_cond || p_cond.length < 1){return true;}
			var l_cond = p_cond.split( ',');
			for (var i = 0 ; i < l_cond.length ; i ++)
			{
				var l_a = l_cond[i].split(':');
				if (l_a.length == 1)
				{
					switch (l_a[0])
					{
						case 'beta':if (this.status == 0 || this.status > 3){return false;}break;
						case 'modo':if (this.status == 0 || this.status > 2){return false;}break;
						case 'pet':if (g_city.users[this.id].pet == 0){return false;}break;
						case '!pet':if (g_city.users[this.id].pet != 0){return false;}break;
						case 'admin':if (this.status != 1){return false;}break;
						case 'dcode':if (!this.specialDressCode){return false;}break;
						case 'facebook':if (!facebook.inFB){return false;}break;
					}
					continue;
				}
				var val = parseInt(l_a[1]);
				switch (l_a[0])
				{
					case 'q':	if (!g_qm.QuestDone(val))		{return false;}break;
					case '!q':	if (g_qm.QuestDone(val))		{return false;}break;
					case 'cq':	if (!g_qm.QuestCurrent(val))	{return false;}break;
					case '!cq':	if (g_qm.QuestCurrent(val))		{return false;}break;
					case 'r':	if (this.level < val)			{return false;}break;
					case 'r=':	if (this.level != val)			{return false;}break;
					case 'p':	if (this.popu < val)			{return false;}break;
					case 'p-':	if (this.popu >= val)			{return false;}break;
					case 'tk':	if (this.tokens < val)			{return false;}break;
					case 'tk-':	if (this.tokens >= val)			{return false;}break;
					case 'he':	if (this.stats.h < val)			{return false;}break;
					case 'he-':	if (this.stats.h >= val)		{return false;}break;
					case 'hu':	if (this.stats.u < val)			{return false;}break;
					case 'hu-':	if (this.stats.u >= val)		{return false;}break;
					case 'sl':	if (this.stats.s < val)			{return false;}break;
					case 'sex':	if (this.sex != val)			{return false;}break;
					case 'sl-':	if (this.stats.s >= val)		{return false;}break;
					case 'k':	if(l_a.length > 2  && l_a[2]){val = g_qm.GetScale(val);} if (this.credits < val)			{return false;}break;
					case 'k-':	if(l_a.length > 2  && l_a[2]){val = g_qm.GetScale(val);} if (this.credits >= val)		{return false;}break;
					case 'tuto':	if (!g_tm.IsDone(val))		{return false;}break;
					case '!tuto':	if (g_tm.IsDone(val))		{return false;}break;
					case 'rand':	if (Math.random() > parseFloat(l_a[1]))	{return false;}break;
					case 'sk':	if (g_cm.skills[val] && g_cm.skills[val].currentLevel == 0)		{return false;}break;
					case '!sk':	if (g_cm.skills[val] && g_cm.skills[val].currentLevel > 0)		{return false;}break;
				}
			}
			return true;
		},
		CheckCondition: function(p_text){
			var level = 0;
			var l_start = -1;
			var l_end = -1;
			var l_negPos = -1;
			for (var i = 0 ; i < p_text.length ; i ++)
			{
				var u = p_text.charAt(i);
				if (u=='(')
				{
					if (level == 0)
					{
						l_start = i;
					}
					++ level ;
				}
				if (u==')')
				{
					-- level ;
					if (level == 0)
					{
						l_end = i;
					}
				}
				else if(level == 0 && u == '!')
				{
					l_negPos = i;
				}
				else if(level == 0 && (u == '&' || u == ','))
				{
					return this.CheckCondition(p_text.substr(0,i)) && this.CheckCondition(p_text.substr(i+1,p_text.length));
				}
				else if(level == 0 && u == '|')
				{
					return this.CheckCondition(p_text.substr(0,i)) || this.CheckCondition(p_text.substr(i+1,p_text.length));
				}
			}
			if (l_negPos != -1)
			{
				return !this.CheckCondition(p_text.substr(l_negPos+1,p_text.length));
			}
			if (l_start != -1 && l_end != -1)
			{
				return this.CheckCondition(p_text.substr( l_start+1, l_end-l_start-1));
			}
			var l_ret = this._chk(p_text);
			return l_ret;
		},
		PrintCondition: function( p_cond){
			var textCond = '';
			if ( ! p_cond || p_cond.length < 1){return textCond;}
			var l_cond = p_cond.split( ',');
			for (var i = 0 ; i < l_cond.length ; i ++)
			{
				var l_a = l_cond[i].split(':');
				if (l_a.length > 2){continue;}
				if (l_a.length == 1)
				{
					switch (l_a[0])
					{
						case 'beta':textCond += g_text.gchar['c_beta']+'<br/>';break;
						case 'modo':textCond += g_text.gchar['c_modo']+'<br/>';break;
						case 'admin':textCond += g_text.gchar['c_admin']+'<br/>';break;
						case 'pet':textCond += g_text.gchar['c_pet']+'<br/>';break;
						case '!pet':textCond += g_text.gchar['c_nopet']+'<br/>';break;
					}
					continue;
				}
				var val = parseInt(l_a[1]);
				switch (l_a[0])
				{
					case 'q':	textCond += g_text.gchar['c_quest']+'<br/>';break;
					case '!q':	break;
					case 'cq':	textCond += g_text.gchar['c_quest']+'<br/>';break;
					case '!cq':	break;
					case 'r':	textCond += 'Niveau supérieur à '+val+'<br/>';break;
					case 'r=':	textCond += 'Niveau egal à '+(val)+'<br/>';break;
					case 'p':	textCond += g_text.gchar['c_popu']+val+'<br/>';break;
					case 'p-':	textCond += g_text.gchar['c_maxpopu']+val+'<br/>';break;
					case 'he':	textCond += g_text.gchar['c_health']+(val/100.0)+'%<br/>';break;
					case 'he-':	textCond += g_text.gchar['c_maxhealth']+(val/100.0)+'%<br/>';break;
					break;
				}
			}
			return textCond;
		},
		Set: function( p_id, p_name, p_credits, p_popu, p_numGifts, p_language, p_avatar, p_tier, p_rank,p_tokens){
			this.id = p_id;
			this.name = p_name;
			this.rank = p_rank;
			this.SetCredits( p_credits);
			this.numGifts = p_numGifts;
			this.language = p_language;
			this.avatar = p_avatar;
			this.tier = p_tier;
			this.popu = p_popu;
			this.tokens = p_tokens;
			this.RecalcLevel();
			$('user_popu').update( this.NumFormatImg(this.level,true));
			$('user_tok').update( this.NumFormatImg(p_tokens,true));
			
			$('TestInBar').setStyle({width:(((this.popu - this.offsetLevel)/this.XpForLevel(this.level)) * 280)+'px'});
		},
		SetStats: function( p_hunger, p_health, p_sleep, p_sex){
			if ($('RMenuHpBar'))
			{
				$('RMenuHpBar').setStyle({height:(p_health*0.015)*g_map.globalScale+'px'});
			}
			this.stats = {u:p_hunger,h:p_health,s:p_sleep};
			this.sex = p_sex;
		},
		SetCredits: function( p_amount){
			this.credits = p_amount;
			if ($('user_kaz'))
			{
				$('user_kaz').update( this.NumFormatImg(p_amount,false));
			}
		},
		NumFormatImg: function(p_num,p_gold){
			var str='';
			var gold = p_num.toString();
			for(var i = 0 ; i < gold.length ; i ++)
			{
				if (p_gold==4)
				{
					str += '<img src="/i/num/t2/'+gold[i]+'.png" class="i64">';
				}
				else if (p_gold==3)
				{
					str += '<img src="/i/num/t/'+gold[i]+'.png" class="i64">';
				}
				else if(p_gold === true)
				{
					str += '<img src="/i/num/g/'+gold[i]+'.png" style="height:1em">';
				}
				else
				{
					str += '<img src="/i/num/'+gold[i]+'.png" style="height:1em">';
				}
			}
			return str;
		},
		UpdateCredits: function( p_amount){
			if (this.credits != p_amount)
			{
				if (this.credits != 0 && (this.credits - p_amount) < 0)
				{
					g_sound.Play("argent02");
				}
				this.AdjustCredits( p_amount, p_amount - this.credits);
			}
		},
		AdjustCredits: function( p_current, p_diff){
			if (p_diff==0){return;}
			if ($('user_kaz_diff'))
			{
				$('user_kaz_diff').update( (p_diff > 0?'+':'')+numberFormat(p_diff));
				$('user_kaz_diff').show();
				$('user_kaz_diff').style.top='-0.5em';
				$('user_kaz_diff').style.color = p_diff > 0 ? 'green':'red';
				new Effect.Move('user_kaz_diff', { x:0,y: -25, mode: 'absolute' });
				new Effect.Fade('user_kaz_diff');
			}
			this.SetCredits( p_current);
		},
		AdjustPopu: function( p_current, p_diff){
			if (p_diff==0){return;}
			
			if ($('user_popu_diff'))
			{
				
				$('user_popu_diff').update( (p_diff > 0?'+':'')+numberFormat(p_diff));
				$('user_popu_diff').show();
				$('user_popu_diff').style.top='-0.5em';
				$('user_popu_diff').style.color = p_diff > 0 ? 'green':'red';
				new Effect.Move('user_popu_diff', { x:0, y:-25, mode: 'absolute' });
				new Effect.Fade('user_popu_diff');
			}
			
			this.popu = p_current;
			var loldlvl = this.level;
			this.RecalcLevel();
		
			if (g_city.users[this.id])
			{
				g_city.users[this.id].popu = p_current;
//				g_city.users[this.id].AdjustWalkSpeed();
			}
			if (this.level > loldlvl)
			{
				this.LevelUp();
			}
			else
			{
				this.PopuEffect1( p_diff);
			}
			if ($('user_popu'))
			{
				$('user_popu').update( this.NumFormatImg(this.level,true));
			}	
			
		},
		PopuEffect1: function( p_amount){
			if (this.PopuInterval)
			{
				clearInterval( this.PopuInterval);
			}
			var l_prev = this.popu - this.offsetLevel;
			var l_diff = this.XpForLevel(this.level+1);
			this.xpPercent = (l_prev-p_amount) / l_diff;
			this.FinalPercent = (l_prev) / l_diff;
			if (this.FinalPercent > 1.0){this.FinalPercent = 1.0};
			this.upPercent = p_amount / l_diff;
			if (this.upPercent < 0.05){return;}
			$('TestInBar').setStyle({width:(this.xpPercent * 280)+'px'});
			$('PrevLvl').update(g_mainChar.NumFormatImg(this.level,true));
			$('CurrXp').update(g_mainChar.NumFormatImg(l_prev,false));
			$('NextXp').update(g_mainChar.NumFormatImg(l_diff,false));
			$('NextLvl').update(g_mainChar.NumFormatImg(this.level + 1,true));
			
			new Effect.Appear('TPopu',{duration:0.3});
			new Effect.Highlight('CurrXp',{delay:1.0,afterFinish:function(){g_mainChar.PopuInterval = setInterval( 'g_mainChar.PopuEffect2();',20);}});
			
		},
		PopuEffect2: function(){
			this.xpPercent += this.upPercent/20;
			if (this.xpPercent > this.FinalPercent)
			{
				this.xpPercent = this.FinalPercent;
				clearInterval(this.PopuInterval);
				this.PopuInterval = 0;
				new Effect.Fade('TPopu',{duration:0.3,delay:1});
			}
			
			$('TestInBar').setStyle({width:(this.xpPercent * 280)+'px'});
		},
		UpdatePopu: function( p_amount){
			if (this.popu != p_amount)
			{
				if (this.popu != 0 && (this.popu - p_amount) < 0)
				{
				//	g_sound.Play("popu",false,0.1);
				}
				this.AdjustPopu( p_amount, p_amount - this.popu);
			}
		},
		UpdateTokens: function(p_amount){
			this.tokens = p_amount;
			if($('user_tok')){$('user_tok').update(this.NumFormatImg(p_amount,true));}
		},
		SetGifts: function( p_amount){
			this.numGifts = p_amount;
			if ($('user_mail'))
			{
				$('user_mail').update( this.NumFormatImg(p_amount,false));
			}
		},
		AdjustGifts: function( p_amount, p_diff){
			if (p_diff==0){return;}
			if ($('user_mail_icon'))
			{
				new Effect.Pulsate('user_mail_icon');
			}
			this.SetGifts( p_amount);
		},
		UpdateGifts: function( p_num){
			if (this.numGifts != p_num)
			{
				this.AdjustGifts( p_num, p_num - this.numGifts);
			}
		},
		LoadOnMap: function( p_rid, p_x, p_y, p_zid){
			var l_char = new MovableUser( this.id, this.name, this.avatar, this.popu, this.tier, this.rank);
//			if (this.rid == 0 || p_zid)
			{
				if (p_rid)
				{
					this.rid = p_rid;
					this.zid = p_zid;
				}
				else
				{
					this.rid = p_rid;
					this.zid = 1;
				}
				this.x = p_x;
				this.y = p_y;
			}
			l_char.ShowAt( this.x, this.y, this.rid);
			g_city.FocusOn(this.id);
		},
		SavePosition: function( p_rid, p_x, p_y){
			this.rid = p_rid;
			this.x = p_x;
			this.y = p_y;
			this.needSave = true;
		},
		needSavePosition: function(){
			return this.needSave;
		},
		AddSkill: function( p_skill, level, xp, current){
			this.skills[p_skill] = {l:level,x:xp,c:current};
		},
		LoadSkills: function(){
			for (var i in this.skills)
			{
				if (!g_cm.skills[i]){continue;}
				var s = this.skills[i];
				g_cm.skills[i].SetActive( s.l, s.x, s.c);
			}
		},
		SetAvatar: function( p_avatar){
			this.avatar = p_avatar;
			if (g_city.loaded && g_city.users[this.id])
			{
				g_city.users[this.id].walkImageBase = p_avatar.substr( 0, p_avatar.length-7);
				if (!g_city.users[this.id].moving)
				{
					$('user_img_'+this.id).src = p_avatar;
				}
				g_city.users[this.id].img = p_avatar;
			}
		},
		Teleport: function( rid,x,y){
			g_city.ChangeRoom( this.id, rid, x, y);
		},
		XpForLevel: function( p_level){
			return p_level * 10 * Math.floor((90+5*p_level + p_level*p_level)/10);
		},
		RecalcLevel: function(){
			var l_xp = this.popu;
			var l_total = 0;
			for (var i = 2 ; i < 100; i ++)
			{
				var x = this.XpForLevel(i);
				l_xp = this.popu - l_total - x;
				if (l_xp < 0)
				{
					this.level = i-1;
					this.offsetLevel = l_total;
					return;
				}
				l_total += x;
			}
			this.level = 100;
		},
		CheckNpcTarget: function(){
			if (this.npcTarget != 0)
			{
				if (g_npcm.npcs[this.npcTarget] && g_npcm.npcs[this.npcTarget].loaded)
				{
					g_npcm.npcs[this.npcTarget].Interact();
					this.npcTarget = 0;
				}
			}
		},
		CalcLevelForXp: function(p_xp){
			var l_xp = p_xp;
			var l_total = 0;
			for (var i = 2 ; i < 500; i ++)
			{
				var x = this.XpForLevel(i);
				l_xp = p_xp - l_total - x;
				if (l_xp < 0)
				{
					return {l:i-1,o:l_total};
				}
				l_total += x;
			}
		},
	};
}
{ /***************Map**********************/
	var g_map = {
		allScale: 1.0,
		globalScale: 1.0,
		ts: 1.0,
		Reset: function(){
			this.rooms = {};
			this.numRooms = 0;
			this.shown = false;
			this.loaded = false;
			this.dims = {x:0,y:0};
			this.currentRoom = 0;
			this.unselectFunction = function(){};
		},
		SetGlobalScale: function( p_scale){
			this.globalScale = p_scale;
			$('body').setStyle({fontSize:p_scale+'em'});
			this.ts = this.globalScale * this.allScale;
		},
		SetAllScale: function( p_scale){
			var l_scaling = p_scale / this.allScale;
			this.allScale = p_scale;
			if (this.loaded && l_scaling != 1.0)
			{
				this.rooms[this.currentRoom].Rescale( l_scaling);   
			}
			this.ts = this.globalScale * this.allScale;
		},
		Load: function( p_where){
			this.shown = true;
			this.loaded = true;
			this.currentRoom = false;
		},
		ChangeRoom: function( p_id){
			if (p_id != this.currentRoom)
			{
				tooltip.hide();
				if (this.currentRoom && this.rooms[this.currentRoom])
				{
					this.rooms[this.currentRoom].Unload();
				}
				if (this.rooms[p_id])
				{
					this.currentRoom = p_id;
					try
					{
						this.rooms[p_id].Load();
					}
					catch(e){/*Firefox 3.6 crashes somewhere between the end of Room::Load(), and the return true, due to "too much recursion". if anyone has a clue why, contact me >.< */}
					return true;
				}
			}
			return false;
		},
		Finalise: function(){
			var l_count=0;
			var l_w = 0;
			var l_h = 0;
			for (var i in this.rooms)
			{
				++ l_count;
				if (this.rooms[i].gx > l_w){l_w = this.rooms[i].gx;}
				if (this.rooms[i].gy > l_h){l_h = this.rooms[i].gy;}
			}
			this.numRooms = l_count;
			l_w += 1; l_h += 1;
			if (l_count > 1)
			{
				$('Furnit_Map').style.width=(l_w * this.itemWidth)/16+'em';
				$('Furnit_Map').style.height=(l_h * this.itemHeight)/16+'em';
				this.dims.x = l_w * this.itemWidth;
				this.dims.y = l_h * this.itemHeight;
				for (var i in this.rooms)
				{
					this.rooms[i].AddToMap();
				}
			}
			else
			{
				$('Furnit_Map').hide();
			}
		}
	};
	var Room = Class.create({
		initialize: function( p_id, p_img, p_scale, p_mainAxis, p_name,gx,gy){
			this.img = p_img;
			// this.prImg = new Image;
			// this.prImg.src = '/i/b/' + this.img;
			// this.prImg.onload = this.LoadImageFinished.bind(this);
			this.id = p_id;
			this.scale = p_scale;
			this.name = p_name;
			this.statics = {};
			this.movables = {};
			this.adds = {};
			this.walls = [];
			this.gx=gx || 0;
			this.gy=gy || 0;
			this.numStatic = 0;
			this.numMovable = 0;
			this.axis = p_mainAxis || 3;
			this.pathMap = new PathMap( this.id);
			g_map.rooms[this.id] = this;
		},
		LoadImageFinished: function(){
			this.prImg = false;
		},
		Load: function(){
			$('MainMapImg').src = '/i/b/' + this.img;
			for (var i in this.movables)
			{	
				this.movables[i].Load();
			}
			for (var i in this.statics)
			{	
				this.statics[i].Load();
			}
			for (var i in this.adds)
			{	
				this.adds[i].Load();
			}
			if (!this.pathMap.complete)
			{
				this.CreatePathMap();
			}
		},
		Unload: function(){
			for (var i in this.movables)
			{	
				this.movables[i].Unload();
			}
			for (var i in this.statics)
			{	
				this.statics[i].Unload();
			}
			for (var i in this.adds)
			{	
				this.adds[i].Unload();
			}
		},
		Save: function(){
			var l_data = '';
			for (var i in this.movables)
			{
				if (this.movables[i] && this.movables[i].Save)
				{
					l_data += this.movables[i].Save();
				}
			}
			for (var i in this.statics)
			{	
				l_data += this.statics[i].Save();
			}
			return l_data;
		},
		Rescale: function( p_scale){
			for (var i in this.movables)
			{	
				this.movables[i].Rescale( p_scale);
			}
			for (var i in this.statics)
			{	
				this.statics[i].Rescale( p_scale);
			}
			for (var i in this.adds)
			{	
				this.adds[i].Rescale();
			}
		},
		DelMovable: function( p_id){
			delete this.movables[p_id];
		},
		DelStatic: function( p_id){
			delete this.statics[p_id];
		},
		AddStatic: function( p_stat){
			this.statics[p_stat.id] = p_stat;
			++ this.numStatic;
		},
		AddMovable: function( p_mov){
			this.movables[p_mov.id] = p_mov;
			++ this.numMovable;
		},
		GetLocalCoords: function( p_event){
			var l_aCoords = getActualMouseCoords( p_event);
			return{x:Math.floor(l_aCoords.x*-0.7 + l_aCoords.y*0.3),y:Math.floor(l_aCoords.x * 0.3 + l_aCoords.y * 0.7)};
		},
		GetLocalCoords2: function( p_x, p_y){
			return{x:Math.floor(p_x*-0.57 + p_y*0.43),y:Math.floor(p_x * 0.3 + p_y * 0.7)};
		},
		CalcZ: function( p_x, p_y, p_z){
			if (g_city.inVisuRoom){return p_z;}
			if (p_z > 200){return p_z;}
			switch (this.axis)
			{
				case 1://local X
				{
					return 500+Math.floor(p_x*-0.07 + p_y*0.03) + p_z;
				}
				case 2: 
				{
					return 500+Math.floor(p_x * 0.1) + p_z;
				}
				case 3: 
				{
					return 500+Math.floor(p_x * 0.03 + p_y * 0.07) + p_z;
				}
				case 4: 
				{
					return 500+Math.floor(p_y * 0.1) + p_z;
				}
			}
			return 0;
		},
		CreatePathMap: function(){
			for (var i = 0 ; i < this.walls.length ; ++ i)
			{
				this.pathMap.AddObject( this.walls[i]);
			}
			this.pathMap.Complete();
		},
		AddToMap: function(){
			$('Furnit_Map').insert( '<a href="#" onclick="return g_map.ChangeRoom( '+this.id+');"><img style="width:4em;height:2em;position:absolute;top:'+(this.gy*32)/16+'em;left:'+(this.gx*64)/16+'em;" src="/i/b/'+this.img+'" /></a>');
		}
	});
}
{ /***************Furnit*******************/
	var g_fm = {
		Load: function(){
			g_unloadFunction = this.Reset.bind(this);
			var l_map = new Element( 'div', {id:'Furnit_Map', 'class':'top_left'});
			l_map.setStyle(
			{
				position:	'absolute',
				background:	'#000',
				zIndex:		'999',
				border:		'2px solid black',
				opacity:	0.75
			});
			l_map.update( '<a href="" onclick="return g_map.Toggle();"><img id="FurnitMapIcon" style="position:absolute;bottom:-1em;right:-1em;z-index:800;" src="/i/mapout.png"></a>');

			$('MainHome').appendChild( l_map);
			g_map.unselectFunction = this.Unselect.bind(this);
			g_map.Load( 'MainHome');
			this.loaded = true;
		},
		Reset: function(){
			this.filter = 0;
			this.currentMeuble = 0;
			this.totalPrice = 0;
			this.cats = {};
			this.meubles = {};
			this.instances = {};
			this.currentCat = 0;
			this.currentMangle = 0;
			this.selectedInstance = 0;
			this.instanceId = 0;
			this.loaded = false;
			this.hiddenMapOnOpen = false;
			g_map.Reset();
		},
		Finalise: function( p_fromShop){
			for (var i in this.cats)
			{
				this.cats[i].Finalise();
			}
			if (!p_fromShop)
			{
				g_map.Finalise();
			}
		},
		OpenMenu: function(){
			$('Furnit_MainMenu').show();
			$('Furnit_Map').hide();
			this.Unselect();
			this.SetFilter( this.filter);
			if (this.currentMeuble !=0)
			{
				this.meubles[this.currentMeuble].Load();
			}
			return false;
		},
		CloseFurnitMenu: function(){
			$('Furnit_MainMenu').hide();
			if (g_map.numRooms > 1)
			{
				$('Furnit_Map').show();
			}
			UpdateEncartPub();
			return false;
		},
		SetFilter: function( p_filter){
			this.filter = p_filter;
			if (this.currentCat != 0)
			{
				this.cats[this.currentCat].Open();
			}
		},
		SpawnMeuble: function(){
			var m = new FInstance( g_map.currentRoom, this.currentMeuble, this.currentMangle, 200, 100);
			m.Load();
			$('Furnit_OwnedUsed').update( this.meubles[this.currentMeuble].used);
			this.CloseFurnitMenu();
			
//			this.RecalcPrice();
			return false;
		},
		TurnLeft: function(){
			this.instances[this.selectedInstance].TurnLeft();
		},
		TurnRight: function(){
			this.instances[this.selectedInstance].TurnRight();
		},
		ListMeubles: function( p_meubles, p_room){
			for (var i in p_room.movables)
			{
				var lm = p_room.movables[i];
				if (p_meubles[lm.meubleId])
				{
					p_meubles[lm.meubleId].num ++;
				}
				else
				{
					p_meubles[lm.meubleId] = {num:1,id:lm.meubleId};
				}
			}
		},
		EndDelete: function( p_elem){
			g_map.rooms[g_map.currentRoom].movables[p_elem.meubleiID].todestroy = true;
			g_map.rooms[g_map.currentRoom].DelMovable( p_elem.meubleiID);
		},
		Unselect: function(){
			$('Furnit_Turn').hide();
			if (this.selectedInstance != 0 && this.instances[this.selectedInstance])
			{
				this.instances[this.selectedInstance].Unselect();
			}
			this.selectedInstance = 0;
		},
		SaveAll: function(){
			this.Unselect();
			var l_data = '';
			for (var i in g_map.rooms)
			{
				l_data += g_map.rooms[i].Save();
			}
			return _openUrl( 'furnit', {saveverif:1,action:'save',data:l_data});
		}
	};g_fm.Reset();
	var FCat = Class.create({
		initialize: function( p_id, p_name, p_icone, p_num){
			this.name = p_name;
			this.id = p_id;
			this.meubles = {};

			var l_div = $( 'Furnit_Menu');
			if (l_div == null){return;}
			
			l_div.insert( '<a href="#" onclick="g_fm.cats['+this.id+'].Open();return false;" id="menu_cat_'+this.id+'"><img src="/i/'+p_icone+'" class="i40" style="margin:0.3em"></a>');
			
			g_fm.cats[this.id] = this;
		},
		MouseOver: function(){
			tooltip.show( this.name);
		},
		Finalise: function(){
			$('menu_cat_'+this.id).onmouseover = this.MouseOver.bind(this);
			$('menu_cat_'+this.id).onmouseout = tooltip.hide.bind(tooltip);
		},
		Open: function(){
			$('FurnitMenuRight').show();
			g_fm.currentCat = this.id;
			l_div = $('ListeMeublesInCat');
			l_div.update();
			for (var i in this.meubles)
			{
				m = this.meubles[i];
				if ((g_fm.filter == 1 && m.owned == 0)
				|| (g_fm.filter == 2 && m.owned > 0)
				|| (g_fm.filter == 3 && m.used == 0)){continue;}
				l_div.insert( '<a onclick="g_fm.meubles['+m.id+'].Load();return false;"onmouseout="tooltip.hide();"onmouseover="tooltip.show(\''+m.name+'\')"><img src="/i/b/m/'+m.icone+'" class="h48"/></a>');
			}
		},
		AddItem: function( p_m){
			this.meubles[p_m.id] = p_m;
		}
	});
	var FMeuble = Class.create({
		initialize: function( p_id, p_name, p_price, p_minPopu, p_num, p_img, p_cats, p_angles, p_sold){
			this.name = p_name;
			this.id = p_id;
			this.price = p_price;
			this.icone = p_img;
			this.owned = p_num;
			this.popu = p_minPopu;
			this.used = 0;
			this.sold = p_sold || false;
			this.mangles = {};
			this.uMangles = [];
			this.numMangles = p_angles.length;
			
			for (var i = 0 ; i < p_angles.length ; ++ i)
			{
				p_angles[i].umIndex = this.uMangles.length;
				this.mangles[p_angles[i].id] = p_angles[i];
				this.uMangles.push(p_angles[i].id);
			}
			
			g_fm.meubles[p_id] = this;
			
			if (this.owned > 0 || this.sold)
			{
				for (var i in p_cats)
				{
					if (g_fm.cats[p_cats[i]])
					{
						g_fm.cats[p_cats[i]].AddItem( this);
					}
				}
			}
		},
		Load: function(){
			g_fm.currentMeuble = this.id;
			$('FurnitMenuCenter').show();
			if (this.sold)
			{
				$('Add').show();
			}
			else if(this.used < this.owned)
			{
				$('Add').show();
			}
			else
			{
				$('Add').hide();
			}
			$('Furnit_Name').update( this.name);
			$('Furnit_Price').update( this.price);
			$('Furnit_OwnedNum').update( this.owned);
			$('Furnit_OwnedUsed').update( this.used);
			if (this.popu > 0)
			{
				$('Furnit_Popu').style.display='inline';
				$('Furnit_Popu_Amount').update( this.popu);
				if (this.popu > g_mainChar.popu)
				{
					$('Furnit_Popu').style.color='red';
					$('Add').hide();
				}
				else
				{
					$('Furnit_Popu').style.color='black';
				}
			}
			else
			{
				$('Furnit_Popu').style.display='none';
			}
			l_div = $('Furnit_Mangles');
			l_div.update();
			var l_first = false;
			for (var i in this.mangles)
			{
				if(!l_first){this.LoadMangle(i);l_first=true;}
				m = this.mangles[i];
				l_div.insert( '<a onclick="g_fm.meubles['+this.id+'].LoadMangle('+i+');return false;"><img class="i48" src="/i/b/m/'+m.icone+'" style="margin:0.3em;"/></a>');
			}
		},
		LoadMangle: function( p_index){
			if(!this.mangles[p_index]){return;}
			m=this.mangles[p_index];
			g_fm.currentMangle = p_index;
			$('Furnit_FurImg').src='/i/b/m/'+m.icone;
			if (Math.max(m.height,m.width) < 200)
			{
				$('Furnit_FurImg').style.width=m.width/16+'em';
				$('Furnit_FurImg').style.height=m.height/16+'em';
				$('Furnit_FurImg').style.marginTop = ((200-m.height)/2)/16+'em';
			}
			else
			{
				l_ratio = m.height / m.width;
				$('Furnit_FurImg').style.width=(l_ratio < 1?200:200/l_ratio)/16+'em';
				$('Furnit_FurImg').style.height=(l_ratio > 1?200:200*l_ratio)/16+'em';
				if (l_ratio < 1)
				{
					$('Furnit_FurImg').style.marginTop = ((100-100*l_ratio))/16+'em';
				}
				else
				{
					$('Furnit_FurImg').style.marginTop ='0';
				}
			}
		}
	});
	var FMangle = Class.create({
		initialize: function( p_id, p_icon, p_width, p_height){
			this.id = p_id;
			this.icone = p_icon;
			this.width = p_width;
			this.height = p_height;
		}
	});
	var FInstance = Class.create({
		initialize: function( p_roomId, p_meubleId, p_mangleId, p_x, p_y, p_id){
			if ( ! g_fm.meubles[p_meubleId]){return;}
			p_id = p_id || (++g_fm.instanceId);
			if ( ! g_map.rooms[p_roomId])
			{
				return;
			}

			this.meubleId = p_meubleId;
			this.mangleId = p_mangleId;
			this.x = p_x;
			this.rid = p_roomId;
			this.y = p_y;
			this.z = 1 + g_map.rooms[p_roomId].numMovable;
			this.id = p_id;
			this.scale = g_map.rooms[p_roomId].scale;
			this.todestroy = false;
			
			++ g_fm.meubles[this.meubleId].used;


			g_map.rooms[p_roomId].AddMovable( this);
//			g_fm.RecalcPrice();
			g_fm.instances[this.id] = this;
		},
		Destroy: function(){
			-- g_fm.meubles[this.meubleId].used;
			this._readjustZ();
			this.Unload();
			tooltip.hide();
			delete g_fm.instances[this.id];
		},
		Unload: function(){
			if (g_fm.selectedInstance == this.id)
			{
				g_fm.Unselect();
			}
			if (this.draggable)
			{
				this.draggable.destroy();
				var l_temp = $('hdfs_' + this.id);
				l_temp.parentNode.removeChild( l_temp);
				this.draggable = null;
			}
		},
		Load: function(){
			var l_meuble = g_fm.meubles[this.meubleId];

			if (!l_meuble || !l_meuble.mangles[this.mangleId])
			{
				return;
			}
			var l_div = $( 'MainHome');
			if (l_div == null)
			{
				return;
			}
			var m = l_meuble.mangles[this.mangleId];
			var l_width = m.width * this.scale * g_map.allScale;
			var l_height = m.height * this.scale * g_map.allScale;
			this.w = l_width;

			var l_temp = new Element('span', {id:'hdfs_' + this.id});
			
			l_temp.update( '<a href="javascript:;" onmouseover="tooltip.show(\'' + l_meuble.name + '\');" onmouseout="tooltip.hide();"><img id="Furnish_' + this.id + '" src="/i/b/m/' + m.icone + '" class="deletable" style="position:absolute;left:' + this.x  * g_map.allScale*g_map.globalScale+ 'px;top:' + this.y  * g_map.allScale*g_map.globalScale+ 'px;width:' + l_width/16 + 'em;height:' + l_height/16 + 'em;z-index:'+this.z+'" /></a>');
			l_div.appendChild( l_temp);
			
			$( 'Furnish_' + this.id).style.zIndex = this.z;
			$( 'Furnish_' + this.id).meubleiID = this.id;
			
			var l_id = this.id;
			
			$( 'Furnish_' + this.id).onclick = this.Select.bind(this);
			this.draggable = new Draggable( 'Furnish_' + this.id, { instance: this, onStart:function(){$('Furnit_Turn').hide()},onEnd: function( p_elem, p_event){ $('Furnit_Turn').show();this.instance.Move( p_event, p_elem);} });
		},
		Save: function(){
			return this.rid + '!' + this.x + '!' + this.y + '!' + this.z + '!' + this.meubleId + '!' + this.mangleId+'$';
		},
		Select: function(){
			g_fm.Unselect();
			if (g_fm.meubles[this.meubleId].numMangles > 1)
			{
				$('Furnit_Turn').show();
			}
			g_fm.selectedInstance = this.id;
			$('Furnish_' + this.id).style.left = (this.x*g_map.allScale-1)*g_map.globalScale+'px';
			$('Furnish_' + this.id).style.top = (this.y*g_map.allScale-1)*g_map.globalScale+'px';
			$('Furnish_' + this.id).style.border='1px dashed red';
			$('Furnit_Turn').style.left = (this.x*g_map.allScale)*g_map.globalScale+'px';
			$('Furnit_Turn').style.top = (this.y*g_map.allScale-24)*g_map.globalScale+'px';
			$('Furnit_Turn').style.width = Math.max(50,this.w)/16+'em';
		},
		Turn: function(p_wantedId){
			l_wanted = g_fm.meubles[this.meubleId].mangles[p_wantedId];
			if (l_wanted)
			{
				this.mangleId = p_wantedId;
				$( 'Furnish_' + this.id).src='/i/b/m/'+l_wanted.icone;
				l_width = l_wanted.width * this.scale;
				l_height = l_wanted.height * this.scale;
				$( 'Furnish_' + this.id).style.width = l_width/16+'em';
				$( 'Furnish_' + this.id).style.height = l_height/16+'em';
				this.w = l_width;
			}
		},
		TurnLeft: function(){
			var l_current = g_fm.meubles[this.meubleId].mangles[this.mangleId].umIndex+1;
			l_current = l_current%(g_fm.meubles[this.meubleId].uMangles.length);
			this.Turn(g_fm.meubles[this.meubleId].uMangles[l_current]);
		},
		TurnRight: function(){
			var l_current = g_fm.meubles[this.meubleId].mangles[this.mangleId].umIndex-1;
			if (l_current < 0){l_current = g_fm.meubles[this.meubleId].uMangles.length-1;}
			this.Turn(g_fm.meubles[this.meubleId].uMangles[l_current]);
		},
		Unselect: function(){
			$( 'Furnish_' + this.id).style.left = (this.x* g_map.allScale)*g_map.globalScale+'px';
			$( 'Furnish_' + this.id).style.top = (this.y* g_map.allScale)*g_map.globalScale+'px';
			$( 'Furnish_' + this.id).style.border='';
		},
		ReZ: function(){
			-- this.z;
			-- $('Furnish_' + (this.id)).style.zIndex;
		},
		ResetPos: function(){
			this.x = 400 * g_map.allScale;
			this.y = 200 * g_map.allScale;
			this.img.style.left = this.x*g_map.globalScale+'px';
			this.img.style.top = this.y*g_map.globalScale+'px';
			this.x = this.x / g_map.allScale;
			this.y = this.y / g_map.allScale;
		},
		_readjustZ: function(){
			var l_min = this.z;
			var l_max = 0;
			for (var i in g_map.rooms[this.rid].movables)
			{
				++ l_max;
				if (g_map.rooms[this.rid].movables[i].z > l_min)
				{
					g_map.rooms[this.rid].movables[i].ReZ();
				}
			}
			this.z = l_max;
			$('Furnish_' + this.id).style.zIndex = 10 + this.z;
			return 10 + this.z;
		},
		Move: function( p_event, p_elem){
			if (this.todestroy)
			{
				this.Destroy();
				g_map.rooms[this.rid].DelMovable(this.id);
				g_fm.Unselect();
				return;
			}

			this.img = $( 'Furnish_' + this.id);
			if ( ! p_event) { p_event = window.event; }
			
			containerLeft = Position.page($('MainHome'))[0];
			containerTop = Position.page($('MainHome'))[1];

			mouseX = Position.page(this.img)[0] + (this.img.naturalWidth ? this.img.naturalWidth : this.img.width) / 2;
			mouseY = Position.page(this.img)[1] + (this.img.naturalHeight ? this.img.naturalHeight : this.img.height) / 2;

			horizontalPosition = mouseX - containerLeft;
			verticalPosition = mouseY - containerTop;
			
			if (horizontalPosition < 0 || horizontalPosition > 1024 * g_map.allScale*g_map.globalScale
			|| verticalPosition < 0 || verticalPosition > 600 * g_map.allScale*g_map.globalScale)
			{
				this.ResetPos();
				return;
			}
			
			this.x = parseInt( this.img.style.left);
			this.y = parseInt( this.img.style.top);
			$('Furnit_Turn').style.left = this.x+'px';
			$('Furnit_Turn').style.top = (this.y-16)+'px';
			this.x = this.x / g_map.allScale / g_map.globalScale;
			this.y = this.y / g_map.allScale / g_map.globalScale;
			p_elem.originalZ = this._readjustZ();
		}
	});
}
{ /***************Kazukea******************/
	var g_kazukea = {
		Reset: function(){
			this.cats = {};
			this.meubles = {};
			this.currentCat = 0;
			this.currentMeuble = 0;
			this.numBoughtItems = 0;
		},
		Load: function(p_shopId){
			this.shopid = p_shopId;
			g_unloadFunction = this.Reset.bind(this);
			for (var i in this.cats)
			{
				if (this.cats[i].numMeubles == 0)
				{
					this.cats[i].Hide();
				}
			}
			for (var i in this.cats)
			{
				this.cats[i].OpenFirst();
				break;
			}
		},
		Buy: function(){
			if (this.currentMeuble != 0 && this.meubles[this.currentMeuble])
			{
				this.meubles[this.currentMeuble].BuyOne();
			}
		},
		RecalcPrice: function(){
			var l_price = 0;
			for (var i in this.meubles)
			{
				var l = this.meubles[i];
				l_price += l.price * l.tobuy;
			}
			
			$('KazukeaCreds').update(g_mainChar.credits);
			$('KazukeaPrice').update(l_price);
			$('KazukeaTotal').update(g_mainChar.credits - l_price);
			if (g_mainChar.credits - l_price > 0)
			{
				$('KazukeaTotal').setStyle('font-color:#000');
				$('Kazukea_BuyIcon').show();
				$('Kazukea_NoKazIcon').hide();
			}
			else
			{
				$('KazukeaTotal').setStyle('font-color:#F00');
				$('Kazukea_BuyIcon').hide();
				$('Kazukea_NoKazIcon').show();
			}
		},
		BuySave: function(){
		var l_data = '';
			for (var i in this.meubles)
			{
				l_data += this.meubles[i].Save();
			}
			return _openUrl2( 'shopfurnit', {action:'save',data:l_data,id:this.shopid});
		}
	};g_kazukea.Reset();
	var KazukeaCat = Class.create({
		initialize: function( p_id, p_name, p_icone, p_num){
			this.name = p_name;
			this.id = p_id;
			this.meubles = {};
			this.numMeubles = 0;

			var l_div = $( 'Furnit_Menu');
			if (l_div == null){return;}
			
			l_div.insert( '<a href="#" onclick="g_kazukea.cats['+this.id+'].Open();return false;" id="menu_cat_'+this.id+'"><img src="/i/'+p_icone+'" class="i40" style="margin:0.3em"></a>');
			
			g_kazukea.cats[this.id] = this;
		},
		MouseOver: function(){
			tooltip.show( this.name);
		},
		Finalise: function(){
			$('menu_cat_'+this.id).onmouseover = this.MouseOver.bind(this);
			$('menu_cat_'+this.id).onmouseout = tooltip.hide.bind(tooltip);
		},
		Open: function(){
			$('FurnitMenuRight').show();
			g_kazukea.currentCat = this.id;
			l_div = $('ListeMeublesInCat');
			l_div.update();
			for (var i in this.meubles)
			{
				m = this.meubles[i];
				l_div.insert( '<a onclick="g_kazukea.meubles['+m.id+'].Load();return false;"onmouseout="tooltip.hide();"onmouseover="tooltip.show(\''+m.name+'\')"><img src="/i/b/m/'+m.icone+'" class="h48"/></a>');
			}
		},
		AddItem: function( p_m){
			this.meubles[p_m.id] = p_m;
			++ this.numMeubles;
		},
		Hide: function(){
			$('menu_cat_'+this.id).hide();
		},
		OpenFirst: function(){
			this.Open();
			for (var i in this.meubles)
			{
				this.meubles[i].Load();
				break;
			}
		}
	});
	var KazukeaMeuble = Class.create({
		initialize: function( p_id, p_name, p_price, p_minPopu, p_num, p_img, p_cats, p_angles, p_sold){
			this.name = p_name;
			this.id = p_id;
			this.price = p_price;
			this.icone = p_img;
			this.owned = p_num;
			this.popu = p_minPopu;
			this.sold = p_sold || false;
			this.mangles = {};
			this.uMangles = [];
			this.numMangles = p_angles.length;
			this.tobuy = 0;
			
			for (var i = 0 ; i < p_angles.length ; ++ i)
			{
				p_angles[i].umIndex = this.uMangles.length;
				this.mangles[p_angles[i].id] = p_angles[i];
				this.uMangles.push(p_angles[i].id);
			}
			
			g_kazukea.meubles[p_id] = this;
			
			if (this.owned > 0 || this.sold)
			{
				for (var i in p_cats)
				{
					if (g_kazukea.cats[p_cats[i]])
					{
						g_kazukea.cats[p_cats[i]].AddItem( this);
					}
				}
			}
		},
		Load: function(){
			g_kazukea.currentMeuble = this.id;
			$('FurnitMenuCenter').show();
			if (this.sold)
			{
				$('Add').show();
			}
			else
			{
				$('Add').hide();
			}
			$('Furnit_Name').update( this.name);
			$('Furnit_Price').update( this.price);
			$('Furnit_OwnedNum').update( this.owned);
			if (this.popu > 0)
			{
				$('Furnit_Popu').style.display='inline';
				$('Furnit_Popu_Amount').update( this.popu);
				if (this.popu > g_mainChar.popu)
				{
					$('Furnit_Popu').style.color='red';
					$('Add').hide();
				}
				else
				{
					$('Furnit_Popu').style.color='black';
				}
			}
			else
			{
				$('Furnit_Popu').style.display='none';
			}
			l_div = $('Furnit_Mangles');
			l_div.update();
			var l_first = false;
			for (var i in this.mangles)
			{
				if(!l_first){this.LoadMangle(i);l_first=true;}
				m = this.mangles[i];
				l_div.insert( '<a onclick="g_kazukea.meubles['+this.id+'].LoadMangle('+i+');return false;"><img class="i48" src="/i/b/m/'+m.icone+'" style="margin:0.3em;"/></a>');
			}
		},
		LoadMangle: function( p_index){
			if(!this.mangles[p_index]){return;}
			m=this.mangles[p_index];
			g_kazukea.currentMangle = p_index;
			$('Furnit_FurImg').src='/i/b/m/'+m.icone;
			if (Math.max(m.height,m.width) < 200)
			{
				$('Furnit_FurImg').style.width=m.width/16+'em';
				$('Furnit_FurImg').style.height=m.height/16+'em';
				$('Furnit_FurImg').style.marginTop = ((200-m.height)/2)/16+'em';
			}
			else
			{
				l_ratio = m.height / m.width;
				$('Furnit_FurImg').style.width=(l_ratio < 1?200:200/l_ratio)/16+'em';
				$('Furnit_FurImg').style.height=(l_ratio > 1?200:200*l_ratio)/16+'em';
				if (l_ratio < 1)
				{
					$('Furnit_FurImg').style.marginTop = ((100-100*l_ratio))/16+'em';
				}
				else
				{
					$('Furnit_FurImg').style.marginTop ='0';
				}
			}
		},
		BuyOne: function(){
			if (this.tobuy == 0)
			{
				++ g_kazukea.numBoughtItems;
				$('KazukeaBuyList').setStyle('width:'+5*g_kazukea.numBoughtItems+'em');
				var ele = new Element( 'span', {id:'KazukeaBuyListItem_'+this.id,'class':'base'});
				ele.setStyle({width:'5em','text-align':'right'});
				ele.update('<a href="javascript:;"onclick="g_kazukea.meubles['+this.id+'].Load()"><img src="/i/b/m/'+this.icone+'"onmouseover="g_kazukea.meubles['+this.id+'].MouseOver2()"onmouseout="tooltip.hide()"class="i64"></a><br/>x <span id="KazukeaBuyListItemNum_'+this.id+'"></span><br/>'
				+'<a href="javascript:;"onclick="g_kazukea.meubles['+this.id+'].RemoveOne()"><img class="top_right i16m" style="z-index:2500"src="/i/b_drop.png"onmouseover="tooltip.show(\'Supprimer\')"onmouseout="tooltip.hide()"/></a>');
				$('KazukeaBuyList').insert(ele);
			}
			++ this.tobuy;
			$('KazukeaBuyListItemNum_'+this.id).update(this.tobuy);
			g_kazukea.RecalcPrice();
		},
		MouseOver2: function(){
			tooltip.show(this.name+'<br/>'+this.price+' x ' + this.tobuy + ' = ' + (this.price * this.tobuy) + ' kaz');
		},
		RemoveOne: function(){
			-- this.tobuy;
			if (this.tobuy == 0)
			{
				var l_temp = $('KazukeaBuyListItem_' + this.id);
				if (l_temp)
				{
					l_temp.parentNode.removeChild( l_temp);
					-- g_kazukea.numBoughtItems;
					$('KazukeaBuyList').setStyle('width:'+5*g_kazukea.numBoughtItems+'em');
				}
			}
			g_kazukea.RecalcPrice();
		},
		Save: function(){
			if (this.tobuy > 0)
			{
				return this.id+'x'+this.tobuy+'$';
			}
			else
			{
				return '';
			}
		}
	});
	var KazukeaMangle = Class.create({
		initialize: function( p_id, p_icon, p_width, p_height){
			this.id = p_id;
			this.icone = p_icon;
			this.width = p_width;
			this.height = p_height;
		}
	});
}
{ /***************City*********************/
	var g_city = {
		axes: ['_M3_', '_M1_', '_M0_', '_M2_'],
		walkSpeed: 75.0,
		scaleChars: 1.0,
		Reset: function(){
			this.portals = {};
			this.highlighted = 0;
			this.selectedUserId = 0;
			this.users = {};
			this.nextObjectId = 0;
			this.loaded = false;
			this.visuRoom = false;
			this.currentPortalTarget = 0;
			this.tcl = false;
			g_map.Reset();
		},
		OpenMap: function(){
			if (this.loaded)
			{
				g_smap.LoadCurrentMap();
				Recenter('CadreMapKazucity');
				if ($('CadreMapKazucity').visible())
				{
					$('CadreMapKazucity').hide();
				}
				else
				{
					CloseAllSubMenus();
					$('CadreMapKazucity').show();
				}
				return false;
			}
			else
			{
				_openUrl('map');
			}
			return false;
		},
		HighlightNpc: function(p_id){
			if (g_npcm.npcs[p_id])
			{
				if(this.highlighted != 0)
				{
					g_npcm.npcs[this.highlighted].UnsetHighlight();
				}
				g_npcm.npcs[p_id].SetHighlight();
				this.highlighted = p_id;
			}
		},
		Unhl: function(){
			if (this.highlighted != 0)
			{
				g_npcm.npcs[this.highlighted].UnsetHighlight();
			}
			this.highlighted = 0;
		},
		Unload: function(){
			for (var i in this.users)
			{
				this.users[i].Delete();
			}
			this.Reset();
			g_pm.Unload();
			g_npcm.ResetAll();
			g_carM.Reset();
			if ($('CadreMapKazucity'))
			{
				deleteNode($('CadreMapKazucity'));
			}
		},
		Load: function( p_visuRoom){
			g_unloadFunction = this.Unload.bind(this);
			g_map.unselectFunction = function(){};
			g_map.Load( 'Map_Main2');
			this.visuRoom = p_visuRoom || false;
			this.loaded = true;
		},
		CheckKeys: function( p_event){
			switch (p_event.keyCode)
			{
				case 77: {g_map.toggle();break;}
				case 69: {this.PrintCoords();break;}
				case 13: {$('ChatText').focus();break;}
				case 37: //left
				case 38: //up
				case 39: //right
				case 40: //down
				case 73: //I
				default:break;
			}
		},
		PrintCoords: function( p_event){
			var l_pos = getActualMouseCoords( p_event);
			var l_off = $('Map_Main2').cumulativeOffset();
//			var l_off2 = $('Map_Main2').cumulativeScrollOffset();
			
			var x = parseInt($('user_'+g_mainChar.id).style.left);
			var y = parseInt($('user_'+g_mainChar.id).style.top);
			var w = parseInt($('user_'+g_mainChar.id).style.width);
			var h = parseInt($('user_'+g_mainChar.id).style.height);
			
			//var p = [l_pos.x - l_off[0] - w/2,18 + l_pos.y - l_off[1] - h];//Coords for pnj
			//var p = [9+l_pos.x - l_off[0] - w/2,18 + l_pos.y - l_off[1] - h*0.85];//coords for bbox ?
			var p = [l_pos.x - l_off[0],l_pos.y - l_off[1]];//coords for the rest ?
			tooltip.show( 'Coords : x:' + (Math.floor((p[0]) / g_map.allScale)) + ' y:' + (Math.floor((p[1]) / g_map.allScale)) + ' room:' + g_map.currentRoom);
		},
		OpenCharInfos: function( p_id){
			if (!this.users[p_id]){return;}
			$('CharInfoName').update(this.users[p_id].name);
			$('CharInfos').setStyle({left:(this.users[p_id].x-$('CharInfos').getWidth())+'px',top:(this.users[p_id].y-64)+'px'});
			$('CharInfos').show();
			this.selectedUserId = p_id;
		},
		HideCharInfos: function(){
			$('CharInfos').hide();
			this.selectedUserId = 0;
		},
		GoSelectedProfile: function(){
			_openUrl2( 'profile', {id_user:this.selectedUserId});
			this.HideCharInfos();
		},		
		GoSelectedHome: function(){
			_openUrl( 'home', {id:this.selectedUserId});
			this.HideCharInfos();
		},
		MoveTo: function( p_event){
			if (!this.users[g_mainChar.id] || !this.users[g_mainChar.id].loaded){return false;}
			g_mainChar.npcTarget = 0;
			this.HideCharInfos();

			var l_off = $('Map_Main2').cumulativeOffset();

			var l_pos = getActualMouseCoords( p_event);
			var targetX = l_pos.x-l_off[0];
			var targetY = l_pos.y-l_off[1];

			if (this.fadingCursor){this.fadingCursor.cancel();$('MoveCursor').setOpacity(1.0);}
			this.fadingCursor = Effect.Fade('MoveCursor',{duration:3.0});
			$('MoveCursor').setStyle({left:(targetX-26)+'px',top:(targetY-40)+'px'});
			$('MoveCursor').show();
			
			var l_c = this.users[g_mainChar.id].GetCoords();

			var path = g_map.rooms[g_map.currentRoom].pathMap.GetPath([l_c.x,l_c.y],[targetX,targetY]);
			if (path.length == 0)
			{
				$('MoveCursor').src='/i/walk/None.png';
				$('MoveCursor').setStyle({left:(targetX-16)+'px',top:(targetY-16)+'px',width:'32px',height:'32px'});
				return false;
			}
			$('MoveCursor').src='/i/walk/curseur.gif';
			$('MoveCursor').setStyle({width:'80px',height:'66px'});
			this.users[g_mainChar.id].FollowPath(path);

			return false;
		},
		FocusOn: function( p_id){
			if (this.users[p_id])
			{
				g_map.ChangeRoom( this.users[p_id].rid);
			}
		},
		SetupMove: function(){
			if (!this.users[g_mainChar.id])
			{
				return;
			}
			$('Map_Main2').onclick = this.MoveTo.bind(this);
			var num = 0;
			for (var i in g_npcm.npcs)
			{
				++ num;
				g_npcm.npcs[i].LoadOPos();
			}
		},
		ChangeRoom: function( p_userId, p_id, p_arx, p_ary){
			if (!g_map.rooms[p_id] || !this.users[p_userId]){return;}
			
			this.users[p_userId].ShowAt( p_arx, p_ary, p_id);
			if (g_map.currentRoom == p_id){return;}
			hideDiv('MoveCursor');
			this.portals = {};
			g_map.ChangeRoom( p_id);
		},
		UpdatePlayers: function( p_players){
			var l_u = {};
			for (var i in g_chat.users)
			{
				l_u[i] = true;
			}
			l_u[g_mainChar.id] = false;
			for (var i = 0 ; i < p_players.length ; ++ i)
			{
				var l_p = p_players[i];
				if (l_p.i == g_mainChar.id){continue;}
				if (g_mainChar.zid && l_p.z != g_mainChar.zid){continue;}
				
				l_u[l_p.i] = false;
				if ( ! this.users[l_p.i])
				{
					var lu;
					if (parseInt(l_p.a) > 0)
					{
						lu = new MovableUser( l_p.i, l_p.l, '/ui/'+l_p.l+'_'+l_p.a+'_0_.png', l_p.p, l_p.t, l_p.k);
					}
					else
					{
						lu = new MovableUser( l_p.i, l_p.l, '/i/default_0_.png', l_p.p, l_p.t, l_p.k);
					}

					if (l_p.pet)
					{
						lu.SetupPet(l_p.pet);
					}
					
					lu.ShowAt( l_p.x, l_p.y, l_p.r);
				}
				else
				{
					if (l_p.pet)
					{
						this.users[l_p.i].SetupPet(l_p.pet);
					}
					if (parseInt(l_p.a) > 0)
					{
						this.users[l_p.i].UpdateStatus( '/ui/'+l_p.l+'_'+l_p.a+'_0_.png',l_p.p, l_p.t, l_p.k);
					}
					this.users[l_p.i].MoveTowards( l_p.r, l_p.x, l_p.y);
				}
			}
			for (var i in g_chat.users)
			{
				if(l_u[i] && this.users[i] && this.users[i].loaded){this.users[i].Delete();}
			}
		},
		RemoveUser: function( p_id){
			if (!this.loaded){return;}
			if (this.users[p_id])
			{
				this.users[p_id].Hide();
				delete this.users[p_id];
			}
		},
		RecheckPortals: function(){
			for (var i in this.portals)
			{
				this.portals[i].Recheck();
			}
			g_npcm.RecheckNPCs();
		},
		ClutterHouse: function( p_cl1, p_cl2){
			if (p_cl1 > 0)
			{
				for (var i in g_map.rooms)
				{
					var l_map = g_map.rooms[i].pathMap;
					for (var j = 0 ; j < p_cl1 ; j ++)
					{
						var done = false;
						var x=0,y=0;
						var count = 0;
						while(!done && count < 10)
						{
							x = 100 + Math.random()*800;
							y = 100 + Math.random()*400;
							if (!l_map.CheckPoint(x,y))
							{
								done = true;
							}
							++ count;
						}
						new MapObject(i,'/i/b/m/tas_vetements.png',x,y,-10,169,123,0,0,1);
					}
				}
			}
			if (p_cl2 > 0)
			{
				for (var i in g_map.rooms)
				{
					var l_map = g_map.rooms[i].pathMap;
					for (var j = 0 ; j < p_cl2 ; j ++)
					{
						var done = false;
						var x=0,y=0;
						var count = 0;
						while(!done && count < 10)
						{
							x = 100 + Math.random()*800;
							y = 100 + Math.random()*400;
							if (!l_map.CheckPoint(x,y))
							{
								done = true;
							}
							++ count;
						}
						new MapObject(i,'/i/b/m/tas_objet.png',x,y,-10,185,139,0,0,1);
					}
				}
			}
		},
		GpsN: function( p_id){
			var n = g_npcm.npcs[p_id];
			if (n)
			{
				this.HighlightNpc(p_id);
				
				if (n.otherPos)
				{
					for (var i in n.otherPos)
					{
						if (g_mainChar.CheckCondition(n.otherPos[i].c))
						{
							g_gps.GetPath( i);
							return;
						}
					}
				}
				
				g_gps.GetPath( n.rid);
			}
		}
	};g_city.Reset();
	var MapObject = Class.create({
		sm_baseDiv:'Map_Main2',
		initialize: function( p_roomID, p_img, p_x, p_y, p_z, p_w, p_h, p_noscale, p_power,p_nourl){
			if ( ! g_map.rooms[p_roomID]){ return; }
			
			this.rid = p_roomID;
			this.x = p_x;
			this.y = p_y;
			this.nourl = p_nourl ||false;
			this.z = g_map.rooms[p_roomID].CalcZ( p_x, p_y, p_z);
			this.power = p_power || false;
			this.onClick = false;
			this.onMouseOver = false;
			this.onMouseOut = false;
			this.onWalkOver = false;
			this.noScale = p_noscale || false;
			this.id = ++ g_city.nextObjectId;
			this.img = p_img;
			if (this.noScale)
			{
				this.w = p_w;
				this.h = p_h;
			}
			else
			{
				this.w = p_w * g_map.rooms[p_roomID].scale;
				this.h = p_h * g_map.rooms[p_roomID].scale;
			}
			g_map.rooms[p_roomID].AddStatic(this);
		},
		LoadImageFinished: function(){
			this.prImg = false;
		},
		ActivatePower: function(){
			switch (this.power)
			{
				case 1:return _openUrl2( 'avatar');break;
				case 5:
				if (g_npcm.npcs[1] && g_mainChar.CheckCondition('q:375'))
				{
					g_npcm.npcs[272].InitDlg();
					g_diM.OpenDiscussion( 1069);
				}break;
			}
		},
		Load: function(){
			var l_div = $( this.sm_baseDiv);
			if (l_div == null)
			{
				return;
			}
			if (this.img)
			{
				var l_img = new Element( 'img', {id:'MapObj_' + this.id, src:(this.nourl?'':'/i/b/') + this.img});
				l_img.setStyle(
				{
					position:	'absolute',
					zIndex:		this.z,
					left:		g_map.allScale * this.x / 16 +'em',
					top:		g_map.allScale * this.y / 16 +'em',
					width:		g_map.allScale * this.w / 16 +'em',
					height:		g_map.allScale * this.h / 16 +'em'
				});
				l_img.onmousedown = function(){return false};
				if (this.power)
				{
					l_img.onclick = this.ActivatePower.bind(this);
				}
				else if (this.onClick)
				{
					l_img.onclick = this.onClick.bind( this);
				}
				if (this.onMouseOver)
				{
					l_img.observe( 'mouseover', this.onMouseOver.bind( this));
					l_img.onmouseover = this.onMouseOver.bind( this);
					l_img.onmouseout = this.onMouseOut.bind( this);
				}
				l_div.appendChild( l_img);
				
			}

			if (this.onWalkOver)
			{
				g_city.portals[this.id] = this;
			}
		},
		Unload: function(){
			var l_temp = $('MapObj_' + this.id);
			if (l_temp)
			{
				l_temp.parentNode.removeChild( l_temp);
			}
		},
		IsInside: function( p_x, p_y){
			return p_x >= this.x && p_y >= this.y && p_x <= (this.x+this.w) && p_y <= (this.y+this.h);
		},
		Rescale: function( p_scale){
			if (this.img && $('MapObj_'+this.id))
			{
				$('MapObj_'+this.id).setStyle(
				{
					left:		g_map.allScale * this.x / 16+'em',
					top:		g_map.allScale * this.y / 16+'em',
					width:		g_map.allScale * this.w / 16+'em',
					height:		g_map.allScale * this.h / 16+'em'
				});
			}
		}
	});
	var BoundingSphere = Class.create({
		initialize: function( p_roomId, p_radius, p_x, p_y){
			this.radius = p_radius * p_radius;
			this.cx = p_x;
			this.cy = p_y;
			g_map.rooms[p_roomId].walls.push(this);
		},
		IsInside: function( p_absX, p_absY){
			var l_diffx = Math.abs(p_absX-this.cx);
			var l_diffy = Math.abs(p_absY-this.cy);
			return ((l_diffx*l_diffx + l_diffy*l_diffy) < this.radius);
		},
		LinePassesThrough: function(){
			return false;
		}
	});
	function _crossProd( p_a, p_b){
		return p_a[0] * p_b[1] - p_a[1] * p_b[0];
	}
	var BoundingPoly = Class.create({
		initialize: function( p_roomId, p_points, p_inverse){
			this.id = 0;
			this.numPoints = p_points.length;
			this.points = p_points;
			this.lines = [];
			this.inverse = p_inverse || false;
			var l_cx = 0, l_cy = 0;
			for (var i = 0 ; i < this.numPoints ; ++ i)
			{
				this.points[i][0] += 40;
				this.points[i][1] += 60;
				l_cx += this.points[i][0];
				l_cy += this.points[i][1];
			}
			this.center = {x:Math.floor(l_cx / this.numPoints), y: Math.floor(l_cy / this.numPoints)};
			for (var i = 0 ; i < this.numPoints-1 ; ++ i)
			{
				this.lines.push( [this.points[i+1][0]-this.points[i][0], this.points[i+1][1]-this.points[i][1]]);
			}
			this.lines.push( [this.points[0][0]-this.points[this.numPoints-1][0], this.points[0][1]-this.points[this.numPoints-1][1]]);
			g_map.rooms[p_roomId].walls.push(this);
		},
		OffsetPoint: function(p_index){
			var l_point = this.points[p_index];
			var x = l_point[0] - this.center.x;
			var y = l_point[1] - this.center.y;
			var dist = Math.sqrt(x*x+y*y);
//			return {x:l_point[0],y:l_point[1]};
			return {x:l_point[0] + x*30/dist,y:l_point[1] + y*30/dist};
		},
		IsInside: function( p_absX, p_absY){
			var x = p_absX;
			var y = p_absY;
			var b = true;
			for (var i = 0 ; i< this.numPoints ; ++ i)
			{
				var l = _crossProd( [x - this.points[i][0], y - this.points[i][1]], this.lines[i]);
				if (l < 0)
				{
					b = false;break;
				}
			}
			if (this.inverse){return !b;}
			return b;
		},
		LinePassesThrough: function( p_origin, p_end){
			if (this.inverse){return false;}
			var pos = neg = false;
			for (var i = 0 ; i < this.numPoints; ++ i)
			{
				var a = [ this.points[i][0], this.points[i][1]];
				var b = [ this.points[i][0] + this.lines[i][0], this.points[i][1] + this.lines[i][1]];
				if (this.IntersectsLine( p_origin, p_end, a,b))
				{
					return true;
				}
			}
			return false;
		},
		IntersectsLine: function( p_startA, p_endA, p_startB, p_endB){
			var denom = (p_endB[1] - p_startB[1])*(p_endA[0] - p_startA[0]) - (p_endB[0] - p_startB[0])*(p_endA[1] - p_startA[1]);
			if (denom == 0){return false;}
			var ua = ((p_endB[0]-p_startB[0])*(p_startA[1]-p_startB[1]) - (p_endB[1]-p_startB[1])*(p_startA[0]-p_startB[0])) / denom;
			if (ua <0.0 || ua > 1.0){return false;}
			var ub = ((p_endA[0]-p_startA[0])*(p_startA[1]-p_startB[1]) - (p_endA[1]-p_startA[1])*(p_startA[0]-p_startB[0])) / denom;
			return (ub >= 0.0 && ub <= 1.0)
		}
	});
	var TextBulle = Class.create({
		initialize: function(p_id,p_text,p_userId){
			this.bid = 'CharBulle_'+p_userId+'_'+p_id;
			this.uid = p_userId;
			this.id = p_id;
			var ele = new Element('div', {'class':'BaseCadre2pxW',id:this.bid});
			ele.update(p_text);
			$('user_text2_' + this.uid).insert(ele);
			ele.hide();
			this.inEffect = new Effect.Appear(ele);
			this.outEffect = new Effect.Fade( this.bid,{afterFinish:this.End.bind(this),delay:3+p_text.length*0.05});
		},
		Delete: function(){
			if (this.inEffect)this.inEffect.cancel();
			if (this.outEffect)this.outEffect.cancel();
			this.End();
		},
		End: function(){
			var l_temp = $(this.bid);
			if (l_temp.parentNode)
			{
				l_temp.parentNode.removeChild( l_temp);
			}
			if (g_city.users[this.uid]){g_city.users[this.uid].DeleteBulle(this.id);}
//			if($('user_text_' + this.uid)){$('user_text_' + this.uid).setStyle('height:auto')};
		}
	});
	var MovableUser = Class.create({
		initialize: function( p_id, p_name, p_img, p_popu, p_tier, p_rank){
			this.walkImageBase = p_img?p_img.substr( 0, p_img.length-7):false;
			
			this.name = p_name;
			this.img = p_img;
			this.id = p_id;
			this.human = true;
			this.hightlight = false;
			this.popu = p_popu || 0;
			this.rank = p_rank || 0;
			this.tier = p_tier || 0;
			this.rid = 0;
			this.loaded = false;
			this.x = 0;
			this.y = 0;
			this.speed = 150;
			this.bulle = false;
			this.bulleEffects = {};
			this.baseWidth = 160 * g_city.scaleChars;
			this.baseHeight = 160 * g_city.scaleChars;
			this.noShadow = false;
			this.pet = 0;
			this.shadow = 'ombre_base.png';
			this.targetPos = false;
			this.path = [];
			this.texts = {};
			this.numText = 0;
			this.otherPos = false;
			
			this.AdjustStatus();
			g_city.users[this.id] = this;
		},
		SetHighlight: function(){
			if (this.highlight){return;}
			this.highlight = true;
			if (this.loaded)
			{
				$('user_'+this.id).insert('<div id="user_hl_'+this.id+'" style="position:absolute;left:25%;top:-55%;width:4em;z-index:1800;"><img src="/i/walk/highlight'+(this.human?'2':'')+'.gif" style="width:'+(this.human?'4':'1')+'em;height:'+(this.human?'4':'1')+'em"></div>');
			}
		},
		UnsetHighlight: function(){
			this.highlight = false;
			var l_temp = $('user_hl_' + this.id);
			if (l_temp)
			{
				l_temp.parentNode.removeChild( l_temp);
			}
		},
		Load: function(){
			if (this.loaded){return false;}
			this.loaded = true;
			this.bulle = false;
			this.numText = 0;
			this.walking = false;
			var l_div = new Element( 'div', {id:'user_'+this.id});
			l_div.onmouseover = this.MouseOver.bind(this);
			l_div.onmouseout = tooltip._hide;

			l_div.setStyle({
				position: 	'absolute',
				height: 	(this.h * g_map.ts)+'px',
				width: 		(this.w * g_map.ts)+'px',
				zIndex: 	605
			});
			if ( ! this.noShadow)
			{
				l_div.update('<img id="user_shadow_'+this.id+'"src="/i/walk/' + (this.highlight?'target.gif':this.shadow) + '" style="position:absolute;left:-5%;top:65%;width:110%;height:45%">');
			}
			if (this.highlight)
			{
				if (this.human)
				{
					l_div.insert('<div id="user_hl_'+this.id+'" style="position:absolute;left:25%;top:-55%;width:4em;z-index:1800;"><img src="/i/walk/highlight2.gif" style="width:4em;height:4em"></div>');
				}
				else
				{
					l_div.insert('<div id="user_hl_'+this.id+'" style="position:absolute;left:25%;top:-55%;width:4em;z-index:1800;"><img src="/i/walk/highlight.gif" style="width:1em;height:3em"></div>');
				}
			}
			if (this.specialEffect)
			{
				l_div.insert('<img src="'+(this.specialEffect.img)+'" style="z-index:5;width:'+(this.specialEffect.w*g_map.allScale*this.scale/16)+'em;height:'+(this.specialEffect.h*g_map.allScale*this.scale/16)+'em;position:absolute;left:'+(this.specialEffect.l*g_map.allScale*this.scale/16)+'em;top:'+(this.specialEffect.t*g_map.allScale*this.scale/16)+'em">');
			}
			if (this.img)
			{
				l_div.insert( '<img src="'+this.img+'" id="user_img_' + this.id+'"style="position:absolute;left:0;top:0;width:100%;height:100%;">');
			}

			$( 'Map_Main2').appendChild( l_div);
			/*
			if (!this.isNPC)
			{
				$('user_'+this.id).ondblclick = this.OpenMenu.bind(this);
			}
			*/
			if (this.pet != 0)
			{
				this.LoadPet();
			}
			this.SetCoords( this.x, this.y);
		},
		Delete: function(){
			this.Unload();
			if (g_map.rooms[this.rid])
			{
				g_map.rooms[this.rid].DelMovable( this.id);
			}
			this.rid = 0;
		},
		Unload: function(){
			if(!this.loaded){return;}
			this.EndWalk();
			this.loaded = false;
			this.DeleteAllBulles();
			var l_temp = $('user_' + this.id);
			l_temp.parentNode.removeChild( l_temp);
		},
		OpenMenu: function(){
			g_city.OpenCharInfos( this.id);
		},
		MoveProgress: function(){
			if (!g_map.rooms[this.rid]){return;}
			var c = this.GetCoords();
			this.x = c.x;
			this.y = c.y;
			var l_z = g_map.rooms[this.rid].CalcZ( c.x,c.y, 0);
			this.z = l_z;
			$('user_' + this.id).style.zIndex = l_z;
			if (this.id == g_mainChar.id)
			{
				g_mainChar.SavePosition( this.rid, this.x, this.y);
			}
		},
		EndWalk: function( p_stop){
			if ( ! this.walking){return;}
			this.walking.cancel();
			this.walking = false;
			if (this.ContinuePath()){return;}
			var c = this.GetCoords();
			this.x = c.x;
			this.y = c.y;
			
			$('user_img_'+this.id).src = this.img;
			if (this.pet != 0)
			{
				$('user_img_pet' + this.id).src = g_petM.pets[this.pet].image;
			}
			if (this.bulle)
			{
				$('user_text_' + this.id).setStyle({left:(this.x) * g_map.ts+'px',top:(this.y-48) * g_map.ts+'px'});
			}
			if (!this.isNPC)
			{
				if (p_stop){this.CheckPortals();}
				if (this.id == g_mainChar.id)
				{
					g_mainChar.SavePosition( this.rid, this.x, this.y);
					g_mainChar.CheckNpcTarget();
				}
			}
		},
		WalkTo: function(x,y){
			if (this.walking)
			{
				this.walking.cancel();
				this.walking = false;
			}
			var l_c = this.GetCoords();
			var l_target = [x-l_c.x,y-l_c.y];
			var l_index = (l_target[0] < 0 ? 2 : 0) + (l_target[1] < 0 ? 1 : 0);

			var l_time = (Math.sqrt(l_target[0]*l_target[0] + l_target[1]*l_target[1])) / (this.speed);
			if (l_time < 0.1)
			{
				this.SetCoords(x,y);
				this.ContinuePath();
				return;
			}

			if (this.shadow != 'ombre_nuage3.gif' && this.human)
			{
				$('user_img_'+this.id).src = this.walkImageBase+g_city.axes[l_index]+'.gif';
			}
			if (this.pet != 0)
			{
				$('user_img_pet' + this.id).src = g_petM.pets[this.pet].wimages[l_index];
			}
			l_target[0] *= g_map.ts;
			l_target[1] *= g_map.ts;
			this.walking = new Effect.Move( $('user_'+this.id), { afterUpdate: this.MoveProgress.bind(this),transition: Effect.Transitions.linear, duration: l_time, x: l_target[0], y: l_target[1], mode: 'relative', afterFinish:this.EndWalk.bind(this)});
		},
		CheckPortals: function(){
			if (g_city.tcl){return;}
			var l_c2 = this.GetCoords();
			for (var i in g_city.portals)
			{
				if (g_city.portals[i].IsInside( l_c2.x, l_c2.y))
				{
					this.TouchPortal( i);
					return;
				}
			}
		},
		TouchPortal: function( p_portalId){
			if (this.id != g_mainChar.id)
			{
				var t = g_city.portals[p_portalId].target;
				this.ShowAt( t.x, t.y, t.id);
			}
			else
			{
				g_city.portals[p_portalId].onWalkOver( this.id);
			}
		},
		MoveTowards: function( p_rid, p_x, p_y){
//			p_x = p_x * g_map.allScale;
//			p_y = p_y * g_map.allScale;
			/*
			if (this.targetPos)
			{
				this.Unload();
				this.ShowAt( this.targetPos.x, this.targetPos.y, this.targetPos.rid);
				this.targetPos = false;
				return;
			}
			*/
			this.targetPos = false;
			if (this.rid != g_map.currentRoom)	//If you're somewhere else
			{
				this.ShowAt( p_x, p_y, p_rid);
				if (p_rid == g_map.currentRoom)	//If you're coming in
				{
					this.Load();
				}
			}
			else								//If you start in our room
			{
				if (p_rid != g_map.currentRoom)	//And you're exiting
				{
					var l_pos = false;
					for (var i in g_city.portals)
					{
						var p = g_city.portals[i];
						if (p.target.id == p_rid)
						{
							var l_pos = {x:p.x+(p.w/2),y:(p.y+p.h/2)};
							break;
						}
					}
					if (l_pos)	//Found portal, going towards it
					{
						this.WalkTo( l_pos.x, l_pos.y);
//						this.targetPos = {rid:p_rid,x:p_x,y:p_y};
					}
					else	//warping 2 rooms or more ?
					{
						this.Unload();
						this.ShowAt( this.targetPos.x, this.targetPos.y, this.targetPos.rid);
						this.targetPos = false;
					}
				}
				else
				{
					this.WalkTo( p_x, p_y);
				}
			}
		},
		LoadPet: function(){
			var l_pet = g_petM.pets[this.pet];
			if ( ! $('user_img_pet'+this.id))
			{
				$('user_'+this.id).insert('<img src="' + l_pet.image + '" id="user_img_pet'+this.id+'"style="position:absolute;left:'+l_pet.x+'%;top:'+l_pet.y+'%;width:'+l_pet.w+'%;height:'+l_pet.h+'%">');
			}
			else
			{
				$('user_img_pet'+this.id).src = l_pet.image;
				$('user_img_pet'+this.id).setStyle({left:l_pet.x+'%', top:l_pet.y+'%', width:l_pet.w+'%', height:l_pet.h+'%'});
			}
		},
		SetupPet: function( p_id){
			this.pet = p_id;
			if (this.loaded)
			{
				this.LoadPet();
			}
		},
		ShowAt: function( p_x, p_y, p_roomId){
			if (this.id == g_mainChar.id){}
			if ( ! g_map.rooms[p_roomId]){return;}
			if (this.rid != p_roomId)
			{
				this.Delete();
				this.scale = g_map.rooms[p_roomId].scale;
				this.w = this.baseWidth * this.scale;
				this.h = this.baseHeight * this.scale;
				this.rid = p_roomId;
				g_map.rooms[p_roomId].AddMovable(this);
			}
			if (this.otherPos && !this.otherPos[this.rid])
			{
				this.otherPos[this.rid] = {r:this.rid,x:this.x,y:this.y,c:this.showCond};
				this.showCond = '';
			}
			if (p_roomId == g_map.currentRoom && ! this.loaded)
			{
				this.Load();
			}
			this.SetCoords(p_x,p_y);
		},
		UpdateStatus: function( p_img, p_popu){
			if (p_popu != this.popu)
			{
				this.popu = p_popu;
				this.AdjustStatus();
			}
			if (this.img == p_img){return;}
			this.img = p_img;
			if (!this.loaded || this.walking)
			{
				return;
			}
			$('user_img_' + this.id).src = this.img;
		},
		AdjustStatus: function(){
			if 		(this.popu > 5000000)	{this.walkSpeed = 200.0;this.shadow = 'ombre_nuage3.gif';}
			else if	(this.popu > 100000)	{this.walkSpeed = 170.0;this.shadow = 'ombre_or.png';}
			else if	(this.popu > 50000)		{this.walkSpeed = 170.0;this.shadow = 'ombre_argent.png';}
			else if	(this.popu > 10000)		{this.walkSpeed = 170.0;this.shadow = 'ombre_bronze.png';}
			else 							{this.walkSpeed = 170.0;this.shadow = 'ombre_base.png';}
		},
		Hide: function(){
			this.Delete();
		},
		CreateBulle: function(){
			this.bulle = true;
			var l_temp = new Element( 'div', {id:'user_text_' + this.id, 'class':''});
			l_temp.setStyle(
			{
				position:	'absolute',
				'font-weight': 'bold',
				'text-align':'left',
				width:'15em',
				zIndex: 	1110
			});
			l_temp.update('<div style="position:absolute;left:0;bottom:0;" id="user_text2_'+this.id+'"></div>');
			$( 'Map_Main2').appendChild( l_temp);
		},
		DeleteBulle: function(p_id,p_all){
			if (this.texts[p_id])
			{
				delete this.texts[p_id];
			}
		},
		DeleteAllBulles: function(){
			for (var i in this.texts)
			{
				this.texts[i].Delete( false);
			}
			this.texts = {};
			this.bulle = false;
		},
		ShowText: function( p_text){
			if (!this.loaded)
			{
				return;
			}
			if (!$('user_text_' + this.id))
			{
				this.CreateBulle();
			}
			
			$('user_text_' + this.id).setStyle(
			{
				left: 	parseInt($('user_' + this.id).style.left) + 'px',
				top: 	(parseInt($('user_' + this.id).style.top)-45) + 'px'
			});
			try{
			this.texts[++this.numText] = new TextBulle( this.numText, p_text, this.id);
			}
			catch(a)
			{_echo('failed : ' + a );
			}
		},
		AddText: function(){
			
		},
		MouseOver: function(){
			var tt = '';
//			if ( ! this.tooltip)
			{
				if (this.popu)
				{
					if (!this.calcPopu || this.calcPopu != this.popu)
					{
						this.calcPopu = this.popu;
						this.level = g_mainChar.CalcLevelForXp(this.calcPopu);
					}
					
					var l_style = (this.tier == 0?'Copper':this.tier==1?'Bronze':this.tier==3?'Silver':'Gold');
					//(this.rank<4?'<img src="/i/VIP.png"class="h24m" style="margin-right:10px;"/>':'') + 
					tt += '<h3 class="'+l_style+'">' + this.name;
					if (this.rank == 0)
					{
						tt += '<img src="/i/icone_staff.png" class="i24m" style="margin-left:0.6em;">';
					}
					if (this.id != g_mainChar.id)
					{
						if (g_mainChar.popu >= this.popu)
						{
							tt += '<img class="i24m" style="margin-left:0.6em;"src="/i/like.png"></h3><p style="line-height:1.5em;"><img src="/i/popu.png" class="h24m">' + this.level.l;
						}
						else
						{
							tt += '<img class="i24m" style="margin-left:0.6em;"src="/i/dislike.png">&nbsp;(+'+(this.popu-g_mainChar.popu)+'&nbsp;<img src="/i/popu.png" class="i24m">)</h3><p style="line-height:1.5em;"><img src="/i/popu.png" class="i24m">' + this.level.l;
						}
					}
					
					if (this.rank > 0)
					{
						tt +='<img src="/i/coupeor.png" class="h24m" style="margin-left:0.6em;">' + this.rank+'°';
					}
					tt +='</p>';
				}
				else
				{
					tt += '<h3>' + this.name + '</h3>';
				}
				if (this.pet > 0)
				{
					tt += '<hr/>Pet : ' + g_petM.pets[this.pet].name+'<br/>';
				}
				/*
				if (!this.isNPC && this.id != g_mainChar.id)
				{
					tt += 'Double cliquez pour<br/>acceder au profil !';
				}
				*/
			}
			tooltip.show( tt);
		},
		Rescale: function( p_scale){
			if (this.loaded)
			{
				$('user_'+this.id).setStyle(
				{
					position: 	'absolute',
					left: 		p_scale * parseInt($('user_'+this.id).style.left)+'px',
					top: 		p_scale * parseInt($('user_'+this.id).style.top)+'px',
					height: 	p_scale * parseInt($('user_'+this.id).style.height)+'px',
					width: 		p_scale * parseInt($('user_'+this.id).style.width)+'px'
				});
			}
		},
		ContinuePath: function(){
			if (this.path.length <= 0){return false;}
			var target = this.path.pop();
			this.WalkTo( target[0], target[1]);
			return true;
		},
		GetCoords: function(){
			var base = $('user_'+this.id);
			var pos = base.positionedOffset();
			var dim = base.getDimensions();
			return {x:(pos.left+dim.width/2)/g_map.ts,y:(pos.top+dim.height*0.85)/g_map.ts};
		},
		SetCoords: function(x,y){
			this.x = x;
			this.y = y;
			if (!this.loaded){return;}
			var base = $('user_'+this.id);
			var dim = base.getDimensions();
			var l = (x*g_map.ts-dim.width/2);
			var t = (y*g_map.ts-dim.height*0.85);
			base.setStyle({left:l+'px',top:t+'px'});
			if (this.bulle)
			{
				$('user_text_' + this.id).setStyle({left:l+'px',top:(t-48)+'px'});
			}
		},
		FollowPath: function(p_path){
			this.path = p_path.reverse();
			this.ContinuePath();
		},
		SetEffect: function(p_img,w,h,x,y){
			this.specialEffect = {img:'/i/'+p_img,w:w,h:h,l:x,t:y};
			if (this.loaded)
			{
				$('user_'+this.id).insert('<img src="'+(this.specialEffect.img)+'" style="z-index:5;width:'+(this.specialEffect.w*g_map.allScale*this.scale/16)+'em;height:'+(this.specialEffect.h*g_map.allScale*this.scale/16)+'em;position:absolute;left:'+(this.specialEffect.l*g_map.allScale*this.scale/16)+'em;top:'+(this.specialEffect.t*g_map.allScale*this.scale/16)+'em">');
			}
		}
	});
	var Panneau = Class.create( MapObject,{
		initialize: function( $super, p_rid, p_icon, x, y, w, h, z, p_text, p_click, p_range){
			$super( p_rid, p_icon,x,y,z,w,h);
			this.onMouseOver = function(){tooltip.show(p_text);}
			this.onMouseOut = tooltip.hide.bind(tooltip);
			if (p_range)
			{
				this.range = p_range * p_range;
				this.onClickActual = p_click;
				this.onClick = this.Activate.bind(this);
			}
			else
			{
				this.onClick = p_click;
			}
		},
		Activate: function(){
			if ( ! g_city.users[g_mainChar.id]){return;}
			var l_x = g_city.users[g_mainChar.id].x - this.x;
			var l_y = g_city.users[g_mainChar.id].y - this.y;

			if ((l_x*l_x + l_y*l_y) > this.range) {return false;}
			
			this.onClickActual();
		}
	});
	var c_portalImages = {5:'warp/warp.png',1:'warp/1.png',2:'warp/2.png',3:'warp/3.png',4:'warp/4.png'};
	var c_portalImagesH = {5:'warp/hwarp.png',1:'warp/h1.png',2:'warp/h2.png',3:'warp/h3.png',4:'warp/h4.png'};
	var c_portalImagesN = {5:'warp/warpNO.png',1:'warp/n1.png',2:'warp/n2.png',3:'warp/n3.png',4:'warp/n4.png'};
	var Portal = Class.create( MapObject,{
		initialize: function( $super, p_rid, x,y, p_target, p_axis, p_cond){
			this.axis = p_axis || 1;
			this.showCircle = true;
			$super( p_rid, (this.showCircle?c_portalImages[this.axis]:false), x,y,-400,64,64);
			this.target = p_target;
			this.target.x += 40;
			this.target.y += 60;
			this.onWalkOver = this.TouchPortal.bind(this);
			this.onMouseOver = this._onMouseOver;
			this.onMouseOut = this.UnHighlight;
			this.cond = p_cond || false;
			if (!g_city.visuRoom)
			{
				g_gps.AddEdge( this.rid, this.target.id, this.id, 1, false);
			}
		},
		TouchPortal: function(p_id){
			if (this.failed){return;}
			if ( ! g_mainChar.CheckCondition( this.cond))
			{
				this.failed = true;
				return false;
			}
			else
			{
				UnloadCurrentInline();
				g_diM.CloseDiscussion();
				g_city.ChangeRoom( p_id, this.target.id, this.target.x, this.target.y);
				return true;
			}
		},
		_onMouseOver: function(){
			if (g_map.rooms[this.target.id].name)
			{
				if (g_mainChar.CheckCondition( this.cond))
				{
					tooltip.show("Vers -&gt; " + g_map.rooms[this.target.id].name);
				}
				else
				{
					tooltip.show("Vers -&gt; " + g_map.rooms[this.target.id].name + '<hr/><br/><font color="red">' + g_mainChar.PrintCondition( this.cond)+'</font>');
				}
			}
			this.Highlight();
		},
		onClick: function(){
			
		},
		Load: function($super){
			this.failed = false;
			if (this.showCircle && this.cond)
			{
				this.img = g_mainChar.CheckCondition( this.cond)?c_portalImages[this.axis]:c_portalImagesN[this.axis];
			}
			$super();
		},
		Recheck: function(){
			this.failed = false;
			if (this.showCircle && this.cond)
			{
				this.img = g_mainChar.CheckCondition( this.cond)?c_portalImages[this.axis]:c_portalImagesN[this.axis];
				if ($('MapObj_' + this.id))
				{
					$('MapObj_' + this.id).src = '/i/b/' + this.img;
				}
			}
		},
		Highlight: function(){
			$('MapObj_' + this.id).src = '/i/b/'+c_portalImagesH[this.axis];
		},
		UnHighlight: function(){
			tooltip.hide();
			$('MapObj_' + this.id).src = '/i/b/'+(g_mainChar.CheckCondition( this.cond)?c_portalImages[this.axis]:c_portalImagesN[this.axis]);
		}
	});
	var WRoom = Class.create( Room,{
		initialize: function( $super, p_id, p_zone, p_name, p_icon, p_axis, p_mapX, p_mapY, p_size, p_music){
			p_size = p_size || 1;
			$super( p_id, p_icon, p_size, p_axis,p_name);
			this.mapX = (p_mapX)/16+'em';
			this.mapY = (p_mapY-16)/16+'em';
			this.mapZone = p_zone || 5;
			this.music = p_music || false;
			if (!g_city.visuRoom)
			{
				g_gps.AddPoint( this.id);
			}
		},
		Load: function( $super){

			$super();
			$('Map_YouAreHere').setStyle( {left:this.mapX, top:(this.mapY)});
			g_gps.Hl();
			g_sound.SetBackground( this.music);
		},
		portals: function( p_details){
			for (var i in p_details)
			{
				var l = p_details[i];
				new Portal(this.id,l.from[0],l.from[1],{id:i,x:l.to[0],y:l.to[1]},l.dir,l.cond?l.cond:false);
			}
		},
		objects: function(p_base,p_details){
			for (var i in p_details)
			{
				var l = p_details[i];
				new MapObject(this.id,p_base+i,l[0],l[1],l[2],l[3],l[4]);
			}
		},
		roads: function(){
			for (var i = 0 ; i < arguments.length;++i)
			{
				var l = arguments[i];
				new Road(this.id,l[0],l[1],l[2],l[3],l[4]);
			}
		},
		colls: function(){
			for (var i = 0 ; i < arguments.length;++i)
			{
				var l = arguments[i];
				if (l=='r')
				{
					++i;
					l = arguments[i];
					new BoundingPoly(this.id,l,true);
				}
				else
				{
					new BoundingPoly(this.id,l);
				}
			}
		}
	});
}
{ /***************Immokaz******************/
	var g_immo = {
		Load: function(){
			this.loaded = true;
			g_unloadFunction2 = this.Reset.bind(this);
			new ImmoTier( 0,'','Tous');
		},
		Reset: function(){
			this.current = 0;
			this.moving = false;
			this.loaded = false;
			this.selectedTier = 0;
			this.tiers = {};
		},
		Hide: function(){
			$( 'PreviewAppart').hide();
		},
		RecalcPrice: function(){
			var l_price = this.pparts[c_current].rentPrice * $('rent_dura').options[$('rent_dura').selectedIndex].value;
			
			if (! $('furnished').checked)
			{
				l_price *= 0.8;
			}
			
			$( 'rentDetails_price').update( l_price);
		},
		Show: function(p_id){
			this.tiers[this.selectedTier].Show(p_id);
			
			return false;
		},
		Buy: function(){
			return _openUrl2( 'immokaz', {a:'buy',id:this.current});
		},
		Rent: function(){
			return _openUrl2( 'immokaz', {a:'rent',id:this.current});
		},
		Use: function(){
			return _openUrl2( 'immokaz', {a:'chr',id:this.current});
		},
		ToggleAllBut: function( p_id, p_reverse){
			for (var i in this.tiers)
			{
				if (i != p_id)
				{
					if (p_reverse)
					{
						new Effect.Appear('ImmoMenu'+i);
					}
					else
					{
						new Effect.Fade('ImmoMenu'+i);
					}
				}
			}
		},
		Final: function(){
			for (var i in this.tiers)
			{
				this.tiers[i].Final();
			}
			new Pager( 'ImmoKazList',{size:{width:100,height:54},csize:{width:600,height:80}});
		}
	};g_immo.Reset();
	var ImmoTier = Class.create({
		initialize: function( p_id, p_img, p_desc){
			this.id = p_id;
			this.desc = p_desc;
			this.apparts = {};
			this.selected = false;
			g_immo.tiers[this.id] = this;
		},
		MouseOver: function(){
			tooltip.show( this.desc);
		},
		Activate: function(){
			if (g_immo.moving){return false;}
			g_immo.moving = true;
			if (this.selected)
			{
				$('ImmoKazList').update();
				$('ImmoKazList').hide();
				new Effect.Move( 'ImmoMenu'+this.id, {x:(200*this.id+75),y:5, mode: 'absolute', afterFinish:this.EndMove.bind(this)});
				g_immo.ToggleAllBut(this.id, true);
			}
			else
			{
				new Effect.Move( 'ImmoMenu'+this.id, {x:10,y:5, mode: 'absolute', afterFinish:this.EndMove.bind(this)});
				g_immo.ToggleAllBut(this.id);
			}
			return false;
		},
		Show: function( p_id){
			if ( ! this.apparts[p_id]){return false;}
			if (this.apparts[p_id])
			{
				this.apparts[p_id].Load();
			}
			
			g_immo.current = p_id;
		},
		Final: function(){
			$('ImmoKazList').show();
			g_immo.selectedTier = this.id;
			for (var i in this.apparts)
			{
				this.apparts[i].LoadOnList();
			}
		}
	});
	var Appart = Class.create({
		initialize: function( p_id, p_price, p_rentPrice, p_name, p_desc, p_ico, p_prevImg, p_status, p_tier){
			this.id = p_id;
			this.price = p_price;
			this.rentPrice = p_rentPrice;
			this.name = p_name;
			this.desc = p_desc;
			this.ico = p_ico;
			this.prevImg = p_prevImg;
			this.status = p_status;
			this.tier = p_tier;
			g_immo.tiers[0].apparts[this.id] = this;
		},
		LoadOnList: function(){
			$('ImmoKazList').insert( 
				'<span class="base" style="width:98px;height:50px;">'
			+	'<a id="link_tap_'+this.id+'" href="javascript:;" onclick="return g_immo.Show('+this.id+');" onmouseover="tooltip.show(\''+addslashes(this.name)+'\')" onmouseout="tooltip.hide();">'
			+	'<img src="/i/b/x/'+this.ico+'" style="width:6em;height:3em;" />'
			+	(this.status != 0 ? '<img src="/i/'+g_mainChar.language+'/'+(this.status==1?'achete.png':'loue.png')+'" style="position:absolute;top:0;left:0;height:3em;width:6em;">' : '')
			+	'</a></span>');
		},
		MouseOver: function(){
			$( 'PreviewAppart').show();
		},
		Load: function(){
			if (g_immo.current == this.id) { return; }
			$('PreviewAppart').show();
			$('PreviewAppartImg').src = '/i/b/' + this.prevImg;
			$('tap_name').update( this.name);
			$('tap_desc').update( this.desc);
			$('tap_price').update( this.price);
			if (this.status == 0)
			{
				$('Immokaz_Buy').show();
				$('Immokaz_Use').hide();
			}
			else
			{
				$('Immokaz_Buy').hide();
				$('Immokaz_Use').show();
			}
		}
	});
}
{ /***************NPC**********************/
	var g_diM = {
		inFB: false,
		questNote: 0,
		qGroupId:4,
		currentSound:'',
		Reset: function(){
			this.discussions = {};
			this.ansId = 0;
			this.currentNpc = 0;
			this.answers = {};
			this.smMove1 = false;
			this.smMove2 = false;
		},
		CloseDiscussion: function(p_gwinShow){
			this.SetCSound('');
			if ($('Disc_Main'))
			{
				$('Disc_Main').hide();
				$('SpanInPub').update();
			}
			if ($('Disc_Main2'))
			{
				$('Disc_Main2').hide();
			}
			if (!p_gwinShow)
			{
				g_win.Show();
			}
			return false;
		},
		OpenDiscussion: function( p_id){
			this.RemoveEffects();
			CloseAllSubMenus();
			if ( ! this.discussions[p_id]){return false;}
			$('Disc_Main').show();
			$('Disc_Main2').show();
			g_mainChar.noreload = false;
			if (this.discussions[p_id])
			{
				this.discussions[p_id].Load();
			}
			return false;
		},
		ChangeNpc: function(p_id){
			if (g_npcm.npcs[p_id])
			{
				g_npcm.npcs[p_id].InitDlg();
			}
		},
		ActivateAnswer: function( p_ans){
			var l_actions = p_ans.split( ',');
			for (var i = 0 ; i < l_actions.length ; i ++)
			{
				var l_a = l_actions[i].split( ':');
				l_a[0] = trim(l_a[0]);
				switch (l_a[0])
				{
					case 'd':{g_diM.OpenDiscussion( parseInt(l_a[1])); break; }
					case 'r':{g_diM.CloseDiscussion();_openUrl2( l_a[1]); break; }
					case 'tuto':{if(l_a[1] == 'next'){g_tm.EndCurrent();}else{g_tm.SwitchTo(l_a[1]);} break; }
					case 'hospital':{g_diM.CloseDiscussion();_openUrl2( 'hospital',{t:l_a[1]}); break; }
					case 'shop':{g_diM.CloseDiscussion();_openUrl2( 'perso',{id:l_a[1]}); break; }
					case 'avashop':{g_diM.CloseDiscussion();_openUrl2( 'avatar',{id:l_a[1]}); break; }
					case 'furnshop':{g_diM.CloseDiscussion();_openUrl2( 'shopfurnit',{id:l_a[1]}); break; }
					case 'immokaz':{g_diM.CloseDiscussion();_openUrl2( 'immokaz',{id:l_a[1]}); break; }
					case 'howkaz':{g_diM.CloseDiscussion();_openUrl2( 'howkaz'); break; }
					case 'howpopu':{g_diM.CloseDiscussion();_openUrl2( 'howpopu'); break; }
					case 'howtok':{g_diM.CloseDiscussion();_openUrl2( 'howtok'); break; }
					case 'slaves':{g_diM.CloseDiscussion();_openUrl2( 'slaves'); break; }
					case 'pirates':{g_diM.CloseDiscussion();_openUrl2( 'pirates'); break; }
					case 'hlnpc':{g_city.HighlightNpc(l_a[1]);break;}
					case 'nohl':{g_city.Unhl();break;}
					case 'bg':{if (l_a[1] == 'base'){$('MainMapImg').src = '/i/b/' + g_map.rooms[g_map.currentRoom].img;}else{$('MainMapImg').src='/i/bg/'+l_a[1];}break;}
					case 'name':{$('DiscCharName').update( l_a[1]);break;}
					case 'sm':{this.ShowSmiley(l_a[1]);break;}
					case 'tele':{g_city.ChangeRoom(g_mainChar.id,l_a[1],l_a[2],l_a[3]);break;}
					case 'sp':{g_npcm.StartPath(l_a[1],l_a[2]);break;}
					case 'smr':{this.ShowSmiley(l_a[1],true);break;}
					case 'eff':{this.ShowEffect(l_a[1]);break;}
					case 'wnpc':{g_npcm.npcs[l_a[1]].MoveTowards(l_a[2],l_a[3],l_a[4])}
					case 'gif':{this.SetupGif(l_a[1],l_a[2],l_a[3],l_a[4],l_a[5]);break;}
					case 'ueff':{if (l_a[1] == 'none'){g_city.users[g_mainChar.id].specialEffect = false;}else{g_city.users[g_mainChar.id].SetEffect(l_a[5],l_a[1],l_a[2],l_a[3],l_a[4]);}break;}
					case 'neff':{if (l_a[2] == 'none'){g_npcm.npcs[l_a[1]].specialEffect = false;}else{g_npcm.npcs[l_a[1]].SetEffect(l_a[6],l_a[2],l_a[3],l_a[4],l_a[5]);}break;}
					case 'snpc':{g_npcm.ShowNPC(l_a[1],l_a[2],l_a[3],l_a[4]);break;}
					case 'hdnpc':{g_npcm.HideNPC(l_a[1]);break;}
					case 'wimg':{this.InitWide(l_a[1]);break;}
					case 'himg':{this.InitHuge(l_a[1]);break;}
					case 'simg':{this.InitSmall(l_a[1]);break;}
					case 'chn':{g_diM.ChangeNpc(l_a[1]); break; }
					case 'eq':{g_qm.EndQuest(l_a[1]); break; }
					case 'rq':{g_qm.RemoveQuest(l_a[1]); break; }
					case 'hp':{g_mainChar.SetStats(g_mainChar.stats.u,g_mainChar.stats.h+parseInt(l_a[1]),g_mainChar.stats.s); break; }
					case 'hu':{g_mainChar.SetStats(g_mainChar.stats.u+parseInt(l_a[1]),g_mainChar.stats.h,g_mainChar.stats.s); break; }
					case 'sl':{g_mainChar.SetStats(g_mainChar.stats.u,g_mainChar.stats.h,g_mainChar.stats.s+parseInt(l_a[1])); break; }
					case 'sq':{g_qm.StartQuest( parseInt(l_a[1]));break;}
					case 'gps':{g_gps.GetPath( parseInt(l_a[1]));g_qm.currentTarget=l_actions[i];break;}
					case 'gpsn':{g_city.GpsN(l_a[1]);g_qm.currentTarget=l_actions[i];break;}
					case 'jdq':{g_diM.ChangeNpc(270);g_diM.OpenDiscussion( parseInt(l_a[1]));break;}
					case 'q':
					{
						var l_qID = parseInt(l_a[1]);
						if (l_a.length == 3)
						{
							g_mainChar.onQuestFail = parseInt(l_a[2]);
						}
						else if (l_a.length == 4)
						{
							g_mainChar.onQuest = parseInt(l_a[2]);
							g_mainChar.onQuestFail = parseInt(l_a[3]);
						}
						if (!g_mainChar.noreload)
						{
							new Ajax.Request( '/callback/quest.php', { method: 'post', parameters: {qid : l_qID, a : 'start'}, evalScripts:true,onSuccess:_printJaxReq});
							g_mainChar.noreload = true;
						}
						break;
					}
					case 'qe':
					{
						g_diM.CloseDiscussion(true);
						this.OpenQuestEnd(l_a[1],l_a[2],l_a[3]);
						break;
					}
					case 'frame':{this.Frame( l_a[1],l_a[2]);break;}
					case 'scene':{this.Frame( l_a[1],l_a[2], true);break;}
					case 'ximg':{this.XImg( l_a[1],l_a[2], true);break;}
					case 'lsnd':{g_sound.Load(l_a[2]);break;}
					case 'psnd':{g_sound.Play(l_a[1]);break;}
					case 'fbpub':{facebook.PublishPre(l_a[1]);break;}
					case 'timer':{this.gameDiscId = l_a[2];g_countdown.Start(parseInt(l_a[1]), this.EndTimer.bind(this));break;}
					case 'chainsound':{g_sound.ChainSoundDisc(l_a[1],l_a[2],l_a[3]);break;}
					case 'x':{g_diM.CloseDiscussion();break;}
				}
			}
		},
		Frame: function( p_url, p_id, p_in){
			this.gameDiscId = p_id;
			if (!p_in)
			{
				_openFrame( p_url);
			}
			else
			{
				this.CloseDiscussion( true);
				g_cutscene.Play( p_url, this.EndScene.bind(this));
			}
		},
		EndFrame: function(){
			UnloadCurrentInline();
			this.OpenDiscussion( this.gameDiscId);
			this.gameDiscId = 0;
		},
		EndTimer: function(){
			this.OpenDiscussion( this.gameDiscId);
			this.gameDiscId = 0;
		},
		EndScene: function(){
			g_cutscene.Close();
			this.OpenDiscussion( this.gameDiscId);
			this.gameDiscId = 0;
		},
		XImg: function( p_img, p_did){
			this.CloseDiscussion();
			this.gameDiscId = p_did;
			if (!$('cutscene')){g_cutscene.Create();}
			$('Disc_Main2').show();
			$('cutscene').show();
			$('cutscene').update('<a href="javascript:;" onclick="g_diM.EndScene();"><img src="/i/npc/icone/'+p_img+'" style="width:100%;height:100%"></a>');
		},
		OpenQuestEnd: function(p_img, p_style,p_groupId){
			$('Main_EndQ').show();
			$('Disc_Main2').show();
			if (p_style == 1)
			{	//intro
				g_sound.Play('jingleintro');
				$('Man_EQ_Share').hide();
				$('Man_EQ_Ok').show();
			}
			else
			{
				g_sound.Play('jingleoutro');
				$('Man_EQ_Share').show();
				this.qGroupId = p_groupId;
				$('Man_EQ_Ok').hide();
				g_qm.currentTarget = '';
				g_gps.Reset();
			}
			$('Main_EndQ_I').src = '/i/'+g_mainChar.language+'/qe/'+p_img+'.jpg';
		},
		OpenQuestNote: function(){
			$('Main_EndQ').hide();
			_openUrl2('qnotes',{id:this.qGroupId});
		},
		InitWide: function( p_img,p_noPrefix){
			$('Disc_icon_I').src=(p_noPrefix?'':'/i/npc/icone/')+p_img;
			$('Disc_icon').setStyle({width:'12em',height:'24em',top:'-1em',left:0});
			$('Disc_icon_I').setStyle({width:'100%',height:'100%',top:0,left:0});
			$('Disc_icon_S').hide();
			$('DiscPnjDesc').setStyle('bottom:-5em');
		},
		InitHuge: function( p_img,p_noPrefix){
			$('Disc_icon_I').src=(p_noPrefix?'':'/i/npc/icone/')+p_img;
			$('Disc_icon').setStyle({width:'16em',height:'32em',top:'-3em',left:0});
			$('Disc_icon_I').setStyle({width:'100%',height:'100%',top:0,left:0});
			$('Disc_icon_S').hide();
			$('DiscPnjDesc').setStyle('bottom:0');
		},
		InitSmall: function( p_img,p_noPrefix){
			$('Disc_icon_I').src=(p_noPrefix?'':'/i/npc/')+p_img;
			$('Disc_icon').setStyle({width:'16em',height:'16em',top:'5em',left:0});
			$('Disc_icon_I').setStyle({width:'100%',height:'100%',top:0,left:0});
			$('Disc_icon_S').show();
			$('DiscPnjDesc').setStyle('bottom:-5em');
		},
		InitTiny: function( p_img,p_noPrefix){
			$('Disc_icon_I').src=(p_noPrefix?'':'/i/npc/')+p_img;
			$('Disc_icon').setStyle({width:'6em',height:'6em',top:'13em',left:'5em'});
			$('Disc_icon_I').setStyle({width:'100%',height:'100%',top:0,left:0});
			$('Disc_icon_S').hide();
			$('DiscPnjDesc').setStyle('bottom:-9em');
		},
		RemoveEffects: function(){
			if ($('DiscWI_SM'))
			{
				$('DiscWI_SM').hide();
			}
			if (this.smMove1)
			{
				this.smMove1.cancel();
				this.smMove1 = false;
				if (this.smMove2)
				{
					this.smMove2.cancel();
					this.smMove2 = false;
				}
			}
			$('Disc_icon_I').setStyle({top:0,left:0});
		},
		SetupGif: function(x,y,w,h,img){
			if (!$('DiscWI_SM'))
			{
				var ele = new Element('img',{id:'DiscWI_SM','class':'i32'});
				ele.setStyle({position:'absolute',zIndex:'1300'});
				$('Disc_icon').insert(ele);
			}
			var ele = $('DiscWI_SM');

			ele.show();
			if (img)
			{
				ele.src = '/i/'+img;
				ele.setStyle({left:(x*g_map.globalScale)+'px',top:(y*g_map.globalScale)+'px',width:(w*g_map.globalScale)+'px',height:(h*g_map.globalScale)+'px'});
			}
			else
			{
				ele.src = '/i/'+w;
				ele.setStyle({left:(x*g_map.globalScale)+'px',top:(y*g_map.globalScale)+'px',width:'auto',height:'auto'});
			}
		},
		ShowEffect: function( p_eff){
			switch (p_eff)
			{
				case 'shake':
				{
					this.smMove1 = new Effect.Shake('Disc_icon',{afterFinish:this.EndSM.bind(this)});
					break;
				}
				case 'vshake':
				{
					this.smMove1 = new Effect.Shake('Disc_icon',{delay:0.5});
					this.smMove2 = new Effect.Move('Disc_icon',{mode:'relative',x:0,y:40,delay:1.0,afterFinish:this.EndSM.bind(this)});
					break;
				}
				case 'scale':
				{
					this.smMove1 = new Effect.Scale('Disc_icon_I',150,{scaleFrom:25,scaleFromCenter:true,afterFinish:this.EndSM.bind(this)});
				}
			}
		},
		ShowSmiley: function( p_sm, p_loop){
			var l_img = false;
			for (var i = 0 ; i < g_chat.smileys.length ; i ++)
			{
				if (g_chat.smileys[i].txt == ':'+p_sm+':')
				{
					l_img = g_chat.smileys[i].img;
				}
			}
			if (!l_img){l_img='/i/'+p_sm;}
			if (!$('DiscWI_SM'))
			{
				var ele = new Element('img',{id:'DiscWI_SM','class':'i32'});
				ele.setStyle({position:'absolute',zIndex:'1300'});
				$('Disc_icon').insert(ele);
			}
			this.RemoveEffects();
			$('DiscWI_SM').src = l_img;
			$('DiscWI_SM').show();
			$('DiscWI_SM').setStyle({left:'175px',top:'180px'});
			if (p_loop)
			{
				this.smMove1 = new Effect.Move('DiscWI_SM',{mode:'absolute',x:175,y:0,duration:2.0,afterFinish:this.ShowSmiley.bind(this,p_sm,p_loop)});
			}
			else
			{
				this.smMove1 = new Effect.Move('DiscWI_SM',{mode:'absolute',x:175,y:0,duration:2.0,afterFinish:this.EndSM.bind(this)});
			}
			this.smMove2 = new Effect.Fade('DiscWI_SM',{duration:2.0});
//			this.movement = new Effect.Move( $('MetroTrain'), {mode:'absolute',x:'-50em',y:'22em',duration:2.0,afterFinish:this.TakeTwo.bind(this)});
		},
		EndSM: function(){
			this.smMove = false;
		},
		ToggleDiscSound: function(p_id){
			this.discussions[p_id].ToggleSound();
		},
		NoteQuest: function(p_note){
			this.questNote = p_note;
			showStars( p_note);
		},
		SubmitVote: function(){
			_openUrl2('qnotes',{id:this.qGroupId,note:this.questNote,comm:$F('QuestComm')});
		},
		SetCSound: function(p_sound){
			if (this.currentSound != '')
			{
				g_sound.Pause(this.currentSound,true);
			}
			this.currentSound = p_sound;
		}
	};g_diM.Reset();
	var g_am = {
		Chdlg: function( p_npcId, p_dlg){
			if (g_npcm.npcs[p_npcId])
			{
				g_npcm.npcs[p_npcId].defaultDiscussion = p_dlg;
			}
		}
	};
	var Discussion = Class.create({
		initialize: function( p_id, p_text, p_audio){
			this.id = p_id;
			this.text = p_text;
			this.audio = (p_audio?g_mainChar.language+'/'+p_audio : false);
			this.audioPlaying = false;
			this.has_zpub = false;
			this.answersLoaded = false;
			this.answers = [];
			g_diM.discussions[this.id] = this;
		},
		AddAnswer: function( p_ans){
			this.answers.push( p_ans);
		},
		_getParams:function(t,s,e){
			return t.substring(s+1,e).toQueryParams();
		},
		TreatDisc: function(){
			var l_sI,l_eI;
			var l_text = this.text;
			if ((l_sI = l_text.indexOf('<pub')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				l_text = l_text.substr(0,l_sI) + '<div align=center><iframe style="border:0;width:350px;height:140px;overflow:hidden"src="/callback/view_cpc.php"scrolling=no></iframe></div>' + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<tpub')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				l_text = l_text.substr(0,l_sI) + '<div align=center><iframe style="border:0;width:350px;height:20px;overflow:hidden"src="/callback/google_frame3.html"scrolling=no></iframe></div>' + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<zpub')) != -1)
			{
				this.has_zpub = true;
			}
			if ((l_sI = l_text.indexOf('<tweet')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				l_text = l_text.substr(0,l_sI) + '<div align=center><iframe style="border:0;width:350px;height:260px;overflow:hidden"src="/callback/tweet.html"scrolling=no></iframe></div>' + l_text.substr(l_eI+2,l_text.length);
			}
			if (g_diM.inFB && (l_sI = l_text.indexOf('<fb')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				l_text = l_text.substr(0,l_sI)
				+ '<a href="javascript:;"onclick="facebook.PrePostOnWall('+l_params.fb+',\''+l_params.msg.replace('@name@',g_mainChar.name)+'\',\''+l_params.img+'\',\''+l_params.name.replace('@name@',g_mainChar.name)+'\',\''+l_params.link+'\',\''+l_params.caption.replace('@name@',g_mainChar.name)+'\',\''+l_params.descr.replace('@name@',g_mainChar.name)+'\',\'\',\''+l_params.descr2.replace('@name@',g_mainChar.name)+'\');return false;"><img src="/i/Facebookpublic.png" id="PublishFacebook"style="margin-left:48px;width:225px;"></a>'
				+ l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<share')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				l_text = l_text.substr(0,l_sI) + '<div align=center><iframe style="width:350px;height:48px;border:0;"transparency="true"src="/callback/share.php?url='+urlencode(l_params.share)+'&title='+urlencode(l_params.title)+'&big=true"></iframe></div>' + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<price')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				
				l_text = l_text.substr(0,l_sI) + g_qm.GetScale(l_params.price) + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<name')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				
				l_text = l_text.substr(0,l_sI) + g_mainChar.name + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('</timer>')) != -1)
			{
				g_countdown.Cancel();
			}
			
//			this.text.replace('@pub@',)
			return l_text;
		},
		Load: function(){
			this.answersLoaded = false;
			$('DiscussionCadre').update( this.TreatDisc());
			var l_numAns = 0;
			for (var i=0 ; i < this.answers.length ; ++i)
			{
				if (this.answers[i].Check())
				{
					++ l_numAns;
				}
			}
			
			if (l_numAns <= 3)
			{
				l_zob = '<div align=center style="margin:0 auto"><iframe style="border:0;margin:0 auto;width:500px;height:64px;overflow:hidden"src="/callback/view_cpc.php"scrolling=no></iframe></div>' ;
				$('SpanInPub').update(l_zob);
			}
			else
			{
				$('SpanInPub').update();
			}
			if (this.audio)
			{
				$('AnswersCadreMain').hide();
				g_sound.Play( this.audio, this.EndSound.bind(this));
				g_diM.SetCSound(this.audio);
				this.audioPlaying = true;
				$('DiscussionCadre').insert('<a href="javascript:;"onclick="g_diM.ToggleDiscSound('+this.id+');"><img id="DiscSound"src="/i/pause.png"class="i24 bottom_right" style="right:32px;bottom:0;"></a>');
			}
			else
			{
				this.LoadAnswers();
			}
		},
		ToggleSound: function(){
			this.audioPlaying = !this.audioPlaying;
			if (this.audioPlaying)
			{
				$('DiscSound').src='/i/pause.png';
				g_sound.Play( this.audio, this.EndSound.bind(this));
				g_diM.SetCSound(this.audio);
			}
			else
			{
				$('DiscSound').src='/i/play.png';
				g_sound.Pause( this.audio);
				if (!this.answersLoaded)
				{
					this.LoadAnswers();
				}
			}
		},
		EndSound: function(){
			this.audioPlaying = false;
			if (!g_sound.mutedVoice && $('DiscSound'))
			{
				$('DiscSound').src='/i/play.png';
			}
//			g_diM.SetCSound('');
			if (!this.answersLoaded)
			{
				this.LoadAnswers();
			}
		},
		LoadAnswers: function(){
			this.answersLoaded = true;
			if ( this.answers.length > 0)
			{
				$('AnswersCadreMain').show();
				$('AnswersCadre').update();
				for (var i=0 ; i < this.answers.length ; ++i)
				{
					this.answers[i].Load();
				}
			}
			else
			{
				$('AnswersCadreMain').hide();
			}
		},
		Preload: function(){
			if (this.audio)
			{
				g_sound.Load( this.audio);
			}
		}
	});
	var g_baseIcones = ['coeur.png','SMILEY01.png','SMILEY02.png','SMILEY03.png','SMILEY04.png','SMILEY05.png','SMILEY06.png','SMILEY07.png','SMILEY08.png','SMILEY09.png','SMILEY10.png','SMILEY11.png','SMILEY12.png','SMILEY13.png','SMILEY14.png','SMILEY15.png','SMILEY16.png','SMILEY17.png','SMILEY18.png','SMILEY19.png','SMILEY20.png','SMILEY21.png','SMILEY22.png','SMILEY23.png','SMILEY24.png','SMILEY25.png','SMILEY26.png','SMILEY27.png'];
	var Answer = Class.create({
		initialize: function( p_discID, p_text, p_action, p_cond, p_baseIcon, p_img, p_audio){
			if (!g_diM.discussions[p_discID]){return;}
			this.text = p_text;
			this.audio = (p_audio?g_mainChar.language+'/'+p_audio : false);
			this.action = p_action;
			this.id = ++ g_diM.ansId;
			this.cond = p_cond;
			this.active = false;
			if (p_baseIcon > 0)
			{
				this.img = 'j/sm/'+g_baseIcones[p_baseIcon-1];
			}
			else
			{
				this.img = p_img;
			}
			g_diM.discussions[p_discID].AddAnswer( this);
			g_diM.answers[this.id] = this;
		},
		_getParams:function(t,s,e){
			return t.substring(s+1,e).toQueryParams();
		},
		TreatDisc: function(){
			var l_sI,l_eI;
			var l_text = this.text;
			if ((l_sI = l_text.indexOf('<price')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				
				l_text = l_text.substr(0,l_sI) + g_qm.GetScale(l_params.price) + l_text.substr(l_eI+2,l_text.length);
			}
			if ((l_sI = l_text.indexOf('<name')) != -1)
			{
				l_eI = l_text.indexOf( '/>',l_sI);
				var l_params = this._getParams( l_text, l_sI, l_eI);
				
				l_text = l_text.substr(0,l_sI) + g_mainChar.name + l_text.substr(l_eI+2,l_text.length);
			}
			
//			this.text.replace('@pub@',)
			return l_text;
		},
		Load: function(){
			this.active = false;
			if (!this.Check())
			{
				return false;
			}
			$('AnswersCadre').insert( '<div class="Roundered2"id="Answer_'+this.id+'"style="position:relative;line-height:1.5em;width:22em;text-align:left;"onclick="return g_diM.answers['+this.id+'].Activate()"><h2>' + (this.img?'<img src="/i/'+this.img+'" class="i32m"style="margin-left:-2em;"/>':'') + this.TreatDisc()+'</h2></div>');
			/*
			var l_actions = this.action.split( ',');
			for (var i = 0 ; i < l_actions.length ; i ++)
			{
				var l_a = l_actions[i].split( ':');
				l_a[0] = trim(l_a[0]);
				if (l_a[0] == 'd')
				{
					if (g_diM.discussions[l_a[1]])
					{
						g_diM.discussions[l_a[1]].Preload();
					}
				}
			}
			if (this.audio)
			{
				g_sound.Load(this.audio);
			}
			*/
			return true;
		},
		Activate: function(){
			if (this.active){return false;}
			var l_actions = this.action.split( ',');
			for (var i = 0 ; i < l_actions.length ; i ++)
			{
				var l_a = l_actions[i].split( ':');
				l_a[0] = trim(l_a[0]);
				if (l_a[0] == 'd' || l_a[0] == 'jdq')
				{
					if (g_diM.discussions[l_a[1]])
					{
						g_diM.discussions[l_a[1]].Preload();
					}
				}
			}
			if (this.audio && !g_sound.mutedVoice)
			{
				this.active = true;
				this.Action();
//				g_sound.Play( this.audio, this.DelayAction.bind(this));
			}
			else
			{
				this.Action();
			}
		},
		Check: function(){
			return g_mainChar.CheckCondition( this.cond);
		},
		DelayAction: function(){
			setTimeout( this.Action.bind(this), 400);
		},
		Action: function(){
			if (this.action.length == 0){g_diM.CloseDiscussion();return false;}
//			g_diM.SetCSound('');
			g_diM.ActivateAnswer(this.action);

			return false;
		}
	});
	var g_npcm = {
		npcs: {},
		canTalk: true,
		HideNPC: function( p_id){
			var n = this.npcs[p_id];
			if (n.otherPos)
			{
				delete n.otherPos[n.rid]
			}
			n.Hide();
		},
		ShowNPC: function( p_id, p_rid, p_x, p_y){
			var n = this.npcs[p_id];
			if (!n){return;}
			if (!n.otherPos && n.rid != 0)
			{
				n.otherPos = {};
				n.otherPos[this.rid] = {r:n.rid,x:n.x,y:n.y,c:n.showCond};
			}
			if (n.otherPos && n.rid != 0)
			{
				n.otherPos[p_rid] = {r:p_rid,x:p_x,y:p_x,c:''};
			}
			n.ShowAt( p_x, p_y, p_rid);
		},
		MoveNPC: function( p_id, p_x, p_y, p_rid){
			if(!this.npcs[p_id]){return;}
			this.npcs[p_id].MoveTowards( p_rid || g_map.currentRoom, p_x, p_y);
		},
		StartPath: function( p_npcId, p_pathId){
			this.npcs[p_npcId].StartAction( p_pathId, 0);
		},
		Talk: function(){
			if (!this.canTalk){return;}
			this.canTalk = false;
			setTimeout( this.EndNoTalk.bind(this), 20000);
			new Ajax.Request( '/callback/talk.php', {method: 'post'});
		},
		EndNoTalk: function(){
			this.canTalk = true;
		},
		RecheckNPCs: function(){
			for (var i in this.npcs)
			{
				if (!this.npcs[i].CouldBeWithin(g_map.currentRoom)){continue;}
				this.npcs[i].RecheckVisible();
			}
		},
		ResetAll: function(){
			for (var i in this.npcs)
			{
				this.npcs[i].Unload();
				this.npcs[i].rid = 0;
				this.npcs[i].loaded = false;
			}
		}
	};
	var NPC = Class.create( MovableUser,{
		initialize: function( $super, p_id, p_name, p_specialNPC, p_img, p_disc, p_w, p_h, p_discDist, p_cond, p_talkIcon, p_wide, p_popu, p_human, p_sig){
			this.icon = p_img || false;

			$super( 'N' + p_id, p_name, (this.icon?(p_specialNPC?this.icon:'/i/npc/'+this.icon):false));
			this.noShadow = false;
			this.shadow = 'ombre_base.png';
			this.specialNPC = p_specialNPC;
			this.baseWidth = p_w;
			this.sig = p_sig;
			this.baseHeight = p_h;
			this.talkIcon = p_talkIcon || this.icon;
			this.wideIcon = p_wide;
			this.discDist = p_discDist * p_discDist;
			this.defaultDiscussion = p_disc || 0;
			this.discs = [];
			this.popu = p_popu;
			this.human = p_human == 1;
			if (this.popu > 0)
			{
				this.rank = -1;
			}
			this.showCond = p_cond;
			this.forcedDiscussions = false;
			this.isNPC = true;
			this.paths = false;
			this.currentActionId = 0;
			this.currentPathId = 0;
			this.oID = p_id;
			this.paused = false;
			this.otherPos = false;
			g_npcm.npcs[p_id] = this;
			if (this.human)
			{
				this.baseWidth = this.baseHeight = 160;
			}
		},
		RecheckVisible: function(){
			var vis = false;
			if (!this.otherPos)
			{
				vis = g_mainChar.CheckCondition(this.showCond);
			}
			else
			{
				if(!this.otherPos[g_map.currentRoom]){vis = false;}
				else
				{
					vis = g_mainChar.CheckCondition(this.otherPos[g_map.currentRoom].c);
				}
				
			}
			if (vis != this.loaded)
			{
				if (vis){this.Load();}
				else {this.Unload();}
			}
		},
		CouldBeWithin: function( p_id){
			if(p_id == this.rid){return true;}
			if (this.otherPos && this.otherPos[p_id]){return true;}
			return false;
		},
		AddOtherPos: function( p_rid, p_x, p_y, p_cond){
//			if ( ! g_map.rooms[p_rid]){return;}
			if (!this.otherPos)
			{
				this.otherPos = {}
			}
			this.otherPos[p_rid] = {r:p_rid,x:p_x,y:p_y, c:p_cond};
//			g_map.rooms[p_rid].AddMovable(this);
		},
		LoadOPos: function(){
			for(var i in this.otherPos)
			{
				if (g_map.rooms[i])
				{
					g_map.rooms[i].AddMovable(this);
				}
			}
		},
		AddPath: function (p_id, p_proba){
			if (!this.paths){this.paths = {};}
			this.paths[p_id] = p_proba;
		},
		ExecNext: function(){
			var l_delay = g_pm.paths[this.currentPathId].actions[this.currentActionId].d;
			if (l_delay > 0)
			{
				this.nextActTime = setTimeout( this.StartNextAction.bind(this), l_delay);
			}
			else
			{
				this.StartNextAction();
			}
		},
		EndWalk: function($super){
			$super();
			if (this.currentPathId != 0 && !this.paused)
			{
				this.ExecNext();
			}
		},
		StartNextAction: function(){
			++this.currentActionId;
			
			if (g_pm.paths[this.currentPathId].actions.length <= this.currentActionId)
			{
				this.currentActionId = 0;
				this.currentPathId = 0;
			}
			else
			{
				this.StartAction( this.currentPathId, this.currentActionId);
			}
		},
		AddForcedDisc: function(p_discId, p_cond){
			if ( ! this.forcedDiscussions)
			{
				this.forcedDiscussions = [];
			}
			this.forcedDiscussions.push( {d:p_discId,c:p_cond});
		},
		InitDlg: function(){
			if (this.highlight)
			{
				g_city.Unhl();
			}
			g_diM.currentNpc = this.id;
			this.Pause();
			$('DiscCharName').update( this.name);
			if (this.popu > 0)
			{
				$('Disc_caric_popu1').show();
				$('Disc_caric_popu2').update(this.popu);
				if (this.sig)
				{
					$('Disc_caric_popu2').insert('<a href="javascript:;" onclick="facebook.PrePostOnWall(18,\'/i/npc/sig/'+this.sig+'\',\'\',\'\',\'\',\''+ g_mainChar.name+addslashes(g_text.fb['sig1'])+this.name+g_text.fb['sig2']+'\',\'\',\''+g_mainChar.name+addslashes( g_text.fb['sig3'])+this.name+'\')"onmouseover="tooltip.show(\''+g_text.fb['sig4']+'\')"onmouseout="tooltip.hide();"><img src="/i/'+g_mainChar.language+'/menu/autofacebook.png" style="z-index:2500;"id="OMapButton"class="i24m bottom_right"></a>');
				}
			}
			else
			{
				$('Disc_caric_popu1').hide();
			}
			if (this.wideIcon == 2)
			{
				g_diM.InitHuge('/i/npc/'+this.talkIcon,true);
			}
			else if (this.wideIcon == 1)
			{
				g_diM.InitWide('/i/npc/'+this.talkIcon,true);
			}
			else
			{
				if (this.human)
				{
					g_diM.InitSmall(this.talkIcon,this.specialNPC);
				}
				else
				{
					g_diM.InitTiny(this.talkIcon,this.specialNPC);
				}
			}
			
			g_npcm.Talk();
		},
		Load: function( $super){
			if (g_city.visuRoom){return;}
			if (!this.otherPos)
			{
				if (this.rid == g_map.currentRoom &&  ! g_mainChar.CheckCondition(this.showCond)){return;}
			}
			else
			{
				if(!this.otherPos[g_map.currentRoom]){return;}
				if( ! g_mainChar.CheckCondition(this.otherPos[g_map.currentRoom].c)){return;}
			}
			if (g_map.currentRoom != this.rid && this.otherPos && this.otherPos[g_map.currentRoom])
			{
				var l_pos = this.otherPos[g_map.currentRoom];
				this.x = l_pos.x;
				this.y = l_pos.y;
				this.rid = l_pos.r;
				this.scale = g_map.rooms[this.rid].scale;
				this.w = this.baseWidth * this.scale;
				this.h = this.baseHeight * this.scale;
			}
			$super( true);
			
			if (this.icon == '/i/npc/empty.png' || !this.icon)
			{
				$('user_'+this.id).style.zIndex = 999;
			}
			$('user_'+this.id).observe( 'click', this.Interact.bind(this));
			
			if (this.forcedDiscussions)
			{
				for (i=0;i< this.forcedDiscussions.length; i++)
				{
					if (g_mainChar.CheckCondition(this.forcedDiscussions[i].c))
					{
						this.InitDlg();
						g_diM.OpenDiscussion( this.forcedDiscussions[i].d);
						break;
					}
				}
			}
			if (this.paths){ g_pm.AddNpc(this.oID);}
		},
		UnPause: function(){
			this.paused = false;
			this.StartNextAction();
		},
		Pause: function(){
			if (this.nextActTime)
			{
				this.paused = true;
				clearTimeout( this.nextActTime);
				this.nextActTime = false;
			}
		},
		Unload: function( $super){
			this.Pause();
			this.currentActionId = 0;
			this.currentPathId = 0;
			this.paused = false;
			if (this.paths){ g_pm.RemoveNpc(this.oID);}
			$super();
		},
		AddDisc: function( p_cond, p_refDisc){
			this.discs.push({c:p_cond,d:p_refDisc});
		},
		Interact: function( p_event){
			if (p_event){p_event.stop();}
			if (this.defaultDiscussion != 0 || this.discs.length > 0)
			{
				/*
				if (this.popu > g_mainChar.popu && this.popu > 5)
				{
					this.InitDlg();
					g_diM.OpenDiscussion( 1046);
					return;
				}
				*/
				
				var l_x = parseInt( $('user_'+g_mainChar.id).style.left) - parseInt( $('user_'+this.id).style.left);
				var l_y = parseInt( $('user_'+g_mainChar.id).style.top) - parseInt( $('user_'+this.id).style.top);

				if ((l_x*l_x + l_y*l_y) > this.discDist)
				{
					g_city.MoveTo(p_event);
					g_mainChar.npcTarget = this.oID;
					
					return false;
				}
				
				for (var i=0;i<this.discs.length;++i)
				{
					if (g_mainChar.CheckCondition(this.discs[i].c))
					{
						this.InitDlg();
						g_diM.OpenDiscussion( this.discs[i].d);
						return true;
					}
				}
				
				if (this.defaultDiscussion != 0)
				{
					this.InitDlg();
					g_diM.OpenDiscussion( this.defaultDiscussion);
					return true;
				}
			}
			return false;
		},
		UpdatePaths: function(){
			if (this.currentPathId != 0)
			{
				return;
			}
			this.currentActionId = 0;
			//otherwise, pick one
			for (var i in this.paths)
			{
				if (this.paths[i] > Math.random())
				{
					this.StartAction( i, 0);
				}
			}
		},
		StartAction: function( p_pathId, p_actId){
			if ( ! g_pm.paths[p_pathId]){return;}
			this.currentActionId = p_actId;
			this.currentPathId = p_pathId;
			var l_nextAct = g_pm.paths[this.currentPathId].actions[this.currentActionId].i;
			g_pm.actions[l_nextAct].Execute( this);
		}
	});
	var Action = Class.create({
		initialize: function( p_id, p_postype, x, y, ref_room, ref_disc, p_special){
			this.id = p_id;
			this.ptype = p_postype;
			this.x = x;
			this.y = y;
			this.room = ref_room;
			this.discId = ref_disc;
			this.special = p_special;
			g_pm.actions[this.id] = this;
		},
		Execute: function( p_npc){
			if (this.special)
			{
				if (this.special == 'hide')
				{
					$('user_'+p_npc.id).hide();
				}
				else if (this.special == 'show')
				{
					$('user_'+p_npc.id).show();
				}
				p_npc.ExecNext();
				return;
			}
			if (this.discId)
			{
				g_diM.OpenDiscussion( this.discId, p_npc.icon, p_npc.name);
				p_npc.ExecNext();
				return;
			}
			p_npc.MoveTowards( g_map.currentRoom, this.x , this.y);
		}
	});
	var Path = Class.create({
		initialize: function( p_id){
			this.id = p_id;
			this.actions = [];
			g_pm.paths[this.id] = this;
		},
		AddAction: function( p_actId, p_delay){
			this.actions.push({i:p_actId,d:p_delay});
		},
		GetFirstAction: function(){
			if (this.actions.length <= 0){return 0;}
			return this.actions[0].i;
		}
	});
	var g_pm = {
		paths: {},
		actions: {},
		npcs: {},
		numNpcs: 0,
		updateLoop: 0,
		Unload: function(){
			if (this.updateLoop)
			{
				clearInterval( this.updateLoop);
				this.updateLoop = 0;
			}
		},
		AddPathAct: function( p_ordre, p_refPath, p_refAction, p_delay){
			if (this.paths[p_refPath])
			{
				this.paths[p_refPath].AddAction( p_refAction, p_delay);
			}
		},
		AddNpcPath: function( p_refNpc, p_refPath, p_proba){
			if ( ! g_npcm.npcs[p_refNpc])
			{
				return;
			}
			g_npcm.npcs[p_refNpc].AddPath( p_refPath, p_proba);
		},
		AddNpc: function( p_id){
			if (this.npcs[p_id]){return;}
			if (this.numNpcs == 0)
			{
				this.updateLoop = setInterval( this.Update.bind(this), 1000);
			}
			this.npcs[p_id] = true;
			++ this.numNpcs;
		},
		RemoveNpc: function( p_id){
			if (!this.npcs[p_id]){return;}
			delete this.npcs[p_id];
			-- this.numNpcs;
			if (this.numNpcs == 0)
			{
				clearInterval( this.updateLoop);
				this.updateLoop = 0;
			}
		},
		Update: function(){
			for (var i in this.npcs)
			{
				g_npcm.npcs[i].UpdatePaths();
			}
		}
	};
}
{ /***************Quests*******************/
	var g_collections = {
		Reset: function(){
			this.collections = {};
		},
		Colls: function(){
			for (var i = 0 ; i < arguments.length; ++ i)
			{
				var l = arguments[i];
				new Collection( l[0], l[1], l[2], l[3], l[4], l[5]);
			}
			
			new Pager('CollecTop',{size:{width:80,height:50},cisze:{width:720*g_map.allScale,height:64*g_map.allScale}});
			
			for (var i in this.collections)
			{
				this.collections[i].Load();
				break;
			}
		},
		LoadColl: function(p_id){
			if (this.collections[p_id])
			{
				this.collections[p_id].Load();
			}
		},
		LoadItems: function(){
		},
		LoadSkills: function( p_listDone){
			var l_temp = {};
			for (var i in p_listDone)
			{
				l_temp[p_listDone[i][0]] = p_listDone[i][1];
			}

			for (var i in g_cm.skills)
			{
				var l_s = g_cm.skills[i];
				var l_clevel = 0;
				if (l_temp[i])
				{
					l_clevel = l_temp[i];
				}
				for (var j in l_s.tiers)
				{
					if (l_s.tiers[j].minTier > 3){continue;}
					var l_div = new Element( 'span', {'class':'base i32'});
					l_div.setStyle({margin:'1px'});
					l_div.update( '<img src="/i/s/' + l_s.tiers[j].icon + '" class="i32"/>');
					if (l_clevel < l_s.tiers[j].min_level || l_clevel == 0)
					{
						l_div.insert('<img class="top_left0 i32" src="/i/defisnofait.png"/>');
					}
					$('SkillCol').insert(l_div);
				}
			}
		}
	};g_collections.Reset();
	var Collection = Class.create({
		initialize: function( p_id, p_name, p_desc, p_done, p_reward, p_items){
			this.id = p_id;
			this.name = p_name;
			this.desc = p_desc;
			this.reward = p_reward;
			this.items = p_items;
			g_collections.collections[this.id] = this;
			$('CollecTop').insert( '<span class="base" style="width:80px;height:50px;"><a href="javascript:;"onclick="g_collections.LoadColl('+this.id+')"><img src="/i/'+this.reward+'" onmouseover="tooltip.show(\''+this.name+'\');"onmouseout="tooltip.hide()"class="i48"></a></span>');
		},
		Load: function(){
			$('SColl_ItemsRight').update('<img src="/i/'+this.reward+'" class="i96">');
			$('SColl_ItemsLeft').update();
			for (var i = 0 ; i < this.items.length; ++ i)
			{
				$('SColl_ItemsLeft').insert('<img src="/i/'+this.items[i]+'" class="i96">');
			}
			$('CollDescr').update(this.desc);
		}
	});
	var g_qm = {
		queue: [],
		groups: {},
		quests: {},
		moving: false,
		AdviceDone: false,
		numScaled: 0,
		currentTarget: '',
		scales:[1,3,6,10,15,21,28,36,45,55],
		LoadTarget: function(){
			if (this.currentTarget != '')
			{
				g_diM.ActivateAnswer(this.currentTarget);
			}
			else
			{
				g_diM.ActivateAnswer('gps:51');
			}
		},
		Create: function(){
			var l_div = new Element( 'div', {id:'QuestRewardCadre'});
			l_div.setStyle(
			{
				display:'none',
				position:'absolute',
				bottom:'3em',
				right:'10em',
				zIndex:1300
			});
			
			l_div.update( '<div style="opacity:0.75;position:absolute;top:-1.5em;width:16em;left:3em;background:#FFFFFF;text-align:center;border:1px solid #AAA;border-bottom:0; line-height:1.5em;height:1.5em;border-top-left-radius: 2em;border-top-right-radius: 2em;"><h3 id="QuestRewardCadre_Title">Récompense !</h3></div>'
						+ 	'<div class="BaseCadre1px" style="opacity:0.85;background:#FFFFFF;border:2px solid #AAA;text-align:center;line-height:2em;width:22em;">'
						+	'<span class="base i64"><img id="QuestRewardCadre_Icon"src="/i/icone_inventaire.png" class="i64"></span>'
						+	'<span class="base h64" style="width:16em;"id="QuestRewardCadre_Details"></span></div>');
			l_div.observe('click',function(e){e.stop();});
			$('Map_Main2').insert( l_div);
		},
		Start: function( p_rew){
			this.moving = true;
			$('QuestRewardCadre_Title').update( p_rew.t);
			$('QuestRewardCadre_Details').update( p_rew.c);
			$('QuestRewardCadre_Icon').src= p_rew.i;
			new Effect.Appear( 'QuestRewardCadre', {duration:0.8, delay:0.2});
			new Effect.Morph( 'QuestRewardCadre_Details', {duration:0.3,delay:0.5,style:{backgroundColor:'#CCCCCC',borderColor:'#000'}});
			new Effect.Morph( 'QuestRewardCadre_Details', {duration:0.3,delay:0.8,style:{backgroundColor:'#FFFFFF',borderColor:'#AAA'}});
			
			if (p_rew.l)
			{
				new Effect.Fade( 'QuestRewardCadre', {duration:0.6, delay:p_rew.l, queue:'end',afterFinish:this.Stop.bind(this)});
			}
		},
		Stop: function(){
			this.moving = false;
			if (this.queue.length > 0)
			{
				this.Start(this.queue.pop());
			}
		},
		PrintReward: function( p_rew,p_sec, p_fb){
			g_win.Add('<h2>'+g_text.qm['reward_title']+'<h2><br/>'+p_rew+(p_sec?('<br/><br/>'+g_text.qm['reward_fb']+'<br/> '+p_sec):'<br/><br/><a href="javascript:;"onclick="g_win.Close();"><img src="/i/'+g_mainChar.language+'/menu/t/valider.png"></a>'));
		},
		PrintRewardFurnit: function( p_rew){
			this.Queue( g_text.qm['furnit_title'], '/i/iconesanstexte/meubler.png', p_rew, 4.0);
		},
		PrintDefi: function( p_icon,p_descr, p_rew){
			g_win.Add('<h2>'+g_text.qm['defi_title']+'<br/>'+p_descr+'</h2><div style="background:url(\'/i/'+g_mainChar.language+'/menu/trophee.png\');height:132px;width:125px;position:relative;margin:0 auto;"><img src="/i/d/'+p_icon+'" class="i64" style="position:absolute;left:30px;top:20px;"></div><br/>'+g_text.qm['defi_fb']+'<br/><a href="javascript:;"onclick="facebook.PublishPre(12);return;"><img src="/i/'+g_mainChar.language+'/menu/t/partager.png"></a>');
		},
		PrintAdvice: function( p_descr){
			this.Queue( g_text.qm['advtitle'], '/i/aide.png', p_descr, 8.0);
		},
		PrintAdviceRequest: function( p_descr){
			this.AdviceDone = false;
			this.Queue('Un admin peux vous aider !', '/i/aide.png', g_text.qm['helpreq']+'<br/><a href="javascript:;"onclick="return g_qm.AcceptAdvice();"class="Bordered"style="line-height:1.5em;margin-right:1.5em;width:4.75em;">'+g_text.gen['yes']+'</a><a href="javascript:;"onclick="return g_qm.RefuseAdvice();"class="Bordered"style="width:4.75em;line-height:1.5em;">'+g_text.gen['no']+'</a>', false);
		},
		AcceptAdvice: function(){
			if (this.AdviceDone){return;}
			this.AdviceDone = true;
			new Effect.Fade( 'QuestRewardCadre', {duration:0.6, queue:'end',afterFinish:this.Stop.bind(this)});
			new Ajax.Request( '/callback/helpreq.php', {method: 'post', parameters: {help: 1}} );
		},
		RefuseAdvice: function(){
			if (this.AdviceDone){return;}
			this.AdviceDone = true;
			new Effect.Fade( 'QuestRewardCadre', {duration:0.6, queue:'end',afterFinish:this.Stop.bind(this)});
			new Ajax.Request( '/callback/helpreq.php', {method: 'post', parameters: {help: 0}} );
		},
		Queue: function(p_title, p_icone, p_contents, p_length){
			p_length = p_length || 3.0;
			if (this.moving)
			{
				this.queue.unshift( {t:p_title,i:p_icone,c:p_contents,l:p_length});
				return;
			}
			if ( ! $('QuestRewardCadre'))
			{
				this.Create();
			}
			
			this.Start( {t:p_title,i:p_icone,c:p_contents,l:p_length});
		},
		AddQToQG: function( p_q, p_qg){
			if (this.groups[p_qg])
			{
				this.groups[p_qg].quests[p_q] = true;
			}
		},
		Npc: function( p_npc, p_group){
			this.groups[p_group].AddNpc( p_npc);
		},
		QuestDone: function( p_id){
			return this.quests[p_id] && this.quests[p_id].done;
		},
		QuestCurrent: function( p_id){
			return this.quests[p_id] && this.quests[p_id].current;
		},
		StartQuest: function( p_id){
			if (this.quests[p_id])
			{
				this.quests[p_id].current = true;
			}
			else
			{
				var l_q = new Quest( p_id,0,0);
				l_q.current = true;
			}
			g_city.RecheckPortals();
		},
		EndQuest: function( p_id){
			if (this.quests[p_id])
			{
				this.quests[p_id].current = false;
				this.quests[p_id].done = true;
				this.quests[p_id].GroupCheck();
			}
			g_city.RecheckPortals();
		},
		RemoveQuest: function(p_id){
			if (this.quests[p_id])
			{
				this.quests[p_id].current = false;
				this.quests[p_id].done = false;
				this.quests[p_id].GroupCheck();
			}
			g_city.RecheckPortals();
		},
		ActivateGroups: function(){
			var l_toLoad = [];
			this.numScaled = 0;
			for (var i in this.groups)
			{
				this.groups[i].Reset();
				this.groups[i].Recheck();
				if (this.groups[i].started && !this.groups[i].done)
				{
					l_toLoad.push(i);
				}
			}
		},
		GetScale: function(p_value){
			return p_value * this.scales[this.numScaled];
		}
	};
	var QuestGroup = Class.create({
		initialize: function( p_id, p_name, p_start, p_end, p_follow, p_offsetS, p_offsetE, p_autoload,p_scaling, p_gps){
			this.id = p_id;
			this.name = p_name;
			this.offsetS = p_offsetS;
			this.offsetE = p_offsetE;
			this.npcs = {};
			this.quests = {};
			this.endQ = p_end;
			this.startQ = p_start;
			this.autoload = p_autoload;
			this.scaling = p_scaling;
			this.Reset();
			g_qm.groups[this.id] = this;
		},
		Reset: function(){
			this.done = false;
			this.started = false;
		},
		AddNpc: function( p_id){
			this.npcs[p_id] = true;
		},
		_end: function(){
			if (this.done){return;}
			if(this.scaling){++g_qm.numScaled;}
			this._start();
			this.done = true;
			this._applyEnd();
		},
		_start: function(){
			if (this.started){return;}
			this.started = true;
			this._applyStart();
		},
		_applyStart: function(){
			if (this.offset <= 0){return;}
			for (var i in g_npcm.npcs)
			{
				if (!this.npcs[i])
				{
					var l = g_npcm.npcs[i];
					if (l.popu > 0)
					{
						l.popu += (this.scaling?g_qm.GetScale(this.offsetS):this.offsetS);
					}
				}
			}
		},
		_applyEnd: function(){
			if (this.offset <= 0){return;}
			for (var i in this.npcs)
			{
				var l = g_npcm.npcs[i];
				if (l.popu > 0)
				{
					l.popu += (this.scaling?g_qm.GetScale(this.offsetE):this.offsetE);
				}
			}
		},
		Recheck: function(){
			if (this.done){if(this.scaling){++g_qm.numScaled;}return;}
			if (this.endQ != 0 && g_qm.quests[this.endQ].done)
			{
				this._end();
			}
			else if (this.startQ != 0 && g_qm.quests[this.startQ].done)
			{
				this._start();
			}
			else
			{
				var l_numD = 0;
				var l_numT = 0;
				for (var i in this.quests)
				{
					++ l_numT;
					if (this.quests[i].done){++ l_numD;}
				}
				if (l_numD == l_numT){this._end();}
				else if (l_numD > 0){this._start();}
			}
		}
	});
	var Quest = Class.create({
		initialize: function( p_id, p_group, p_done){
			this.id = p_id;
			this.groupId = p_group;
			this.done = p_done == 1;
			this.current = false;
			g_qm.quests[this.id] = this;
			g_qm.AddQToQG(this.id, this.groupId);
		},
		GroupCheck: function(){
		}
	});
	var g_ql = {
		Reset: function(){
			this.items = {};
			this.loaded = 0;
		},
		Load: function(){
			g_unloadFunction2 = this.Reset.bind(this);
		},
		Final: function(){
			for (var i in this.items)
			{
				if (i > 0){continue;}
				this.items[i].Load();
			}
			for (var i in this.items)
			{
				if (i < 0){continue;}
				this.items[i].Load();
			}
			new Pager( 'QuestList',{size:{width:80*g_map.globalScale,height:71*g_map.globalScale},csize:{width:40*16*g_map.globalScale,height:72*g_map.globalScale}});
			for (var i in this.items)
			{
				if (i > 0){continue;}
				this.items[i].Select();
				this.loaded = i;
				return;
			}
			for (var i in this.items)
			{
				if (i < 0){continue;}
				this.items[i].Select();
				this.loaded = i;
				return;
			}
		},
		Show: function(p_id){
			if (this.items[p_id])
			{
				this.items[p_id].Select();
				this.loaded = p_id;
			}
		},
		ActivateGPS: function(){
			this.items[this.loaded].StartGps();
		}
	};g_ql.Reset();
	var QuestItem = Class.create({
		initialize: function( p_id, p_title, p_descr, p_img, p_gpsVal, p_cond){
			this.id = p_id;
			this.title = p_title;
			this.descr = p_descr;
			this.img = p_img;
			this.gps = p_gpsVal;
			this.scond = p_cond;
			if (this.scond && !g_mainChar.CheckCondition(this.scond)){return;}
			g_ql.items[this.id] = this;
		},
		Load: function(){
			$('QuestList').insert( 
				'<span class="base" style="padding:2px;margin:0.3em;">'
			+	'<a id="ql_link'+this.id+'" href="javascript:;" onclick="return g_ql.Show('+this.id+');" onmouseover="tooltip.show(\''+addslashes(this.title)+'\')" onmouseout="tooltip.hide();">'
			+	'<img src="/i/'+this.img+'" class="i64" />'
			+	'</a></span>');
		},
		Select: function(){
			$('QuestList_Title').update( this.title);
			$('QuestList_Descr').update( this.descr);
			$('QuestList_Img').src = '/i/'+this.img;
			if (this.gps == '')
			{
				$('IndicGPS').hide();
				$('FinishQuest').show();
			}
			else
			{
				$('IndicGPS').show();
				$('FinishQuest').hide();
			}
		},
		StartGps: function(){
			g_diM.ActivateAnswer(this.gps);
			UnloadCurrentInline();
		}
	});
}
{ /***************Items********************/
	var g_itemManager = {
		items: {}
	};
	var Item = Class.create({
		initialize: function( p_id, p_icon, p_name,p_value, p_hp, p_fod, p_slp, p_bonus, p_rank, p_buyable, p_sendable, p_sellable, p_quest, p_tier, p_refSkill, p_minSkill, p_shops){
			this.id = p_id;
			this.name = p_name;
			this.shops = {};
			for (var i = 0 ; i < p_shops.length; i ++)
			{
				this.shops[p_shops[i]] = true;
			}
			this.value = p_value;
			this.icon = '/i/r/'+p_icon;
			this.stats = {h:p_hp,f:p_fod,s:p_slp,b:p_bonus};
			this.rank = p_rank;
			this.tier = p_tier;
			this.refSkill = p_refSkill;
			this.minSkill = p_minSkill;
			this.actions = {b:p_buyable!=0,f:p_sendable!=0,s:p_sellable!=0,q:p_quest!=0,c:p_refSkill!=0,u:!p_quest&&(p_hp!=0||p_fod!=0||p_slp!=0||p_bonus!=0.0)};
			g_itemManager.items[this.id] = this;
			/*if (this.actions.b && this.tier <= g_mainChar.tier){new ShopItem(this.id);}*/
			if (this.actions.c){new SkillRecipe( this.id);}
		}
	});
}
{ /***************Pets*********************/
	var g_petM = {
		pets: {}
	};
	var Pet = Class.create({
		initialize: function( p_id, x, y, w, h, image, name, descr){
			this.id = p_id;
			this.x=x;
			this.y=y;
			this.h=h;
			this.w=w;
			this.image = '/i/pets/' + image;
			var l_imgBase = this.image.substr(0, this.image.length-7);
			this.wimages = [l_imgBase+'_M3_.gif',l_imgBase+'_M1_.gif',l_imgBase+'_M0_.gif',l_imgBase+'_M2_.gif'];
			this.name = name;
			this.descr = descr;
			g_petM.pets[this.id] = this;
		}
	});
}
{ /***************Submaps******************/
	var g_smap = {
		subs: {},
		questNames: {},
		bimages: ['','fleche01.png','fleche02.png','fleche03.png','fleche04.png','fleche05.png','fleche06.png','fleche07.png','fleche08.png','iconeporte.png','iconepnj.png','iconebus.png','iconequartier.png','metro.png'],
		Load: function( p_id){
			if (!this.subs[p_id])
			{
				return;
			}
			$('OvermapDiv').hide();
			$('Map_details').show();
			this.subs[p_id].Load();
		},
		LoadOverMap: function(){
			$('Map_details').hide();
			$('OvermapDiv').show();
			
			for (var i in this.subs)
			{
				if ( ! this.subs[i].created){this.subs[i].Create();continue;}
				$('ClickMap_'+i).update();
				var l = this.subs[i].GetPartList();
				if (l)
				{
					$('ClickMap_'+i).update( '<img src="/i/map/mid/quete02.png" class="i32"style="z-index:2000">');
					this.subs[i].currentQuests = l;
				}
				else
				{
					this.subs[i].currentQuests = false;
				}
			}
		},
		LoadCurrentMap: function(){
			if (IsDev())
			{
				var l_room = g_map.currentRoom;
				if (g_map.rooms[l_room].mapZone)
				{
					this.Load(g_map.rooms[l_room].mapZone);
				}
			}
		}
	};
	var Submap = Class.create({
		initialize: function( p_id, x,y,w,h,p_name, p_img, p_icones){
			this.id = p_id;
			this.image = p_img;
			this.icones = p_icones;
			this.quests = {};
			this.questParts = [];
			this.name = p_name;
			this.created = false;
			this.tooltip = false;
			this.x = x;
			this.y = y;
			this.w = w;
			this.h = h;
			g_smap.subs[this.id] = this;
		},
		Create: function(){
			this.created = true;
			$('OvermapDiv').insert('<a href="javascript:;"onclick="g_smap.Load('+this.id+');return false"><div id="ClickMap_'+this.id+'" style="width:'+(this.w*g_map.globalScale)+'px;height:'+(this.h*g_map.globalScale)+'px;left:'+((this.x*g_map.globalScale))+'px;top:'+((this.y*g_map.globalScale))+'px;position:absolute;" onmouseover="g_smap.subs['+this.id+'].MouseOver();"onmouseout="tooltip.hide()"></div></a>');
		},
		MouseOver: function(){
			tooltip.show(this.name + (this.currentQuests?'<br/>'+this.currentQuests:''));
		},
		GetPartList: function(){
			var l = '<ul>';
			var li = {};
			var l_numI = 0;
			for (var i=0;i<this.questParts.length;i++)
			{
				var p = this.questParts[i];
				if (li[p.i])continue;
				if (g_mainChar.CheckCondition(p.c))
				{
				
					++ l_numI;
					l += '<li>'+g_smap.questNames[p.i]+'</li>';
					li[p.i] = true;
				}
			}
			l += '</ul>';
			if (l_numI > 0)
			{
				return l;
			}
			else
			{
				return false;
			}
		},
		Load: function(){
			$('MapDetailsImage').src = '/i/map/mid/'+this.image;
			$('MapDetailsInside').update();
			$('MapZoneName').update();
			var l = this.GetPartList();
			if (l)
			{
				$('MapZoneName').insert( '<img src="/i/map/mid/quete02.png" class="i24m"style="z-index:2000;margin-right:0.625em;" onmouseover="g_smap.subs['+this.id+'].MouseOver()"onmouseout="tooltip.hide()">');
				this.currentQuests = l;
			}
			else
			{
				this.currentQuests = false;
			}
			$('MapZoneName').insert( this.name);
			
			for (var i = 0 ; i < this.icones.length; ++ i)
			{
				var li = this.icones[i];
				var l = '<img src="/i/map/mid/'+g_smap.bimages[li.i]+'"class="i32" style="position:absolute;left:'+(li.x*g_map.globalScale-16)+'px;top:'+(li.y*g_map.globalScale-16)+'px;" onmouseover="tooltip.show(\''+addslashes(li.n)+'\')"onmouseout="tooltip.hide()">';
				if (li.t)
				{
					l = '<a href="javascript:;"onclick="g_smap.Load('+li.t+');return false;">'+l+'</a>';
				}
				$('MapDetailsInside').insert(l);
			}
			
			for (var i in this.quests)
			{
				var q = this.quests[i];
				if (g_mainChar.CheckCondition(q.cond))
				{
					$('MapDetailsInside').insert( '<img src="/i/map/mid/quete01.png" class="i32"style="position:absolute;left:'+q.c.x*g_map.globalScale+'px;top:'+q.c.y*g_map.globalScale+'px;" onmouseover="tooltip.show(\''+addslashes(q.name)+'\')"onmouseout="tooltip.hide()">');
				}
			}
		}
	});
	var Questline = Class.create({
		initialize: function( p_id, p_name, p_coords, p_condition, p_parts){
			this.id = p_id;
			this.name = p_name;
			this.c = p_coords;
			this.cond = p_condition;
			this.parts = p_parts || [];
			g_smap.subs[this.c.z].quests[this.id] = this;
			g_smap.questNames[this.id] = this.name;
			if (p_parts)
			{
				for (var i=0;i<p_parts.length;i++)
				{
					var p = p_parts[i];
					g_smap.subs[p.z].questParts.push({c:p.c,i:this.id});
				}
			}
		}
	});
}
{ /***************Subway*******************/
	var g_subway = {
		stations: {},
		mstations: {},
		movement: false,
		hl: false,
		Load: function(){
			g_unloadFunction2 = this.Reset.bind(this);
			this.Reset();
			for (var i in this.stations)
			{
				var s = this.stations[i];
				s.Load();
				if (this.hl == s.r)
				{
					$('GpsMetro').show();
					$('GpsMetro').setStyle({left:(s.gx*g_map.globalScale)+'px',top:(s.gy*g_map.globalScale)+'px'});
				}
			}
		},
		Reset: function(){
			if (this.movement)
			{
				this.movement.cancel();
			}
			this.movement = false;
		},
		Take: function(p_id){
			if (this.movement){return;}
			$('MetroTrain').setStyle({left:-800*g_map.globalScale+'px',top:352*g_map.globalScale+'px'});
			$('MetroTrain').show();
			g_sound.Play('metro');
			this.mid = p_id;
			this.movement = new Effect.Move( $('MetroTrain'), {mode:'absolute',delay:0.8,x:800*g_map.globalScale,y:352*g_map.globalScale,duration:2.0,afterFinish:this.TakeTwo.bind(this)});
		},
		TakeTwo: function(){
			this.movement = false;
			if (this.hl == this.stations[this.mid].r){this.hl = false;}
			new Ajax.Request( '/callback/subway.php', { evalScripts:true,method: 'post', parameters: {mid: this.mid}} );
			UnloadCurrentInline();
		},
		LoadGps: function(){
			for (var i in this.mstations)
			{
				for (var j in this.mstations)
				{
					if (j == i){continue;}
					var si = this.mstations[i];
					var sj = this.mstations[j];
					g_gps.AddEdge(si.rid,sj.rid,si.id,1.5,true);
				}
			}
		},
		HlStation: function(p_id){
			if (this.mstations[p_id])
			{
				this.hl = p_id;
				var m = this.mstations[p_id];
				if ($('MapObj_'+m.id))
				{
					$('GPS_Arrow').setStyle({left:$('MapObj_'+m.id).style.left,top:$('MapObj_'+m.id).style.top});
				}
			}
		}
	};
	var Station = Class.create({
		initialize: function( p_id, p_name,x,y,w,h, p_rid, p_img,gx,gy){
			this.id = p_id;
			this.name = p_name;
			this.x = x;
			this.y = y;
			this.w = w;
			this.h = h;
			this.r = p_rid;
			this.gx = gx;
			this.gy = gy;
			this.img = p_img;
			g_subway.stations[this.id] = this;
		},
		Load: function(){
			if (this.r != g_map.currentRoom)
			{
				var t = '<div onmouseover="this.style.background=\'url(/i/map/metro/'+this.img + ')\';tooltip.show(\''+this.name+'\');"';
				t += 'style="position:absolute;background:url(\'/i/empty.png\');z-index:2500;left:'+this.x/16.0+'em;top:'+this.y/16.0+'em;width:'+this.w/16.0+'em;height:'+this.h/16.0+'em;" ';
				t += 'onclick="return g_subway.Take('+this.id+');" ';
				t += 'onmouseout="this.style.background=\'url(/i/empty.png)\';tooltip.hide()"></div>';
				$('StationMetroMap').insert(t);
			}
			else
			{
				$('YouAreHere').show();
				$('YouAreHere').setStyle({left:this.x/16.0+'em',top:this.y/16.0+'em'});
				$('StationMetroMap').insert('<a href="javascript:;" onclick="return g_subway.Take('+this.id+');" onmouseover="tooltip.show(\'Vous etes ici\')" onmouseout="tooltip.hide()"><div style="position:absolute;left:'+this.x/16.0+'em;top:'+this.y/16.0+'em;width:'+this.w/16.0+'em;height:'+this.h/16.0+'em;"></div></a>');
			}
		}
	});
	var MetroStation = Class.create( MapObject,{
		initialize: function( $super, p_rid, x,y, p_name){
			$super( p_rid, 'warpVIP.png', x, y, -400, 64, 64);
			this.used = false;
			this.onMouseOver = function(){tooltip.show(p_name);}
			this.onMouseOut = tooltip.hide.bind(tooltip);
			this.onWalkOver = this.WalkOver;
			g_subway.mstations[this.rid] = this;
		},
		WalkOver: function(){
			if (!this.used && g_mainChar.popu > 290)
			{
				this.used = true;
				_openUrl2('metro');
				setTimeout(this.Reuse.bind(this),5000);
				return true;
			}
			return false;
		},
		Reuse: function(){
			this.used = false;
		}
	});
}
{ /***************Tutos********************/
	var g_tm = {
		parts: {},
		autoplay: true,
		warping: false,
		currentPart: 0,
		startConds: [],
		previousPosition: false,
		loaded: false,
		StartNext: function(){
			if (this.parts[this.currentPart].next != 0)
			{
				this.currentPart = this.parts[this.currentPart].next;
				if (this.parts[this.currentPart])
				{
					this.parts[this.currentPart].Start();
					return;
				}
			}
			this.currentPart = 0;
			$('CadreTuto').hide();
		},
		IsDone: function( p_id){
			if(!this.parts[p_id]){return true;}
			if (this.parts[p_id].done)
			{
				return true;
			}
			return false;
		},
		Load: function(){
			if ($('CadreTuto')){return;}
			$('Contents').insert('<div id="CadreTuto"class="BaseCadre2pxW"style="width:300px;height:auto;z-index:2500;"><a href="javascript:;"onclick="$(\'CadreTuto\').hide();return false;" onmouseover="tooltip.show(g_text.gen[\'close\'])"onmouseout="tooltip.hide()"><img class="i20 top_right" src="/i/b_drop.png" ></a><h3 id="TutoPartName"></h3><hr class="grey"/><div id="TutoPartText"></div></div>');
			$('CadreTuto').setStyle({position:'absolute',right:'1.5em',bottom:'1.5em'});
			$('CadreTuto').hide();
		},
		EndCurrent: function(){
			this.parts[this.currentPart].Stop();
		},
		FinishedOne: function(){
			$('Disc_Main').hide();
			$('CadreTuto').hide();
			this.currentPart = 0;
		},
		StartOne: function(p_id){
			if (this.currentPart != 0)
			{
				this.EndCurrent();
			}
			this.currentPart = p_id;
			this.warping = true;
			this.autoplay = false;
			
			if (g_fm.loaded){this.previousPosition = 'furnit';}
			else if (g_city.loaded && g_city.visuRoom){this.previousPosition = 'home';}
			else {this.previousPosition = {rid:g_mainChar.rid,x:g_mainChar.x,y:g_mainChar.y};}
			
			if (this.parts[this.currentPart])
			{
				this.parts[this.currentPart].Start();
			}
		},
		StartAll: function(){
			this.currentPart = 0;
			this.warping = false;
			this.autoplay = true;
			this.StartNext();
		},
		TutoDone: function( p_tutoList){
			for (var i = 0 ; i< p_tutoList.length ; i ++)
			{
				if (this.parts[p_tutoList[i]])
				{
					this.parts[p_tutoList[i]].done = true;
				}
			}
		},
		SwitchTo: function( p_id){
			if ( ! this.parts[p_id]){return false;}
			if (!$('CadreTuto')){this.Load();}
			this.warping = false;
			this.autoplay = false;
			if (this.currentPart != 0)
			{
				this.EndCurrent();
			}
			this.warping = false;
			this.autoplay = true;
			this.currentPart = p_id;
			this.parts[p_id].Start();
			return false;
		},
		Warp: function( p_where){
			if (p_where == 'home')
			{
				_openUrl('home');
			}
			else if (p_where == 'furnit')
			{
				_openUrl('furnit');
			}
			else if (g_map.currentRoom != p_where.rid)
			{
				if (!g_city.Loaded || g_city.visuRoom)
				{
					_openUrl('map');
				}
				g_city.ChangeRoom( g_mainChar.id, p_where.rid, p_where.x, p_where.y);
			}
		}
	};
	var TutorialPart = Class.create({
		initialize: function( p_id, p_next, p_autozap, p_where, p_position, p_title, p_contents, p_start, p_spot){
			this.id = p_id;
			this.next = p_next;
			this.where = p_where;
			this.position = p_position;
			this.title = p_title;
			this.contents = p_contents;
			this.intervalFunction = false;
			this.startFunction = p_start;
			this.stopFunction = false;
			this.usingSpot = p_spot;
			this.autozap = p_autozap;
			this.done = false;
			g_tm.parts[this.id] = this;
		},
		SetIntervalFunc: function( p_func){
			this.intervalFunction = p_func;
		},
		Start: function(){
			if (this.done && this.autozap && g_tm.autoplay){g_tm.StartNext();return;}
			if (!$('CadreTuto')){g_tm.Load();}
			$('CadreTuto').show();
			switch(this.position)
			{
				case 0:$('CadreTuto').setStyle({position:'absolute',left:'0.5em',right:'auto',bottom:'0.5em',top:'auto',width:'300px'});break;
				case 1:$('CadreTuto').setStyle({position:'absolute',left:'auto',right:'0.5em',bottom:'0.5em',top:'auto',width:'300px'});break;
				case 2:$('CadreTuto').setStyle({position:'absolute',left:'0.5em',right:'auto',bottom:'auto',top:'0.5em',width:'300px'});break;
				case 3:$('CadreTuto').setStyle({position:'absolute',left:'auto',right:'0.5em',bottom:'auto',top:'0.5em',width:'300px'});break;
				case 4:$('CadreTuto').setStyle({position:'absolute',left:'10%',right:'auto',bottom:'auto',top:'0.5em',width:'80%'});break;
			}
			
			if (g_tm.warping)
			{
				g_tm.Warp( this.where);
			}
			
			$('TutoPartName').update( this.title);
			$('TutoPartText').update( this.contents);

			if (this.startFunction)
			{
				this.startFunction();
			}
			
			if (this.intervalFunction)
			{
				this.interval = setInterval( this.IntFunc.bind( this), 400);
			}
		},
		Skip: function(){
			if (!this.done)
			{
				this.done = true;
				new Ajax.Request( '/callback/end_tuto.php', { evalScripts:true,method: 'post', parameters: {tid : this.id}} );
			}
		},
		IntFunc: function(){
			if (this.intervalFunction())
			{
				this.Stop();
			}
		},
		Stop: function(){
			if (!this.done)
			{
				this.Skip();
			}
			if (this.interval != 0)
			{
				clearInterval( this.interval);
				this.interval = 0;
			}
			if (this.usingSpot)
			{
				var l_temp = $('TutoSpot');
				if (l_temp)
				{
					l_temp.parentNode.removeChild( l_temp);
				}
			}
			if (this.stopFunction)
			{
				this.stopFunction();
			}
			if (g_tm.autoplay)
			{
				g_tm.StartNext();
			}
			else
			{
				if (g_tm.warping)
				{
					g_tm.Warp( g_tm.previousPosition);
					g_tm.FinishedOne();
				}
				$('CadreTuto').hide();
			}
		}
	});
}
{ /***************Cars*********************/
	var g_carM = {
		Reset: function(){
			this.cars = {};
			this.traffic = {};
			this.roadGroups = {};
			this.numRoad = 0;
			this.currentTrafficGroup = 0;
		}
	};
	var Car = Class.create({
		initialize: function( p_id, p_name, p_speed, p_images){
			this.id = p_id;
			this.name = p_name;
			this.speed = p_speed;
			if (p_images.length > 2)
			{
				this.images = p_images;
			}
			else
			{
				this.images = g_carM.cars[p_images].images;
			}
			
			g_carM.cars[this.id] = this;
			
		}
	});
	var TrafficGroup = new Class.create({
		initialize: function( p_id, p_scale, p_baseTime, p_baseVariance, p_cars){
			
			this.id = p_id;
			this.cars = p_cars;
			this.scale = p_scale;
			this.baseT = p_baseTime;
			this.varT = p_baseVariance;
			g_carM.traffic[this.id] = this;
			g_carM.currentTrafficGroup = this.id;
			
		},
		RandomTime: function(){
			return this.baseT + Math.random() * this.varT;
		},
		PickCar: function(){
			var l_r = Math.random();
			for (var i =0; i< this.cars.length;i++)
			{
				if (l_r-this.cars[i].p<0)return this.cars[i].i;
				l_r -= this.cars[i].p;
			}
		}
	});
	var RoadGroup = Class.create({
		initialize: function( p_rid){
			this.id = p_rid;
			this.group = g_carM.currentTrafficGroup;
			this.roads = [];
			this.time = 0;
			g_carM.roadGroups[this.id] = this;
			if (g_map.rooms[this.id])
			{
				g_map.rooms[this.id].adds['roads'] = this;
			}
		},
		Rescale: function(p_scale){
			
		},
		Load: function(){
			this.time = setTimeout( this.Update.bind(this), 1000);
		},
		Update: function(){
			this.time = setTimeout( this.Update.bind(this), 1000.0*g_carM.traffic[this.group].RandomTime());
			var lr = Math.floor(Math.random() * this.roads.length);
			if (!this.roads[lr] || this.roads[lr].move)
			{
				return;
			}
			var lc = g_carM.traffic[this.group].PickCar();
			this.roads[lr].Start( lc);
		},
		Unload: function(){
			for (var i =0 ; i < this.roads.length; i ++)
			{
				this.roads[i].Unload();
			}
			if (this.time != 0)
			{
				clearTimeout(this.time);
				this.time = 0;
			}
		},
		Add: function(p_road){
			this.roads.push(p_road);
		}
	});
	var Road = Class.create({
		initialize: function( p_rid, x,y,ex,ey,p_angle){
			++g_carM.numRoad;
			if (!g_carM.roadGroups[p_rid]){new RoadGroup(p_rid);}
			this.rid = p_rid;
			x +=40;y+=60;ex +=40;ey+=60;
			var l_diffx = ex-x;
			var l_diffy = ey-y;
			this.sx = x-0.5*l_diffx;
			this.sy = y-0.5*l_diffy;
			this.ex = ex+0.5*l_diffx;
			this.ey = ey+0.5*l_diffy;
			l_diffx = this.ex-this.sx;
			l_diffy = this.ey-this.sy;
			this.dist = Math.sqrt(l_diffx*l_diffx + l_diffy * l_diffy);
			this.did = 'RoadCar'+g_carM.numRoad;
			this.car = '';
			this.move = false;
			this.angle = p_angle || 0;
			this.scale = g_carM.traffic[g_carM.currentTrafficGroup].scale;
			g_carM.roadGroups[this.rid].Add(this);
		},
		Create: function(){
			var ele = new Element('img',{id:this.did});
			ele.setStyle({position:'absolute',zIndex:125});
			$('Map_Main2').insert(ele);
		},
		Start: function( p_carId){
			if (!$(this.did))
			{
				this.Create();
			}
			if (!g_carM.cars[p_carId])
			{
				return;
			}
			$(this.did).src='/i/b/Voitures/'+g_carM.cars[p_carId].name+'/'+g_carM.images[this.angle]+'.png';
			var l_car = g_carM.cars[p_carId].images[this.angle];
			if (!l_car)
			{
				return;
			}
			$(this.did).show();
			var l_scale = this.scale * g_map.allScale;
			$(this.did).setStyle({width:l_car[0]*l_scale+'px',height:l_car[1]*l_scale+'px',left:(this.sx-l_car[2]*this.scale)*g_map.allScale+'px',top:(this.sy-l_car[3]*this.scale)*g_map.allScale+'px'});
			var l_time = this.dist / g_carM.cars[p_carId].speed;
			this.move = new Effect.Move( this.did,{afterFinish:this.EndMove.bind(this),mode:'absolute',x:(this.ex-l_car[2]*this.scale)*g_map.allScale,y:(this.ey-l_car[3]*this.scale)*g_map.allScale,duration:l_time});
		},
		EndMove: function(){
			$(this.did).hide();
			this.move = false;
		},
		Unload: function(){
			if (this.move)
			{
				this.move.cancel();
			}
			var l_temp = $(this.did);
			if (l_temp)
			{
				l_temp.parentNode.removeChild( l_temp);
			}
		}
	});
}
{ /***************Gps**********************/
	var g_gps = {
		points: {},
		currentGoal: 0,
		currentPath: [],
		openList: [],
		numPoints: 0,
		numEdges: 0,
		onSubway: false,
		GetPath: function( p_targetId){
			if (!this.points[g_map.currentRoom])
			{
				return false;
			}
			for (var i in this.points)
			{
				this.points[i].Reset();
			}
			
			var start = g_map.currentRoom;
			this.currentGoal = p_targetId;
			this.openList = [];
			this.currentPath = [];
			var found = false;
			var a;
			this.points[start].currentCost = 0;
			this.openList.push(start);
			while (this.openList.length > 0)
			{
				a = this.openList[0];
				this.openList.splice(0,1);
				if (this.points[a].Open())
				{
					found = true;break;
				}
				this.openList.sort(this.SortEdge);
			}
			if (found)
			{
				this.points[this.currentGoal].GetPath();
				this.CreateHl();
				this.Hl();
				return true;
			}
			return false;
		},
		AddEdge: function( p_rid,p_tid, p_oid,p_weight,p_m){
			this.points[p_rid].AddEdge( p_tid, p_oid, p_weight,p_m);
		},
		AddPoint: function( p_id){
			new GpsPoint(p_id);
		},
		SortEdge: function( a,b){
			return a.currentCost<b.currentCost?-1:a.currentCost>b.currentCost?1:0;
		},
		StopGps: function(){
			this.currentGoal = 0 ;this.RemoveHl();
		},
		Hl: function(){
			if (this.currentGoal == 0){return;}
			if (this.currentGoal == g_map.currentRoom){this.StopGps();}
			var next = 0;
			hideDiv( 'GPS_Arrow');
			for (var i = 0; i < this.currentPath.length; i ++)
			{
				if (this.currentPath[i] != g_map.currentRoom){continue;}
				if (i < this.currentPath.length-1)
				{
					next = this.currentPath[i+1];
				}
				else
				{
					next = this.currentGoal;
				}
				var h = this.points[g_map.currentRoom];
				for (var i = 0;i<h.edges.length;i++)
				{
					if (h.edges[i].t == next)
					{
						if ( ! $('GPS_Arrow'))
						{
							this.CreateHl();
						}
						$('GPS_Arrow').show();
						var li = h.edges[i].o;
						if ($('MapObj_'+li))
						{
							$('GPS_Arrow').setStyle({left:$('MapObj_'+li).style.left,top:$('MapObj_'+li).style.top});
						}
						if(h.edges[i].m)
						{
							g_subway.HlStation(next);
						}
						return;
					}
				}
				return;
			}
			this.GetPath(this.currentGoal);
		},
		RemoveHl: function(){
			deleteNode('GPS_Arrow');
		},
		Reset: function(){
			this.RemoveHl();
			this.currentPath = [];
			this.currentGoal = 0;
		},
		MouseOver: function(){
			if (this.currentGoal != 0)
			{
				tooltip.show(g_text.gps['desc'] + g_map.rooms[this.currentGoal].name);
			}
		},
		CreateHl: function(){
			this.onSubway = false;
			if ($('GPS_Arrow'))
			{
				$('Map_Main2').insert( $('GPS_Arrow'));
				return;
			}
			var l_temp = new Element('img',{id:'GPS_Arrow',src:'/i/walk/gps.gif'});
			l_temp.setStyle({position:'absolute',zIndex:1000,width:48*g_map.allScale * g_map.globalScale + 'px',height:48*g_map.allScale * g_map.globalScale + 'px'});
			l_temp.onmouseout=tooltip.hide.bind(tooltip);
			l_temp.onmouseover = this.MouseOver.bind(this);
			$('Map_Main2').insert( l_temp);
		}
	};
	var GpsPoint = Class.create({
		initialize: function( p_rid){
			this.id = p_rid;
			this.edges = [];
			this.metros = [];
			this.Reset();
			g_gps.points[p_rid] = this;
		},
		GetPath: function(){
			if (this.parent > 0)
			{
				g_gps.points[this.parent].GetPath();
			}
			g_gps.currentPath.push(this.id);
		},
		Reset: function(){
			this.currentCost = 9999;
			this.parent = 0;
		},
		AddEdge: function(p_rid, p_oid,p_weight,p_m){
			var obj = {t:p_rid,o:p_oid,w:p_weight};
			if(p_m){obj.m=true;}
			this.edges.push(obj);
		},
		Open: function(){
			for (var i=0;i<this.edges.length;i++)
			{
				var p = g_gps.points[this.edges[i].t];
				var w = this.edges[i].w;
				if (p.currentCost > (this.currentCost + w))
				{
					p.parent = this.id;
					p.currentCost = this.currentCost + w;
					g_gps.openList.push(p.id);
					if (p.id == g_gps.currentGoal)
					{
						return true;
					}
				}
			}
			return false;
		}
	});
}
{ /***************Pathing******************/
	var PathMap = Class.create({
		initialize: function( p_rid){
			this.nodes = [];
			this.lines = {};
			this.complete = false;
			this.rid = p_rid;
			this.objectId = 0;
		},
		CheckPoint: function( x, y){
			var r = g_map.rooms[this.rid];
			for (var i=0;i<r.walls.length;++i)
			{
				if (r.walls[i].IsInside( x,y))
				{
					return true;
				}
			}
			return false;
		},
		AddObject: function( p_obj){
			if (!p_obj.points){return;}
			p_obj.id = this.objectId;
			var l_nodeOffset = this.nodes.length;
			for (var i = 0 ; i < p_obj.points.length; ++ i)
			{
				var pos = p_obj.OffsetPoint(i);
				if (pos.x > 1024 || pos.y > 600 || pos.x < 0 || pos.y <0){continue;}
				if (this.CheckPoint(pos.x,pos.y))
				{
					continue;
				}
				else
				{
					var n = new PathNode( this.nodes.length,pos.x, pos.y, this.objectId);
					this.nodes.push( n);
				}
			}
			++ this.objectId;
		},
		Complete: function(){
			this.complete = true;
			for (var i =0 ; i < this.nodes.length ; ++ i)
			{
				var a = this.nodes[i];
				for (var j = i+1;j<this.nodes.length; ++ j)
				{
					var b = this.nodes[j];
					if (!this.Raytrace([a.x,a.y],[b.x,b.y]))
					{
						a.AddLink(b);
					}
				}
			}
		},
		Raytrace: function(p_start, p_end){
			var r = g_map.rooms[this.rid];
			for (var i=0; i < r.walls.length; ++i)
			{
				var w = r.walls[i];
				if(w.LinePassesThrough(p_start,p_end))
				{
					return true;
				}
			}
			return false;
		},
		GetClosestClearNodeTo: function( p_where){
		if (this.nodes.length == 0){return false;}
			var l_nodes  = [];
			for (var i = 0 ; i < this.nodes.length ; ++ i)
			{
				var n = this.nodes[i];
				var dx = n.x-p_where[0];
				var dy = n.y-p_where[1];
				var ds = dx*dx+dy*dy;
				l_nodes.push({id:i,d:ds});
			}
			l_nodes.sort(function(a,b){return a.d - b.d;});
			
			for (var i = 0; i < l_nodes.length; ++ i)
			{
				var n = this.nodes[l_nodes[i].id];
				if (!this.Raytrace(p_where,[n.x,n.y]))
				{
					return n;
				}
			}
			return false;
		},
		GetPath: function( p_start, p_end){
			p_end[0] /= g_map.ts;
			p_end[1] /= g_map.ts;
			if( this.CheckPoint(p_start[0],p_start[1])){return [p_end];}
			if( this.CheckPoint(p_end[0],p_end[1])){return [];}
			if (!this.Raytrace(p_start,p_end))
			{
				return [p_end];
			}
			l_sn = this.GetClosestClearNodeTo(p_start);
			l_en = this.GetClosestClearNodeTo(p_end);
			if (!l_sn || !l_en){return [p_end];}
			if (l_sn.id == l_en.id)
			{
				return [[l_en.x,l_en.y],p_end];
			}
			
			var p = this._pathing( l_sn.id, l_en.id);
			this.OptimPath( p_start, p, p_end);
			p.push(p_end);
			return p;
		},
		OptimPath: function(start, path, end){
			var numr = 0;
			for(var i=0;i<path.length;++i)
			{
				if (this.Raytrace( start, path[i])){break;}
				++ numr;
			}
			for(var i=0;i<numr-1;++i){path.shift();}
			numr = 0;
			for(var i=path.length-1;i>=0;--i)
			{
				if (this.Raytrace( path[i],end)){break;}
				++ numr;
			}
			for(var i=0;i<numr-1;++i){path.pop();}
		},
		_pathing: function( p_start, p_end){
			for (var i=0; i< this.nodes.length;++i)
			{
				this.nodes[i].Reset();
			}
		
			this.currentGoal = p_end;
			var openList = [];
			var currentPath = [];
			var found = false;
			var a;
			a = this.nodes[p_start];
			a.currentCost = 0;
			openList.push(a);
			while (openList.length > 0)
			{
				a = openList.shift();
				
				if (a.Open( openList, this))
				{
					found = true;break;
				}
				openList.sort(function(a,b){return a.currentCost-b.currentCost;});
			}
			
			var c = this.nodes[p_end];
			do
			{
				currentPath.push([c.x,c.y]);
				c = this.nodes[c.parent];
			} while (c.parent != -1);
			c = this.nodes[p_start];
			currentPath.push([c.x,c.y]);
			currentPath.reverse();
			return currentPath;
		}
	});
	var PathNode = Class.create({
		initialize: function( id,x,y,objId){
			this.x = x;
			this.y = y;
			this.id = id;
			this.links = {};
			this.objId = objId;
		},
		Reset: function(){
			this.parent = -1;
			this.currentCost = 50000*50000;
		},
		Open: function( list, map){
			for (var i in this.links)
			{
				var p = map.nodes[i];
				
				if (p.currentCost > (this.currentCost + this.links[i]))
				{
					p.parent = this.id;
					p.currentCost = this.currentCost + this.links[i];
					if (p.id == map.currentGoal)
					{
						return true;
					}
					list.push(p);
				}
			}
			return false;
		},
		AddLink: function( p_node){
			var dx = p_node.x - this.x;
			var dy = p_node.y - this.y;
			var d = Math.sqrt(dx*dx + dy*dy);
			this.links[p_node.id] = d;
			p_node.links[this.id] = d;
		}
	});
}
{ /***************Concours*****************/
	var g_concours = {
		selected: 0,
		selectedValue: 0,
		Select: function(p_id){
			if (this.selected)
			{
				$('ConcR'+this.selected).checked = false;
			}
			this.selected = p_id;
			$('ConcR'+this.selected).checked = true;
			this.selectedValue = $('ConcR'+this.selected).value;
		},
		Submit: function(){
			if (this.selectedValue != 0)
			{
				_openUrl2('concours',{ref:this.selectedValue});
			}
		}
	}
}
{ /***************Windowing****************/
	var g_win = {
		queue: [],
		eff: false,
		shown:false,
		Add: function( p_code,p_type){
			this.queue.push( {c:p_code,t:p_type || false});
			if (!$('KLWinMain'))
			{
				this.Create();
			}
			if (!this.shown && !$('Disc_Main').visible() && !$('CadreContents').visible())
			{
				this.Show();
			}
		},
		Show: function(){
			if (this.eff){return;}
			if (this.queue.length <= 0){return;}
			this.shown = true;
			var code = this.queue.shift();
			$('KLWin').update( code.c);
			if (code.t){$('KlWinFel').hide();$('KlWinAtt').show();}
			else {$('KlWinFel').show();$('KlWinAtt').hide();}
			this.eff = new Effect.Appear('KLWinMain',{duration:0.8,afterFinish:this.PostShow.bind(this)});
			Recenter( 'KLWinMain');
			$('KlWinPub').update( '<iframe src="/callback/view_pub.php" style="border:0;width:19em;height:17em;" frameborder=0 scrolling=no transparent=true vspace=0 hspace=0></iframe>');
		},
		PostClose: function(){
			this.eff = false;
			this.shown = false;
			$('KlWinPub').update('');
			this.Show();
		},
		PostShow: function(){
			this.eff = false;
		},
		Close: function(){
			if (this.eff){return;}
			this.eff = new Effect.Fade('KLWinMain',{duration:0.8,afterFinish:this.PostClose.bind(this)});
		},
		Create: function(){
			var l_div = new Element( 'div', {id:'KLWinMain','class':'BaseCadre2pxW'});
			l_div.setStyle(
			{
				display:'none',
				position:'absolute',
				textAlign:'center',
				width:'45em',
				height:'17em',
				zIndex:2500,
				background:"url(/i/barfond.jpg)"
			});
			
			l_div.update('<a href="javascript:;"onclick="g_win.Close();return false;"><img src="/i/b_drop.png"class="i24m top_right" style="z-index:2000"></a><span class="base" style="width:24em;" id="KlWinPub"></span><span class="base" style="width:20em;"><img id="KlWinFel" src="/i/'+g_mainChar.language+'/menu/t/Felicitation.png"><img id="KlWinAtt" src="/i/'+g_mainChar.language+'/menu/t/Attention.png"><div id="KLWin"style="width:100%;height:16em;"></div></span>');
			
			$('Main').insert(l_div);
		},
		empty: function(){
			return !this.shown;
		}
	}
}
{ /***************Focus********************/
	var g_focus = {
		current:-1,
		tt:'',
		open: false,
		text: '',
		created: false,
		cur: 0,
		timeOk : 0,
		timeSinceSwitch: 0,
		Load: function(){
			if (this.created) {return;}
			this.Create();
			setInterval(this.Check.bind(this),5000);
		},
		SetPromo: function( p_img, p_txt, p_tooltip,p_link){
			this.promoImg = p_img;
			if (!p_img){return;}
			this.promoTT = p_tooltip;
			this.promoTxT = p_txt;
			this.promoLink = p_link;
		},
		Check: function(){
			//this.SetCurrent(1 + (++this.cur) % 6);
			
			var l_skill = false;
			var l_numAmis = 0;
			var possibles = [];
			for (var i in g_mainChar.skills)
			{
				l_skill = true;break;
			}
			
			for (var i in g_chat.friends)
			{
				++ l_numAmis;
			}
			
			if ( ! l_skill)
			{
				possibles.push(2);
			}
			if (this.promoImg)
			{
				possibles.push(0);
			}
			if (l_numAmis < 3 + g_mainChar.level / 2)
			{
				possibles.push(4);
			}
			if (g_mainChar.tokens < 20)
			{
				possibles.push(3);
			}
			if (g_mainChar.credits > (5000 + 1000 * g_mainChar.level))
			{
				if (g_mainChar.numHouse == 1){
					possibles.push(1);
				}
				if (g_mainChar.numFringues < 20){
					possibles.push(5);
				}
				possibles.push(6);
			}
			
			if (possibles.length == 0)
			{
				this.timeOk = 0;
				this.current = 0;
				return;
			}
			
			var c = false;
			for (var i = 0 ; i < possibles.length ; ++ i)
			{
				if (possibles[i] === this.current){c=true;break;}
			}
			
			if (c)
			{
				++ this.timeSinceSwitch;
				if (this.timeSinceSwitch > 60)
				{
					this.SetCurrent(possibles[Math.floor(Math.random() * possibles.length)]);
				}
			}
			else
			{
				if (possibles[2])
				{
					this.SetCurrent( 2);
				}
				else
				{
					this.SetCurrent(possibles[Math.floor(Math.random() * possibles.length)]);
				}
			}

			if (possibles.length == 0)
			{
				this.timeOk = 0;
				this.current = 0;
			}

			if (!$('Disc_Main').visible() && !$('CadreContents').visible() && (!$('KLWinMain') || !$('KLWinMain').visible()))
			{
				++this.timeOk;
			}
			else
			{
				this.timeOk = 0;
			}
			
			if (this.timeOk > 5 && !this.open)
			{
				this.Open();
			}
		},
		SetCurrent:function( p_id){
			if (!this.open)
			{
				$('KLFocusHL').show();
			}

			if (this.current == p_id){return;}
			this.current = p_id;
			this.open = false;
			this.timeSinceSwitch = 0;
			this.timeOk = false;
			$('KLFocusHL').show();
			$('KLFocus').show();
			switch (p_id)
			{
				case 0:{
					this.tt = this.promoTT;
					this.text = '<h2>' + this.promoTxT+'</h2><br/><img src="/i/'+this.promoImg+'"><br/><a href="javascript:;"onclick="g_win.Close();return _openUrl2(\''+this.promoLink+'\');"><img src="/i/'+g_mainChar.language+'/menu/t/valider.png"></a>' ;
					$('KLFocus').src='/i/'+this.promoImg;
					break;
				}
				case 1:{
					this.tt = g_text.focus['tt_immo'];
					this.text = "<h2>"+g_text.focus['desc_immo']+"</h2><img src='/i/"+g_mainChar.language+"/menu/icone_maison.png'><br/><a href='javascript:;'onclick=\"g_win.Close();return _openUrl2('immokaz');\"><img src='/i/"+g_mainChar.language+"/menu/t/valider.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/icone_maison.png';
					break;
				}
				case 2:{
					this.tt = g_text.focus['tt_skill'];
					this.text = "<h2>"+g_text.focus['desc_immo']+"</h2><img src='/i/"+g_mainChar.language+"/menu/Metiers.png'><br/><a href='javascript:;'onclick='g_win.Close();'><img src='/i/"+g_mainChar.language+"/menu/t/valider.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/Metiers.png';
					break;
				}
				case 3:{
					this.tt = g_text.focus['tt_starz'];
					this.text = "<h2>"+g_text.focus['desc_immo']+"</h2><img src='/i/"+g_mainChar.language+"/menu/icone_starz.png'><br/><a href='javascript:;'onclick=\"g_win.Close();return _openUrl2('creditage')\"><img src='/i/"+g_mainChar.language+"/menu/t/valider.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/icone_starz.png';
					break;
				}
				case 4:{
					this.tt = g_text.focus['tt_friends'];
					this.text = "<h2>"+g_text.focus['desc_immo']+"</h2><img src='/i/"+g_mainChar.language+"/menu/icone_amis.png'><br/><a href='javascript:;'onclick='facebook.Invites(\""+g_text.fb['invite1']+"\",\""+g_text.fb['invite2']+"\")'><img src='/i/"+g_mainChar.language+"/menu/t/inviter.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/icone_amis.png';
					break;
				}
				case 5:{
					this.tt = g_text.focus['tt_dress'];
					this.text = "<h3>"+g_text.focus['desc_dress']+"</h3><br/><img src='/i/"+g_mainChar.language+"/menu/icone_vetement.png'><br/><a href='javascript:;'onclick=\"g_win.Close();return _openUrl2('avatar');\"><img src='/i/"+g_mainChar.language+"/menu/t/valider.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/icone_vetement.png';
					break;
				}
				case 6:{
					this.tt = g_text.focus['tt_furnish'];
					this.text = "<h3>"+g_text.focus['desc_furnish']+"</h3><img src='/i/"+g_mainChar.language+"/menu/Meubler.png'><br/><a href='javascript:;'onclick=\"g_win.Close();return _openUrl2('shopfurnit');\"><img src='/i/"+g_mainChar.language+"/menu/t/valider.png'></a>";
					$('KLFocus').src='/i/'+g_mainChar.language+'/menu/Meubler.png';
					break;
				}
			}
		},
		MouseOver: function(){
			tooltip.show(this.tt);
		},
		Create: function(){
			this.created = true;
			var l_div = new Element( 'img', {id:'KLFocusHL'});
			l_div.setStyle('z-index:1980;display:none;width:100px;height:100px;position:absolute;left:-18px;top:-100px;');
			l_div.src='/i/'+g_mainChar.language+'/menu/icone_attention.gif';
			$('MenuPhoneOuter').insert(l_div);
			l_div = new Element( 'img', {id:'KLFocus'});
			l_div.setStyle('z-index:2000;display:none;width:64px;height:64px;position:absolute;left:0px;top:-82px;');
			l_div.onmouseover = this.MouseOver.bind(this);
			l_div.onmouseout = tooltip._hide;
			l_div.onclick = this.Open.bind(this);
			$('MenuPhoneOuter').insert(l_div);
		},
		Open: function( p_id){
			if (!this.open || g_win.empty()){
				if (this.current > 0)
				{
					this.open = true;
					$('KLFocusHL').hide();
					g_win.Add(this.text,true);
				}
			}
		}
	}
}
{ /***************Countdown****************/
	var g_countdown = {
		interval:0,
		timeout:0,
		end: false,
		timeLeft:0,
		Start: function( p_time, p_end){
			this.end = p_end;
			this.timeLeft = p_time;
			this.interval = setInterval( this.Update.bind(this), 1000);
			this.timeout = setTimeout( this.Out.bind(this), p_time * 1000);
			if (!$('Countdown')){this.Create();}
		},
		Create: function(){
			var e = new Element('div',{id:'Countdown'});
			e.setOpacity(0.5);
			var w = (''+this.timeLeft).length * 64;
			e.setStyle('width:'+w+'px;height:auto;position:absolute;z-index:3000');
			$('Main').insert(e);
			e.update(g_mainChar.NumFormatImg(this.timeLeft,3));
			Recenter('Countdown');
		},
		Update: function(){
			--this.timeLeft;
			$('Countdown').update( g_mainChar.NumFormatImg(this.timeLeft,3));
		},
		Out: function(){
			clearInterval( this.interval);
			$('Countdown').hide();
			this.end();
		},
		Stop: function(){
			clearInterval( this.interval);
		},
		Cancel: function(){
			$('Countdown').hide();
			clearTimeout( this.timeout);
			clearInterval( this.interval);
		}
	}
}
{ /***************Cutscene*****************/
	var g_cutscene = {
		Play: function( p_url, p_func){
			this.url = p_url;
			this.func = p_func;
			if (!g_sound.supported){p_func();}
			if (!$('cutscene')){this.Create();}
			$('Disc_Main2').show();
			$('cutscene').show();
			$('cutscene').update('<iframe src="'+this.url+'" style="border:0;width:100%;height:100%" transparent=true></iframe>');
		},
		Create: function(){
			var e = new Element('div',{id:'cutscene'});
			e.setStyle('width:37.5em;height:24em;position:absolute;z-index:3000');
			$('Main').insert(e);
			Recenter('cutscene');
		},
		Close: function(){
			$('cutscene').hide();
			$('cutscene').update('');
			$('Disc_Main2').show();
		}
	}
}
{ /***************Treasure Hunt************/
	var g_treasureHunt = {
		points:[],
		selected:[],
		order:[],
		currentStatus:0,
		timeStarted:0,
		timeEnded:0,
		reward:'',
		loaded: false,
		SetParticipants: function(){
			var text = '<div style="width:100%;height:140px;overflow:auto;">';
			for (var i = 0 ; i < arguments.length;++i)
			{
				text += arguments[i].l + ' - '+arguments[i].s + ' / ' + this.order.length + '<br/>';
			}
			text += '</div>';
			g_win.Add('<h2>Chasse au trésor en cours !<h2>Scores actuels : <br>'+text+'<br/>Bonne chance !<br/><a href="javascript:;"onclick="g_win.Close();"><img src="/i/'+g_mainChar.language+'/menu/t/valider.png"></a>');
		},
		Reset: function(){
			this.order = [];
		},
		AddOrder: function( p_mindiff, p_maxdiff){
			this.order.push( {min:p_mindiff, max:p_maxdiff});
		},
		Load: function(){
//			for (var i = 0 ; i < this.numItems ; ++ i){this.points[i].Identify();}
			this.OpenCurrentPoint();
//			this.Check();
			setInterval(this.Check.bind(this), 120000);
		},
		Check: function(){
			new Ajax.Request( '/callback/checkhunt.php',{evalScripts:true,onSuccess:_printJaxReq});
		},
		Setup: function( p_numItems, reward, status){
			this.reward = reward;
			this.numItems = p_numItems;
			this.currentStatus = status || 0;
			this.points = [];
		},
		Unload: function(){
			for (var i = 0 ; i < p_numItems; ++ i)
			{
				this.points[i].active = false;
			}
		},
		ActiveNext: function(){
			++ this.currentStatus;
			if (this.currentStatus < this.numItems)
			{
				this.OpenCurrentPoint();
				g_win.Add('<h2>Chasse au trésor en cours !<h2><br/><br/>Il vous reste <br/><img src="/i/num/t/'+(this.numItems-this.currentStatus)+'.png"><br/> objets à trouver !<br/>Bonne chance !<br/><a href="javascript:;"onclick="g_win.Close();"><img src="/i/'+g_mainChar.language+'/menu/t/valider.png"></a>');
				new Ajax.Request( '/callback/treashunt.php', { evalScripts:true,parameters:{a:'part',i:this.currentStatus}} );
			}
			else
			{
				this.Win();
			}
		},
		OpenCurrentPoint: function(){
			var poss = [];
			var o = this.order[this.currentStatus];
			for (var i = 0 ; i < this.points.length ; ++ i)
			{
				var p = this.points[i];
				if (p.difficulty >= o.min && p.difficulty <= o.max)
				{
					poss.push(i);
				}
			}
			if (poss.length <= 0){return;}
			poss.shuffle();
			this.points[poss[0]].Identify();
			this.points[poss[0]].active = true;
		},
		Win: function(){
			var t = "";
			for (var i = 0 ; i < this.numItems; ++ i)
			{
				t+= this.points[i].rid+'|';
			}
			new Ajax.Request( '/callback/treashunt.php', { evalScripts:true,parameters:{r:t,a:'end'}});
		}
	};
	var TreasureItem = Class.create( MapObject, {
		initialize: function( $super, p_roomID, p_img, p_x, p_y, p_diff){
			$super( p_roomID, p_img, p_x, p_y, 999, 64, 64);
			this.onClick = this.Activate.bind( this);
			this.active = false;
			this.difficulty = p_diff;
			g_treasureHunt.points.push( this);
		},
		Load: function( $super){
			if (!this.active){return;}
			$super();
		},
		Identify: function(){
			_echo('Treasure item : ', this.rid, this.x, this.y);
		},
		Activate: function(){
			g_treasureHunt.ActiveNext();
			this.Unload();
			this.active = false;
			this.difficulty = -1;
			
		}
	});
}
{ /***************Ghost evade************/
	var g_ghostEvade = {
		Load: function(){
			this.npc = new NPC( 'ghost', 'Demon', false, 'H/npc_7.png',0,128,128,0,'',false,false,0,false,false);
			this.timeGhost = 30;
			this.speedGhost = 50.0;
			this.numUnloads = 0;
			this.Next();
			this.timer = new Timer();
			this.npc.Unload= function($super){
				if(!this.loaded){return;}
				this.nocontinue = true;
				++ g_ghostEvade.numUnloads;
				this.EndWalk();
				this.nocontinue = false;
				this.loaded = false; 
				this.DeleteAllBulles();
				var l_temp = $('user_' + this.id);
				l_temp.parentNode.removeChild( l_temp);
				g_map.rooms[this.rid].DelMovable( this.id);
				g_ghostEvade.Next();
			};
			this.npc.ContinuePath = function()
			{
				if (this.nocontinue){return false;}
				var dx = g_mainChar.x - this.x;
				var dy = g_mainChar.y - this.y;
				var d = Math.sqrt( dx*dx + dy*dy);
				if (d > 50)
				{
					this.WalkTo( g_mainChar.x, g_mainChar.y);
				}
				else
				{
					g_ghostEvade.Win();
				}
				return true;
			}
			this.loaded = false;
		},
		Win: function(){
			var t = Math.floor(this.timer.Time());
			g_map.rooms[this.npc.rid].DelMovable( this.npc.id);
			this.ended = true;
			new Ajax.Request( '/callback/ghosthunt.php', { method: 'post', evalScripts:true,onSuccess:_printJaxReq,parameters:{t:t,a:'end'}});
		},
		Next: function(){
			if (this.ended){return;}
			if (this.interval){ clearInterval( this.interval);}
			this.timeGhost = 1.0 + this.timeGhost * 0.5;
			this.speedGhost += 3.0;
			this.npc.speed = this.speedGhost;
			this.time = setTimeout( this.ShowGhost.bind(this), Math.floor( this.timeGhost * 1000));
		},
		ShowGhost: function(){
			var x = Math.random() * (1024 - 8 * this.numUnloads)-(512 - 4* this.numUnloads);
			if (x > -50 && x <0){x = -100;}
			if (x > 50 && x >0){x = 100;}
			var y = Math.random() * (600 - 5 * this.numUnloads)-(300 - 2.5* this.numUnloads);
			if (y > -50 && y <0){x = -100;}
			if (y > 50 && y >0){x = 100;}
			g_npcm.ShowNPC('ghost',g_map.currentRoom,g_mainChar.x + x,g_mainChar.y + y);
			this.npc.WalkTo( g_mainChar.x, g_mainChar.y);
			this.interval = setInterval( this.UpdateGhostInRoom.bind(this), 1000);
		},
		UpdateGhostInRoom: function(){
			this.npc.speed += 5;
		},
		SetParticipants: function(){
			var text = '<div style="width:100%;height:140px;overflow:auto;">';
			for (var i = 0 ; i < arguments.length;++i)
			{
				text += arguments[i].l + ' - '+arguments[i].s + ' secondes<br/>';
			}
			text += '</div>';
			g_win.Add('<h2>Chasse fantome finie !<h2>Scores actuels : <br>'+text+'<br/><br/><a href="javascript:;"onclick="g_win.Close();"><img src="/i/'+g_mainChar.language+'/menu/t/valider.png"></a>');
		}
	};
}
