var ah, me = document.title, p = parseInt($("meta[name=p]").attr("content"), 10), IE = document.all, traceCount = 0;
var spinner = "<img src=/img/spinner.gif class=spinner />";

var fadeInStep = 20, fadeOutStep = 30, zoomInStep = 1, zoomOutStep = 10, scroller = 0, ammount = 0, sloMo = 1;
var eventsVisible = false, dragHot = false, ddEnabled = false, keyPressed = -1, brTime = new Array();
var inTimer = new Array(), outTimer = new Array(), lastOpac = new Array(0, 0, 0, 0), standardTimer = 0, contentTimer = 1, menuTimer = 2, selektorTimer = 3;
var mon = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

function selektorInit() {
	if (window.waitSlk) clearTimeout(waitSlk);
	LoadCss("/resources/selektor/selektor.css", "all");
	LoadScript("/resources/selektor/selektor.js");
}

function modalSwitch() {
	var el = "modalizer";
	var E = $("#" + el);

	if (E.is(":hidden")) {
		E.width($(document).width());
		E.height($(document).height());
		jFadeIn(el, 250, .65);
	}
	else {
		jFadeOut(el, 350);
	}
}

function menuInit() {
	_lastMenu = ""; 	 										/* GLOBAL! */
	_updateMenu = function() {									/* GLOBAL! */
		if (window.outTimer) clearTimeout(outTimer);
	}
	_resetMenu = function() {									/* GLOBAL! */
		if (window.outTimer) clearTimeout(outTimer);
		outTimer = window.setTimeout("closeMenu();", 350);
	}

	var config = {
		sensitivity: 2,
		interval: 50,
		over: function() { showMenu(this.rel) },
		timeout: 0,
		out: fnDummy
	};

	$("a[rel!=]").hoverIntent(config);
	$("div.ddMenu").appendTo("body");
	$("span.ddHelper").hover(
		function() { _updateMenu(); },
		function() { _resetMenu(); }
	);
	$("div.ddMenu").hover(
		function() { _updateMenu(); },
		function() { if ($(this).attr("rel") != "noAuto") _resetMenu(); }
	);
}

function showMenu(name) {
	if (name != _lastMenu) {
		closeMenu();
		var D = $("#" + name);
		if (D.attr("rel") != "noAuto") document.onclick = function() { closeMenu(_lastMenu); }
		D.css($("a[rel=" + name + "]").offset({ lite: true, scroll: false }));
		if (D.is(":hidden")) D.slideDown(150);
		_lastMenu = name;
	}
}

function closeMenu(name) {
	if (_lastMenu != "") {
		if (!name) name = _lastMenu;
		var U = $("#" + name);
		if (U.is(":visible")) {
			U.slideUp(100);
			document.onclick = "";
			_lastMenu = "";
		}
	}
}

fnDummy=function(){}

$.fn.clickUrl=function(){var regexp=/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&amp;%@!\-\/]))?)/gi;this.each(function(){$(this).html($(this).html().replace(regexp,'<a href="$1">$1</a>'));});return $(this);}
$.fn.mousehold=function(timeout,f){if(timeout&&typeof timeout=="function"){f=timeout;timeout=100;}if(f&&typeof f=="function"){var timer=0;var fireStep=0;return this.each(function(){$(this).mousedown(function(){fireStep=1;var ctr=0;var t=this;timer=setInterval(function(){ctr++;f.call(t,ctr);fireStep=2;},timeout);});clearMousehold=function(){clearInterval(timer);if(fireStep==1)f.call(this,1);fireStep=0;};$(this).mouseout(clearMousehold);$(this).mouseup(clearMousehold);});}}
$.fn.centerMe=function(options){var opt={force:false,container:window,cb:null};$.extend(opt, options);return this.each(function(i){var el=$(this);var jWin=$(opt.container);var isWin=opt.container==window;if(opt.force){if(isWin)el.remove().appendTo("body");else el.remove().appendTo(jWin.get(0));}el.css("position","absolute");var fudge=isWin?2.0:1.8;var x=(isWin?jWin.width():jWin.outerWidth())/2-el.outerWidth()/2;var y=(isWin?jWin.height():jWin.outerHeight())/fudge-el.outerHeight()/2;el.css("left",x+jWin.scrollLeft());el.css("top",y+jWin.scrollTop());if(opt.cb)opt.cb(this);});}

function IdealA() { $("a").focus(function() { if (this.blur) this.blur(); }); $("a[href=#]").attr("href", "").bind("click", function() { return false; }); }
function LoadCss(href, media) { var header = document.getElementsByTagName("head")[0]; css = document.createElement("link"); css.type = "text/css"; css.rel = "stylesheet"; css.href = href; header.appendChild(css); css.media = media; } 
function LoadScript(src) { var header = document.getElementsByTagName("head")[0]; script = document.createElement("script"); script.type = "text/javascript"; script.src = src; header.appendChild(script); }
function ToObject(x) { return (typeof x == "object") ? x : cross(x); }

function jFadeIn(x, speed, opacity) { $(ToObject(x)).css("opacity", 0).show().fadeTo(speed, SetDefault(opacity, 1)); } //, function() { this.style.removeAttribute("filter"); }
function jFadeOut(x, speed) { $(ToObject(x)).fadeOut(speed, function() { $(this).hide(); }); }

function DoubleDigit(num) { if (parseInt(num, 10) < 10) { return "0" + num; } else { return num; } }
function Z(data) { traceCount += 1; cross("tr_ace").innerHTML = traceCount + "|" + data; }


function toggleBox(el, textOn, textOff) {
	if (cross(el + "Off").style.display == "none") {
		scroller = document.body.scrollTop;
		cross(el + "On").style.display = "none";
		cross(el + "Off").style.display = "";
		//document.body.scrollTop = getRealTop(cross(el)) - 8;
		cross(el).innerHTML = textOff;// + "&nbsp;&nbsp;&nbsp;&nbsp;";
	}
	else {
		cross(el + "On").style.display = "";
		cross(el + "Off").style.display = "none";
		//document.body.scrollTop = scroller;
		cross(el).innerHTML = textOn;// + "&nbsp;&nbsp;&nbsp;&nbsp;";
	}
}

var lastSeasonID = "";

function showSeason(objID)
{
	if(lastSeasonID != "")
	{
		var obj = cross(lastSeasonID);
		obj.style.display = "none";
	}
	
	lastSeasonID = objID;
	
	var newObj = cross(lastSeasonID);
	newObj.style.display = "block";
}

// Layer (category) toggle
function toggleLayer(whichLayer, txtOn, txtOff) {
// Current standards
	if (document.getElementById) {
		var txt1 = document.getElementById(whichLayer + 'l');
		var style2 = document.getElementById(whichLayer).style;
	}
// Old, MSIE 5.5
	else if (document.all) {
		var txt1 = document.all[whichLayer + 'l'];
		var style2 = document.all[whichLayer].style;
	}
// REALLY old, Netscape 4 etc
	else if (document.layers) {
		var txt1 = document.layers[whichLayer+'l'];
		var style2 = document.layers[whichLayer].style;
	}
// Toggle!
	if (style2.display == "none") {
		txt1.innerHTML = txtOff;
		style2.display = "";
	}
	else {
		txt1.innerHTML = txtOn;
		style2.display = "none";
	}
}

var _lastOff = null;
var _last = null;

function showHide(el, textOn, textOff) {

	var current = cross(el + "Off");
	
	var currentEL = cross(el);
	
	if(_lastOff != null && current != _lastOff)
	{
		_lastOff.style.display = "none";
		_last.innerHTML = "&nbsp;&nbsp;&nbsp;" + textOn;
	}

	_lastOff = current;	
	_last = currentEL;

	if (current.style.display == "none") 
	{
		current.style.display = "";
		currentEL.innerHTML = "&nbsp;&nbsp;&nbsp;" + textOff;
	}
	else 
	{
		current.style.display = "none";
		currentEL.innerHTML = "&nbsp;&nbsp;&nbsp;" + textOn;
	}
}

function showMatch(el1, el2, typ) {
	if (IE) {
		var mt = IE.tags("div");
	}
	else if (document.getElementById) {
		var mt = document.getElementsByTagName("div");
	}
	else {
		return;
	}
	
	for (var i = 0; i < mt.length; i++) if (mt[i].id.indexOf("m_") == 0) cross(mt[i].id).style.display = "none";

	cross(el1).style.display = "";
}

function checkObject(ev) {
	newObj = getEventObject(ev);
}

function loadEvents(that, delayed) {
	if (window.delayTimer) clearTimeout(delayTimer);

	if (delayed && !eventsVisible) {
		lastObj = that;
		delayTimer = window.setTimeout(function () { loadEvents(that, false); }, 750);
		document.onmouseover = checkObject;

		return;
	}
	else {
		document.onmouseover = "";

		if (newObj == lastObj) { 
			cross("info_loader").innerHTML = spinner;

			var day = that.id.replace("dy_", "");
			getContent("&o=" + day + "&p=3", "", "auto");
			showInfo(that, toEnDate(day), 0, 0, -4, -4, false);
			document.onmouseup = function() { hideInfo(); }
			eventsVisible = true;
		}
		else {
			eventsVisible = false;
			hideInfo();
		}
	}
}

function openInfo(that, left, top, parm, title) {
	cross("info_loader").innerHTML = spinner;
	showInfo(that, title, 0, 0, left, top, true, false);
	getContent(parm, "",  false);
}

function showInfo(that, title, absX, absY, offsetX, offsetY, letDrag) {
	if (window.outTimer[standardTimer]) clearTimeout(outTimer[standardTimer]);
	if (window.autoTimer) clearTimeout(autoTimer);

	if (letDrag) {
		cross("info").onmousedown = function() { ddPrepare("info", "drag_me"); }
		cross("info").onmouseup = function() { ddEnabled = false; dragHot = false; }
	}
	else {
		cross("info_title").title = "";
		cross("info_title").style.cursor = "default";
		cross("info_loader").style.cursor = "default";
		cross("drag_me").style.cursor = "default";
	}

	if (absX +  absY != 0 && absX +  absY != "") {
		cross("info").style.left = absX + "px";
		cross("info").style.top = absY + "px";
	}
	else if (offsetX +  offsetY != "") {
		cross("info").style.left = getRealLeft(that) + offsetX + "px";
		cross("info").style.top = getRealTop(that) + offsetY + "px";
	}

	cross("info_title").innerHTML = title;
	fadeIn("info", standardTimer);
}

function hideInfo() {
	if (eventsVisible) eventsVisible = false;
	if (window.inTimer[standardTimer]) clearTimeout(inTimer[standardTimer]);
	if (window.autoTimer) clearTimeout(autoTimer);

	fadeOut("info", standardTimer, "info_loader");

	cross("info").onmousedown = "";
	cross("info").onmouseup = "";
	cross("drag_me").onmouseover = "";
	cross("drag_me").onmouseout = "";
	cross("info_handle").innerHTML = "";
	cross("more_handle").innerHTML = "";
	cross("more_handle").className = "";
	cross("more_handle").onmouseover = "";
	cross("more_handle").onmouseout = "";
	cross("more_handle").onclick = "";
	cross("more_handle").title = "";
	
	document.onmouseup = "";
}

function autoHide(out) {
	if (window.autoTimer) clearTimeout(autoTimer);
	if (out) autoTimer = window.setTimeout("hideInfo();", 350);
}
 
function cross(el) { return document.getElementById ? document.getElementById(el) : IE[el]; }
function test(x) { var obj = ToObject(x); return !(obj === null || typeof obj != "object") }

function getField(fieldID) { return cross(fieldID).value; }
function getMetaContent(name) { if (IE) mt = IE.tags("meta"); else if (document.getElementById) mt = document.getElementsByTagName("meta"); else return; for(var i = 0; i < mt.length; i++) if (mt[i].name == name) return mt[i].content; } 
function getEventObject(ev) { ev = ev || window.event; if (ev.srcElement) return ev.srcElement; else return ev.target; }
function getNextHref(that) { var child = that.childNodes; for (var i = 0; i < child.length; i++) { var subChild = child[i].childNodes;for (var j = 0; j < subChild.length;  j++) if (subChild[j].href != "") return subChild[j].href; } }
function getStyleVal(x, attr) { var obj = ToObject(x); return (IE) ? obj.currentStyle[attr] : document.defaultView.getComputedStyle(obj, null).getPropertyValue(attr); }

function getRealTop(x) { var obj = ToObject(x); yPos = obj.offsetTop; tempObj = obj.offsetParent; while (tempObj != null) { yPos += tempObj.offsetTop; tempObj = tempObj.offsetParent; } return yPos; }
function getRealLeft(x) { var obj = ToObject(x); xPos = obj.offsetLeft; tempObj = obj.offsetParent; while (tempObj != null) { xPos += tempObj.offsetLeft; tempObj = tempObj.offsetParent; } return xPos; }
function centerMe(x) { var X = $(ToObject(x)); var top = $(document).scrollTop() + Math.round(($(window).height() / 2) - (X.height() / 2)); var left = $(document).scrollLeft() + Math.round(($(window).width() / 2) - (X.width() / 2)); X.css("top", top).css("left", left); }

function hideReset() { if (window.hideTimer) clearTimeout(hideTimer); }
function hideDelayed(el, fade, dir, tTarget, hTarget) { if (window.hideTimer) clearTimeout(hideTimer); hideTimer = window.setTimeout("fullHide('" + el + "', '" + fade + "', '" + dir + "', " + tTarget + ", " + hTarget + ")", 500); }
function fullHide(el, fade, dir, tTarget, hTarget) { if (window.hideTimer) clearTimeout(hideTimer); if (fade) fadeOut(el); if (tTarget && hTarget) if (dir == "up") { minimizeUp(el, tTarget, hTarget); } else { minimizeDn(el, tTarget, hTarget); } }
function maximizeUp(el, tTarget, hTarget) { if (window.zoomTimer) clearTimeout(zoomTimer); var obj = cross(el); try { var objInner = cross(el + "_inner"); } catch (ex) { var objInner = cross(el); } if (ammount == 0) obj.style.display = "block"; ammount += (zoomInStep + ammount); var actTop = parseInt(obj.style.top, 10); var actHeight = parseInt(objInner.style.height, 10); var newTop = actTop - ammount; if (newTop < tTarget) newTop = tTarget; var newHeight = actHeight + ammount; if (newHeight > hTarget) newHeight = hTarget; if (newTop > tTarget && newHeight < hTarget) { obj.style.top = newTop + "px"; objInner.style.height = newHeight + "px"; zoomTimer = window.setTimeout("maximizeUp('" + el + "', " + tTarget + ", " + hTarget + ")", 25 * sloMo); } else { if (window.zoomTimer) clearTimeout(zoomTimer); obj.style.top = tTarget + "px"; objInner.style.height = hTarget + "px"; ammount = 0; try { setAutoHide(); } catch (ex) { } } }
function minimizeDn(el, tTarget, hTarget) { if (window.zoomTimer) clearTimeout(zoomTimer); var obj = cross(el); try { var objInner = cross(el + "_inner"); } catch (ex) { var objInner = cross(el); } ammount += (zoomOutStep + ammount); var actTop = parseInt(obj.style.top, 10); var actHeight = parseInt(objInner.style.height, 10); var newTop = actTop + ammount; if (newTop > tTarget) newTop = tTarget; var newHeight = actHeight - ammount; if (newHeight < hTarget) newHeight = hTarget; if (newTop < tTarget && newHeight > hTarget) { obj.style.top = newTop + "px"; objInner.style.height = newHeight + "px"; zoomTimer = window.setTimeout("minimizeDn('" + el + "', " + tTarget + ", " + hTarget + ")", 25 * sloMo); } else { if (window.zoomTimer) clearTimeout(zoomTimer); obj.style.top = tTarget + "px"; objInner.style.height = hTarget + "px"; obj.style.display = "none"; ammount = 0; try { resetAutoHide(); } catch (ex) { } } }

function fadeIn(el, idx, opac) { idx = ZeroDefault(idx); if (window.outTimer[idx]) clearTimeout(outTimer[idx]); var obj = cross(el); lastOpac[idx] += fadeInStep; opac = SetDefault(opac, 100); if (lastOpac[idx] < opac) { changeOpac(obj, lastOpac[idx]); if (lastOpac[idx] == fadeInStep) if ($(obj).css("visibility") == "hidden") $(obj).css("visibility", "visible"); else obj.style.display = "block"; inTimer[idx] = window.setTimeout("fadeIn('" + el + "', " + idx + ", " + opac + ");", 30 * sloMo); } else { if (window.inTimer[idx]) clearTimeout(inTimer[idx]); changeOpac(obj, opac); lastOpac[idx] = opac; try { setAutoHide(); } catch (ex) { } } }
function fadeOut(el, idx, cls) { idx = ZeroDefault(idx); if (window.inTimer[idx]) clearTimeout(inTimer[idx]); var obj = cross(el); lastOpac[idx] -= fadeOutStep; if (lastOpac[idx] > 0) { changeOpac(obj, lastOpac[idx]); outTimer[idx] = window.setTimeout("fadeOut('" + el + "', '" + cls + "', " + idx + ");", 30 * sloMo); } else { lastOpac[idx] = 0; if (window.outTimer[idx]) clearTimeout(outTimer[idx]); obj.style.display = "none"; if (window.hideTimer) { clearTimeout(hideTimer); if (typeof cls == "string") cross(cls).innerHTML = ""; try { resetAutoHide(); } catch (ex) { } } } }
function changeOpac(obj, opacity) { obj.style.filter = "alpha(opacity=" + opacity + ")"; obj.style.opacity = (opacity / 100); obj.style.MozOpacity = (opacity / 100); obj.style.KhtmlOpacity = (opacity / 100); }
function clearOpac(obj) { obj.style.filter = ""; obj.style.opacity = ""; obj.style.MozOpacity = ""; obj.style.KhtmlOpacity = ""; }

function SetDefault(variable, value) { return (typeof variable == "undefined") ? value : ((variable === "") ? value : variable); }
function ZeroDefault(variable) { return (typeof variable == "number") ? variable : 0; }

function isValidEmail(src) { var emailReg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var regex = new RegExp(emailReg); return regex.test(src); }
function toEnDate(day) { var dsplt = day.split("."); var dyDat = new Date(dsplt[2], dsplt[1]-1, dsplt[0]); return mon[dyDat.getMonth()] + " " + dyDat.getDate() + ", " + dyDat.getFullYear(); }
function wait(msecs) { var start = new Date().getTime(); var cur = start; while(cur - start < msecs) { cur = new Date().getTime(); } }

function getXMLRequester() { var xmlHttp = false; try { if (window.ActiveXObject) { for (i=5; i; i--) { try { if (i==2) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); else xmlHttp = new ActiveXObject("Msxml2.XMLHTTP." + i + ".0" ); break; } catch(e) { xmlHttp = false; } } } else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); } catch(e) { xmlHttp = false; } return xmlHttp; }
function getContent(parm, path, option) { xmlHttp = getXMLRequester(); if (xmlHttp) { xmlHttp.open("GET", path + "/?async=true" + parm, true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) completeRequest(xmlHttp.responseText, option); } } xmlHttp.send(null); }
function sendData(field) { parm = cross(field).name + "=" + cross(field).value; xmlHttp = getXMLRequester(); xmlHttp.open("POST", "/?async=true", true); xmlHttp.setRequestHeader("xmlHttptent-type", "application/x-www-form-urlencoded"); xmlHttp.setRequestHeader("xmlHttptent-length", parm.length); xmlHttp.onreadystatechange = handleResponse; xmlHttp.send(parm); return false; }

function completeRequest(html, option) {
	if (option === "auto") {
		cross("info_loader").innerHTML = html;
		cross("drag_me").onmouseover = function() { autoHide(false); }
		cross("drag_me").onmouseout = function() { autoHide(true); }
	}
	else if (option === false) cross("info_loader").innerHTML = html;
	else cross(option).innerHTML = html;
}

function onTournamentsClick()
{
	var p_matchType = getField("m_type"); 
	
	if(p_matchType == "1")
		p_matchType = "/handball";
	else if(p_matchType == "2")
		p_matchType = "/beachhandball";
	else 
		p_matchType = "";
	
	var p_gender = getField("gender"); p_gender = p_gender == "any" ? "" : "/" + p_gender;
	var p_country = getField("country"); p_country = p_country == "any" ? "" : "/" + p_country.toLowerCase();

	var params = "/" + getField("saison") + p_gender + "/tournaments" + p_country + p_matchType;
	
	if(cross("yob").style.display != "none")
		params += getField("yob") != "any" ? "/query=" + getField("yob") : "";
	else
		params += getField("category") != "any" ? "/query=" + getField("category").replace(" ", "+") : "";
	
	location = params;
}

function switchEvent() {
    var requestString = "";

    var g = cross("ev_gender");
    if (g != null)
        requestString += "&g=" + g.options[g.selectedIndex].value;

    g = cross("ev_type");
    if (g != null)
        requestString += "&type=" + g.options[g.selectedIndex].value;

    g = cross("ev_nation");
    if (g != null)
        requestString += "&nation=" + g.options[g.selectedIndex].value;

    g = cross("ev_general");
    if (g != null)
        requestString += "&general=" + g.options[g.selectedIndex].value;

    g = cross("ev_comp");
    if (g != null)
        requestString += "&comp=" + g.options[g.selectedIndex].value;

    g = cross("ev_saison");
    if (g != null)
        requestString += "&s=" + g.innerHTML;

    g = cross("ev_month");
    if (g != null)
        requestString += "&mon=" + g.innerHTML;

    xmlHttp = getXMLRequester();
    if (xmlHttp) {
        if (test("eventSwitcher")) {
            cross("eventSwitcher").innerHTML = spinner;
            xmlHttp.open("GET", "/?async=true&p=1002" + requestString, true);

            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    cross("eventSwitcher").innerHTML = xmlHttp.responseText;
                }
            }
            xmlHttp.send(null);
        }
    }
}

function oncatclick(showcat)
{
	cross("yob").style.display = showcat ? "none" : "inline";
	cross("category").style.display = showcat ? "inline" : "none";
}

function ddPrepare(el, handle) {
	if (ddEnabled) return;

	crossEl = cross(el);
	dragHandle = (handle != "") ? handle : crossEl.id;
	crossEl.style.zIndex = 1001;

	dragHot = true;
}

function ddInit(ev) {
	if (!dragHot) return;

	ev = ev || window.event;

	var topMost = IE ? "BODY" : "HTML";
	var selected = IE ? ev.srcElement : ev.target;

	while (selected.id != dragHandle && selected.tagName != topMost) selected = IE ? selected.parentElement : selected.parentNode;

	if (selected.id == dragHandle) {
		offsetX = ev.clientX;
		offsetY = ev.clientY;
		newX = parseInt(crossEl.style.left);
		newY = parseInt(crossEl.style.top);

		ddEnabled = true;
		document.onmousemove = dd;
	}
}

function dd(ev) {
	if (!ddEnabled) return;

	ev = ev || window.event;

	crossEl.style.left = newX + ev.clientX - offsetX + "px"; 
	crossEl.style.top = newY + ev.clientY - offsetY + "px";

	return false;  
}

function captureKey(ev) {
	ev = ev || window.event;
	
	if (ev.shiftKey && ev.ctrlKey && ev.altKey && ev.keyCode == 32) pageRefresh(rootUrl);
}


function mmHandler(ev) {
	ev = ev || window.event;

	if (ev.srcElement) var obj = ev.srcElement;
	else var obj = ev.target;

	tr(obj.id);
}

document.onkeydown = captureKey;
document.onkeyup = function() { keyPressed = -1; }
document.onmousedown = ddInit;
//document.onmousemove = mmHandler;
