var c_craftLoaded;
var c_current=0;

var g_unloadFunction  = false;
function UnloadCurrent()
{
	tooltip.hide();
	if (g_unloadFunction)
	{
		g_unloadFunction();
	}
	g_unloadFunction = false;
}

var g_unloadFunction2  = false;
function UnloadCurrentInline()
{
	if ($('CadreContents'))
	{
		$('CadreContents').hide();
		$('CadreContents').update('');
	}
	g_win.Show();
	tooltip.hide();
	hideDiv('Disc_Main2');
	if (g_unloadFunction2)
	{
		g_unloadFunction2();
	}
	g_unloadFunction2 = false;
}

function _showMap(){$('CadreContents')?UnloadCurrentInline():_openUrl( 'map');}

function _loadAny( p_index, p_page)
{
	UnloadCurrent();
	g_friends = [];
	if (c_current != p_index)
	{
		c_current = p_index;
		new Ajax.Updater( '_contents', c_baseSite + '/ajax.php?p=' + p_page, {evalScripts:true});
		tooltip.hide();
		return true;
	}
	return false;
}

function SetupMenuItem( p_id)
{
	$( p_id).onmouseover = function(){new Effect.Scale( this, 150, {duration:0.2,scaleMode: { originalHeight: 64, originalWidth: 64 }});};
	$( p_id).onmouseout = function(){new Effect.Scale( this, 66, {duration:0.2,scaleMode: { originalHeight: 96, originalWidth: 96 }});};
}

var c_id = 0;
var g_currentPage = 'page_podium';
var c_textPopuVote = '';
var c_textPopuVisit = '';
var c_textPopuFriend = '';

function _addLinks( p_div, p_userId)
{
	++ c_id;
	$(p_div).insert('<div id="links_for_' + c_id + '" style="position:absolute;bottom:0;left:6em;height:1.25em;line-height:1.25em;text-align:center;">'
	+ '<a href="" onclick="return _openUrl2( \'profile\', {c:\'ami\',id_user:'+p_userId+',action:\'ask\'});" style="margin:0 1em;">'+c_textPopuFriend+'</a>'
	+ '<a href="" onclick="return _openUrl2( \'profile\', {id_user:'+p_userId+'});" style="margin:0 1em;">' + c_textPopuVote + '</a>'
	+ '<a href="" onclick="return _openUrl( \'home\', {id:'+p_userId+'});" style="margin:0 1em;">' + c_textPopuVisit + '</a></div>');
}

function _hidePage()
{
	Effect.Fade( g_currentPage);
}

function _showPage( p_page, p_dir)
{
	if (g_currentPage != p_page)
	{
		_hidePage();
		g_currentPage = p_page;
		Effect.Grow(p_page, {direction:p_dir});
	}
}

function _openUrl( page, p_params)
{
	CloseAllSubMenus();
	UnloadCurrent();
	UnloadCurrentInline();
	p_params = p_params || {};
	p_params.p = page;
	new Ajax.Updater( '_contents', c_baseSite + '/ajax.php', {method:'post', parameters:p_params,evalScripts:true});
	return false;
}

function _openUrl2( page, p_params)
{
	if (!$('CadreContents')){_openUrl('map',{subp:page});return false;}
	CloseAllSubMenus();
	UnloadCurrentInline();
	$('Disc_Main2').show();
	p_params = p_params || {};
	p_params.p = page;
	
//	$('CadreContents').show();
	new Ajax.Updater( 'CadreContents', c_baseSite + '/ajax.php', {method:'post', parameters:p_params,evalScripts:true});
	return false;
}

function _openFrame( page, p_size){
	CloseAllSubMenus();
	UnloadCurrentInline( true);
	$('Disc_Main2').show();

	$('CadreContentsIn').insert('<iframe style="width:'+(p_size?p_size.x:600)+'px;height:'+(p_size?p_size.y:380)+'px;border:0" src="'+page+'"transparent=true></iframe>');

	Windowise('CadreContents','UnloadCurrentInline();return false;', false, '&nbsp');
	$('CadreContents').show();
	Recenter('CadreContents');
	return false;
}
function _openUrl3( page, p_params)
{
	UnloadCurrentInline();
	p_params = p_params || {};
	p_params.p = page;
	
	new Ajax.Updater( 'CadreContents2', c_baseSite + '/ajax.php', {method:'post', parameters:p_params,evalScripts:true});
	return false;
}

var c_textProfAva_NotFound = 'Not found';
function CheckFriend()
{
	var val = $F('SearchFriend');
	if( ! val){return;}
	new Ajax.Request( '/callback/friendlookup.php', { method: 'post', parameters: {fr : val},
	onSuccess: function(p_ans)
	{
		p_ans = p_ans.responseText;
		if (p_ans.substr(0,2)== 'ok')
		{
			_openUrl2( 'profile', {id_user:p_ans.substr(2)}, 8);
		}
		else
		{
			$('SearchFriend').value = c_textProfAva_NotFound;
		}
	}});
}
		
function _CheckFriendIfEnter(event)
{
	if(ConsumeEnter(event)){ CheckFriend();}
}

var g_currentPub = 0;
var g_pubs = {};
var g_admin = false;

var Pub = Class.create(
{
	initialize: function( p_id, p_imgSrc, p_link, w, h, p_done, p_admin, p_descr, p_numCodes)
	{
		if (p_admin && ! g_admin){return;}
		w = parseInt(w);
		h = parseInt(h);
		this.id = p_id;
		this.done = p_done == 1;
		this.admin = p_admin;
		this.img = p_imgSrc;
		this.descr = p_descr;
		this.numCodes = p_numCodes;
		this.link = p_link;

		g_pubs[this.id] = this;
		this.Load();
	},
	Load: function()
	{
		var l_img = new Element( 'img', {id:'Pub_' + this.id, 'class':'i64m'});
		l_img.setStyle(
		{
			margin: '1px'
		});
		l_img.src=this.img;

		l_img.onmouseover = this.MouseOver.bind(this);
		l_img.onmouseout = this.MouseOut.bind(this);
		l_img.onclick = this.LoadRight.bind(this);

		$('ListPubsMain').insert( l_img);
	},
	LoadRight: function()
	{
		g_currentPub = this.id;
		$('ListPubs_Image').setStyle({width:this.w/16+'em',height:this.h/16+'em',left:((256-this.w)/2)/16+'em',top:((256-this.h)/2)/16+'em'});
		$('ListPubs_Image').src = this.img;
		$('ListPubs_Descr').update(this.descr);
		$('ListPubs_Reward').update(this.numCodes);
		$('ListPubs_Link').href = this.link;
		this.done?$('ListPubs_Done').show():$('ListPubs_Done').hide();
	},
	MouseOver: function()
	{
		var l_text;
		if (g_admin)
		{
			l_text = 'Id : ' + this.id + '<br/>';
			if (this.admin)
			{
				l_text += 'Admins uniquement<br/>';
			}
		}
		l_text += '<img src="'+this.img+'"class="i128"><br/>';
		l_text += this.numCodes + ' codes';
		tooltip.show(l_text);
	},
	MouseOut: function()
	{
		tooltip.hide();
	},
	Open: function()
	{
		ValidatePub( this.id);
		$('ListPubs_Done').show();
	}
});
function ActivatePub()
{
	if (g_pubs[g_currentPub])
	{
		g_pubs[g_currentPub].Open();
	}
	return true;
}
function ValidatePub( p_id)
{
	new Ajax.Request( '/callback/verifpub.php', { method:'post',parameters:{id_pub:p_id},evalScripts:true});
}

function _addPFriend( p_id, p_name, p_img)
{
	var l_add = '<span class="base" style="border-bottom: 1px dashed #AAA;margin-bottom:0.3em;width:100%;"><span class="base i32" style="background:url(' + p_img + ');background-size:6em 10em;background-position:0 0" onclick="return _openUrl2( \'profile\', {id_user:'+p_id+'});" onmouseover="tooltip.show(\''+c_profileText.visitProfile+'\')" onmouseout="tooltip.hide()"></span><img src="/i/iconesanstexte/profil.png" class="h32"/></a>'
	+ '<a href="" onclick="return _openUrl( \'home\', {id:'+p_id+'});" onmouseover="tooltip.show(\''+c_profileText.visitHouse+'\')" onmouseout="tooltip.hide()"> <img src="/i/oeil.png" class="h32"/></a>';
	if (g_profileID == g_currentUser)
	{
		l_add += '<a href="" onclick="g_confirm.Show(c_confirmDeleteFriendTxt,\'_contents\',function(){PrfDelFriend('+p_id+')});return false;"onmouseover="tooltip.show(\''+c_profileText.deleteFriend+'\')" onmouseout="tooltip.hide()"> <img src="/i/b_drop.png" class="h24" style="margin:0.25em"/></a>';
	}
	$('table_').insert( l_add+'</span><br/>');
}

function PrfDelFriend( p_id)
{
//	if (confirm( c_confirmDeleteFriendTxt))
	{
		_openUrl2( 'profile', {action:'delfriend',c:'ami',id_user:g_profileID,id_target:p_id}, 8);
	}
	return false;
}
var ie = document.all ? true : false;
var Tooltip = Class.create({
	initialize: function( p_id, p_cl){
		this.id = p_id;
		this.maxw = 300;
		this.speed = 30;
		this.fadeoutDelay = 50;
		this.fadeTime = 0.2;
		this.minAlpha = 0;
		this.currentAlpha = 0;
		this.maxAlpha = 0.85;
		this.left = 3;
		this.shown = false;
		this.div = false;
		this.cl = p_cl;
		this._hide = this.hide.bind(this);
	},
	show: function( p_contents)	{
		if (!this.div)
		{
			this.div = new Element( 'div', {id:this.id,'class':this.cl});
			this.div.hide();
			document.body.appendChild(this.div);
		}
	
		$(this.id).update(p_contents);
		this.div.setOpacity( this.maxAlpha);
		$(this.id).show();
		this.shown = true;

		document.onmousemove = this.Move.bind(this);
		this.h = parseInt(this.div.offsetHeight) + 5;
	},
	Move: function( e){
		if (!this.shown){return;}
		e = e || window.event;
		var u = ie ? e.clientY + document.documentElement.scrollTop : e.pageY;
		var l = ie ? e.clientX + document.documentElement.scrollLeft : e.pageX;
		var viewport = document.viewport.getDimensions(); // Gets the viewport as an object literal
		var width = viewport.width; // Usable window width
		var height = viewport.height; // Usable window height
		/*
		if ((this.div.getWidth() + l - this.left) > (width-30))
		{
			this.div.style.left = (width -30  - this.div.getWidth()) + 'px';
		}
		else
		*/
		{
			this.div.style.left = (l + this.left) + 'px';
		}
		
		if ((u - this.h) < 0)
		{
			this.div.style.top = '0';
		}
		else
		{
			this.div.style.top = (u - this.h) + 'px';
		}
	},
	EndFade: function(){
		this.effect = false;
		this.div.setOpacity( this.maxAlpha);
		this.div.hide();
	},
	hide: function(){
		this.div = $(this.id);
		if (!this.div){return;}
		this.div.hide();
		this.shown = false;
		document.onmousemove = false;
		/*
		if (this.effect){this.effect.cancel();}
		this.effect = Effect.Fade( this.id, { from:this.maxAlpha, to:this.minAlpha, duration:this.fadeTime, afterFinish:this.EndFade.bind(this)});
		*/
	}
});
var tooltip = new Tooltip('tt', 'BaseTooltip');

var ScaledMenuManager = Class.create(
{
	initialize: function()
	{
		this.Reset();
	},
	
	Reset: function()
	{
		this.menus = {};
		this.updating = 0;
		this.updateList = {};
		this.updateNum = 0;
		this.shown = true;
		this.moving = false;
//		this.StopUpdating();
	},
	
	StartUpdate: function( p_id)
	{
		if (this.updateNum == 0)
		{
			this.updating = setInterval(this.Update.bind(this),30);
		}
		if (this.updateList[p_id]){return;}
		++ this.updateNum;
		this.updateList[p_id] = true;
	},
	
	Update: function()
	{
		for(var i in this.updateList)
		{
			this.menus[i].Update();
		}
	},
	
	StopUpdating: function( p_id)
	{
		delete this.updateList[p_id];
	},
	
	EndMove: function()
	{
		this.moving = false;
	},
	
	Toggle: function()
	{
		if (this.moving){this.moving.cancel();}
		if (this.shown)
		{
			this.moving = new Effect.BlindUp( 'MenuInline', {duration:0.2,afterFinish:this.EndMove.bind(this)});
			$('ToggleMenuIcon').src = '/i/up2.png';
		}
		else
		{
			this.moving = new Effect.BlindDown( 'MenuInline', {duration:0.2,afterFinish:this.EndMove.bind(this)});
			$('ToggleMenuIcon').src = '/i/down2.png';
		}
		this.shown = !this.shown;
		return;
	}
});
var g_sMM = new ScaledMenuManager;
var g_menus = {};
var ScaledMenu = Class.create(
{
	initialize: function( p_outerId, p_id, p_tooltip,w,dw,l,dl)
	{
		this.id = p_id;
		this.tooltip = p_tooltip;
		this.updating = false;
		this.direction = 0;//1 expand, -1 collapse, 0 static
		this.stage = 0; //0 default = collapsed, 8 = expanded
		$(p_outerId).onmouseover = this.MouseOver.bind(this);
		$(p_outerId).onmouseout = this.MouseOut.bind(this);
		this.div = $(this.id);
		this.w = w || 32;
		this.dw = dw || 4;
		this.l = l || 12;
		this.dl = dl || 2;
		g_sMM.menus[this.id] = this;
	},
	Update: function()
	{
		this.stage += this.direction;
		if (this.stage <= 0)
		{
			g_sMM.StopUpdating( this);
			this.updating = false;
			this.stage = 0;
		}
		else if (this.stage >= 6)
		{
			g_sMM.StopUpdating( this.id);
			this.updating = false;
			tooltip.show(this.tooltip);
			this.stage = 6;
		}
		this.div.style.width = (this.w + this.dw*this.stage)/16 + 'em';
		this.div.style.height = this.div.style.width;
		this.div.style.left = (this.l - this.dl*this.stage)/16 + 'em';
//		this.div.style.height = this.div.style.width;
	},
	
	MouseOver: function()
	{
		this.direction = 1;
		if ( ! this.updating && this.stage < 8)
		{
			g_sMM.StartUpdate(this.id);
		}
//		tooltip.show(this.tooltip);
	},
	
	MouseOut: function()
	{
		this.direction = -1;
		if ( ! this.updating && this.stage > 0)
		{
			g_sMM.StartUpdate(this.id);
		}
		tooltip.hide();
	}
});


function UpdateEncartPub( p_type)
{
	p_type = p_type || '';
	$('SpanPub' + p_type).update( '<iframe src="/callback/view_pub.php" style="border:0;width:20.5em;height:18em;" frameborder=0 scrolling=no vspace=0 hspace=0></iframe>');
}

function HideTierMenus()
{
	$('RankDetailSkills','RankDetailApparts','RankDetailDresses','RankDetailFurnit','RankDetailWorld').invoke('hide');
}
function ShowTierMenus( p_id)
{
	switch (p_id)
	{
		case 0:HideTierMenus();$('RankDetailSkills').show();break;
		case 1:HideTierMenus();$('RankDetailApparts').show();break;
		case 2:HideTierMenus();$('RankDetailDresses').show();break;
		case 3:HideTierMenus();$('RankDetailFurnit').show();break;
		case 4:HideTierMenus();$('RankDetailWorld').show();break;
	}
}

function ActualResize(p_forcedSize){
	var viewport = document.viewport.getDimensions();
	var l_width = (viewport.width-60) || 1024;
	var l_height = (viewport.height-40) || 600;

	var l_wantedWidth = 1024;
	var l_wantedHeight = 600;
	if (p_forcedSize)
	{
		l_width = p_forcedSize;
	}
	
	l_wantedWidth = (l_width < 600?600:l_width);
	l_wantedHeight = (l_height < 390?350:l_height);

	var r1 = l_wantedWidth / 1024;
	var r2 = l_wantedHeight / 600;
	var r = (r1 < r2?r1:r2);
	if(r>1.0){r=1.0;}
	if(r<0.6){r=0.6;}
	if(r<0.8)
	{
		g_world.SetGlobalScale(r/0.8);
		r = 0.8;
	}
	l_wantedWidth = 1024*r;
	l_wantedHeight = 600*r;
	g_world.SetAllScale(r);
	
	if ($('Main'))
	{
		$('Main').setStyle({width: l_wantedWidth / 16 + 'em',height:l_wantedHeight / 16+'em'});
		Recenter('Main');
	}
	if ($('CadreContents'))
	{
		$('CadreContents').setStyle({width:l_wantedWidth});
	}
	if ($('Map_Main2'))
	{
		$('Map_Main2').setStyle( {width: l_wantedWidth / 16 + 'em',height: l_wantedHeight / 16 + 'em'});
	}
	if ($('_contents'))
	{
		$('_contents').setStyle( {width: l_wantedWidth / 16 + 'em',height: l_wantedHeight / 16 + 'em'});
	}
}

function SubmitAnswer()
{
	new Ajax.Request( '/callback/concours.php', { method: 'post', parameters: {text : $('AnswerText').value}} );
}

function ClearAnswerFields()
{
	_openUrl2('concours');
}
var SiteUnderManager = Class.create(
{
	initialize: function()
	{
		this.pubs = [];
		this.baseClicks = 10;
		this.currentClick = 0;
		this.currentPub = 0;
	},
	Start: function(){
		setInterval( this.ShowPub.bind(this),15*60*1000);
	},
	Click: function()
	{
		++ this.currentClick;
		if (this.currentClick == this.baseClicks)
		{
			this.currentClick = 0;
			this.ShowPub();
		}
	},
	ShowPub: function()
	{
		if (this.currentPub >= this.pubs.length){this.currentPub = 0;}
		this._open(this.pubs[this.currentPub]);
		++ this.currentPub;
	},
	_open: function( p_url)
	{
		l_d = new Date();
		_include( p_url + l_d.getTime());
	}
});

function _include( p_url)
{
	document.getElementsByTagName('HEAD').item(0).appendChild( new Element("script",{type:"text/javascript",src:p_url}));
}

var g_sum = new SiteUnderManager();


var HelpArrow = Class.create(
{
	initialize: function( p_id,p_class)
	{
		this.id = p_id;
		this.cl = p_class;
		this.created = false;
		this.effect = false;
		this.images = ['ha0.png','ha1.png','ha2.png','ha3.png','ha4.png','ha5.png','ha6.png','ha7.png'];
	},
	ShowFor: function( p_target, p_direction, p_duration, p_numPulses)
	{
		if (!this.created)
		{
			this.Create();
		}
		
		if (this.effect)
		{
			this.effect.cancel();
		}
		
		$(this.id).src='/i/h/'+this.images[p_direction];
		var l_t1 = $(p_target).viewportOffset();
		var l_t2 = $(p_target).cumulativeScrollOffset();
		l_t1[0] += l_t2[0];l_t1[1] += l_t2[1];
		var l_s = $(p_target).getDimensions();
		var l_s2 = $(this.id).getDimensions();
		var l_x = l_t1[0];
		var l_y = l_t1[1];
		switch (p_direction)
		{
			case 2:case 6:{l_x -= l_s2.width;l_y += l_s.height;break;}
			case 3:case 7:{l_x -= l_s2.width;l_y -= l_s2.height;break;}
			case 0:case 4:{l_x += l_s.width;l_y -= l_s2.height;break;}
			case 1:case 5:{l_x += l_s.width;l_y += l_s.height;break;}
		}
		$(this.id).setStyle({left:l_x+'px',top:l_y+'px'});
		$(this.id).show();
		if (p_duration)
		{
			this.fadeLength = p_duration;
			this.effect = new Effect.Pulsate(this.id,{pulses:p_numPulses||4,duration:this.fadeLength,afterFinish:this.FadeOut.bind(this)});//
		}
	},
	FadeOut: function()
	{
		this.effect = new Effect.Fade(this.id,{duration:this.fadeLength, afterFinish: this.EndEffect.bind(this)});
	},
	EndEffect: function()
	{
		this.effect = false;
	},
	Highlight: function()
	{
		this.effect = new Effect.Pulsate(this.id, {pulses:3,duration:1.5,afterFinish: this.EndEffect.bind(this)});
	},
	Create: function()
	{
		var l_temp = new Element('img',{id:this.id,'class':this.cl});
		l_temp.setStyle({position:'absolute',display:'none',zIndex:2900});
		$('body').insert(l_temp);
		this.created = true;
	},
	Hide: function()
	{
		$(this.id).hide();
	}
});
var g_ha = new HelpArrow( '__HA','i64');


var FlyingNum = Class.create({
	initialize: function( p_id)
	{
		this.created = false;
		this.id = p_id;
	},
	Create: function()
	{
		var l_temp = new Element('div',{id:this.id});
		l_temp.setStyle({position:'absolute',display:'none',zIndex:2900});
		l_temp.setStyle({fontSize:'150%',color:'#7F7'});
		$('body').insert(l_temp);
		this.created = true;
	},
	FlyTo: function(p_from, p_target, p_contents)
	{
		if (!this.created)
		{
			this.Create();
		}
		
		$(this.id).update(p_contents);
		
		var l_f1 = $(p_from).viewportOffset();
		var l_f2 = $(p_from).cumulativeScrollOffset();
		l_f1[0] += l_f2[0];l_f1[1] += l_f2[1];
		
		var l_t1 = $(p_target).viewportOffset();
		var l_t2 = $(p_target).cumulativeScrollOffset();
		var l_x = l_t1[0]+ l_t2[0] + $(p_target).getWidth()/2;
		var l_y = l_t1[1] + l_t2[1];
		
		$(this.id).setStyle({left:l_f1[0]+'px',top:l_f1[1]+'px'});
		$(this.id).show();
		new Effect.Appear(this.id,{duration:0.3});
		new Effect.Move(this.id,{mode:'absolute',duration:0.9,x:l_x,y:l_y,afterFinish:function(p_ele){new Effect.Puff(p_ele.element,{duration:0.5});}});
	}
});

var g_fly = new FlyingNum('g_fly');

function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
);}

var g_help = {
	initialize: function()
	{
	},
	CreateScreen: function()
	{
		if (!$('KL_Help'))
		{
			this.Create();
		}
		$('KL_Help_Contents').update();
	},
	Create: function()
	{
		var ele = new Element('div',{id:'KL_Help','class':'BaseCadre2pxW'});
		ele.setStyle('display:none;width:650px;font-weight:bold;padding:10px;position:absolute;left:250px;top:50px;z-index:2300;text-align:justify');
		ele.update('<br/><br/><div id="KL_Help_Contents"></div>');
		$('_contents').insert(ele);
		Windowise(ele.id);
	},
	AddTopic: function(p_img, p_targetId, p_angle, p_text)
	{
		$('KL_Help_Contents').insert('<p onclick="g_ha.Highlight()"onmouseover="g_ha.ShowFor(\''+p_targetId+'\','+p_angle+')"onmouseout="g_ha.Hide();"><img src="/i/'+p_img+'"class="i32m" style="float:left;margin-right:15px;">'+p_text+'</p><br/>');
	}
};
g_help.initialize();

var g_confirm = {
	created: false,
	ycallback: false,
	ncallback: false,
	Show: function( p_msg, p_where, p_ycallback, p_ncallback,p_width){
		if (!this.created || !$('g_confirmA'))
		{
			this.Create(p_where);
		}
		p_width = p_width || 300
		$(p_where).insert( $('g_confirmA'));
		$(p_where).insert( $('g_confirmB'));
		
		this.ycallback = p_ycallback || false;
		this.ncallback = p_ncallback || false;
		$('g_confirmContents').setStyle('width:'+p_width+'px');
		$('g_confirmContents').update(p_msg);
		
		if ( this.ycallback || this.ncallback)
		{
			$('g_confirmButtons').show();
		}
		else
		{
			$('g_confirmButtons').hide();
		}
		
//		Recenter('g_confirmA');
		Recenter('g_confirmB');
		// var ldim1 = $(p_where).getDimensions();
		// var ldim2 = $('g_confirmB').getDimensions();
		
		// $('g_confirmB').setStyle({left:(ldim1.width - ldim2.width)/2+'px',top:(ldim1.height - ldim2.height)/2+'px'});
		
		$('g_confirmA').show();
		$('g_confirmB').show();
	},
	Hide: function(){
		$('g_confirmA').hide();
		$('g_confirmB').hide();
	},
	Yes: function(){
		this.Hide();
		if (this.ycallback){this.ycallback();}
	},
	No: function(){
		this.Hide();
		if (this.ncallback){this.ncallback();}
	},
	Create: function(p_where){
		this.created = true;
		var ele = new Element('div',{id:'g_confirmA'});
		ele.setStyle({display:'none',position:'absolute',width:'100%',height:'100%',top:0,bottom:0,background:'#FFFFFF',opacity:'0.7',zIndex:3500});
		$(p_where).insert( ele);
		ele = new Element('div',{id:'g_confirmB','class':'BaseCadre2pxW'});
		ele.setStyle({display:'none',position:'absolute',zIndex:3600,'text-align':'center'});
		ele.insert( '<div id="g_confirmContents" style="width:300px;margin:10px;"></div><div id="g_confirmButtons"><br/><span style="width:140px;"class="base"><a href="javascript:;"onclick="return g_confirm.Yes();"class="Bordered" style="padding:5px 10px">Oui</a></span><span style="width:140px;"class="base"><a href="javascript:;"onclick="return g_confirm.No();"class="Bordered"style="padding:5px 10px">Non</a></span></div>');
		$(p_where).insert( ele);
	}
};
function Windowise( p_id, p_closeFunction, p_long, p_title){
	if (p_title)
	{
		$(p_id).insert({top:'<div id="'+p_id+'_Handle"style="cursor:move;width:100%;height:32px;"><h2>'+p_title+'</h2></div>'});
	}
	else
	{
		if (p_long)
		{
			var move = '<a href="javascript:;"onclick="tooltip.hide();return false;"><div class="top_left"style="z-index:2800;border-radius:8px;-moz-border-radius:8px;width:100%;height:24px;padding-top:4px;"id="'+p_id+'_Handle"><img class="i24 top_left" src="/i/h/cross.png"></div></a>';
		}
		else
		{
			var move = '<div style="position:absolute;top:0;background:#DDDDDD;left:0;width:28px;height:28px;border:0 px solid white;border-bottom-right-radius:16px;border-top-left-radius:12px;-moz-border-radius-bottomright:16px;-moz-border-radius-topleft:12px;"><a href="javascript:;"onclick="tooltip.hide();return false;"><img class="i24" id="'+p_id+'_Handle"src="/i/h/cross.png"></div></a>';
		}
	}
	var close = '<div style="position:absolute;top:0;background:#DDDDDD;right:0;width:28px;height:28px;border:0 px solid white;border-bottom-left-radius:16px;border-top-right-radius:12px;-moz-border-radius-bottomleft:16px;-moz-border-radius-topright:12px;"><a href="javascript:;"onclick="'+(p_closeFunction?p_closeFunction:'$(\''+p_id+'\').hide();return false;')+'" onmouseover="tooltip.show(g_text.gen[\'close\']);"onmouseout="tooltip.hide()"><img class="i20 top_right"style="z-index:2900" src="/i/b_drop.png" ></a></div>';
	$(p_id).insert( close);
	$(p_id).insert( move);
	$(p_id).KL_DragItem = new Draggable(p_id,{handle:p_id+'_Handle',zindex:2800,starteffect:false,endeffect:false});//
}
var Resizable = Class.create({
	initialize: function(p_id, p_target){
		this.id = p_id;
		this.target = p_target || this.id;
		this.minSize = {x:260,y:150};
		var ele = new Element('div',{id:this.id+'_RsH'});
		ele.setStyle('cursor:move;z-index:3000;position:absolute;bottom:-8px;right:-8px;width:20px;height:20px');
		ele.onmousedown=this.StartResize.bind(this);
		ele.onmousedup=this.EndResize.bind(this);
		$(this.id).insert( ele);
	},
	StartResize: function( e)
	{
		e = e || window.event;
		$('body').onmousemove = this.MouseMove.bind(this);
		$('body').onmouseup = this.EndResize.bind(this);
		this.currentCoords = {x:e.x,y:e.y};
		this.currentDims = $(this.target).getDimensions();
		return false;
	},
	MouseMove: function( e)
	{
		e = e || window.event;
		var w = e.x - this.currentCoords.x;
		var h = e.y - this.currentCoords.y;
		w = w+this.currentDims.width < this.minSize.x ? this.minSize.x : w+this.currentDims.width;
		h = h+this.currentDims.height < this.minSize.y ? this.minSize.y : h+this.currentDims.height;
		$(this.target).setStyle({width:w+'px',height:h+'px'});
		return false;
	},
	EndResize: function()
	{
		$('body').onmousemove = false;
		$('body').onmouseup = false;
		return false;
	}
});
function Recenter(p_id, p_parent){
	if (!p_id || ! $(p_id)){return;}
	
	var l_parent = (p_parent?$(p_parent):$(p_id).getOffsetParent());
	
	if (!l_parent){return;}
	
	var dp = (l_parent.tagName == 'BODY'?document.viewport.getDimensions():l_parent.getDimensions());
		
	var d = $(p_id).getDimensions();
	var w = (d.width > dp.width?0:(dp.width-d.width)/2);
	var h = (d.height > dp.height?0:(dp.height-d.height)/2);
	$(p_id).setStyle({left:w+'px',top:h+'px'});
}
var facebook = {
	appId: 0,
	friends: [],
	cookie: false,
	loadedPost: {},
	loaded: false,
	logged: false,
	inFB: false,
	liked: 3,
	selectedOffer: 0,
	selectOffValue:0,
	uid:0,
	invite:0,
	needHlFor: function(p_id,p_msg,p_antiStyle, p_time){
		if (!this.inFB)
		{
			setTimeout(function(){
			g_hintBox.ShowFor(p_id,p_msg,p_antiStyle);
			},p_time);
			return;
		}
		if (this.like == 3){setTimeout('facebook.needHlFor('+p_id+',"'+p_msg+'","'+p_antiStyle+'",'+p_style+')',2000);return;}
		if (this.liked)
		{
			setTimeout(function(){
			g_hintBox.ShowFor(p_id,p_msg,p_antiStyle);
			},p_time);
		}
		else
		{
			setTimeout(function(){
			g_hintBox.ShowFor('FBLikeButton',g_text.fb['likeus']+'<img src="/i/j/sm/coeur.png"class="i24m">!','top_right');
			},5000);
		}
	},
	Load: function( p_appId, p_inFB, p_uid){
		if (this.loaded){return;}
		this.loaded = true;
		this.uid = p_uid;
		this.inFB = p_inFB;
		this.appId = p_appId;
		$('body').insert('<div id="fb-root"></div>');
		_include( 'http://connect.facebook.net/en_US/all.js');
		
		if (this.inFB)
		{
			window.fbAsyncInit = this.AsynInit.bind(this);
		}
		else
		{
			window.fbAsyncInit = this.DelayedLogin.bind(this);
		}
	},
	SelectOffer: function( p_id, p_value){
		if (this.selectedOffer != 0)
		{
			$('FbSelOff_'+this.selectedOffer).checked = false;
		}
		this.selectedOffer = p_id;
		$('FbSelOff_'+this.selectedOffer).checked = true;
		this.selectOffValue = p_value;
	},
	AsynInit: function(){
		this.cookie = GetCookie( 'fbs_'+this.appId);
		if (!this.cookie){this.needReload = true;}
		FB.init({appId: this.appId, status: true, cookie: true, xfbml: true});
		this.cookie = GetCookie( 'fbs_'+this.appId);
		this.session = getQueryVariable( this.cookie.replace('"',''), 'access_token');
		this.CheckInvites();
		this.Check();
		
		FB.Event.subscribe('auth.login', function (response){
			if (response.session && response.perms)
			{
				self.location = '/?fb=true';
			}
		});
	},
	DelayedLogin: function(){
		FB.init({appId: this.appId, status: true, cookie: true, xfbml: true});
		this.cookie = GetCookie( 'fbs_'+this.appId);
		this.session = getQueryVariable( this.cookie.replace('"',''), 'access_token');
		
		FB.Event.subscribe('auth.login', function (response){
			if (response.session && response.perms)
			{
				self.location = '/?fb=true';
			}
		});
	},
	Check: function(){
		FB.getLoginStatus(function(response) {
			if (response.session){
				facebook.FinalCheck( response)
			} else {
				self.parent.location = 'https://graph.facebook.com/oauth/authorize?client_id='+facebook.appId+'&redirect_uri='+urlencode('http://apps.facebook.com/kazulife/'+(facebook.invite?'?request_ids='+this.invite:''))+'&scope=email,publish_stream&display=page';
			}
		});
	},
	FinalCheck: function( response){
		this.cookie = GetCookie( 'fbs_'+this.appId);
		if (this.cookie.length > 0)
		{
			this.session = getQueryVariable( this.cookie.replace('"',''), 'access_token');
			var uid = getQueryVariable( this.cookie.replace(/\"/gi,''), 'uid');
			
			if (response.session.uid != uid || (this.uid != 0 && response.session.uid != this.uid))
			{
				del_cookie('fbs_'+this.appId);
				del_cookie('PHPSESSID');
				self.location = '/?fb=true'+(this.invite?'&request_ids='+this.invite:'');
				return false;
			}
			if (this.needReload)
			{
				self.location = '/?fb=true'+(this.invite?'&request_ids='+this.invite:'');
				return true;
			}
			this.uid = uid;
			this.logged = true;
			this.CheckLike();
			this.ClearInvites();
			return true;
		}
		if(this.inFB)
		{
			self.location = '/?fb=true'+(this.invite?'&request_ids='+this.invite:'');
			return false;
		}
		return false;
	},
	Invites: function( p_msg, p_title, p_record){
		if (!this.logged)
		{
			this.delaydAct = 'facebook.Invites("'+p_msg+'","'+p_title+'")';
			this.LateLogin();
			return;
		}
		var callB;
		if(p_record){callB = function(response){
			g_win.Close();
			if (response && response.request_ids)
			{
				new Ajax.Request( '/callback/inviteFB.php', { method: 'post', parameters: {f : response.request_ids}});
			}
		};}
		else
		{
			callB = function(){g_win.Close();}
		}
		FB.ui({
			method: 'apprequests',
			message: p_msg,
			data: g_mainChar.id,
			title:p_title
		},callB);
	},
	ClearInvites: function(){
		if(g_mainChar.id > 0)
		{
			if (this.uid > 0)
			{
				FB.api( '/me/apprequests?access_token='+this.session,function(response)
				{
					for (var i = 0 ; i < response.data.length ; ++ i)
					{
						var r = response.data[i];
						FB.api( '/'+r.id+'?method=delete');
					}
				});
			}
		}
	},
	CheckInvites: function(){
		var url = window.location.href;
		var ind = url.indexOf('request_ids');
		if (ind == -1)
		{
			return ;
		}
		this.invite = url.substr(ind+12);
		FB.api( '/'+this.invite,function(response)
		{
			var req = response.data[0];
			facebook.invite = response.data;
		});
	},
	PrePostOnWall: function( p_idMsg, p_picture, p_name, p_link, p_caption, p_descr, p_msg, p_descr2,p_details){
		this.loadedPost = {id:p_idMsg,pic:p_picture,name:p_name,link:p_link,cap:p_caption,descr:p_descr,msg:p_msg,descr2:p_descr2,det:p_details};
			g_confirm.Show('<div style="width:100%;max-height:300px;overflow:auto;display:none"id="FBListMn"></div>','Main');
			this.ListFriendsForPost();
	},
	ListFriendsForPost: function(){
		FB.api( '/me/friends?access_token='+this.session,function(response)
		{
			facebook.friends = response.data;
			if (facebook.friends && facebook.friends.length > 0)
			{
				$('FBListMn').update('<a href="javascript:;"onclick="facebook.PostPreLoaded(0);return false;"class="Bordered">'+g_text.fb['postyourwall']+'</a><br/><hr></br>'+g_text.fb['postother']+'<br/>');
				for (var i = 0 ; i < facebook.friends.length ; ++ i)
				{
					var f = facebook.friends[i];
					$('FBListMn').insert('<a href="javascript:;"onmouseover="tooltip.show(\''+f.name+'\');"onmouseout="tooltip.hide()"onclick="facebook.PostPreLoaded('+f.id+')"><img class="i32m" style="margin:2px"src="http://graph.facebook.com/'+f.id+'/picture"></a>');
				}
				
				$('g_confirmA').show();
				$('g_confirmB').show();
				$('FBListMn').insert('<br><br/><a href="javascript:;"onclick="g_confirm.Hide();return false;"class="Bordered">'+g_text.gen['cancel']+'</a>');
				$('FBListMn').show();
				Recenter('g_confirmB');
			}
			else
			{
				facebook.PostPreLoaded(0);
			}
		});
	},
	PublishPre: function( p_id){
		if (!this.logged)
		{
			this.delayAct = 'facebook.PublishPre('+p_id+')';
			this.LateLogin();
			return;
		}
		new Ajax.Request( '/callback/pfbpre.php', { method: 'post', parameters: {id : p_id}});
	},
	LateLogin: function(){
		FB.login(function(response)
		{
			if (response.session)
			{
				if (facebook.FinalCheck(response))
				{
					eval(facebook.delayAct);
					facebook.delayAct = '';
				}
			}
		}, {perms:'email,publish_stream'});
	},
	PostPreLoaded: function(p_to){
		FB.ui(
		{
			method:'feed',
			message: this.loadedPost.msg,
			to:p_to,
			picture: 'http://www.kazulife.com'+this.loadedPost.pic,
			name:this.loadedPost.name,
			link : 'http://apps.facebook.com/kazulife/' + this.loadedPost.link,
			caption: this.loadedPost.cap,
			description:(p_to > 0 ? this.loadedPost.descr2:this.loadedPost.descr)
		},		
		function(response)
		{
			g_confirm.Hide();
			if (response && response.post_id)
			{
				new Ajax.Request( '/callback/publishFB.php', { method: 'post', parameters: {f : facebook.loadedPost.id,det:facebook.loadedPost.det}});
			}
		});
	},
	placeOrder: function(){
		if (!this.logged)
		{
			this.delaydAct = 'facebook.placeOrder()';
			this.LateLogin();
			return;
		}
		var order_info = {'data':g_mainChar.id,'item_id':facebook.selectedOffer};
		var obj =
		{
			method: 'pay',
			order_info: order_info,
			purchase_type: 'item'
		};

		FB.ui(obj, facebook.RZcallback.bind(facebook));
	},
	RZcallback:function(data){
		if (data['order_id'])
		{
			if (this.selectOffValue > 5000)
			{
				g_mainChar.UpdateCredits( parseInt(g_mainChar.tokens) + parseInt(facebook.selectOffValue));
			}
			else
			{
				g_mainChar.UpdateTokens( parseInt(g_mainChar.tokens) + parseInt(facebook.selectOffValue));
			}
			UnloadCurrentInline();
		}
		else if (data['error_code'])
		{
		_echo("Transaction Failed! </br></br>"
		+ "Error message returned from Facebook:</br>"
		+ data['error_message']);
		} else {
		_echo("Transaction failed!");
		}
	},
	GetEMail: function(){
		FB.api( '/me/?fields=id,name,email&access_token='+this.session,function(response)
		{
			if (response.email && $('email'))
			{
				$('email').value = response.email;
			}
		});
	},
	CheckLike: function(){
		var query = FB.Data.query('SELECT user_id FROM like WHERE object_id={0} AND user_id={1}',this.appId, this.uid);
		query.wait(function(rows)
		{
			if (rows.length > 0 && rows[0].user_id == facebook.session.uid)
			{
				facebook.liked = true;
			}
			else
			{
				facebook.liked = false;
			}
		});
	}
};

var MovableMenu = Class.create({
	initialize: function( p_id){
		this.id = p_id;
		this.div = $(p_id);
		this.basePos = this.div.positionedOffset();
		this.basePos[0] /= g_world.ts;
		this.basePos[1] /= g_world.ts;
		this.move = false;
		this.out = !this.div.visible();
	},
	MoveOut: function( p_dir){
		if (this.out){return;}
		if(this.move){this.move.cancel();this.move = false;}
		this.out = true;
		var x = this.basePos[0];
		var y = this.basePos[1];
		switch (p_dir)
		{
			case 0: y -= 600;break;
			case 1: x += 1024;break;
			case 2: y += 600;break;
			case 3: x -= 1024;break;
		}
		this.div.setStyle({left:this.basePos[0]*g_world.ts+'px',top:this.basePos[1]*g_world.ts+'px'});
		this.move = new Effect.Move( this.div, {mode:'absolute',x:x*g_world.ts,y:y*g_world.ts,afterFinish:this.EndMove.bind(this)});
	},
	MoveIn: function( p_from){
		if (!this.out){return;}
		if(this.move){this.move.cancel();this.move = false;}
		this.out = false;
		this.div.show();
		var x = this.basePos[0];
		var y = this.basePos[1];
		switch (p_from)
		{
			case 0: y -= 600;break;
			case 1: x += 1024;break;
			case 2: y += 600;break;
			case 3: x -= 1024;break;
		}
		this.div.setStyle({left:x*g_world.ts+'px',top:y*g_world.ts+'px'});
		this.move = new Effect.Move( this.div, {mode:'absolute',x:this.basePos[0]*g_world.ts,y:this.basePos[1]*g_world.ts,afterFinish:this.EndMove.bind(this)});
	},
	EndMove: function(){
		if (this.out){this.div.hide();}
		this.move = false;
	}
});


var g_hintBox = {
	id: 'HintBox',
	created: false,
	effect: false,
	div: false,
	images: {top_right:'hb1.png',top_left:'hb2.png',bottom_left:'hb3.png',bottom_right:'hb4.png'},
	ShowFor: function( p_target, p_text, p_class){
		if(!$(p_target)){return;}
		if (!this.created)
		{
			this.Create();
		}
		if (this.effect)
		{
			this.effect.cancel();
		}
		
		this.div.update(p_text);

		var queue = $(this.id+'Q');
		queue.src='/i/h/'+this.images[p_class];
		var l_t1 = $(p_target).viewportOffset();
		var l_t2 = $(p_target).cumulativeScrollOffset();
		l_t1[0] += l_t2[0];l_t1[1] += l_t2[1];
		var l_s = $(p_target).getDimensions();
		var l_s2 = $(this.id).getDimensions();
		var l_x = l_t1[0];
		var l_y = l_t1[1];
		switch (p_class)
		{
			case 'top_right':{
				$(this.id).setStyle({left:(l_x+l_s.width)+'px',top:(l_y-l_s2.height-25)+'px'});
				queue.setStyle({position:"absolute",left:'0px',right:'auto',top:'auto',bottom:'-25px'});
				break;
			}
			case 'bottom_right':{
				$(this.id).setStyle({left:(l_x+l_s.width)+'px',top:(l_y+l_s.height+25)+'px'});
				queue.setStyle({position:"absolute",left:'0px',right:'auto',top:'auto',top:'-25px'});
				break;
			}
			case 'top_left':{
				$(this.id).setStyle({left:(l_x-l_s2.width)+'px',top:(l_y-l_s2.height-25)+'px'});
				queue.setStyle({position:"absolute",left:'auto',right:'0px',top:'auto',bottom:'-25px'});
				break;
			}
			case 'bottom_left':{
				$(this.id).setStyle({left:(l_x-l_s2.width)+'px',top:(l_y+l_s.height+25)+'px'});
				queue.setStyle({position:"absolute",left:'auto',right:'0px',top:'auto',top:'-25px'});
				break;
			}
		}
		this.effect = new Effect.Appear(this.id,{duration:0.5,afterFinish:this.EndEffect.bind(this)});//
	},
	EndEffect: function(){
		this.effect = false;
	},
	Create: function(){
		var temp = new Element('div',{id:this.id,'class':'BaseCadre2pxW'});
		temp.setStyle({position:'absolute','text-align':'center',display:'none',width:'300px',zIndex:2900});
		temp.update('<a href="javascript:;"onclick="g_hintBox.Hide();" onmouseover="tooltip.show(g_text.gen[\'close\'])"onmouseout="tooltip.hide();"><img class="i20 top_right" src="/i/b_drop.png"></a>');
		temp.insert('<div id="'+this.id+'In"style="margin:20px auto;width:300px;"></div>');
		temp.insert('<img id="'+this.id+'Q"style="position:absolute;width:64px;height:25px;">');
		$('body').insert(temp);
		this.created = true;
		this.div = $(this.id+'In');
	},
	Hide: function(){
		$(this.id).hide();
	}
};
