/// <reference path="~/scripts/jquery-vsdoc.js"/>
var googleID = "UA-2538302-1", _uacct = null;
var motdSlideCount, selektorBaseUrl = "/resources/selektor/", selektorImgUrl = "/img/header/";
var EHF = {};

function slkOpen(s, b, bt, mf) {
	/* nur vorübergehend nötig ... selektor.js verteilung bei benutzern */
	lS(s, b, bt, mf);
	modalSwitch();
	centerMe("slk");
	selektorTimer = window.setTimeout("$('#slk').show(); setAutoHide();", 100);
}

$(document).ready(function() {
	jQuery.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("AJAX", "true"); } });

	gMaps.init();

	Search.init();

	$(document).resize(function() { setSize(); });

	$('#page_content').css('visibility', 'visible');
	cross('logoMap').onmouseover = function() { $('#logoMain').css('opacity', .85).toggleClass('mouse'); };
	cross('logoMap').onmouseout = function() { $('#logoMain').css('opacity', 1).toggleClass('mouse'); };

	menuInit();
	//IdealA();
	calendarInit();
});


function calendarInit() {
    $("#calRange td[id]").each(function() {
        this.onmouseover = function() { lastClass = this.className; this.className = "V"; loadEvents(this, true); }
        this.onmouseout = function() { this.className = lastClass; }
        this.onclick = function() { loadEvents(this); }
    });

    $("#calRange div").each(function() { $(this).css("width", 153); });

    $("#calRange").cycle({
        fx: "scrollHorz",
        speed: "fast",
        startingSlide: calStartMonth,
        timeout: 0,
        next: ".CN",
        prev: ".CP"
    });
}

$(window).load(function() {
	jBasic();

	if (p != 1) $("div.pHeadWrapper div.pHead").animate({ marginTop: 5 }, 500);

	switch (p) {
		case 1:
			waitStart = window.setTimeout("startFx();", 250);
			break;

		case 3:
			eventsInit();
			break;
			
		case 16:
			fedBoxSize();
			break;

		case 21:
			tvGuideInit();
			break;

		case 34:
			tournamentsInit();
			break;

		case 38:
			eNewsInit();
			break;
			
		case 24:
			refereeInit();	
			break;

		default:
			break;
	}

	waitStart = window.setTimeout("startMisc();", 350);
	waitSlk = window.setTimeout("try{selektorInit();}catch(ex){}", 650);
});

function onMailFormLoaded(html)
{
	$("#mailcontent").css("text-align", "left");
	$("#mailcontent").html(html);
}

function doMail()
{
	modalSwitch();
	centerMe("mailpopup");
	$("#mailpopup").css("display", "block");
	$("#mailcontent").css("text-align", "center");
	$("#mailcontent").html(spinner);
	$.get("/", {async: true, p: 19}, onMailFormLoaded);
}

function doMailAbort()
{
	$("#mailpopup").css("display", "none");
	modalSwitch();
}

function mailCheck(valid, target)
{
	$(target).css("visibility", valid ? "visible" : "hidden");
	return valid;
}

function submitMailForm()
{
	var mName = $("#name").val().replace(/<.*?>/g, '');
	var mMail = $("#mail").val().replace(/<.*?>/g, '');
	var mSubject = $("#subject").val().replace(/<.*?>/g, '');
	var mEmail = $("#email").val().replace(/<.*?>/g, '');
	var mStatement = $("#statement").val().replace(/<.*?>/g, '');
	
	var failed = false;
	
	failed = mailCheck(!(mName.length > 3 && mName.length < 50), '#iName');
	failed = mailCheck(!(mSubject.length > 3 && mSubject.length < 50), '#iSubject') || failed;
	failed = mailCheck(!(mStatement.length > 3 && mStatement.length < 250), '#iStatement') || failed;
	var eReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	failed = mailCheck(!eReg.test(mMail), '#iEmail') || failed;
	
	if(!failed)
	{
		$.post("/?async=true&p=19", {name: mName, mail: mMail, subject: mSubject, email: mEmail, statement: mStatement }, onMailFormLoaded);
		$("#mailcontent").css("text-align", "center");
		$("#mailcontent").html(spinner);
	}
}

var refBlock = null, refBlockA = null;

function refereeInit() {
	refBlock = $(".leftContent .R:first");
	refBlock.slideDown("fast");

	refBlockA = $(".rightContent a:first");
	refBlockA.addClass("sel");
	
	$(".rightContent a").click(function()
		{
			refBlock.slideUp("fast");
			refBlockA.removeClass("sel");
			
			refBlock = $("#ry_" + $(this).attr("rel"));
			refBlock.slideDown("fast");

			refBlockA = $(this);
			refBlockA.addClass("sel");
		});
}

function setSize() {
	var divLeft = $("#div_left");

	var left = divLeft.outerHeight() + divLeft.offset().top;
	var right = $("#mainFrame").height();
	var fixed = right - $("#td_content").outerHeight();
	var port = $(window).height();
	
	if (port < left && right < left ) 
		$("#td_content").height(left - fixed + ((IE)?-2:4));
	else if (right < port) 
		$("#td_content").height(port - fixed - ((IE)?6:0));

	var F = $("div.jsFixed");
	
	if (F.length > 0) 
	{
		var bottom = $("#td_header").outerHeight() + $("#td_content").outerHeight();
		F.height(bottom - F.offset({ border: true, padding: true })["top"] - 10);
	}
}

function jBasic() {
	_lastClass = "";											/* GLOBAL! */
	_fedFlags = $("#fedFlags img");								/* GLOBAL! */
	_flagsHidden = false;										/* GLOBAL! */

	_fedFlags.css({ opacity: .75 });

	_fedFlags.each(function() {
		$(this).click(function() { $(this).animate({ opacity: 0.25 }, 150); });
		$(this).hover(
			function() {
				if (!_flagsHidden) {
					_flagsHidden = true;
					_fedFlags.stop().animate({ opacity: .25 }, 350);
				}
				$(this).stop().animate({ opacity: 1 }, 100);
			},
			function() { $(this).animate({ opacity: .25 }, 50); }
		);
	});

	$("#fedFlags").hover(
		function() { _fedFlags.stop().animate({ opacity: .25 }, 500); _flagsHidden = true; },
		function() { _fedFlags.stop().animate({ opacity: .75 }, 150); }
	);

	//$("table.cal td.H").each(function() { calEvent(this) });
	//$("table.cal td.E").each(function() { calEvent(this) });
}

function calEvent(that) {
	$(that).click(function() { loadEvents(this); });
	$(that).hover(
		function() { _lastClass = this.className; this.className = "V"; loadEvents(this, true); },
		function() { this.className = _lastClass; }
	);
}

function startMisc() {
	headAnim();

	$.getScript("http://www.google-analytics.com/urchin.js", function() {
		_uacct = googleID;
		urchinTracker();
	});
}

function headAnim() {
	slideStack = []; 										/* GLOBAL! */
	var ani = $("#headAnim");
	var images = "/img/slides/img_";
	var numImages = 20;
	var pickList = new Array();

	for (var i = 1; i < numImages; i++) pickList[i] = i;

	var img = new Image(782, 93);
	img.src = images + DoubleDigit(0) + ".jpg";
	ani.append(img);

	for (var i = numImages - 1; i > 0; i--) {
		var rand = Math.floor(Math.random() * i) + 1;
		var idx = pickList[rand];
		pickList = pickList.slice(0, rand).concat(pickList.slice(rand + 1));
		
		var img = new Image(782, 93);
		img.src = images + DoubleDigit(idx) + ".jpg";
		
		if (i == numImages - 1) {
			ani.append(img);
		}
		else {
			$(img).bind("load", function() { slideStack.push(this); });
		}
	}  

	ani.cycle({
		fx: "fade",
		speed:		6000,
		timeout:	18000,
		before:		onBefore
	});
}

function onBefore(curr, next, opts) { 
	if (opts.addSlide)
		while(slideStack.length) 
			opts.addSlide(slideStack.pop());  
}

function startFx() {
	if (window.waitStart) clearTimeout(waitStart);

	$("#newsImageFader").cycle({
		fx:				"fade",
		speed:			1500,
		delay:		   -3000,
		timeout:		5000
	});

	$("#feedBox div.content").cycle({
		fx:				"scrollHorz",
		slideExpr:		"div",
		next:			"#feedPrev",
		prev:			"#feedNext",
		delay:			-1500,
		speed:			450,
		timeout:		5000,
		pause:			true
	});

	$("#motdMain").cycle({
		fx:				"cover",
		slideExpr:		"div",
		next:			"#motdPrev", 
		prev:			"#motdNext",
		cssBefore:		{ opacity: 1 },
		animOut:		{ opacity: 0 },
		speed:			500,
		timeout:		4000,
		pause:			true,
		autostop:		true,
		autostopCount:	(motdSlideCount * 2) + 1
	});
		
	for (var i = 0; i < brTime.length; i++)
		if (brTime[i] > 0)
			$("#bannerRotator_" + i).cycle({
				fx:		"scrollDown",
				speed:	850,
				timeout:1000 * brTime[i],
				delay:	2000,
				pause:	true
			});
			
	//waitInfo = window.setTimeout("startInfo(true);", 2000);
}

function startInfo(open) {
	if (window.waitInfo) clearTimeout(waitInfo);

	if (open) {
		$('#mainInfo A.info').hover(
			function() { pauseInfo(true); },
			function() { pauseInfo(false); }
		);

		$('#mainInfo').show("slow", function() { $('DIV.showInfo').show(); });

		waitInfo = window.setTimeout("startInfo(false);", 6500);
	}
	else
		$('#mainInfo').hide("fast");
}

function pauseInfo(stop) {
	if (stop) {
		if (window.waitInfo) clearTimeout(waitInfo);
	}
	else
		waitInfo = window.setTimeout("startInfo(false);", 1500);
}

function fedBoxSize() {
	if ($("div.NT").is(":visible")) {
		var maxHeight = 0;
		var T = $("div.NTh");
		var C = $("div.ECh");
		var N = $("div.NPh");

		if (T.height() > maxHeight) maxHeight = T.height();
		if (C.height() > maxHeight) maxHeight = C.height();
		if (N.height() > maxHeight) maxHeight = N.height();

		T.height(maxHeight);
		C.height(maxHeight);
		N.height(maxHeight);
	}
}

function tournamentsInit() {
	_tournamentsClick = function() {							/* GLOBAL! */
		var A = $("div.sel a.sel");
		$("div.content div.X:visible").slideUp("fast");
		A.removeClass("sel");
		$(this).addClass("sel");
		$("#" + $(this).text()).slideDown("fast");
	};

	var A = $("div.sel a.sel").text();
	$("#" + A).show();

	$("div.sel a").click(_tournamentsClick);
}

function eNewsInit() {
	_eNewsClick = function() {									/* GLOBAL! */
		var A = $("div.sel a.sel");
		$("div.content div.X:visible").hide();
		$("#" + A.text() + " div.main div.body:visible").hide();
		A.removeClass("sel");
		$(this).addClass("sel");
		$("#" + $(this).text()).show();
		$("#" + $(this).text() + " div.main:first div.body").slideDown("fast");
	};

	var A = $("div.sel a.sel").text();
	$("#" + A).show();
	$("#" + A + " div.main:first div.body").show();

	$("div.sel a").click(_eNewsClick);
	
	$("div.body p.enewsold").clickUrl();
	$("div.header").click(function() {
		$("div.content div.body:visible").slideUp("fast");
		$(this).parent("div.main").find("div.body").slideDown("fast");
	});
}

function eventsInit() {
	_prefix = _lastDay.substring(0, 3);							/* GLOBAL! */

	if (!isGeneral) {
		daySelect(_lastDay.substring(3, 5));
		$("#eventRuler a").click(function() { daySelect($(this).text()); });
	}
	else {
		$("DIV.events DIV:hidden").show();
	}
}

function daySelect(nbr) {
	var thisDay = parseInt(nbr, 10);
	$("#eventRuler a.sel").removeClass("sel");
	$("#eventRuler a").filter(function (index){ return $(this).text() == thisDay; }).addClass("sel");
	var thisDay = _prefix + (thisDay < 10 ? "0" : "") + thisDay; // DoubleDigit(nbr);
	if (_lastDay != thisDay && _lastDay != "") $("#" + _lastDay).hide();
	$("#" + thisDay).show();
	_lastDay = thisDay;
}

function tvGuideInit() {
	_tvDivArray = new Array();									/* GLOBAL! */
	_tvDivMin = 1; 	 											/* GLOBAL! */
	_tvDivMax = 2;												/* GLOBAL! */
	_tvDivDiff = 1;  											/* GLOBAL! */
	_currentTvDiv = "";											/* GLOBAL! */
	_tvSetMO = function() {										/* GLOBAL! */
		this.onmouseover = null;

		for (var t in _tvDivArray)
			if (_tvDivArray[t].id != this.id && _tvDivArray[t].id != _currentTvDiv && $(_tvDivArray[t]).width() != _tvDivMin)
				tvOverReset(_tvDivArray[t]);

		this.className = this.className + " selected";
		tvXfade(this.id);
	};

	if (IE) var div = document.all.tags("div");
	else if (document.getElementById) var div = document.getElementsByTagName("div");

	var maxHeight = $("#tvWrapper").height();
	var thisHeight, t = 0;

	for (var i = 0; i < div.length;  i++) {
		if (div[i].id.indexOf("tvDay_") == 0) {
			thisHeight = $(div[i]).height();
			div[i].style.height = maxHeight + "px";

			if (t == 0) _currentTvDiv = div[i].id;

			if (div[i].className.indexOf(" open") > 0) {
				_currentTvDiv = div[i].id;
				_tvDivMax = $(div[i]).width();
			}
			else {
				_tvDivMin = $(div[i]).width();
				if (thisHeight > 50) div[i].onmouseover = _tvSetMO;
				else div[i].className = div[i].className + " none";
			}

			_tvDivArray[t] = div[i];
			t++;
		}
	}

	_tvDivDiff = _tvDivMax - _tvDivMin;							/* GLOBAL! */
}

function tvOverReset(obj) {
	obj.style.width = _tvDivMin + "px";
	obj.className = obj.className.replace(" selected", "");
	obj.onmouseover = _tvSetMO;
	cross(_currentTvDiv).style.width = _tvDivMax + "px";
}

function tvXfade(el) {
	if (el == _currentTvDiv) return null;
	if (window.tvTimer) clearTimeout(tvTimer);

	ammount += 10;

	var objWider = ToObject(el);
	var widthWider = $(objWider).width();
	var newWidthWider = widthWider + ammount;

	var objSmaller = cross(_currentTvDiv);
	var widthSmaller = $(objSmaller).width();
	var newWidthSmaller = widthSmaller - ammount;

	if (newWidthWider - newWidthSmaller < _tvDivDiff) {
		objSmaller.style.width = newWidthSmaller + "px";
		objWider.style.width = newWidthWider + "px";
		tvTimer = window.setTimeout("tvXfade('" + el + "')", 20);
	}
	else {
		if (window.tvTimer) clearTimeout(tvTimer);
		_currentTvDiv = el;
		tvOverReset(objSmaller);
		ammount = 0;
	}
}

function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		
		for(i = 0; i < field.form.elements.length; i++)
		{
			if (field == field.form.elements[i])
				break;
		}
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
		return true;
}

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", "/?p=1002" + requestString, true);
			xmlHttp.setRequestHeader("AJAX", "true");
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                    cross("eventSwitcher").innerHTML = xmlHttp.responseText;
                }
            }
            xmlHttp.send(null);
        }
    }
}
