/// <reference path="~/scripts/jquery/jquery-vsdoc.js"/>
var gaJsHost, pageTracker;
var ie = document.all;
var gap = 12;
var input = null;

var div, span, topOffset, tabOffset = 0, generalOffset = 0, totalHeight = 0;
var leftState = '', rightState = '', lastMenu = '', cachedpw = '';
var dotToggle = true, sessionTimeOut = 0, timeoutAlert = 0, isExtranet = true;
var int_secLock_retrys = 0, obj_screensaver_timeout = null, bool_screensaver_isActive = false;
var	watcherMousePosX = 100, watcherMousePosY = 100, scrollposSearchResults = 0;
var watcherScrollPosY = 0;
var watcherScrollPosX = 0;
var watcherRelativeMousePosX = 0;
var watcherRelativeMousePosY = 0;
var actMon, actDay = '', s_hrs, s_min, l_hrs, l_min, t_min = 1, t_sec = 0;
var currentPage = '';

var int_screensaver_retrys		= 3;	// +1 = 4
var int_screensaver_timeout		= 180;	// Seconds
var int_screensaver_opacity		= 85;	// Percent
var int_secureShowTimeOut		= 2000;
var obj_status_screensaver_timeout	= true;
var cookieTimeout				= 60*60;
var hidePWTimeout				= 0;
var eosdebug					= false;

function doInit (page) {
	doPrepareElements();
	try { doLayout(page); } catch(e) {}
	try { doInitClocks(true); } catch(e) {}
}

function EnableDefaultDatetimePicker() { /*$(function() { $('.date-pick').not(':disabled').datePicker({clickInput:false, startDate:'01/01/1900',displayClose:true}); });*/ }
function resetClock() { t_min = sessionTimeOut; t_sec = '01';}

function pageLoad(sender, args) {
	doPrepareElements();

	try { doLayout(''); } catch(e) {}

	if ((t_min === 0 && t_sec === 0) || ($('#tt_m').length === 0 || $('#tt_s').length === 0)) logout(true);
	else resetClock();
	
	if (currentPage === 'News') {
		startCookieDependendTimer();
		bakeCookie('timestamp', '-', 3600*1000, '.ehf.eu');
		bakeCookie('timestamp', '-', 3600*1000, '.ehf');
		bakeCookie('timestamp', '-', 3600*1000, '.ehf.test');
		bakeCookie('timestamp', '-', 3600*1000, '.test');
	}
	EnableDefaultDatetimePicker();
	CreateUserFriendlyFields();
	ApplyLanguageLogic();
}

function CheckDates(date1, date2) {
	var d1 = null;
	var d2 = null;
	if($('#'+date1).length > 0) d1 = $('#'+date1)[0];
	if($('#'+date2).length > 0) d2 = $('#'+date2)[0];
	
	if (d1 !== null && isDate(d1.value)) {
		if (d2 !== null) {
			if (isDate(d2.value)) {
				var jd1 = new Date().setFullYear(d1.value.split('.')[2], d1.value.split('.')[1]-1, d1.value.split('.')[0]);
				var jd2 = new Date().setFullYear(d2.value.split('.')[2], d2.value.split('.')[1]-1, d2.value.split('.')[0]);
				if (jd1 <= jd2) return true;
				alert('End date cannot be before Begin date!');
			} else if(d2.value.length === 0) {
				return true;
			} else alert('End date is not valid!');
			return false;
		}
		return true;
	}
	alert('Begin date is not valid!');
	return false;
}

function setSelected(that) { mNode = that.parentNode.childNodes; for (i = 0; i < mNode.length; i++) if (mNode[i].className) mNode[i].className = 'item'; that.className = 'selected'; }

function doPrepareElements() {
	a = (ie) ? ie.tags('a') : document.getElementsByTagName('a');
	div = (ie) ? ie.tags('div') : document.getElementsByTagName('div');
	span = (ie) ? ie.tags('span') : document.getElementsByTagName('span');
	input = (ie) ? ie.tags('input') : document.getElementsByTagName('input');
	select = (ie) ? ie.tags('select') : document.getElementsByTagName('select');

	for (i=0; i<a.length; i++) { a[i].onfocus = function() { if (this.blur) this.blur(); }; }
	
	var className = ' hover';
	for (i=0; i<span.length; i++) {
		if (span[i].id && span[i].id.indexOf('cd_') !== -1) {
			span[i].onmouseover = function() { this.className += className; };
			span[i].onmouseout = function() { this.className = this.className.replace(className, ''); };
		}
	}
	
	PrepareImg();
}

function imgDnRplc(i) { return i.replace('_dn.gif', '.gif').replace('_ov.gif', '.gif'); }
function PrepareImg() {
	img = (ie) ? ie.tags('img') : document.getElementsByTagName('img');
	for (i=0; i<img.length; i++) {
		if (img[i].src.indexOf('bt_') > 0) {
			img[i].onmouseover = function() { this.src = imgDnRplc(this.src).replace('.gif', '_ov.gif'); };
			img[i].onmouseout = function() { this.src = imgDnRplc(this.src); };
			img[i].onmousedown = function() { this.src = imgDnRplc(this.src).replace('.gif', '_dn.gif'); };
			img[i].onmouseup = function() { this.src = imgDnRplc(this.src).replace('.gif', '_ov.gif'); };
		}
	}
	
	$('.button').bind('mousedown', function(){ $(this).addClass('down');}).
	bind('mouseup mouseenter mouseleave', function(){$(this).removeClass('down');});
}

var theUsualTop = 66;
var bigPageTitle = 35;
function doLayout(page) {
	topOffset = $('#header').outerHeight();
	var tabheightSmall = 18;
	
	if (currentPage === 'MyDesktop') {
		tabheightSmall = 20;
		topOffset = $('#left').position().top;
		totalHeight = getWinHeight() - topOffset - $('#left div div').position().top;
		h_l_t_height = totalHeight - $('#left .tbs').length * tabheightSmall;
		$('#h_l_t').css('height', h_l_t_height-tabheightSmall);
		
		topOffset = ($('#right div div').position().top + $('#right div div:first').position().top -2);
		totalHeight = getWinHeight() - topOffset - ($('#right div div').position().top - $('#right div div:first').position().top);
		h_l_t_height = totalHeight - $('#left .tbs').length * tabheightSmall;
		$('#h_l_b').css('height', h_l_t_height-tabheightSmall+ $('#right div div:first').height());
	}else {
		leftTabOffset = 0;
		rightTabOffset = 0;
		fullTabOffset = 0;
		$('#left .tbs').each(function(){$this = $(this); leftTabOffset += $this.outerHeight();});
		$('#right .tbs').each(function(){$this = $(this); rightTabOffset += $this.outerHeight();});
		$('#full .tbs').each(function(){$this = $(this); fullTabOffset += $this.outerHeight();});

		if ($('#left').length) $('#left').css('visibility', 'hidden').css('top', theUsualTop+generalOffset);
		if ($('#right').length) $('#right').css('visibility', 'hidden').css('top', theUsualTop+generalOffset-bigPageTitle);
		// < 150 because the nat selection.... bad hack but it works..
		if ($('#full').length && theUsualTop+generalOffset-bigPageTitle < 150) $('#full').css('visibility', 'hidden').css('top', theUsualTop+generalOffset-bigPageTitle);

		var lc = $('#l_cont');
		var rc = $('#r_cont');
		var fc = $('#f_cont');

		var rh = theUsualTop + rightTabOffset + generalOffset + gap*2;
		//var lh = theUsualTop + leftTabOffset + generalOffset + gap*2;
		
		// first make them as height as they are
		if (rc.length) rc.css('height', 'auto');
		if (fc.length) fc.css('height', 'auto');
		if (lc.length) lc.css('height', 'auto');

		// then calculate the height as we want
		if (rc.length) setWinHeight(rc, rh);
		if (lc.length) lc.css('height', rc.outerHeight()+rightTabOffset-leftTabOffset - gap);
		if (fc.length) fc.css('height', getDocumentHeight() - fc.position().top - generalOffset-bigPageTitle - gap);

		// if we have search results, we may adjust the calculation again
		var sc = $('#searchResults');
		if (sc.length) {
			setWinHeight(sc, lc.offset().top*2 - sc.offset().top);
			if (sc.outerHeight() > lc.outerHeight()){
				lc.css('height', sc.outerHeight() + gap);
				rc.css('height', lc.outerHeight()+leftTabOffset-rightTabOffset - gap);
			}
		}

		if ($('#r_cont').length) totalHeight = getRealTop($('#r_cont')[0]) + $('#r_cont')[0].offsetHeight;
	}
	
	// This is a try because we really dont know then there is a progbar and when not...
	try {
		if ($('#full').length) $('#progbar').css('height', totalHeight - getRealTop($('#full')[0]));
		else $('#progbar').css('height', totalHeight);
		$('#progbar').css('zIndex', 2000);
		var li = $('#loader_inside');
		if (li.length)
		{
			li.css('top', Math.ceil(((getWinHeight()+parseInt($('#loader_inside')[0].offsetHeight,10))/2)+$('#header')[0].offsetHeight));
			li.css('left', Math.ceil(($('#header')[0].offsetWidth+parseInt($('#loader_inside')[0].offsetWidth,10))/2));
			li.css('zIndex', 2000+1);
			//li.css('display', 'block');
		}
	}
	catch(e){alert(e);}
	
	if (bool_screensaver_isActive) $('#secLock').css('height', getDocumentHeight());

	if ($('#right').length) $('#right').css('visibility', 'visible');
	if ($('#left').length) $('#left').css('visibility', 'visible');
	if ($('#full').length) $('#full').css('visibility', 'visible');    
	if ($('#searchResults').length)	loadScrollPos($('#searchResults')[0]);
}
function hMenu(that, what, typ) {
	setSelected(that);

	for (i=0; i<div.length; i++) if (div[i].id.indexOf(typ) > 1) div[i].style.display = 'none';
	cross(what + typ).style.display = '';
}

function hContextMenu(that, e, typ) {
	if (e.button === 2) {
		el = '#' + typ + 'Menu';
		$(el).css('left', ($(that).offset().left - 5) + 'px');
		$(el).css('top', ($(that).offset().left + 13) + 'px');
		if (el !== lastMenu) showMenu(el);
	}
}

function hTopMenu(that, what) {
	el = '#' + what + 'Menu';
	$(el).css('top',  ($(that).offset().top + $(that).height()) + 'px');
	$(el).css('left', ($(that).offset().left) + 'px');
	
	if (el !== lastMenu) showMenu(el);
}

function hSubMenu(that, what, typ) {
	el = '#' + what + typ + 'Menu';
	$(el).css('left', ($(that).offset().left - $(that.parentNode).offset().left + 2) + 'px');
	if (el !== lastMenu) showMenu(el);
}

function updateMenu(over) {
	if (over) {
		if (window.outTimer) clearTimeout(outTimer);
	} else {
		if (window.outTimer) clearTimeout(outTimer);
		outTimer = window.setTimeout('closeMenu();', 350);
	}
}

function showMenu(el) {
	closeMenu();
	document.onclick = function() { closeMenu(lastMenu); };
	if ($(el).css('display') === 'none') $(el).css('display', '');
	lastMenu = el;
}

function closeMenu(el) {
	if (lastMenu !== '') {
		if (!el) el = lastMenu;
		if ($(el).css('display') == 'block') {
			$(el).css('display', 'none');
			document.onclick = '';
			lastMenu = '';
		}
	}
}

function setUser(name) { $('#userTab').html(name); $('#userTab').css('display', ''); $('#portalUser').css('display', ''); if ($('#userAddon').length) $('#userAddon').css('display', ''); }
function hMax(which) {  }

function monClick(clear, next) { if (actDay !== '') cross(actDay).style.backgroundColor = ''; $('#mn_' + clear).hide(); $('#mn_' + next).show(); actMon = (next > clear) ? actMon + 1 : actMon - 1; }

var calEventShowTimeout = 0;
var calEventHideTimeout = 0;
var eventInfoDiv =null;
var eventInfoGatheringDiv = null;
var calEventShowEventsTime = 250;
var calEventHideEventsTime = 750;
var calCurrentType = 1;
function initMyDesktopCalendar(type, that) {
	var target = Array();
	var color = Array();
	color[0] = '#f00';
	color[1] = '#ff0';

	if (type === null) type = 1;
	calCurrentType = type;
	$('.calD TD').each(function(){
		var sID = this.id.split('_');
		target[0] = (sID[6] === 1 || sID[6] === 3);
		target[1] = (sID[6] === 2 || sID[6] === 3);
		$(this).unbind('mouseenter').unbind('mouseleave');
		$(this).find('b').css('color', '');
		var totalEvents = sID[7];
		if (target[type] && totalEvents > 0) {
			$(this).find('b').css('color', color[type]);			
			
			$(this).hover(function(){
				$(this).addClass('H');
				var i = this.id.split('_');
				var d = $(this).find('b').text();
				var o = (type === 1);
				if (window.calEventShowTimeout) clearTimeout(calEventShowTimeout);
				calEventShowTimeout = window.setTimeout("calGetEventsOfDay("+d+", "+i[2]+", "+i[1]+", '"+this.id+"', "+o+", "+totalEvents+")", calEventShowEventsTime);
			}, function(){
				if (window.calEventShowTimeout) clearTimeout(calEventShowTimeout);
				$(this).removeClass('H');
			});
		}
	});
	
	if (that !== null) {
		oldSelectedLink === null ? $('A.selected').removeClass('selected') : oldSelectedLink.removeClass('selected');
		oldSelectedLink = $(that);
		oldSelectedLink.addClass('selected');
	}
}

var oldSelectedLink = null;
function calGetEventsOfDay(d, m, y, id, own, totalEvents) {
	if (eventInfoGatheringDiv === null) {
		eventInfoGatheringDiv = $(document.createElement('div'));
		eventInfoGatheringDiv.addClass("calDayGathering");
		eventInfoGatheringDiv.append("Gathering Information");
	} else {
		eventInfoGatheringDiv.remove();
		eventInfoGatheringDiv = null;
	}

	var that = $('#'+id);
	
	if (eventInfoDiv !== null) { $(eventInfoDiv).remove(); eventInfoDiv = null; }
	var theD = $(document.createElement('div'));
	theD.addClass('calDayInfo');
	theD.css('top', $(that).position().top + $('#ctl00_ContentPlaceHolder1_upEvents').offset().top + 20);
	theD.css('left', $(that).position().left + $('#ctl00_ContentPlaceHolder1_upEvents').offset().left);

	theD.append(eventInfoGatheringDiv);
	theD.draggable();
	
	if (window.calEventHideTimeout) clearTimeout(calEventHideTimeout);	
	theD.hover(function(){
		if (window.calEventHideTimeout) clearTimeout(calEventHideTimeout);
	}, function(){
		calEventHideTimeout = window.setTimeout("eventInfoDiv.remove()", calEventHideEventsTime);
	});

	
	eventInfoDiv = theD;
	$('body').append(theD);
	
	var userID = '';
	if (own) userID = $('.userName').attr('title').split(';')[0];
	
	
	// request information about that day
	var url = '/MyDesktop/AjaxEvents.aspx';
	var theDate = d + '.' + m + '.' + y;
	var parm = 'f=' + theDate + '&t=' +theDate + '&u=' + userID;
	
	return $.getJSON(url + '?' + parm, function(data){ return calDayShowEvents(data.Events, that, parm, totalEvents); });
}

function calDayShowEvents(eventList, that, parm, totalEvents) {
	if (eventInfoGatheringDiv !== null) {
		eventInfoGatheringDiv.remove();
		eventInfoGatheringDiv = null;
	}
	var eD = $(document.createElement('div'));
	if (eventList !== null) {
		var closeB = $(document.createElement('img')).attr('src','/img/closematchinfo.gif').css('float','right').css('cursor', 'Pointer').attr('alt', 'Close');
		closeB.bind('click', function(){eventInfoDiv.remove();});
		eD.append(closeB);
		
		var count = 0;
		$(eventList).each(function(){
			if (this.Time.length !== 0) count++;
		});
	
		if (count===1) eD.append(count + ' Match');
		else eD.append(count + ' Matches');
		if (totalEvents > 0) eD.append(' (' + totalEvents + ' total Matches)');
		
		if (count > 0) eD.append('&nbsp;&nbsp;&nbsp;<a href="#" onclick="calDayDownload(\''+parm+'\');">Download Schedules as iCal <img src="/img/bt_vcal.gif" alt="iCal" title="iCal"/></a>');
		
		eD.append('<br/>');
		
		var tbl = $(document.createElement('table')).width('100%').css('cursor', 'Default');
		$(eventList).each(function(){
			if (this.Time.length !== 0)
			{
				var a = $(document.createElement('a')).addClass('E').addClass(this.Gender).attr('href', this.ExternalLink).attr('target','_blank');
				
				if (this.Time.length === 0) this.Time = "&nbsp;";
				a.append($(document.createElement('span')).append(this.Time).addClass('t'));
				
				var l1 = $(document.createElement('img')).attr('src', 'http://flags.ehf.eu/1/' + this.VenueKz + '.gif').attr('title',this.VenueKz);
				if (this.VenueKz.length === 0) l1 = "&nbsp;";
				a.append($(document.createElement('span')).append(l1).addClass('i'));
				
				a.append($(document.createElement('span')).append(this.Venue + ' ('+this.VenueKz+')').addClass('v'));
				a.append($(document.createElement('span')).append(this.TeamAName + ' vs ' + this.TeamBName).addClass('op'));
				
				var tr = $(document.createElement('tr'));
				var td1 = $(document.createElement('td'));
				var td2 = $(document.createElement('td'));
				td1.append(a);
				td2.append('<a href="#" style="float:left;" onclick="calDayDownload(\''+parm+'&m=' + this.MatchID + '\');"><img src="/img/bt_vcal.gif" alt="iCal" title="iCal"/></a>');
				tbl.append(tr.append(td1).append(td2));
			}
		});
		eD.append(tbl);
	}
	else{
		eD.append(0 + ' Matches');
	}
	eventInfoDiv.append(eD);
	PrepareImg();
}


function calDayDownload(parm) { var url = '/MyDesktop/DownloadVCal.ashx'; window.open(url + '?'+ parm, 'Download'); }

function doInitClocks(start) {
	if (start) {
		now = new Date();

		$('#l_date')[0].innerHTML = AddZero(now.getDate()) + '.' + AddZero(now.getMonth() + 1) + '.' + now.getFullYear();
		$('#lc_h')[0].innerHTML = AddZero(now.getHours());
		$('#lc_m')[0].innerHTML = AddZero(now.getMinutes());

		s_hrs = parseInt($('#sc_h')[0].innerHTML, 10);
		s_min = parseInt($('#sc_m')[0].innerHTML, 10);
		l_hrs = now.getHours();
		l_min = now.getMinutes();
		t_min = parseInt($('#tt_m')[0].innerHTML, 10);
		t_sec = parseInt($('#tt_s')[0].innerHTML, 10);
		
		timer = window.setInterval('updateTimer();', 1000);
		clocks = window.setTimeout('doInitClocks(false);', (60 - now.getSeconds()) * 1000);
	} else {
		updateClocks();
		if (window.clocks) clearTimeout(clocks);
		clocks = window.setInterval('updateClocks();', 60000);
	}
	
	$('#user')[0].style.display = 'block';
}
function updateClocks() {
	l_min++; if (l_min > 59) { l_min = 0; l_hrs++; if (l_hrs > 23) { l_hrs = 0; } }
	s_min++; if (s_min > 59) { s_min = 0; s_hrs++; if (s_hrs > 23) { s_hrs = 0; } }

	$('#lc_h')[0].innerHTML = AddZero(l_hrs);
	$('#lc_m')[0].innerHTML = AddZero(l_min);
	$('#sc_h')[0].innerHTML = AddZero(s_hrs);
	$('#sc_m')[0].innerHTML = AddZero(s_min);
}

function updateTimer() {
	if (t_min <= 0 && t_sec <= 0) {
		if (window.timer) clearInterval(timer);
		if (window.clocks) clearInterval(clocks);

		if (isExtranet) {
			logout(true);
			bakeCookie('screensaver_isActive', 'false');
		}
		else logout();
	}
	else {
		t_sec--; if (t_sec < 0) { t_sec = 59; t_min--; }

		if (t_min === 0) {
			timeoutAlert = 1;
			$('#timing')[0].className = 'f_rd';
		} else {
			timeoutAlert = 0
			$('#timing')[0].className = '';
		}

		$('#tt_m')[0].innerHTML = AddZero(t_min);
		$('#tt_s')[0].innerHTML = AddZero(t_sec);
	}
}

function blinkAlert() {
	if (dotToggle) {
		dotToggle = false;
		$('#timingAtt')[0].className = 'b_wt f_wt';
	}
	else {
		dotToggle = true;
		$('#timingAtt')[0].className = 'b_rd f_wt';
	}
}

function hookEvent(element, eventName, callback) {
  if(typeof(element) === "string") element = document.getElementById(element);
  if(element === null) return;
  if(element.addEventListener) {
	if(eventName === 'mousewheel') element.addEventListener('DOMMouseScroll', callback, false); 
	element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent) element.attachEvent("on" + eventName, callback);
}

function logout(doNotClose) {
	if (doNotClose) { try { location.href="/Login/Logout.aspx"; } catch(e) {} }
	else {
		if (!isExtranet) {	
			try {
				window.opener='X';
				window.open('','_parent','');
				window.close();
				try{
					$(document.body).html('Sessiontime has expired.<br />Probably because of inactivity.<br /><br />Please <a href="/" target="_self">log in</a> again!');
				} catch(e){}
			} catch (e){ logout(true); }
		}
	}
}
function SetStartPage(permissionStringID) { bakeCookie('StartPage', permissionStringID, 31557600*5); }//31557600 = 1 Year
function GetExtraInfo(that, id) { that.onmouseout = function() { if (window.infoInTimer) clearTimeout(infoInTimer); infoInTimer = window.setTimeout(function() { RequestExtraInfo(that, id) }, 1000); }; }

function RequestExtraInfo(that, id) {
	that.onmouseout = '';
	if (window.infoInTimer) clearTimeout(infoInTimer);
	
	var info = $('#infoPopup')[0];
	var url = './gp.aspx';
	var parm = 'id=' + id;
	
	$.ajax({ type: "POST", url: url, data: parm, success: function(msg){ ShowExtraInfo(msg); } });

	info.style.top = getRealTop(that) + 1 + 'px';
	info.style.left = getRealLeft(that) + 33 + 'px';
}

function ShowExtraInfo(msg) { if (msg.length !== 0) { if (window.infoOutTimer) clearTimeout(infoOutTimer); doShowMsg(msg); } }
function doShowMsg(msg){ var info = $('#infoPopup'); info.html(Base64.decode(msg)).css('display', 'block'); infoOutTimer = window.setTimeout(function() { info.css('display', 'none'); clearTimeout(infoOutTimer); }, int_secureShowTimeOut); }

// obj = an input field
// returns inputfieldIndex
function getInputFieldIndex(obj) {
	var indexNr = -1;
	for (i = 1; i<= input.length; i++) {
		if (input[i-1].id === obj.id) indexNr = i;
	}	
	return indexNr;
}

function handleClick(e) {
	if (document.all) {// grab the x-y pos.s if browser is IE
		var scrollPos;
		if (typeof window.pageYOffset !== 'undefined') scrollPos = window.pageYOffset;
		else if (typeof document.compatMode !== 'undefined' && document.compatMode !== 'BackCompat') scrollPos = document.documentElement.scrollTop;
		else if (typeof document.body !== 'undefined') scrollPos = document.body.scrollTop;
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + scrollPos;
	} else {// grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}
	
	watcherMousePosX = tempX;	
	watcherMousePosY = tempY;
}

// obj = the pw inputfield itself
function doComparePasswords(obj) {
	try {
		var compareWithInputfieldID = (getInputFieldIndex(obj)-2);
		if (obj.value === input[compareWithInputfieldID].value) obj.className = 'field_ok';
		else obj.className = 'field_nok';

		if (input[compareWithInputfieldID].value.length === 0) obj.className = '';
	}
	catch(e) { alert(e); }
}

var modalMsg = false;

function doCheckPassword(el, strength, minlength) {
	var boolIsStrongEnough = false;
	checkPassword(el.value, minlength) >= strength ? boolIsStrongEnough = true : boolIsStrongEnough = false;
	boolIsStrongEnough ? el.className = 'field_ok' : el.className = 'field_nok';
	if (el.value.length === 0) el.className = '';
	
	return boolIsStrongEnough;
}

function checkPassword(pwd, minchars) {
	var strength = -1;
	if (!minchars) { minchars = 6; }
	
	var level1 = new RegExp('(?=.{'+minchars+',}).*', 'g'); // has to have minchars characters
	var level2 = new RegExp('^(?=.{'+minchars+',})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$', 'g'); // has to have minchars characters and: Uppercase and Lowercase letters OR Uppercase and numbers OR Lowercase and numbers
	var level3 = new RegExp('^(?=.{'+minchars+',})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$', 'g'); // has to have minchars characters and: Upper- and Lowercase letters and numbers
	var level4 = new RegExp('^(?=.{'+minchars+',})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$', 'g'); // has to have minchars characters and: Upper- and Lowercase letters, numbers and special-characters

	if (pwd.length===0) { strength = -1; // No password
	} else if (level4.test(pwd)) { strength = 4;
	} else if (level3.test(pwd)) { strength = 3;
	} else if (level2.test(pwd)) { strength = 2;
	} else if (level1.test(pwd)) { strength = 1;
	} else {  strength = 0; } // Less den minchars characters
	
	return strength;
}
function doLoader(str_loaderid,str_targetid,bool_switch,txt, specificId){
	AJAX_is_locked = true;

	if (bool_switch)
	{
		if (!txt) txt = 'Please Wait...';

		var loader_inside = $(document.createElement('div')).addClass('progspinner').css({width:80, height:50});
		var spinner = $(document.createElement('img')).attr('src','/img/aero_light.gif').attr('alt', ' ').css('display', 'inline').css('border', 0);
		loader_inside.append(spinner);
		loader_inside.append('<br/>');
		loader_inside.append($(document.createElement('span')).text(txt));
		var opt = { message: loader_inside, css: {
				border: 'none',
				backgroundColor: ''},
				overlayCSS:  {
					backgroundColor:'#fff',
					opacity:        '0.6'
				}
			};

		if (str_targetid) $('#' + str_targetid).block(opt);
		else{
			opt.overlayCSS.opacity = '0.8';
			$.blockUI(opt);
		}
	}
	else
	{
		AJAX_is_locked = false;
		if (specificId) $('#'+specificId+' .blockUI').remove();
		else $('.blockUI').remove();
	}
}

function reportAjaxError(request){ alert(request.responseText); }
function resizeNews(desiredHeight) { $('#newsFrame').css('height',  desiredHeight); }

function ShowGenericDOTNETPopUp(strPopupID) {
	// We know the MousePosition where the User Clicked!
	// Use watcherMousePosX and watcherMousePosY
	
	// Set Class - The Class can be added to a exisiting class
	$('#'+strPopupID).css('left', watcherMousePosX);
	$('#'+strPopupID).css('top', watcherMousePosY);
	$('#'+strPopupID)[0].className = 'popupShow';	
}
// Set Class - Maybe Remove Sichtbareklasse
function HideGenericDOTNETPopUp(strPopupID){ $('#'+strPopupID)[0].className = 'popupHidden'; }

<!-- BEGIN ScreenSaver //-->
var secLock_offset = 0;

function doShowScreensaver(){
	if (!bool_screensaver_isActive) {
		doShowModal();
		if (readCookie('screensaver_isActive') === 'true') changeOpac($('#secLock')[0], int_screensaver_opacity);
		else fadeIn('secLock', 0, int_screensaver_opacity);
		var s = $('#secLock_inpt');
		s.css('top', Math.ceil(((getWinHeight()+parseInt($('#secLock_inpt')[0].offsetHeight,10))/2)));
		s.css('zIndex', 10000).css('display', '');
		bakeCookie('screensaver_isActive', 'true');

		bool_screensaver_isActive = true;	
		$('#secLock_pw').focus();
	}
}

function doHideScreensaver(){
	doHideModal();
	bakeCookie('screensaver_isActive', 'false');
	doLoader('loader_inside','secLock_inpt',false);
	$('#secLock_inpt').css('zIndex', -1).css('display', 'none');
	
	bool_screensaver_isActive = false;
}

function doShowModal(index) { var elem = 'secLock'; if (index) elem += index; var secLockHeight = getPageHeight(); $('#'+elem).css('display', 'block').css('height', secLockHeight); changeOpac($('#'+elem)[0], int_screensaver_opacity); }
function doHideModal(index) { var elem = 'secLock'; if (index) elem += index; fadeOut(elem, int_screensaver_opacity); }

function init_screensaver(){
	status_screensaver_timeout = int_screensaver_timeout;
	clearTimeout(obj_screensaver_timeout);
	obj_screensaver_timeout		= window.setTimeout('doShowScreensaver();', int_screensaver_timeout*1000);
	if (eosdebug) {
		status_screensaver_timeout = status_screensaver_timeout;
		init_screensaver_status();
	}
}
function init_screensaver_status(){
	clearTimeout(obj_status_screensaver_timeout);
	if (status_screensaver_timeout>=0) {
		if ($('#scr_timeout').length) $('#scr_timeout').html(status_screensaver_timeout + ' until Screensaver');
		window.status = status_screensaver_timeout + ' until Screensaver';
	}
	obj_status_screensaver_timeout = window.setTimeout('init_screensaver_status();', 1000);
	status_screensaver_timeout--;
}

function doCheckReturnScreenSaver(e) { if(window.event) keynum = e.keyCode; else if(e.which) keynum = e.which; if (keynum === 13) doCheckScreensaver(); }

function doCheckScreensaver() {
	var boolGoon = false;
	var pw = MD5($('#secLock_pw').val());

	// Check Password
	if (pw !== cachedpw) {
		$('#secLock_pw').val('');
		// To many trys! Reload page
		if (int_secLock_retrys >= int_screensaver_retrys) document.location.reload();
		else {
			int_secLock_retrys++;
			alert('Wrong password, please try again...');
		}
	} else {
		var boolGoon = true;
		$('#secLock_pw').val('');
		doHideScreensaver();
		init_screensaver();
	}

	var url = '/Login/Check/Authcheck.aspx?t='+new Date()*1;
	var pars = '';
	if (boolGoon) {
		doLoader('loader_inside','secLock_inpt',true); // Show that we are working
		try {
			$.ajax({ type: "POST", url: url, data: pars, success: function(msg){ doCheckScreensaverOK(msg); } });
		} catch(e){ doLogout(); }
	}
}

function doCheckScreensaverOK(msg) {
	try {
		if (msg === 'True') { // We are still logged in - just reset the timer
			t_min = sessionTimeOut;
			t_sec = '01';
			doHideScreensaver();
			init_screensaver();
		} else { // We are logged out. redirect to login page!
			doLogout();
		}
	}
	catch(e){ doLogout(); }
}


function expandLoginTime()
{
	var url = '/Login/Check/Authcheck.aspx?t='+new Date()*1;
	var pars = '';
	$.ajax({ type: "POST", url: url, data: pars, success: function(msg){ doexpandLoginTimeOK(msg); } });
}

function doexpandLoginTimeOK(msg)
{
	if (msg === 'True') { // We are still logged in - just reset the timer
		t_min = sessionTimeOut;
		t_sec = '01';
		init_screensaver();
	} else { // We are logged out. redirect to login page!
		doLogout();
	}
}

var cookieDependendTimer = 0;
function startCookieDependendTimer() {
	clearTimeout(cookieDependendTimer);
	cookieDependendTimer = window.setTimeout('startCookieDependendTimer();', 30000);
	doGetTimeStamp();
}

function doGetTimeStamp() {
	var url = '/Login/Check/GetTimeStamp.ashx';
	var pars = '';
	$.ajax({ type: "POST", url: url, data: pars, success: function(msg){ doCheckTimeStamp(msg); } });
}

function doCheckTimeStamp(msg) {
	var timestamp = msg;
	
	var now = new Date();
	var cH = now.getHours();
	var cM = now.getMinutes();
	var cS = now.getSeconds();

	var tsH = 0, tsM = 0, tsS = 0;
	try {
		var tsSplitted = timestamp.split(':');
		tsH = parseInt(tsSplitted[0], 10);
		tsM = parseInt(tsSplitted[1], 10);
		tsS = parseInt(tsSplitted[2], 10);
		if (isNaN(tsH) || isNaN(tsM)|| isNaN(tsS)) {
			var tsSplitted = eatCookie('timestamp')[0].split(':');
			tsH = parseInt(tsSplitted[0], 10);
			tsM = parseInt(tsSplitted[1], 10);
			tsS = parseInt(tsSplitted[2], 10);
		}
		
		if (isNaN(tsH) || isNaN(tsM)|| isNaN(tsS)) { }
		else {
			// Add SessionTimeout to Timestamp	
			if ((tsM + sessionTimeOut) >= 60) {
				tsH++;
				tsM = (tsM+sessionTimeOut-60);
			} else {
				tsM += sessionTimeOut;
			}
			
			// Check if Timestamp + sessionTimeout < currentime
			if (cH >= tsH && cM >= tsM) { }// current H and current M are > then ts + sT!!
			else {// Everything is fine. Reset Clock to last timediff
				var dH = dM = dS =0;
				
				dM = tsM - cM;
				dS = tsS - cS;
				if (dM > sessionTimeOut) { dM -= sessionTimeOut; }
				if (dM < 0) { dM = sessionTimeOut; }
				if (dS < 0) { dM -= 1; dS += 60; }
				
				t_min = dM;
				t_sec = dS;
			}
		}
	}
	catch(e){}
}

function doWriteTimeStamp() {
	var now = new Date();
	var h = now.getHours();
	var m = now.getMinutes();
	var s = now.getSeconds();
	var ts = h + ':' + m + ':' + s;
	bakeCookie('timestamp', ts, 36000000, '.ehf.eu');
	bakeCookie('timestamp', ts, 36000000, '.ehf');
	bakeCookie('timestamp', ts, 36000000, '.ehf.test');
	bakeCookie('timestamp', ts, 36000000, '.test');
}

function doLogout() {
	// As we dont know on which domain we are, we log out and reload just reload this page!
	try { if ($('#ctl00$Navi1$btnLogout').length){ __doPostBack('ctl00$Navi1$btnLogout','');} } catch(e){}
	try { if ($('#Navi1_btnLogout').length){ __doPostBack('Navi1$btnLogout','');} } catch(e){}
}

function doMoveScreensaver() {  $('#secLock').css('top', window.pageYOffset); }
function doResizeScreensaver() {  $('#secLock').css('height', getWinHeight()); }
<!-- END ScreenSaver //-->



function ChngeRprtRw(id) {
	var className = 'reportActiveRow';
	var tL = $('#trRptLst_'+id);
	if (tL.is('.'+className)) { tL.removeClass(className);
		$('#cbxRptLst_'+id)[0].checked = false;
	} else { tL.addClass(className);
		$('#cbxRptLst_'+id)[0].checked = true;
	}
}

function CheckAllWithRow(that, chkboxPrefix, rowPrefix) {
	check = that.checked;
	var className = 'reportActiveRow';
	tr = (ie) ? ie.tags('tr') : document.getElementsByTagName('tr');
	for (i = 0; i < input.length; i++) {
		if (input[i].id !== null && input[i].id.split('_')[0] === chkboxPrefix) input[i].checked = check;
	}
	
	for (i = 0; i < tr.length; i++) {
		if (tr[i].id !== null && tr[i].id.split('_')[0] === rowPrefix) {
			check ? tr[i].className = className : tr[i].className = '';
		}
	}
}

function ShowPlayinghallReports(detailLvl) {
	var ids = '';
	for (i = 0; i < input.length; i++) {
		if (input[i].id !== null && input[i].id.split('_')[0] === 'cbxRptLst') {
			if (input[i].checked) ids += input[i].id.split('_')[1] + ';';
		}
	}
	
	if (ids.length !== 0) window.open('/SharedControls/GenerateReports.ashx?typ=h&d=' + detailLvl + '&h=' + ids);
	else alert('You have to check at least one Report first');
}

var oldCompTypeID = 0;
function ChngeGrnbkRprtRw(id) {
	// Split Up the ID
	var ids = id.split('_');
	var compTypeID = ids[0];
	var compID = ids[1];
	if (compTypeID !== oldCompTypeID) {
		if (oldCompTypeID !== 0) HideOldGreenbookReportsMarkings(oldCompTypeID);
		oldCompTypeID = compTypeID;
	}
	var tL = $('#trRptLst_'+id);
	var className = 'reportActiveRow';
	if (tL.is('.'+className))  { tL.removeClass(className);
		$('#cbxRptLst_'+id)[0].checked = false;
	} else { tL.addClass(className);
		$('#cbxRptLst_'+id)[0].checked = true;
	}
}

function SChngMrkRw(that) {
	var className = 'reportActiveRow';
	if ($(that).is('.'+className)) $(that).removeClass(className);
	else $(that).addClass(className);
}

function HideOldGreenbookReportsMarkings(compID) {
	for (i = 0; i < input.length; i++) {
		if (input[i].id !== null && input[i].id.split('_')[0] === 'cbxRptLst') {
			if ((input[i].id.split('_')[1] === compID) && input[i].checked) {
				$('#trRptLst_'+input[i].id.split('_')[1]+'_'+input[i].id.split('_')[2])[0].className = '';
				input[i].checked = false;
			}
		}
	}
}

function ShowGreenbookReports(Season, gender) {
	var ids = '';
	for (i = 0; i < input.length; i++) {
		if (input[i].id !== null && input[i].id.split('_')[0] === 'cbxRptLst') {
			if ((input[i].id.split('_')[1] === oldCompTypeID) && input[i].checked) ids += input[i].id.split('_')[2] + ';';
		}
	}
	if (ids.length !== 0) window.open('/SharedControls/GenerateReports.ashx?typ=a&Season=' + Season + '&mw=' + gender + '&bewerbTyp=' + oldCompTypeID + '&b=' + ids);
	else alert('You have to check at least one Report first');
}

function SwitchPoStreet(street) { street ? $('#streetPoBox').html('Street:') : $('#streetPoBox').html('P.O. Box:'); }

function switchMarking(that, unmark, className) {
	unmark ? $(that).removeClass(className) :  $(that).addClass(className);
	that.onclick = function() { calMarkDay(that, !unmark, className); }
}

function ShowCalLegend(that) { $(that).css( { left: "120px", top: "270px", width: "270px", height: "100px", zIndex: "5", display: "block" }); }
function HideCalLegend(that) { $(that).css( { zIndex: "-1", display: "none" }); }

var imgTimer = 0;
function showImg(that, e) { clearImgTimer(); doShowImg(that, e); }

function doShowImg(that, e) {
	handleClick(e);
	clearImgTimer();
	var i = $('#imgShower');
	var iSrc = that.src;
	if ($(that).attr('bigOne')) iSrc = $(that).attr('bigOne');
	i.attr('src', iSrc).attr('alt', that.alt).attr('title', that.title)
	.css('left', watcherMousePosX+10).css('top', watcherMousePosY-10)
	.css('zIndex', 100).css('display', 'block');
}

function doMoveImg(that, e) {
	handleClick(e);
	var i = $('#imgShower');
	i.css('left', watcherMousePosX+10).css('top', watcherMousePosY-10);
	i.css('zIndex', 100).css('display', 'block');
}

function hideImg(that) { clearImgTimer(); imgTimer = window.setTimeout('doHideImg(\''+that.id+'\');', 350); }

function doHideImg(el)
{
	var i = $('#imgShower');
	clearImgTimer();
	
	i.attr('src','/img/p.gif').attr('alt', '').attr('title', '');
	i.css('left', 0).css('top', 0).css('zIndex', -1).css('display', 'none');
}

function clearImgTimer() { if (window.imgTimer) clearTimeout(imgTimer); }
function LoadP(url)
{
	doLoader('loader_inside', 'right', true, 'Requesting...');
	setTimeout(function(){window.location=url;}, 500);
}

function ShowPPMView(that) {
	$(that).parents('div.infoBox').find('div.editBox').hide();	
	$('#r_cont').find('div.viewBox:hidden').show();
}

function ShowPPMEdit(that) {
	$('#r_cont').find('div.viewBox:hidden').show();
	$('#r_cont').find('div.editBox:visible').hide();
	$(that).parents('div.infoBox').find('div.viewBox').hide();
	$(that).parents('div.infoBox').find('div.editBox').show();
	doLayout();
}

function HidePPEdit(that) {
	$('#r_cont').find('div.viewBox:hidden').show();
	$('#r_cont').find('div.editBox:visible').hide();
	$(that).parents('div.infoBox').find('div.viewBox').hide();
	$(that).parents('div.infoBox').find('div.editBox').show();
	doLayout();
}

function SubmitPPEdit(that, id)
{
	if (CheckGroupIfs(id.split('_')[1]))
	{
		var loaderTarget = 'ar_' + id.split('_')[1];
		doLoader('loader_inside', loaderTarget, true, 'Updating...');
		$('#'+id).ajaxSubmit({
			dataType: 'json',
			success: function(data, statusText, xhr){
				if (data.Status == 0 && data.Error.length == 0) // everything fine
				{
					if (data.Type == 1) PPEditUpdateFields(id);
					HidePPEdit(that);
				}
				
				if (data.Status != 0)
				{
					var msg = 'An Error occured. Database Return Status: ' + data.Status + '\n';
					if (data.Error.length != 0) msg += 'ErrorMessage: ' + data.Error;
					alert(msg);
				}
				else if (data.Error.length != 0)
				{
					var msg = 'An Error occured: ' + data.Error;
					alert(msg);
				}
				
				if (data.ImageUpload != 0)
				{
					switch(data.Type)
					{
						case 1:
							if (data.CompetitionId) PPEditUpdatePlayerImage(id, data.CompetitionId);
							else PPEditUpdatePlayerImage(id);
							break;
						case 2:
							if (data.CompetitionId) PPEditUpdateTeamClubImage(data.TeamId, data.ClubId, data.ImageUpload, data.CompetitionId);
							else PPEditUpdateTeamClubImage(data.TeamId, data.ClubId, data.ImageUpload);
							break;
					}					
				}
				
				doLoader('loader_inside', loaderTarget, false);
			},
			error: function(data, statusText)
			{
				alert('The following Serverside Error occured:\n' + data.responseText);
				doLoader('loader_inside', loaderTarget, false);
			}
		});
	}else{
		alert('Some information do not seem right.\nPlease check your Input');
	}
}

function PPEditUpdateFields(id)
{
	var playerId = id.split('_')[1];
	
	var txtPlaceOfBirth = $('#' + id + ' INPUT[id*=txtPlaceOfBirth]');
	var txtCaps = $('#' + id + ' INPUT[id*=txtCaps]');
	var txtWeightInKg = $('#' + id + ' INPUT[id*=txtWeightInKg]');
	var txtHeightInCm = $('#' + id + ' INPUT[id*=txtHeightInCm]');
	var ddlPlayerPosition = $('#' + id + ' SELECT[id*=ddlPlayingPosition]');
	var txtShirtNr = $('#' + id + ' INPUT[id*=txtShirtNr]');	
	
	var spanPlaceOFBrith = $('#pob_' + playerId);
	var spanCaps =$('#caps_' + playerId);
	var spanWeight = $('#weight_' + playerId);
	var spanHeight =  $('#height_' + playerId);
	var spanPP = $('#pp_' + playerId);
	var spanSn = $('#sn_' + playerId);
	
	if (txtPlaceOfBirth.val().length > 0) txtPlaceOfBirth.removeClass('old');
	if (txtCaps.val().length > 0) txtCaps.removeClass('old');
	if (txtWeightInKg.val().length > 0) txtWeightInKg.removeClass('old');
	if (txtHeightInCm.val().length > 0) txtHeightInCm.removeClass('old');
	if (ddlPlayerPosition.find(':selected').val() > 0) ddlPlayerPosition.removeClass('old');
	if (txtShirtNr.val().length > 0) txtShirtNr.removeClass('old');
	
	spanPlaceOFBrith.text(txtPlaceOfBirth.val());
	spanCaps.text(txtCaps.val());	
	spanWeight.text(txtWeightInKg.val());
	spanHeight.text(txtHeightInCm.val());
	spanPP.text(ddlPlayerPosition.find(':selected').text());
	spanSn.text(txtShirtNr.val());
}

function PPEditUpdatePlayerImage(id, compId)
{
	var playerId = id.split('_')[1];
	var season = '';
	$(window.location.search.replace('?','').split('&')).each(function(){
		var s = this.split('=');
		if (s[0]=='s') season = s[1];
	});
	var i = 'http://res.ehf.eu/images/players/' + season + '/P_' + season + '_' + playerId + '_S.jpg?' + new Date()*1;
	var iB = 'http://res.ehf.eu/images/players/' + season + '/P_' + season + '_' + playerId + '_B.jpg?' + new Date()*1;

	if (compId)
	{
		var i = 'http://res.ehf.eu/images/players/c/' + compId + '/thumb/' + playerId + '.jpg?' + new Date()*1;
		var iB = 'http://res.ehf.eu/images/players/c/' + compId + '/' + playerId + '.jpg?' + new Date()*1;
	}
	
	
	$('#iv_' + playerId).find('.ptPic').attr('src', i).attr('bigOne', iB);
	$('#ev_' + playerId).find('.ptPic').attr('src', i).attr('bigOne', iB);
}

function PPEditUpdateTeamClubImage(teamId, clubId, whatToUpdate, compId)
{
	var ct = false;
	$(window.location.search.replace('?','').split('&')).each(function(){
		var s = this.split('=');
		if (s[0]=='s') season = s[1];
		if (s[2]=='ct') ct = s[2];
	});
	
	var tS= 'http://res.ehf.eu/images/teams/' + season + '/T_' + season + '_' + teamId + '_B.jpg?' + new Date()*1;
	var tB = 'http://res.ehf.eu/images/teams/' + season + '/T_' + season + '_' + teamId + '_B.jpg?' + new Date()*1;
	var cS= 'http://res.ehf.eu/images/logos/clubs/' + season + '/C_' + season + '_' + clubId + '_S.jpg?' + new Date()*1;
	var cB = 'http://res.ehf.eu/images/logos/clubs/' + season + '/C_' + season + '_' + clubId + '_B.jpg?' + new Date()*1;
	
	if (ct && ct == 2)
	{
		var tS= 'http://res.ehf.eu/images/teams/c/' + compId + '/thumb/' + teamId + '.jpg?' + new Date()*1;
		var tB = 'http://res.ehf.eu/images/teams/c/' + compId + '/' + teamId + '.jpg?' + new Date()*1;
		var cS= 'http://res.ehf.eu/images/logos/clubs/c/' + compId + '/thumb/' + clubId + '.jpg?' + new Date()*1;
		var cB = 'http://res.ehf.eu/images/logos/clubs/c/' + compId + '/' + clubId + '.jpg?' + new Date()*1;
	}
	
	if (whatToUpdate == 1 || whatToUpdate == 3){
		$('#tV_' + teamId).find('.ptTeamPic').attr('src', tS).attr('bigOne', tB);
		$('#tE_' + teamId).find('.ptTeamPic').attr('src', tS).attr('bigOne', tB);
	}
	if (whatToUpdate == 2)
	{
		$('#tV_' + teamId).find('.ptTeamLogo').attr('src', cS).attr('bigOne', cB);
		$('#tE_' + teamId).find('.ptTeamLogo').attr('src', cS).attr('bigOne', cB);
	}
}

function DeletePPImage(that, id, type, season)
{
	var loaderTarget = $(that).parent();
	doLoader('loader_inside', loaderTarget, true, 'Updating...');

	var pars = 'id=' + id + '&type=' + type + '&s=' + season;

	/*var url = '/Prep/DeleteImage.ashx';
	$.ajax({ type: "POST", url: url, data: pars,
		success: function(data){
			doLoader('loader_inside', loaderTarget, false);
		}
		error: function(){
			doLoader('loader_inside', loaderTarget, false);
		}
	});*/
}

var changes = new Array();
function AddChange(that, name, group) {
	if (group === undefined || group === null) group=0;
	if (!changes[group]) changes[group] = new Array();
	
	for (i = 0; i <= changes[group].length; i++) {
		if (changes[group][i] === name) return;
	} 
	changes[group][changes[group].length] = name;
	if (that !== null) $(that).addClass("fieldChanged");
}

function CheckChanges(group) {
	var proceed = true;
	var catCount = 0;
	var totalChanges = 0;
	var listText = '';
	var confirmText = '';
	
	if (group === null) group = 0;

	if (typeof(group) === 'undefined') group = changes;
	else if (typeof(group) !== 'object') {
		// create an array
		var tempGroup = group;
		group = new Array();
		group[tempGroup] = null;
	}
	
	for (var index in group) {
		if (index === null) index = 0;
		if (changes[index] && changes[index].length > 0) {
			catCount++;
			totalChanges += changes[index].length;
			
			if (index !== 0) listText += '\n' + index + ':\n';
			
			for (i = 0; i < changes[index].length; i++) listText += i+1 + ') ' + changes[index][i] + '\n';
		}
	}
	
	if (totalChanges > 30) {
		listText = 'On:\n';
		for (var index in group) {
			if (index === null) index = 0;
			if (changes[index] && changes[index].length > 0) {
				if (index !== 0) listText += '- ' + index + '\n';
				else listText += '- Mainform\n';
			}
		}
	}
	
	if (catCount !== 0) {
		if (totalChanges > 1) confirmText += 'You did make ' + totalChanges + ' changes:\n\n';
		else confirmText += 'You did make ' + totalChanges + ' change:\n\n';
		confirmText += listText;
		confirmText += '\n';
		confirmText += 'However, if you proceed the following action all changes would be lost...\n';
		confirmText += 'Proceed?\n';
	
		proceed = confirm(confirmText);
		if (proceed) {
			for (var index in group) ClearChanges(index);
		}
	}
	return proceed;
}

function ClearChanges(group) {
	if (group === undefined || group === null) changes = new Array();
	else changes[group] = new Array();
	
	$('.fieldChanged').removeClass('fieldChanged');
}

function CreateUserFriendlyFields(findIn) {
	/*if (typeof(findIn) == 'undefined' || findIn != null) findIn = '';
	var target = $(findIn + ' INPUT, ' + findIn + ' SELECT, ' + findIn + ' TEXTAREA');
	
	target.focus(function() { $(this).addClass("fieldActive"); });
	target.blur(function() { DeactivateField(); });
	target.find('*[friendly]').change(function(){ AddChange(this, $(this).attr('friendly'), $(this).attr('friendlygroup')); });
	*/
}
function RemoveUserFriendlyFields(){ $('*[friendly]').unbind('change'); }
function ActivateField(that) { $(that).addClass("fieldActive"); }
function DeactivateField() { $('.fieldActive').removeClass('fieldActive'); }

function CheckGroupIfs(group, that) {
	var proceed = true;
	if (group == null) group = 0;

	if (group == 0) {
		var searchIn = null;
		if (that != undefined) searchIn = $(that);
		else searchIn = $('*');
		if (searchIn != null) {
			searchIn.find('[checkif]').each(function () {
				var $this = $(this);
				var isOk = true;

				var $checks = $this.attr('checkif').split(';');
				for (var i = 0; i < $checks.length; i++) {
					switch ($checks[i]) {
					case 'email': isOk = this.value.length && isValidEmail(this.value); break;
					case 'hp': isOk = this.value.length && isValidURL(this.value); break;
					case 'int': isOk = this.value.length && isInt(this.value); break;
					case 'Nint': isOk = (this.value.length && isInt(this.value)) || this.value.length == 0; break;
					case 'float': isOk = this.value.length && isFloat(this.value); if (isOk) this.value = isOk; break;
					case 'Nfloat': isOk = (this.value.length && isFloat(this.value)) || this.value.length == 0; break;
					case 'numeric': isOk = this.value.length && isNumeric(this.value); break;
					case 'NNumeric': isOk = (this.value.length && isNumeric(this.value)) || this.value.length == 0; break;
					case 'date': isOk = this.value.length && isDate(this.value); break;
					case 'Ndate': isOk = (this.value.length && isDate(this.value)) || this.value.length == 0; break;
					case 'notnull': isOk = this.value.length > 0; break;
					case 'notzero': isOk = this.value != '0'; break;
					}

					if (!isOk) break;

					if ($checks[i].indexOf('!') == 0) {
						if ($checks[i].substring(1, $checks[i].length) == this.value) isOk = false;
					}

					if (!isOk) break;
				}

				//if(debug && console) console.log('check for if ' + $this.attr('id') + ' > ' + this.value + ' is ' + $this.attr('checkif') + ' => ' + isOk);

				// which field does indicate status?
				var field = $this;
				if ($this.attr('linkedWithID')) var field = $('#' + $this.attr('linkedWithID'));

				if (isOk) field.removeClass('error');
				else field.addClass('error');

				if (!isOk) proceed = false;
			});
		}
	}
	
	return proceed;
}

function ShowMsgBox(title, text, mode, position, logout) {
	$(document).ready(function() {
		var color = 'red', ico = 'problem';
		switch (mode) {
			case 'Error':	color = 'red';		ico = 'problem'; break;
			case 'Warning':	color = 'yellow';	ico = 'warning'; break;
			case 'Info':	color = 'blue';		ico = 'info'; break;
			case 'OK':		color = 'green';	ico = 'ok'; break;
		}
		
		var tbl = $(document.createElement('table')).css('width', 200).addClass('sM').addClass('msg' + mode + 'B').draggable();

		var closeXButton = $(document.createElement('img')).addClass('mouse').attr('alt', 'Close')
			.attr('src', '/img/bt_x_' + color + '.gif');
		closeXButton.unbind('click');
		if (logout === true) closeXButton.click(function() { location.href="/Login/Logout.aspx"; });
		else closeXButton.click(function() { $.unblockUI(); });

		var closeNormalButton = $(document.createElement('a')).attr('alt', 'Close')
			.addClass('button small').text('Close');
		closeNormalButton.unbind('click');
		if (logout === true) closeNormalButton.click(function() { location.href="/Login/Logout.aspx"; });
		else closeNormalButton.click(function() { $.unblockUI(); });

		if (mode == 'OK' && !logout) $('.blockOverlay').attr('title','Click to unblock').click($.unblockUI);
		
		var trh = $(document.createElement('tr')).addClass('sMH').addClass('msg' + mode + 'H');
		var tdh1 = $(document.createElement('td')).addClass('sMHL').attr('colSpan', 2).append(title);
		var tdh2 = $(document.createElement('td')).addClass('sMHR').append(closeXButton);
		var trf = $(document.createElement('tr'));
		var tdf1 = $(document.createElement('td')).addClass('sMBL');
		tdf1.append($(document.createElement('img')).attr('alt', mode).attr('src', '/img/ico_' + ico + '.gif'));
		var tdf2 = $(document.createElement('td')).addClass('sMBR').append(text);
		var tdf3 = $(document.createElement('td'));		
		var trc = $(document.createElement('tr'));
		var tdc1 = $(document.createElement('td')).attr('colSpan', 3).addClass('sMF');
		trc.append(tdc1.append(closeNormalButton));

		trh.append(tdh1).append(tdh2);
		trf.append(tdf1).append(tdf2).append(tdf3);
		tbl.append(trh).append(trf).append(trc);
		
		$.blockUI({ message: tbl, css: {
				border: 'none',
				backgroundColor: ''}
			});
	});
}

function doAddrCopyTo(that, target, maxlength) {
	var val = '';
	var i=0;
	for(i = 0; i < that.length; i++){
		// if we are a selectbox
		if (that[i].find('option').length > 1) val += ' ' + that[i][0].options[that[i][0].selectedIndex].text;
		else val += ' ' + that[i].val();
	}

	val = $.trim(val);
	if (maxlength && val.length > maxlength) val = val.substr(0, maxlength);
	
	for(i = 0; i < target.length; i++) target[i].val(val);

	return true;
}

// search Language Dropdowns
function ApplyLanguageLogic() { $('.language').bind('change', function(){ LanguageLogic($(this)); }); }

function LanguageLogic(sender) {
	var fieldarr = Array();
	$('.language').each(function(){ fieldarr[fieldarr.length] = $(this); });
	doLanguageLogic(fieldarr, sender);
}

function doLanguageLogic(fields, sender) {
	var cval = sender.val();
	if (cval.length > 0) {
		// go through all other fields
		for (f=0; f < fields.length; f++) {
			var ofield = fields[f];
			var oval = ofield.val();
			if (sender.context !== ofield.context) {
				if (cval === oval) ofield[0].selectedIndex = 0;
			}
		}
	}
}

var rulesPageSize = Array();
rulesPageSize['01'] = 13;
rulesPageSize['02'] = 15;
rulesPageSize['03'] = 29;
rulesPageSize['04'] = 27;
rulesPageSize['05'] = 13;
rulesPageSize['06'] = 28;
var currentRulePage = '00';
function LoadRulesPage(pageNr) {
	$('.rulePage').hide();
	$('#page' + pageNr).show();
	$('.rulesPreview IMG').hide();
	$('#rPimg_' + pageNr).show();
	doRulesNavi(pageNr);
	doLayout();
	expandLoginTime();
	
	// remove friendly fields
	RemoveUserFriendlyFields();
}

function doRulesNavi(pageNr){
	currentRulePage = pageNr;
	var tabs = $('#right DIV.tabs');
	tabs.html('');
	
	tabs.append(getRuleLabel('00', pageNr));
	
	for (var i = 1; i <= 6; i++){
		var p = '0' + i;
		var e;
		if ('0' + i === pageNr){ e = $(document.createElement('label'));
		}else{
			e = $(document.createElement('a')).attr('href', '#');
			e.attr('index', p).click(function(){LoadRulesPage($(this).attr('index'));return false;});
		}
		e.text('Page ' + i);
		tabs.append(e);
		tabs.append(' ');
	}
	
	tabs.append(getRuleLabel('07', pageNr));
	tabs.append(getRuleLabel('08', pageNr));
	tabs.append(' ');
	SaveRulesPage(pageNr, 2);
}

function getRuleLabel(page, currentpage)
{
	var e;
	if (page === currentpage){
		e = $(document.createElement('label'));
		RulesReloadAdPics();
	}else{
		e = $(document.createElement('a')).attr('href', '#');
		e.attr('index', page).click(function(){LoadRulesPage($(this).attr('index'));return false;});
	}
	if (page == '00') e.text('Front');
	if (page == '07') e.text('Back');
	if (page == '08') e.text('General');
	return e;
}

function SaveFontSize()
{
	var pars = 'l=' + $('.langSel').val() + '&font_size=' + $('#font_size').val();
	
	var url = 'SaveLang.ashx' + '?t=' + new Date()*1;
	$.ajax({ type: "POST", url: url, data: pars,
		success: function(msg){ SaveRulesDone(msg); }
	});
}

function rteCutTags(s) { return s.replace(/(<[^\/biu][^biu][a-z0-9]*[^>]*>|<\/[^biu][a-z0-9]*>)/gi, ''); } 

function SaveRulesPage(pageNr, previewMode) {
	expandLoginTime();
	
	var pars = 'l=' + $('.langSel').val();

	$('#loader_text').html('Saving Information...');	
	if (previewMode == 1) $('#loader_text').html('Preparing Information...');	
	if (previewMode == 2) $('#loader_text').html('Preparing Information...');	
	
	$('#ctl00_UpdateProgress1').css('display', '');
	
	if (pageNr == '00' || pageNr == undefined) pars += '&target_language_name=' + $('#target_language_name').val();
	if (pageNr == '00' || pageNr == undefined) pars += '&DeactivateFitDiacrit=' + $('#DeactivateFitDiacrit:checked').length;
	if (pageNr == '08' || pageNr == undefined) pars += '&font_size=' + $('#font_size').val() + '&font_type=' + $('#font_type').val() + '&title_size=' + $('#title_size').val();
		
	if (pageNr != undefined)
	{
		for(i = 1; i <= rulesPageSize[pageNr]; i++) {
			var id = pageNr + '' + ((i <=9) ? '0'+i : i );
			var field = $('#' +id);
			if (!rte.instances[id]) {
				pars += '&' + id + '=' + field.val().replace(/\n/g, '<br />');
			}else{ // else its a RTE textarea
				pars += '&' + id + '=' + escape(rteCutTags(rte.instances[id].get_content()));
			}
		}
		pars += '&cbx_p_' + pageNr + '_finished=' + $('#cbx_p_'+pageNr+'_finished:checked').length;
	}else{
		for (j=1; j<=6; j++)
		{
			pageNr = (j<=9)? '0'+j : j;
			for(i = 1; i <= rulesPageSize[pageNr]; i++) {
				var id = pageNr + '' + ((i <=9) ? '0'+i : i );
				var field = $('#' +id);
				if (!rte.instances[id]) {
					pars += '&' + id + '=' + field.val().replace(/\n/g, '<br />');
				}else{ // else its a RTE textarea
					pars += '&' + id + '=' + escape(rteCutTags(rte.instances[id].get_content()));
				}
			}
		}
		for (j=0;j<=7;j++){
			pageNr = (j<=9)? '0'+j : j;
			pars += '&cbx_p_' + pageNr + '_finished=' + $('#cbx_p_'+pageNr+'_finished:checked').length;
		}
	}
	
	var url = 'SaveLang.ashx' + '?t=' + new Date()*1  + '&u=' + userID + '&prev=' + (previewMode ? 1 : 0) + '&p=' + pageNr;
	if (previewMode === 1) $.ajax({ type: "POST", url: url, data: pars, success: function(msg){ SaveRulesDone(msg, 1); } });
	else if (previewMode === 2) $.ajax({ type: "POST", url: url, data: pars, success: function(msg){ SaveRulesDone(msg, 2); } });
	else $.ajax({ type: "POST", url: url, data: pars, success: function(msg){ SaveRulesDone(msg, 0); } });
}

function SaveRulesDone(msg, previewMode){
	$('#ctl00_UpdateProgress1').css('display', 'none');
	if(!previewMode) doRulesCheckPagesFinished();
	expandLoginTime();
	switch(previewMode)
	{
		case 1: LoadRulesPDF($('.langSel').val(), userID, msg); break;
		case 2: doLoadPreviewImage($('.langSel').val(), userID, msg); break;
	}
}

function LoadRulesLang(id) {
	expandLoginTime();
	RulesClearAllFields();
	$('#r_cont .infoBox').css('display', '');
	$('#chooseLang').css('display', 'none');
	$('#btnSaveAll').css('display', '');
	var url = 'GetLang.aspx';
	var parm = 'l=' + id + '&t=' + new Date()*1 + '&u=' + userID;
	
	$('#loader_text').html('Gathering Information...');
	$('#ctl00_UpdateProgress1').css('display', '');
	
	$('#searchResults .hidden').removeClass('hidden');
	
	return $.getJSON(url + '?' + parm, function(data){
		return doLoadRulesLang(data);
	});
}

function doLoadRulesLang(data) {
	if(data != null && data.length > 0)
	{
		$(data).each(function(){
			var field = $('#'+this.Key);
			if (!rte.instances[this.Key]){
				if(field[0]) field[0].checked = (this.Value == '1');
				field.val(this.Value);
			}else rte.instances[this.Key].set_content(this.Value);
		});
	}
	doRulesCheckPagesFinished();
	LoadRulesPage('01');
	$('#ctl00_UpdateProgress1').css('display', 'none');
}

function doRulesCheckPagesFinished()
{
	var checkedLangs = 0;
	for (j=0;j<=7;j++){
		pageNr = (j<=9)? '0'+j : j;
		if ($('#cbx_p_'+pageNr+'_finished:checked').length == 1){
			$('#img_page_'+pageNr+'_ok').css('display', '');
			checkedLangs ++;
		}else{
			$('#img_page_'+pageNr+'_ok').css('display', 'none');
		}
	}
	checkedLangs == 8 ? $('.complete').css('display', 'block'): $('.complete').css('display', 'none');
}

function RulesClearAllFields(){
	$('INPUT:text').val('');
	$('INPUT:checkbox').removeAttr('checked');
	$('TEXTAREA').val('');
	$('#font_size').val('15');
	$('#title_size').val('22');

	for (j = 1; j < 6; j++)
	{
		pageNr = '0' + j;
		for(i = 1; i <= rulesPageSize[pageNr]; i++) {
			var id = pageNr + '' + ((i <=9) ? '0'+i : i );
			if (rte.instances[id]) rte.instances[id].set_content('');
		}
	}
}
function LoadRulesPDF(lang, userID, page, dm, col) {
	expandLoginTime();
	if (lang === 'xx'){
		alert('No language selected');
		return;
	}
	var url = '/Tools/Rules/LoadPDF.ashx?&l=' + lang;
	url += '&u=' + userID;
	if (page) url += '&p=' + page;
	if (page) url += '&preview=1';
	if (dm) url += '&dm=1';
	if (col) url += '&col=1&landscape=1';
	window.open(url, 'PDFdownload');
}

function doLoadPreviewImage(lang, user, pageNr) {
	LoadPreviewImage(lang, userID, pageNr, 266, 341);
}

function LoadPreviewImage(lang, userID, pageNr, width, height) {
	var url = 'LoadPreviewImage.ashx';
	var parm = 'l=' + lang + '&u=' + userID + '&p=' + pageNr + '&w=' + width + '&h=' + height + '&t=' + new Date()*1;
	
	doLoader('loader_inside2','rulesPreview',true, 'Loading Preview...'); // Show that we are working
	return $.getJSON(url + '?' + parm, function(data){ return LoadPreviewImageOK(data); });
}

RulesPDFImagePath = '';
function LoadPreviewImageOK(data) {
	// if textareas ok stable
	var img = new Image();
	img.src = RulesPDFImagePath + 'PDF/' + data.PictureFilename + '?t=' + new Date()*1;
	$('#rPimg_0'+data.Page).attr('src', img.src);
	doLoader('loader_inside2','rulesPreview',false); // Close Loader
}

function RulesReloadAdPics()
{
	var img = new Image();
	img.src = RulesPDFImagePath + 'GetHandbookPicture.ashx?id=1&lang='+$('.langSel').val()+'&userid='+userID+'&t=' + new Date()*1;
	$('#lAdImg').attr('src', img.src);
	img = new Image();
	img.src = RulesPDFImagePath + 'GetHandbookPicture.ashx?id=2&lang='+$('.langSel').val()+'&userid='+userID+'&t=' + new Date()*1;
	$('#rAdImg').attr('src', img.src);
}

var oldIndex = '';
function remIndex(that) { oldIndex = that.selectedIndex; }
function retIndex(that) { that.selectedIndex = oldIndex; }

function GetBrowserStats()
{
	var infoStr = '';
	
	infoStr += '||userAgent:'+navigator.userAgent;
	
	var pluginList = '';
	var i = 0, j = 0;
	var pluginCount = 0;
	var pluginLength = 0;
	try {
		var plugin = navigator.mimeTypes ? navigator.mimeTypes : navigator.plugins;
		var test = plugin && plugin.length && plugin.length > 0;
		pluginLength = plugin.length;
		if(test) {
			pluginCount = plugin.length;
			for (i = 0; i<= plugin.length; i++) {
				if (plugin[i].name || plugin[i].description)
				{
					var p = '';
					if (plugin[i].name) p = plugin[i].name;
					if (plugin[i].description) p = plugin[i].description;
					if (plugin[i].enabledPlugin) p = plugin[i].enabledPlugin.description;

					pluginList += p + ', ';

					j++;
				}
			}
		}
	}
	catch (ex) { }
	infoStr += '||PluginCount:'+pluginLength;
	infoStr += '||PluginUsableInfo:'+j;
	infoStr += pluginList;

	$('#browserStats').val(infoStr);
}


// sender == windows des iframes
function UCDIFH(sender) { return UpdateCoursesDocumentsIFrameHeight(sender); }
function UpdateCoursesDocumentsIFrameHeight(sender){

	try
	{
		var height = ($(sender.document.body).height()+14);
		if (height < 400) height = 400;
		$('IFRAME[src=' + sender.location.pathname+sender.location.search + ']').height(height);
	}
	catch(e) { }
}

function UpdateIFrameHeight(sender){

	try
	{ $('IFRAME[src=' + sender.location.pathname+sender.location.search + ']').height(($(sender.document.body).height()+14)); }
	catch(e)
	{ }
}


jQuery.fn.fadeToggle = function(speed, easing, callback) { return this.animate({opacity: 'toggle'}, speed, easing, callback);  }; 



function updateEventVenueTextField()
{
	/*
		Parsing
	*/
	var bd = $('.beginDate').val();
	var btH = $('.beginTimeH').val();
	var btM = $('.beginTimeM').val();
	var ed = $('.endDate').val();
	var etH = $('.endTimeH').val();
	var etM = $('.endTimeM').val();
	
	var by = 0;
	var bm = 0;	
	var ey = 0;
	var em = 0;

	// Parse Dates
	try{
		if (bd)
		{
			var bdS = bd.split('.');
			var bdD = new Date(bdS[2],bdS[1]-1,bdS[0]);
			by = bdD.getFullYear();
			bm = bdD.getMonth()+1;
			bd = bdD.getDate();
		}
	}
	catch(e){}
	try{
		if (ed){
			var edS = ed.split('.');
			var edD = new Date(edS[2],edS[1]-1,edS[0]);
			ey = edD.getFullYear();
			em = edD.getMonth()+1;
			ed = edD.getDate();
		}
	}
	catch(e){}
	
	// Check Time
	if (btH.length > 0 && !isInt(btH)) $('.beginTimeH').val('');
	if (etH.length > 0 && !isInt(etH)) $('.endTimeH').val('');
	if (btM.length > 0 && !isInt(btM)) $('.beginTimeM').val('');
	if (etM.length > 0 && !isInt(etM)) $('.endTimeM').val('');
	if(btH.length > 0 && parseInt(btH, 10) > 24) $('.beginTimeH').val(24);
	if(etH.length > 0 && parseInt(etH, 10) > 24) $('.endTimeH').val(24);
	if(btM.length > 0 && parseInt(btM, 10) > 59) $('.beginTimeM').val(59);
	if(etM.length > 0 && parseInt(etM, 10) > 59) $('.endTimeM').val(59);
	
	/*
		Building
	*/
	var from = "";
	var to = "";
	
	if (bd || ed) // at least on of the dates exist
	{
		if (bd && ed) // two dates exist
		{
			if (by == ey) // check if same year - print dd.mm - dd.mm.yyyy
			{
				if (bm == em) // check if same month - print dd. - dd.mm.yyyy
				{
					if (bd == ed) // check if same day - print dd.mm.yyyy
					{
						from += padLeft(bd, '0', 2) + '.' + padLeft(bm, '0', 2) + '.' + by;
					}
					else // only different day - print dd. - dd.mm.yyyy
					{
						if (btH || btM) from += padLeft(bd, '0', 2) + '.' + padLeft(bm, '0', 2) + '.' + by;
						else from += padLeft(bd, '0', 2) + '.';
						to += padLeft(ed, '0', 2) + '.' + padLeft(em, '0', 2) + '.' + ey;
					}
				}
				else // else we have same year but different months - print dd.mm - dd.mm.yyyy
				{
					if (btH || btM) from += padLeft(bd, '0', 2) + '.' + padLeft(bm, '0', 2) + '.' + by;
					else from += padLeft(bd, '0', 2) + '.' + bm;
					
					to += padLeft(ed, '0', 2) + '.' + padLeft(em, '0', 2) + '.' + ey;
				}
			}
			else // else print complete date - print dd.mm.yyyy - dd.mm.yyyy
			{
				from = padLeft(bd, '0', 2) + '.' + padLeft(bm, '0', 2) + '.' + by;
				to = padLeft(ed, '0', 2) + '.' + padLeft(em, '0', 2) + '.' + ey;
			}
		}
		else // just on date exists
		{
			if (bd) from = padLeft(bd, '0', 2) + '.' + padLeft(bm, '0', 2) + '.' + by;
			if (ed) to = padLeft(ed, '0', 2) + '.' + padLeft(em, '0', 2) + '.' + ey;
		}
	}
	
	/*if (btH.length > 0 || btM.length > 0 || etH.length > 0 || etM.length > 0){ // if we have a time input
		if ((btH != etH || btM != etM) || ((bd && ed) && bd != ed)) // check if it differes or they are on different days
		{
			if (btH.length > 0 || btM.length > 0) from += AddEventVenueTime(btH, btM, true);
			if (etH.length > 0 || etM.length > 0) to += AddEventVenueTime(etH, etM, ed ? (ed != bd ? true : false) : true);					
		}
		else // same time but on the same day
		{
			if (ed) to += AddEventVenueTime(btH, btM, false);
			else from += AddEventVenueTime(btH, btM, true);			
		}
	}
	*/

	//$('.dateText').val(from + ((bd && ed) || (btH && etH) ? ' - ' : '') + to);
	$('.dateText').val(from + ((bd && ed) ? '-' : '') + to);
}

function AddEventVenueTime(tHour, tMinute, spc)
{
	var str = spc ? ' ' : '';
	if (tHour.length > 0)
	{
		if (tMinute) str += padLeft(tHour, '0', 2)  + ':' + padLeft(tMinute, '0', 2);
		else str += padLeft(tHour, '0', 2) + ':00';
	}
	return str;
}

function BuildUpSelector(options)
{
	var target = options.Target;
	var submitButton = options.SubmitButton;
	var minLevelToSubmit = options.MinLevelToSubmit || 0
	var maxLevel = options.MaxLevel || 0;
	var baseGender = options.BaseGender;
	var season = options.Season;
	var gender = options.Gender || baseGender;
	var competitionType = options.CompetitionType;
	var competition = options.Competition;
	var round = options.Round;
	var loadWithoutSubmit = options.LoadWithoutSubmit;
	var OnSuccessFullSelection = options.OnSuccessFullSelection;
	var OnIncompleteSelection = options.OnIncompleteSelection;


	var tbl = $(document.createElement('TABLE'));

	var currentDeep = selectorObject;
	
	target.html('');
	target.append(tbl);

	// Seasons
	var seasonS = $(document.createElement('SELECT'));

	seasonS.append($(document.createElement('OPTION')).val(0).text('Please select'));		
	$(selectorObject).each(function(){ seasonS.append($(document.createElement('OPTION')).val(this.ID).text(this.Text)); });
	if (season != 0) seasonS.val(season);
	
	seasonS.change(function(){
		options.Season = $(this).val();
		options.Gender = 0;
		options.CompetitionType = 0;
		options.Competition = 0;
		options.Round = 0;
		BuildUpSelector(options);
		return;
	});
	
	tbl.append(buildUpSelectorRow('Season', seasonS));
	seasonS[0].focus();

	// Gender
	if (maxLevel >= 1 && season != 0)
	{
		$(currentDeep).each(function(){
			if (this.ID == season) currentDeep = this;
		});
	
		if (baseGender)
		{
			gender = baseGender;
			options.Gender = gender;
		}
		else {
			var genderS = $(document.createElement('SELECT')).append($(document.createElement('OPTION')).val(0).text('Please select'));
			if (currentDeep.Gender)
			{
				$(currentDeep.Gender).each(function(){
					genderS.append($(document.createElement('OPTION')).val(this.ID).text(this.Text));
				});
				if (gender != 0) genderS.val(gender);
			}
		
			genderS.change(function(){
				options.Gender = $(this).val();
				options.CompetitionType = 0;
				options.Competition = 0;
				options.Round = 0;
				BuildUpSelector(options);
				return;
			});
			
			tbl.append(buildUpSelectorRow('Gender', genderS));
			genderS[0].focus();
		}
	}
	
	if (options.CombineCompetitionTypeAndCompetition)
	{
		if (maxLevel >= 2 && season != 0 && gender != 0)
		{
			$(currentDeep.Gender).each(function(){
				if (this.ID == gender) currentDeep = this;
			});
			
			var competitionTypeCompS = $(document.createElement('SELECT')).append($(document.createElement('OPTION')).val('0;0').text('Please select'));
			
			if (currentDeep.CompetitionTypes)
			{
				$(currentDeep.CompetitionTypes).each(function(){
					var ctID = this.ID;
					// find also Competitions
					$(this.Competitions).each(function(){
						var cID = this.ID;
						competitionTypeCompS.append($(document.createElement('OPTION')).val(ctID + ';' + cID).text(this.Short));
					});
				});
				if (competitionType != 0 && competition != 0){
					$(currentDeep.CompetitionTypes).each(function(){
						if (this.ID == competitionType) currentDeep = this;
					});
					$(currentDeep.Competitions).each(function(){
						if (this.ID == competition) currentDeep = this;
					});
					competitionTypeCompS.val(competitionType + ';' + competition);
				}
			}
			//if (currentDeep.CompetitionTypes.length == 1) {
			//	competitionTypeS.val(currentDeep.CompetitionTypes[0].ID);
			//	competitionType = currentDeep.CompetitionTypes[0].ID;
			//	options.CompetitionType = competitionType;
			//}
			
			competitionTypeCompS.change(function(){
				var vals = $(this).val().split(';');
				options.CompetitionType = vals[0];
				options.Competition = vals[1];
				options.Round = 0;
				BuildUpSelector(options);
				return;
			});
			
			tbl.append(buildUpSelectorRow('Type / Competition', competitionTypeCompS));
			competitionTypeCompS[0].focus();
		}
	}
	else
	{
		// Competition Type
		if (maxLevel >= 2 && season != 0 && gender != 0)
		{
			$(currentDeep.Gender).each(function(){
				if (this.ID == gender) currentDeep = this;
			});

			var competitionTypeS = $(document.createElement('SELECT')).append($(document.createElement('OPTION')).val(0).text('Please select'));
			if (currentDeep.CompetitionTypes)
			{
				$(currentDeep.CompetitionTypes).each(function(){
					competitionTypeS.append($(document.createElement('OPTION')).val(this.ID).text(this.Text));
				});
				if (competitionType != 0) competitionTypeS.val(competitionType);
				
				if (currentDeep.CompetitionTypes.length == 1) {
					competitionTypeS.val(currentDeep.CompetitionTypes[0].ID);
					competitionType = currentDeep.CompetitionTypes[0].ID;
					options.CompetitionType = competitionType;
				}
			}
		
			competitionTypeS.change(function(){
				options.CompetitionType = $(this).val();
				options.Competition = 0;
				options.Round = 0;
				BuildUpSelector(options);
				return;
			});
			
			tbl.append(buildUpSelectorRow('Competitiontype', competitionTypeS));
			competitionTypeS[0].focus();
		}

		// Competition
		if (maxLevel >= 3 && season != 0 && gender != 0 && competitionType != 0)
		{
			$(currentDeep.CompetitionTypes).each(function(){
				if (this.ID == competitionType) currentDeep = this;
			});
			
			var competitionS = $(document.createElement('SELECT')).append($(document.createElement('OPTION')).val(0).text('Please select'));
			if (currentDeep.Competitions)
			{
				$(currentDeep.Competitions).each(function(){
					competitionS.append($(document.createElement('OPTION')).val(this.ID).text(this.Text));
				});
				if (competition != 0) competitionS.val(competition);
				
				if (currentDeep.Competitions.length == 1){
					competitionS.val(currentDeep.Competitions[0].ID);
					competition = currentDeep.Competitions[0].ID;
					options.Competition = competition;
				}
			}
		
			competitionS.change(function(){
				options.Competition = $(this).val();
				options.Round = 0;
				BuildUpSelector(options);
				return;
			});
			
			tbl.append(buildUpSelectorRow('Competition', competitionS));
			competitionS[0].focus();
		}	
	}
	
	// Round
	if (maxLevel >= 4 && season != 0 && gender != 0 && competitionType  != 0 && competition != 0)
	{
		$(currentDeep.Competitions).each(function(){
			if (this.ID == competition) currentDeep = this;
		});
		
		var roundS = $(document.createElement('SELECT')).append($(document.createElement('OPTION')).val(-1).text('Please select'));
		if (currentDeep.Rounds)
		{
			$(currentDeep.Rounds).each(function(){
				roundS.append($(document.createElement('OPTION')).val(this.ID).text(this.Text));
			});
			if (round != 0) roundS.val(round);
			
			if (currentDeep.Rounds.length == 1){
				roundS.val(currentDeep.Rounds[0].ID);
				round = currentDeep.Rounds[0].ID;
				options.Round = round;
			}
		}
	
		roundS.change(function(){
			options.Round = $(this).val();
			BuildUpSelector(options);
			return;
		});
		
		tbl.append(buildUpSelectorRow('Round', roundS));
		roundS[0].focus();
	}
	
	var currentLevel = 0;
	if (season != 0) currentLevel++;
	if (gender != 0) currentLevel++;
	if (competitionType != 0) currentLevel++;
	if (competition != 0) currentLevel++;
	if (round != -1) currentLevel++;
	
	if (currentLevel >= minLevelToSubmit)
	{
		submitButton.show();
		
		if (OnSuccessFullSelection) OnSuccessFullSelection(options);
		submitButton.unbind('click');
		submitButton.click(function(){OnSuccessFullSelection(options);});
	}
	else
	{
		if (OnIncompleteSelection) OnIncompleteSelection();
		submitButton.unbind('click');
		submitButton.hide();
	}
	
	//target.find('SELECT').attr('disabled', 'disabled');
	//$('#ctl00_ContentPlaceHolder1_Search1_lbMen').remove();
}

function buildUpSelectorRow(title, dropdown)
{
	var tr = $(document.createElement('TR'));
	var tdTitle = $(document.createElement('TD')).addClass('iL').text(title);
	var tdValue = $(document.createElement('TD')).append(dropdown);
	return tr.append(tdTitle).append(tdValue);
}

function GetLeftDataFromFilter(target, targetURL, filterData)
{
	doLoader('loader_inside', 'l_cont' ,true, 'Searching...');
	$.ajax({ type: "POST",
		url: targetURL,
		data: filterData,
		success: function(data){
			target.html(data);
			doLoader('loader_inside', 'l_cont' , false, '', 'l_cont');
		},
		error: function(){ doLoader('loader_inside', 'l_cont' , false, '', 'l_cont'); }
	});
}

function UploadGalleryImage(that, mId)
{
	var f = $('#f_' + mId);
	var loaderTarget = 'f_' + mId;
	doLoader('loader_inside', loaderTarget ,true, 'Uploading...');
	f.ajaxSubmit({
		dataType: 'json',
		data: { 'mId': mId },
		success: function(data, statusText, xhr){
			if (data.Error.length == 0){
				var inp = f.find('SPAN[id*=img]');
				
				if (data.UploadedImages != data.SavedImages){
					inp.html(data.SavedImages + ' (' + data.UploadedImages +')');
					alert('Something went wrong - only ' + data.SavedImages + ' of ' + data.UploadedImages + ' haved been saved!');
				}
				else
					inp.html(data.SavedImages);
			}
			else
			{
				alert('Something went wrong:\n' + data.Error);
			}
			
			doLoader('loader_inside', loaderTarget, false, '', loaderTarget);
			f.find('INPUT').val('');
		},
		error: function(data, statusText)
		{
			alert('The following Serverside Error occured:\n' + data.responseText);
			doLoader('loader_inside', loaderTarget, false, '', loaderTarget);
			f.find('INPUT').val('');
		}
	});
}

function generatePwd(targets)
{
	var chars = "abcdefghiknrstuvwxyzABCDEFGHKLPQRSTUVWXY3456789";
	var pass = "";
	var length = 6;
	
	for(x=0;x<length;x++)
	{
		var i = Math.floor(Math.random() * chars.length);
		
		pass += chars.charAt(i);
		if (x%4==0) pass += chars.charAt(i);
	}

	targets.val(pass);
}
