<!--

var scrollInt;
var scrTime, scrSt, scrDist, scrDur, scrInt;

function getResolution()
{
	if(screen.width >= 1024 && screen.height >= 768)
	{
		return "1024x768";
	}
	else
	{
		return "default";
	}
}

function playGame(playURL)
{
	sbt_fullWindow(playURL, false);
	document.fire("game:launched",
	{
		url: playURL
	});
}

function playFree(url)
{
	location.href = url + "?screen=" + getResolution();
}

function preparePlayLinks()
{
	$$("a.play_free", "a.play").each(function(a)
	{
		a.launchGame = function()
		{
			switch(a.className)
			{
				case "play" : playGame(a.readAttribute("href")); break;
				case "play_free" : playFree(a.readAttribute("href")); break;
				default : return true;	break;
			}
		}

		a.observe("click", function(e)
		{
			Event.stop(e);
			a.launchGame();
			return false;
		});
	});
}

function replaceAnchorLinks()
{
	$$("a").each(function(a)
	{
		if (a.href.indexOf("#") != -1 && a.href.indexOf(document.URL) != -1)
		{
			var targ = a.href.substring(a.href.indexOf("#") + 1);
			var targarr = document.getElementsByName(targ);

			if(targarr.length)
			{
				a.addClassName((targarr[0].offsetTop < a.offsetTop) ? "up" : "down");
				a.id = "__" + targ;
				a.observe("mousedown", function(e)
				{
					e.stop();
					scrollToAnchor(a.id.substring(2));
				});
				a.href = "#";
			}
		}
	});
}

function rotateAds()
{
	var slots = [];
	
	$$(".hn_ads").each(function(ads)
	{
		slots.push(ads.identify());
	});
	
	if(slots.length)
	{
		new PeriodicalExecuter(function(pe)
		{
			new Ajax.Request("/scripts/get-ads.php",
			{
				parameters:
				{
					"slot_name[]": slots
				},
				
				onSuccess: function(transport)
				{
					var ads = transport.responseText.evalJSON();
					
					new Hash(ads).each(function(slot)
					{
						$(slot.key).update(slot.value);
					});
				}
			});
		}, 6);
	}
}

function makeOpacity()
{
	$$(".opacity").each(function(elt)
	{
		elt.setOpacity(0.9);

		elt.observe("mouseover", function()
		{
			elt.setOpacity(1);
		});

		elt.observe("mouseout", function()
		{
			elt.setOpacity(0.9);
		});
	});
}

function makeFlags()
{
	if(!$("select-flags"))
	{
		return false;
	}

	$("select-flags").observe("click", function(e)
	{
		if($("select-flags").hasClassName("hover"))
		{
			//
		}
		else
		{
			e.stop();
			$("select-flags").addClassName("hover");
			$$("#select-flags a").invoke("blur");
		}
	});

	$("select-flags").observe("mouseleave", function(e)
	{
		$("select-flags").removeClassName("hover");
	});
}

function scrollPage()
{
	scrTime += scrInt;
	if (scrTime < scrDur) {
		window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );
	} else {
		window.scrollTo( 0, scrSt+scrDist );
		clearInterval(scrollInt);
	}
}

function scrollToAnchor(aname)
{
	var anchors, i, ele;
	
	if (!document.getElementById)
		return;

	anchors = document.getElementsByTagName("a");
	for (i=0;i<anchors.length;i++) {
		if (anchors[i].name == aname) {
			ele = anchors[i];
			i = anchors.length;
		}
	}

	if (window.scrollY)
		scrSt = window.scrollY;
	else if (document.documentElement.scrollTop)
		scrSt = document.documentElement.scrollTop;
	else
		scrSt = document.body.scrollTop;

	scrDist = ele.offsetTop - scrSt;
	scrDur = 500;
	scrTime = 0;
	scrInt = 10;

	clearInterval(scrollInt);
	scrollInt = setInterval( scrollPage, scrInt );
}


function findSWF(movieName)
{
	if(navigator.appName.indexOf("Microsoft") != -1)
	{
		return window[movieName];
	}
	else
	{
		return document[movieName];
	}
}



function easeInOut(t,b,c,d)
{
	return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
}
function onSubmitShowLoading(form, msg)
{
	return onEventShowLoading("submit", form, msg);
}

function onEventShowLoading(event, form, msg)
{
	preloadloading();

	$(form).observe(event, function()
	{
		showLoading(msg);
	});
}

function showLoading(msg)
{
	if(!msg)
	{
		if (txtPleaseWait)
			msg = txtPleaseWait;
		else msg = "Please wait...";
	}

	FullScreen.loading(msg);
}

function preloadloading()
{
	if(this.loaded)
	{
		return;
	}
	
	this.loaded = true;

	return preload(rscDir + "js/progress/progress_bar.gif", "progress_bar");
}

function preload(src, id)
{
	var img = new Element("img",
	{
		id: id,
		src: src,
		style: "display: none;"
	});

	$("main").appendChild(img);
}

function trim(aString)
{
    return String.replace(/^\s+/, "").replace(/\s+$/, "");
}
function ucwords(str)
{
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();    });
}


function checkCreditCard(cardNo, ccName)
{
	switch(ccName)
	{
		case "AmericanExpress" :
			ccName = "American Express";
		break;
	}
	var cards = {	'American Express': {	'length': '15',
											'prefixes': '34,37',
											'checkdigit': true},
					'Carte Blanche': {		'length': '14',
											'prefixes': '300,301,302,303,304,305,36,38',
											'checkdigit': true},
					'Diners Club': {		'length': '14',
											'prefixes': '300,301,302,303,304,305,36,38',
											'checkdigit': true},
					'Discover': {			'length': '16',
											'prefixes': '6011',
											'checkdigit': true},
					'Enroute': {			'length': '15',
											'prefixes': '2014,2149',
											'checkdigit': true},
					'JCB': {				'length': '15,16',
											'prefixes': '3,1800,2131',
											'checkdigit': true},
					'Maestro': {			'length': '16,18',
											'prefixes': '5020,6',
											'checkdigit': true},
					'MasterCard': {			'length': '16',
											'prefixes': '51,52,53,54,55',
											'checkdigit': true},
					'Solo': {				'length': '16,18,19',
											'prefixes': '6334,6767',
											'checkdigit': true},
					'Switch': {				'length': '16,18,19',
											'prefixes': '4903,4905,4911,4936,564182,633110,6333,6759',
											'checkdigit': true},
					'Visa': {				'length': '13,16',
											'prefixes': '4',
											'checkdigit': true},
					'Visa Electron': {		'length': '16',
											'prefixes': '417500,4917,4913',
											'checkdigit': true}};

	var cardType = -1;

	if(!$H(cards).get(ccName))
	{
		return false;
	}
	else if(!/^[0-9]{13,19}$/.test(cardNo))
	{
		return false;
	}

	if($H(cards).get(ccName).checkdigit)
	{
		var checksum = 0;
		var mychar = "";
		var j = 1;

		for(var i = cardNo.length - 1; i >= 0; i--)
		{
			var calc = cardNo[i] * j;

			if(calc > 9)
			{
				checksum = checksum + 1;
				calc = calc - 10;
			}

			checksum += calc;

			j = (j == 1 ? 2 : 1);
		}

		if(checksum % 10 != 0)
		{
			return false;
		}
	}

	var prefix = $H(cards).get(ccName).prefixes.split(/,/);
	var PrefixValid = false;

	for(var i = 0; i < prefix.length; i++)
	{
		if(cardNo.search(prefix[i]) == 0)
		{
			PrefixValid = true;
			break;
		}
	}

	if (!PrefixValid)
	{
		return false;
	}

	var LengthValid = false;
	var lengths = $H(cards).get(ccName).length.split(/,/);

	for(var j = 0; j < lengths.length; j++)
	{
		if(cardNo.length == lengths[j])
		{
			LengthValid = true;
			break;
		}
	}

	if(!LengthValid)
	{
		return false;
	}

	return true;
}

function getEventListeners(elt)
{
	return Event.cache[$(elt)._prototypeEventID];
}

function setEventListeners(elt, events)
{
	$H(events).each((function(e)
	{
		e.value.each((function(f)
		{
			$(elt).observe(e.key, f);
		}).bind(this));
	}).bind(this));
}

function sbt_fullWindow(url, scrollbar)
{
	var str = "left=0,screenX=0,top=0,screenY=0,resizable=yes";
	var ah = screen.availHeight;
	var aw = screen.availWidth;
	str += ",height=" + ah;
	str += ",innerHeight=" + ah;
	str += ",width=" + aw;
	str += ",innerWidth=" + aw;
	str += ",scrollbars=" + (scrollbar ? "yes" : "no");
	var win = window.open(url, "sbt_full_window", str);
	win.focus();

	new PeriodicalExecuter(function(pe)
	{
		if(win.closed)
		{
			pe.stop();

			document.fire("sbt_full_window:closed",
			{
				url: url
			});
		}
	}, 1);
}

function refreshFooter()	// IE6 fix
{
	if($("footer"))
	{
		$("footer").style.position = "relative";
		$("footer").style.position = "absolute";
	}
}

function emailCheck(email)
{
	if(/^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$/.test(email))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function basename(path)
{
	return path.replace(/\\/g, '/').replace(/.*\//, '').replace(/\?.*/, '');
}

function SetCookie(name, value)
{
	var argv=SetCookie.arguments;
	var argc=SetCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
		((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
		((path==null) ? "" : ("; path="+path))+
		((domain==null) ? "" : ("; domain="+domain))+
		((secure==true) ? "; secure" : "");
}

function getCookieVal(offset)
{
	var endstr=document.cookie.indexOf (";", offset);
	if(endstr==-1)
    	endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name)
{
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while(i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg)
			return getCookieVal (j);

        i=document.cookie.indexOf(" ",i)+1;

        if(i==0)
			break;
	}
	return null;
}

var FontSizer = new Class.create
({
	getStep: function()
	{
		if(this.options.cookie)
		{
			var step = GetCookie("HNFontSizer");
			
			if(step && !isNaN(step))
			{
				this.step = step;
			}
			else
			{
				this.step = 0;
			}
		}

		return parseInt(this.step);
	},

	setStep: function(step)
	{
		this.step = parseInt(step);
	
		if(this.options.cookie)
		{
			SetCookie("HNFontSizer", this.step, this.options.cookie_lifetime, "/");
		}
	},

	doStep: function(step)
	{
		var next = parseInt(this.getStep() + (step = parseInt(step)));
		var min = this.options.range.min();
		var max = this.options.range.max();

		if(next >=  min && next <= max)
		{
			this.setStep(next);
			
			$$(this.options.selector).each(function(fs)
			{
				if(next + step > max || next + step < min)
				{
					if(fs.readAttribute("rel") == step)
					{
						fs.setStyle(
						{
							cursor: "not-allowed"
						});
					}
				}
				else
				{
					fs.setStyle(
					{
						cursor: "pointer"
					});
				}
			});
			
			return true;
		}
		else
		{
			return false;
		}
	},

	doFont: function(step)
	{
		if(!this.doStep(step))
		{
			return false;
		}
		
		$$(this.options.elements).each(function(elt)
		{
			if(typeof(elt.current) == "undefined")
			{
				elt.current = 0;
				elt.sizes = [this.options.size + "px"];
			}

			if(parseInt(step) < 0)
			{
				elt.current--;

				if(elt.current < 0)
				{
					elt.sizes.unshift((parseInt(elt.sizes[elt.current + 1]) * (1 - this.options.coef)) + "px");
					elt.current = 0;
				}
			}
			else if(parseInt(step) > 0)
			{
				elt.current++;

				if(elt.current >= elt.sizes.length)
				{
					elt.sizes.push((parseInt(elt.sizes[elt.current - 1]) * (1 + this.options.coef)) + "px");
					elt.current = elt.sizes.length - 1;
				}
			}

			elt.setStyle(
			{
				fontSize: elt.sizes[elt.current]
			});
		}, this);
	},

	initialize: function(options)
	{
		this.options =
		{
			selector: ".fontSizer",
			elements: "#main,#sidebar_left",
			coef: .1,
			cookie: true,
			cookie_lifetime: null,
			size: 13,
			range: [0, 4]
		};

		Object.extend(this.options, options || {});

		var step = this.getStep();
		var sgn = step / Math.abs(step);
		var min = this.options.range.min();
		var max = this.options.range.max();

		this.setStep(0);

		for(var i = 0; i < Math.abs(step); i++)
		{
			this.doFont(sgn);
		}

		$$(this.options.selector).each(function(fs)
		{
			if(this.getStep() + parseInt(fs.readAttribute("rel")) >= max || this.getStep() + parseInt(fs.readAttribute("rel")) <= min)
			{
				fs.setStyle(
				{
					cursor: "not-allowed"
				});
			}
		
			fs.observe("click", (function(e)
			{
				this.doFont(fs.readAttribute("rel"));
			}).bindAsEventListener(this));
		}, this);
	}
});

function TotalGamesCounter()
{
	if(!$("TotalGamesCounterNB"))
	{
		return;
	}

	new Ajax.Request("/scripts/total-games-counter?ajax=PAGE:nbGames",
	{
		onSuccess: function(transport)
		{
			var nb_previous = $("TotalGamesCounterNB").innerHTML;
			var nb_new = transport.responseText.evalJSON(true);

			if(nb_new.nbGames != nb_previous)
			{
				$("TotalGamesCounterNB").update(nb_new.nbGames);
				new Effect.Pulsate("TotalGamesCounterNB", {pulses: 3, duration: 1.5});
			}
		}
	});

	setTimeout("TotalGamesCounter();", 300000);
}

function tellAFriend()
{
	$$("a.tell-a-friend").each(function(a)
	{
		a.observe("click", function(e)
		{
			e.stop();
			window.open(a.readAttribute("href"), "taf_win", "width=470,height=700");
		});
	});
}

var stdDialog = Class.create(
{
	modal: true,			// if false you can exit with a click outside
	closeButton: true,		// add a close button

	initialize: function()
	{
		if(!$("sbt_fullscreen"))
		{
			var div = Builder.node("div",
			{
				id: "sbt_fullscreen",
				className: $A(arguments).join(" ")
			});

			document.body.appendChild(div);

			$("sbt_fullscreen").update("<div id='sbt_fullscreen_background'>&nbsp;</div>" +
												"<div id='sbt_fullscreen_window'></div>");

			document.observe("keyup", this.onEscapeOut.bindAsEventListener(this));
			$("sbt_fullscreen_background").observe("click", this.clickOut.bindAsEventListener(this));
			$("sbt_fullscreen").hide();
		}

		if(!$("sbt_fullscreen").visible())
		{
			$("sbt_fullscreen_background").hide();
			$("sbt_fullscreen_background").appear(
			{
				from: 0,
				to: 0.5
			});
		}

		this.setStyle(
		{
			border: "1px solid black",
			backgroundColor: "#fff"
		});

		this.show();

		if(this.initialize.arguments.length && this.initialize.arguments[0] != undefined)
		{
			this.set(this.initialize.arguments[0]);
		}
		else
		{
			this.set('<div align="center"><img src="'+rscDir+'img/icons/loading.gif" alt="'+txtLoading+'" /></div>');
		}
	},

	onEscapeOut: function(e)
	{
		if(e.keyCode == Event.KEY_ESC)
		{
			this.clickOut();
		}
	},

	clickOut: function()
	{
		if(!this.modal)
		{
			this.close();
		}
	},

	destroy: function()
	{
		this.close();

		if($("sbt_fullscreen"))
		{
			document.stopObserving("keyup", this.onEscapeOut.bindAsEventListener(this));
			$("sbt_fullscreen_background").stopObserving("click", this.clickOut.bindAsEventListener(this));
			$("sbt_fullscreen").remove();
		}
	},

	show: function()
	{
		$("sbt_fullscreen").show();
	},

	close: function()
	{
		if($("sbt_fullscreen"))
		{
			$("sbt_fullscreen").hide();
			document.fire("dialog:close");
		}
	},

	set: function(content)
	{
		$("sbt_fullscreen_window").update("");

		if(this.closeButton)
		{
			var close = Builder.node('div', {align: 'right'},
				img = Builder.node('img',
				{
					id: 'sbt_fullscreen_close',
					src: rscDir+'img/icons/closelabel.gif'
				}));

			$("sbt_fullscreen_window").appendChild(close);
			$("sbt_fullscreen_close").observe("click", this.clickOut.bindAsEventListener(this));

			img.setStyle(
			{
				cursor: 'pointer',
				cssFloat: 'right'
			});
		}

		$("sbt_fullscreen_window").appendChild(inner = Builder.node('div', {id: "sbt_fullscreen_inner"}));
		inner.update(content);
		this.center();
	},
	
	setWidth: function(width)
	{
		$("sbt_fullscreen_window").setStyle(
		{
			width: width + "px"
		});
		
		this.center();
	},

	center: function()
	{
		if($("sbt_fullscreen_window").getHeight() > document.viewport.getHeight())
		{
			$("sbt_fullscreen_inner").setStyle(
			{
				height: (document.viewport.getHeight() - 100) + "px",
				paddingRight: "15px",
				margin: "5px",
				overflowY: "scroll",
				clear: "both"
			});
		}
	
		$("sbt_fullscreen_window").setStyle(
		{
			top: parseInt((document.viewport.getHeight() - $("sbt_fullscreen_window").getHeight()) / 2) + "px",
			left: parseInt((document.viewport.getWidth() - $("sbt_fullscreen_window").getWidth()) / 2) + "px"
		});
	},

	setStyle: function(style)
	{
		return $("sbt_fullscreen_window").setStyle(style);
	}
});

var warnDialog = Class.create(stdDialog,
{
	initialize: function($super, txt)
	{
		$super("sbt_fullscreen_orange");
	
		this.modal = false;
		this.setWidth(360);
		this.set("<div style='margin: 0px auto; text-align: left; font-size: 10pt;'><img src='" + rscDir + "img/icons/maintenance.jpg' style='float: left; padding: 5px;' />" + txt + "</div>");
	}
});

var FullScreen =
{
	win: false,

	initialize: function()
	{
		if(!this.win)
		{
			this.win = new stdDialog("sbt_fullscreen_orange");
			this.win.closeButton = false;
		}
	},

	loading: function(msg)
	{
		this.show('<div id="window-title">' + msg + '</div>' +
							'<div id="window-content"><img src="'+rscDir+'js/progress/progress_bar.gif"></div>');
	},

	show: function(msg)
	{
		this.initialize();
		this.win.modal = true;
		this.win.show();
		this.win.set(msg);
	},

	hide: function()
	{
		this.win.close();
	},

	noModal: function()
	{
		this.win.modal = false;
		this.win.closeButton = true;
	}
};

var AvatarIcon =
{
	status: null,

	initialize: function(status, callBack)
	{
		AvatarIcon.status = status;
	
		var a = Builder.node("a",
			{
				href: "#"
			},
				img = Builder.node("img",
				{
					src: AvatarIcon.getSRC(AvatarIcon.status)
				}));
				
		$("avatar-icons").update(a);

		a.observe("click", function(e)
		{
			e.stop();
			//AvatarIcon.update(AvatarIcon.status);
			
			if(callBack)
			{
				callBack();
			}
		});
	},

	update: function(status)
	{
		AvatarIcon.status = status;
		img.src = AvatarIcon.getSRC(AvatarIcon.status);
	},

	getSRC: function(status)
	{
		return rscDir+"img/avatar/avatar-" + (status ? "enable" : "disable") + ".jpg";
	}
};

var FAQ =
{
	faqs: [],

	initialize: function()
	{
		$$("a.faq_link").each(function(a)
		{
			var params = a.readAttribute("href").toQueryParams();
			if(params.id != undefined)
			{
				a.observe("click", function(e)
				{
					FAQ.show(params.id);

					Event.stop(e);
				});
			}
		});
	},

	show: function(id)
	{
		if(this.faqs[id])
		{
			var win = new stdDialog();
			win.modal = false;
			win.set(this.faqs[id]);
		}
		else
		{
			var win = new stdDialog();
			win.modal = false;

			new Ajax.Request("/ajax-faq?ajax",
			{
				parameters:
				{
					id: id
				},

				onSuccess: function(transport)
				{
					win.set(FAQ.faqs[id] = transport.responseText);
				}
			});
		}
	}
};

function lg_init()
{
	if(!isPrototype)
	{
		return false;
	}

	$$(".listgame_box").each(function(box)
	{
		var parts = box.id.split(/_/);
		var id = parseInt(parts[parts.length - 1]);
		var duration = 0.5;
		var queue = {
						position: 'end',
						scope: 'listgame_box_' + id,
						limit: 2
					};

		box.ismouseout = true;
		box.preview = $("splash_" + id).down(".listgame_preview");
		box.brief = $("splash_" + id).down(".listgame_brief");
		box.effects = [];

		box.isIn = function(e)
		{
			var pos = box.cumulativeOffset();
			var dim = box.getDimensions();

			return ((e.pointerX() > pos.left) &&
				(e.pointerX() < (pos.left + dim.width)) &&
				(e.pointerY() > pos.top) &&
				(e.pointerY() < (pos.top + dim.height)));
		}

		box.cancel = function()
		{
			box.effects.each(function(effect)
			{
				if(effect)
				{
					effect.cancel();
				}
			});
		}

		box.slideUp = function()
		{
			box.preview.hide();
			box.brief.show();

			return;

			if(box.slidingup)
			{
				return;
			}

			box.effects[0] = Effect.SlideUp(box.preview,
			{
				queue: queue,
				delay: 0.1,
				duration: duration,

				beforeStart: function()
				{
					box.slidingup = true;
				},

				afterFinish: function()
				{
					box.effects[1] = Effect.Appear(box.brief,
					{
						duration: duration,

						afterFinish: function()
						{
							box.slidingup = false;
						}
					});
				}
			});
		}

		box.slideDown = function()
		{
			box.brief.hide();
			box.preview.show();

			return;

			if(box.slidingdown)
			{
				return;
			}

			box.effects[2] = Effect.Fade(box.brief,
			{
				queue: queue,
				delay: 1,
				duration: duration,

				beforeStart: function()
				{
					box.slidingdown = true;
				}, 

				afterFinish: function()
				{
					box.effects[3] = Effect.SlideDown(box.preview,
					{
						duration: duration,

						afterFinish: function()
						{
							box.slidingdown = false;
						}
					});
				}
			});
		}
		//box.getElementsBySelector(".listgame_splash", ".listgame_title").each(function(element)
		box.select(".listgame_splash", ".listgame_title").each(function(element)
		{
			element.observe("click", function(e)
			{
				if(a = box.down(".listgame_right a"))
				{
					if(getEventListeners(a).click)
					{
						getEventListeners(a).click.each(function(f)
						{
							f(e);
						});
					}
					else if(a.launchGame)
					{
						a.launchGame();
					}
					else
					{
						location.href = a.readAttribute("href");
					}
				}
			});
		});

		box.observe("mouseover", function(e)
		{
			e.stop();

			if(box.down(".listgame_right a"))
			{
				box.setStyle(
				{
					cursor: "pointer"
				});
			}

			if(box.ismouseout)
			{
				box.ismouseout = false;

				box.fire("box:mouseenter", box);
			}
		}, false);
		
		box.observe("mouseout", function(e)
		{
			e.stop();

			if(!box.isIn(e))
			{
				box.ismouseout = true;

				box.fire("box:mouseleave", box);
			}
		}, false);

		box.observe("box:mouseenter", function(e)
		{
			if(box.slidingdown)
			{
				return;
			}

			e.memo.slideUp();
		});

		box.observe("box:mouseleave", function(e)
		{
			e.memo.slideDown();
		});

	});
}
var AjaxPopup = Class.create(
{
	initialize: function(id)
	{
		$(id).observe("click", (function(e)
		{
			e.stop();
			this.load($(id).readAttribute("rel"));
		}).bindAsEventListener(this));
	},

	load: function(form_name)
	{
		AjaxPopup.open(form_name);
	}
});
AjaxPopup.initialize = function()
{
	$$("a.ajax-popup").each(function(link)
	{
		new AjaxPopup(link);
	});
}
AjaxPopup.history = [];
AjaxPopup.open = function(form_name)
{
	AjaxPopup.history.push(form_name);
	AjaxPopup.win = new stdDialog("sbt_fullscreen_orange");
	AjaxPopup.win.modal = false;
	AjaxPopup.win.set("<div id='sbt_fullscreen_orange_content'></div>");

	new Ajax.Updater("sbt_fullscreen_orange_content", "/scripts/popup",
	{
		method: "get",
		evalScripts: true,
		parameters:
		{
			ajax: "",
			form_name: form_name
		},
		onLoading: (function()
		{
			$("sbt_fullscreen_orange_content").update("Loading.");
			$("sbt_fullscreen_orange_content").direction = 1;
			$("sbt_fullscreen_orange_content").initialHeight = $("sbt_fullscreen_orange_content").getHeight();

			AjaxPopup.pe = new PeriodicalExecuter(function(pe)
			{
				do
				{
					var redo = false;

					if($("sbt_fullscreen_orange_content").direction > 0)
					{
						$("sbt_fullscreen_orange_content").update($("sbt_fullscreen_orange_content").innerHTML + ".");
					}
					else
					{
						$("sbt_fullscreen_orange_content").update($("sbt_fullscreen_orange_content").innerHTML.substr(0, $("sbt_fullscreen_orange_content").innerHTML.length - 1));
					}

					if($("sbt_fullscreen_orange_content").getHeight() > $("sbt_fullscreen_orange_content").initialHeight ||
						$("sbt_fullscreen_orange_content").innerHTML.charAt($("sbt_fullscreen_orange_content").innerHTML.length - 1) != ".")
					{
						$("sbt_fullscreen_orange_content").direction = -$("sbt_fullscreen_orange_content").direction;
						redo = true;
					}
				}while(redo);
			}, 0.01);
		}).bind(this),
		onComplete: (function()
		{
			AjaxPopup.pe.stop();
			AjaxPopup.win.center();
			
			if(id = $("sbt_fullscreen_orange_content").down("form"))
			{
				preloadloading();
			
				$(id).observe("submit", (function(e)
				{
					var ok = true;

					$(id).getElements().each((function(elt)
					{
						if(!elt.present())
						{
							ok = false;
							e.stop();
							
							if(!($("please-enter")))
							{
								if (!txtEnterYourInfo)
									txtEnterYourInfo = "Please enter your information.";
								$(id).insert(
								{
									after: Builder.node("div",
									{
										id: "please-enter",
										align: "center",
										style: "font-weight: bold; font-size: 8pt; color: red; padding: 2px;"
									}, txtEnterYourInfo)
								});
							}

							throw $break;
						}
					}).bind(this));

					if(ok)
					{
						$(id).hide();
						$(id).insert(
						{
							before: Builder.node("div",
							{
								align: "center",
								style: "padding: 15px"
							},
							$("progress_bar").remove())
						});
						$("progress_bar").show();
					}
				}).bindAsEventListener(this));

				$(id).getInputs("reset").each((function(input)
				{
					input.observe("click", (function(e)
					{
						e.stop();
						AjaxPopup.back();
					}).bindAsEventListener(this));
				}).bind(this));
			}
		}).bind(this)
	});
}
AjaxPopup.back = function()
{
	AjaxPopup.history.pop();

	if(form_name = AjaxPopup.history.pop())
	{
		AjaxPopup.open(form_name);
	}
}





var DefaultForm = Class.create(
{
	pe: null,

	initialize: function(id)
	{
		$(id).observe("submit", (function(e)
		{
			var ok = true;

			$(id).getElements().each((function(elt)
			{
				if(elt.the_default && $F(elt) == elt.the_default)
				{
					ok = false;
					e.stop();

					var win = new stdDialog("sbt_fullscreen_orange");
					win.modal = false;
					if (txtEnterYourInfo)
						win.set(txtEnterYourInfo);
					else
						win.set("Please enter your information.");

					throw $break;
				}
			}).bind(this));

			if(ok)
			{
				$(id).setOpacity(0.5);
			}
		}).bindAsEventListener(this));

		$(id).getInputs("reset").each((function(input)
		{
			input.observe("click", (function(e)
			{
				e.stop();
				AjaxPopup.back();
			}).bindAsEventListener(this));
		}).bind(this));

		$(id).select("input[type='text']", "input[type='password']").each((function(input)
		{
			input.the_default = $F(input);
			input.the_type = input.readAttribute("type");

			input.setDefaultStyle = function()
			{
				try
				{
					input.type = "text";
				}
				catch(e)
				{
				}

				input.setStyle(
				{
					padding: "2px",
					color: "#999",
					border: "1px solid #00679a"
				});
			}

			input.observe("focus", (function(e)
			{
				try
				{
					input.type = input.the_type;
				}
				catch(e)
				{
				}

				if($F(input) == input.the_default)
				{
					input.value = "";
				}

				input.setStyle(
				{
					color: "#000"
				});
			}).bindAsEventListener(this));

			input.observe("blur", (function(e)
			{
				DefaultForm.removeMessage(input);

				if($F(input) == "")
				{
					input.setDefaultStyle();
					input.value = input.the_default;
				}
			}).bindAsEventListener(this));

			input.setDefaultStyle();
		}).bind(this));
	}
});
DefaultForm.addMessage = function(where, msg)
{
	if($("msg_" + $(where).identify()))
	{
		$("msg_" + $(where).identify()).update(msg);
	}
	else
	{
		var feedback = Builder.node("div",
		{
			id: "msg_" + $(where).identify(),
			className: "msg_form"
			//style: "font-size: 8pt; float: right; padding: 5px 0px 0px 0px;"
		}, msg);

		where.insert(
		{
			after: feedback
		});
	}
}
DefaultForm.removeMessage = function(where)
{
	if($("msg_" + $(where).identify()))
	{
		$("msg_" + $(where).identify()).remove();
	}
}
DefaultForm.addIcon = function(field, filename)
{
	DefaultForm.removeIcon(field);

	var icon = Builder.node("img",
	{
		id: "icon_" + $(field).identify(),
		src: rscDir + "img/icons/" + filename,
		style: "float: right; padding: 4px 1px 0px 10px;"
	});

	$(field).insert(
	{
		before: icon
	});
}
DefaultForm.removeIcon = function(field)
{
	if($("icon_" + $(field).identify()))
	{
		$("icon_" + $(field).identify()).remove();
	}
}
var ListGames =
{
	areas: new Array("memoire", "attention", "langage", "fonctions-executives", "visuo-spatial"),
	tpl_playLink: new RegExp("\/jeux\/jouer\/(.*)"), // Play Link
	tpl_gameInfoLink: new RegExp("\/jeux\/([-a-z]+)\/(.*)"), // game info link
	tpl_freeGames: new RegExp("\/jeux\/gratuits"), // Free games (list)
	tpl_sectors: new RegExp("\/jeux"), // sector
	tpl_sectorsBis: new RegExp("\/jeux(.*)$", "gi"), // sector with gi at the end...
	gameUrl: "/jeux",
	docTitle: "Entrainement Cérébral - ",
	
	contents: new Array(),

	initialize: function()
	{
		ListGames.update(area = ListGames.getArea(location.href));
	},
	
	setParams: function(areaList, playLink, gameInfoLink, freeGames, sectors, sectorsBis, urlGame, pageTitle)
	{
		ListGames.areas = areaList;
		ListGames.tpl_playLink = playLink;
		ListGames.tpl_gameInfoLink = gameInfoLink;
		ListGames.tpl_freeGames = freeGames;
		ListGames.tpl_sectors = sectors;
		ListGames.tpl_sectorsBis = sectorsBis;
		ListGames.docTitle = pageTitle;
		ListGames.gameUrl = urlGame;
	},
	
	start: function()
	{
		$("listgame_games").innerHTML = "";
		ListGames.initialize();

		this.areas.each(function(area)
		{
			ListGames.load(area, true);
		});

		new PeriodicalExecuter(ListGames.initialize, 0.1);
	},

	cancelBox: function()
	{
		$$(".listgame_box").each(function(box)
		{
			box.cancel();
		});
	},

	getArea: function(href)
	{
		var area = this.areas[0];

		if(path = new RegExp(this.areas.join("|")).exec(href))
		{
			area = path[0];
		}

		return area;
	},
	
	makeAppear: function(id)
	{
		$('game_' + id).hide();
		setTimeout(function()
		{
			if($('game_' + id))
			{
				Effect.Appear('game_' + id, 
				{
					duration: 1
				});
			}
		}, 500);
	},

	load: function(area, asynchronous)
	{
		if(this.contents[area])
		{
			return;
		}

		new Ajax.Request(ListGames.gameUrl + "/" + area,
		{
			method: "GET",
			asynchronous: asynchronous,
			parameters: 
			{
				ajax: "PAGE:TITLE:title,PAGE:MainTitle,TPL:CONTENT:games"
			},
			onLoading: function()
			{
				if(!asynchronous)
				{
					$("page").setStyle({cursor: "progress"});
				}
			},
			onSuccess: function(transport)
			{
				if(!asynchronous)
				{
					$("page").setStyle({cursor: "auto"});
				}
				
				ListGames.contents[area] = transport.responseText.evalJSON();
			},
			onFailure: function()
			{
				return false;
			}
		});

		return true;
	},
	
	update: function(area)
	{
		if(area == this.current_area)
		{
			return true;
		}
		else
		{
			document.fire("listgame:changed", 
			{
				area: area
			});

			this.current_area = area;
		}

		this.load(area, false);
		this.cancelBox();

		$("listgame_title").update(this.contents[area].MainTitle);
		document.title = ListGames.docTitle + this.contents[area].title;
		
		$("listgame_games").update(this.contents[area].games);
		ListGames.initializeLinks();
		preparePlayLinks();

		return true;
	},

	initializeLinks: function()
	{
		lg_init();

		$$("a").each(function(a)
		{
			var href = a.readAttribute("href");
		// /games/play/(.*)	<- Play link
		// /games/([a-z]+)/(.*)	<- game info link
		// /games/([a-z]+)		<- sector
			if (!a.url)
			{
				if (ListGames.tpl_playLink.test(a.href)// Play Link
					|| ListGames.tpl_gameInfoLink.test(a.href)// game info link
					|| ListGames.tpl_freeGames.test(a.href))// Free games (list)
				{
					a.url = href;
				}
				else if (ListGames.tpl_sectors.test(a.href))// sector
				//if(/\/games/.test(a.href) && !/\.html|\.php/.test(a.href) && )
				{
					if(path = new RegExp(ListGames.areas.join("|")).exec(href))
					{
						area = path[0];
						a.url = href;
						a.href = href.replace(ListGames.tpl_sectorsBis, ListGames.gameUrl + "#" + area);
					}
					else a.url = href;
				}
			}
		});
	}
};

var HardPopup = Class.create(
{
	initialize: function(link)
	{
		var popup = $(link.readAttribute("rel"));

		if(popup)
		{
			var lightbox = $("hard-popup");
			var background = lightbox.down(".fullscreen_background");
			var win = lightbox.down(".fullscreen_window");
			var inner = lightbox.down(".fullscreen_inner");

			link.observe("click", function(e)
			{
				e.stop();

				HardPopup.close();

				popup.show();

				if(!lightbox.visible())
				{
					lightbox.show();
					background.hide();
					background.appear(
					{
						from: 0,
						to: 0.5
					});
				}

				if(win.getHeight() > document.viewport.getHeight())
				{
					inner.setStyle(
					{
						height: (document.viewport.getHeight() - 100) + "px",
						paddingRight: "15px",
						margin: "5px",
						overflowY: "scroll",
						clear: "both"
					});
				}

				win.setStyle(
				{
					top: parseInt((document.viewport.getHeight() - win.getHeight()) / 2) + "px",
					left: parseInt((document.viewport.getWidth() - win.getWidth()) / 2) + "px"
				});
			});


			if(!popup.ok)
			{
				preloadloading();

				popup.ok = true;

				popup.observe("submit", (function(e)
				{
					var ok = true;

					popup.getElements().each((function(elt)
					{
						if(!elt.present())
						{
							e.stop();
						
							ok = false;

							if(!($("please-enter")))
							{
								if (!txtEnterYourInfo)
									txtEnterYourInfo = "Please enter your information.";
								popup.insert(
								{
									bottom: Builder.node("div",
									{
										id: "please-enter",
										align: "center",
										style: "font-weight: bold; font-size: 8pt; color: red; padding: 2px;"
									}, txtEnterYourInfo)
								});
							}
							else
							{
								popup.insert(
								{
									bottom: $("please-enter").remove()
								});
							}

							throw $break;
						}
					}).bind(this));

					if(ok)
					{
						popup.hide();
						popup.insert(
						{
							before: Builder.node("div",
							{
								align: "center",
								style: "padding: 15px"
							},
							$("progress_bar").remove())
						});
						$("progress_bar").show();
					}
				}).bindAsEventListener(this));
			}
		}
	}
});
HardPopup.initialize = function()
{
	$$("a.hard-popup").each(function(link)
	{
		new HardPopup(link);
	});

	$("hard-popup").down(".fullscreen_close").observe("click", function()
	{
		HardPopup.close();
		$("hard-popup").hide();
	});
}
HardPopup.close = function()
{
	$("hard-popup").select(".fullscreen_content").invoke("hide");
}

function hn_main()
{
	preparePlayLinks();
	replaceAnchorLinks();
	refreshFooter();

	if(isPrototype)
	{
		makeOpacity();
		lg_init();
		TotalGamesCounter();
		ListGames.initializeLinks();
		FAQ.initialize();
		makeFlags();
		new FontSizer();
		tellAFriend();

		AjaxPopup.initialize();
		HardPopup.initialize();
		
		$$("#TotalGamesCounter", "#avatar-icons", ".tooltips").each(function(elt)
		{
			new Tooltip(elt,
			{
				delay: 50,
				opacity: 90,
				appearDuration: 0,
				hideDuration: 0,
				backgroundColor: '#e6f0f8',
				borderColor: '#3274d5',
				textColor: 'darkblue',
				maxWidth: 250
			});
		});
	}
}

var isPrototype = (typeof(Prototype) != "undefined");

if(isPrototype)
{
	document.observe("dom:loaded", hn_main);
}
else
{
	window.onload = hn_main;
}

-->

