window.addEvent('domready', function () {
	new Tips($$('#medalsTable li[title]', '#medalsTable a[title]', '#badgesTable span[title]', '#statsList a[title]'));

	$$("#rankingTable tbody tr").each(function (el, index) {
		if (index % 2 == 0) {
			el.addClass('dark');
		} else {
			el.addClass('light');
		}
	});
	
	if ($$('.countdownBin').length > 0) {
		timeArray = new Array();
		var duration;
		$$('.countdownBin').each(function (el, index) {
	
			//	TIMEARRAY:	[0]: xml - Timestring,	[1]: duration,	[2]: Milliseconds till Race-Start,	[3]: Milliseconds till Race-End
	
			timeArray[index] = new Array();
			timeArray[index][0] = el.getText();
			
			duration = el.getText().split('T');
			timeArray[index][1] = duration[2] * 1000;
	
			var xmlTimestring = el.getText();
			timeArray[index][2] = new Date(convertStringToDate_New(xmlTimestring));
			timeArray[index][3] = new Date(timeArray[index][2].getTime() + timeArray[index][1].toInt());
			
			setAllTimes(el,index);
		});
		counter.periodical(1000);
	}
	
	
	if($$('.statsTable').length > 0) {
		$$('#main .tableContainer table.statsTable').each(function (elem, counter) {
			elem.setStyle('display', 'none');
		});
		$$('#main .tableContainer table.statsTable').getLast().setStyle('display', '');
		
		$$('#switchLevel').addEvent('change', function (event) {
			var level = this.value;
			$$('#main .tableContainer table.statsTable').each(function (elem, counter) {
				elem.setStyle('display', 'none');
				if (elem.getAttribute('id').replace(/profileTable_/, '') === level) {
					elem.setStyle('display', '');
				}
			});		
		});
	}
});


function counter() {
	$$('.countdownBin').each(function(el, index) {
		setAllTimes(el,index);
	});
}

function setAllTimes(el, index) {	
	now = new Date();
	now = now.getTime();

	var timeString;
	
	var daysLeft = calculateDaysLeft(timeArray[index][2]);

	if (timeArray[index][2].getTime() > now) {
		
		//	case > 1: show Date		case == 1: tomorrow		case== 0: today
		switch (true) {
			case (daysLeft > 1): 
				timeString = timeArray[index][2].getDate()<9?'0'+timeArray[index][2].getDate():timeArray[index][2].getDate()+'.';
				timeString += (timeArray[index][2].getMonth().toInt()+1)<9?'0'+(timeArray[index][2].getMonth().toInt()+1):(timeArray[index][2].getMonth().toInt()+1);
				timeString += '.'+timeArray[index][2].getFullYear();
				break;
			case (daysLeft == 1):
				timeString = langTemp_tomorrow;
				break;
			default:
				timeString = langTemp_today;
		}
	
		timeString += ' @ '+ (timeArray[index][2].getHours()<9?'0'+timeArray[index][2].getHours():timeArray[index][2].getHours());
		timeString += ':'+ (timeArray[index][2].getMinutes()<9?'0'+timeArray[index][2].getMinutes():timeArray[index][2].getMinutes());
		
	} else if (timeArray[index][2].getTime() < now && timeArray[index][3].getTime() > now) {
		var countdownValues = calculateTimeValues(Math.floor((timeArray[index][3].getTime() - now)/1000));
		timeString = langTemp_remaining+': '+ countdownValues[2]+':'+countdownValues[1]+':'+countdownValues[0];
		//var playLink = el.getParent().getElementsBySelector('.playLink a');
		//playLink.setStyle('background','#334433');
		//el.getNext().getNext().getChildren().setStyle('background','#334433');
	} else {
		timeString = langTemp_completed;
		//var rankingLink = el.getParent().getElementsBySelector('.rankingLink a');
		//rankingLink.setStyle('background','#334433');
	}
	el.setText(timeString);	
}

function calculateTimeValues(countdownValue){
	countdownArray = new Array();
	
  var seconds = countdownValue % 60;
  countdownValue = Math.floor(countdownValue / 60);
  
  var minutes = countdownValue % 60;
  countdownValue = Math.floor(countdownValue / 60);
  
  var hours = countdownValue % 24;
  countdownValue = Math.floor(countdownValue / 24);
  
  //var days = countDownValue % 24;
  if(seconds < 10?seconds='0'+seconds:seconds);
  if(minutes < 10?minutes='0'+minutes:minutes);
  if(hours < 10?hours='0'+hours:hours);
  //if(days &lt; 10?days='0'+days:days);
  
  countdownArray[0] = seconds;
  countdownArray[1] = minutes;
  countdownArray[2] = hours;
  
  return countdownArray;
}

function convertStringToDate_New(timeString) {
	timeString = timeString.split('T');

	timeString[0] = timeString[0].split('-');
	timeString[1] = timeString[1].split(':');
	
	var timeStamp = new Date(timeString[0][0], (timeString[0][1] -1), timeString[0][2], timeString[1][0], timeString[1][1], timeString[1][2]);

	return (Date.parse(timeStamp));
}

function calculateDaysLeft(milliseconds) {
	var result;
	var raceDay = new Date(milliseconds)
	raceDay.setHours(0);
	raceDay.setMinutes(0);
	var now = new Date();
		
	//If now is on the day of the race (after 00:00 that day)
	if(now > raceDay)result = 0;
		
	//If now is on the day before the day of the race
	else if(now > raceDay-1*24*60*60*1000)result = 1;
	else result = 2;
	
	return result;
}


// ----------------------------------------------------------------------------------------------------------------------------- //
// -----------------                               Old Functions (still in use)                               ------------------ //
// ----------------------------------------------------------------------------------------------------------------------------- //


function createGroupRace(){
	//setLevelWeather(true);
	$('date').addEvent('change', function(evt){
		new Event(evt).stop();
		checkRaceDate();
	});
	$('time').addEvent('mouseup', function(evt){
		new Event(evt).stop();
		checkRaceDate();
	});
	$('time').addEvent('keyup', function(evt){
		new Event(evt).stop();
		checkRaceDate();
	});
	$('time').addEvent('select', function(evt){
		new Event(evt).stop();
		checkRaceDate();
	});
	$('time').addEvent('change', function(evt){
		new Event(evt).stop();
		checkRaceDate();
	});
	$$('#duration input').each(function (el) {
		el.addEvent('click', function (event) {
			duration = el.value;
			checkRaceDate();
		});
	});
}

function checkRaceDate(){
	if(raceStartDate != ''){
		checkDate = true;
	}
	checkTime = testMyTime();
	if(duration != 0){
		var inputDate = convertStringToDate(raceStartDate+'T'+$('time').value+':00',  duration);
		
		$$('#levelId option').each(function(el){el.remove();});
		
		for(i=0;i<levelArray.length;i++){
			levelArray[i][levelArray[i].length] = convertStringToDate(levelArray[i][2],0);
			
			if(levelArray[i][3] <= inputDate){
				createLevelOptions(levelArray[i]);
				checkDuration = true;
			}			
		}
		createWeatherSelect(0);
	}
	
	if(checkDate && checkTime && checkDuration){
		setLevelWeather(false);
	}else{
		setLevelWeather(true);
	}
}

function createLevelOptions(inputArray){
	levelOption = new Element('option',{'value': inputArray[0]});
	levelOption.setProperty('title',inputArray[2]);
	levelOption.setText(inputArray[1]);
	levelOption.injectInside($('levelId'));
}

function testMyTime(){
	var inputValue = $('time').value;
	var reg = new RegExp(/^[0-2]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/);
	var numbers = inputValue.split(':');


  if(reg.test(inputValue)){
		if(numbers[0] >= 24){
			numbers[0] -= 24;
			if(numbers[0]< 10 ? numbers[0] ='0'+numbers[0]:numbers[0]=numbers[0]);	
		}
		$('time').value = numbers[0]+':'+numbers[1];
		return true;
	}else{
		return false;
	}
}

function setLevelWeather(flag){
	$('levelId').disabled = flag;
	$('competitionId').disabled = flag;
}


function convertStringToDate(timeString, durationToAdd){
	timeString = timeString.split('T');
	//console.log(timeString);

	timeString[0] = timeString[0].split('-');
	timeString[1] = timeString[1].split(':');
	
	var timeStamp = new Date(timeString[0][0], (timeString[0][1] -1), timeString[0][2], timeString[1][0], timeString[1][1], timeString[1][2]);

	return (Date.parse(timeStamp));
}

function printBlockedDates(datesArray, fixedBlockedDates){
	
	var startDates = new Array();
	var endDates = new Array();
	var blockedDatesArray = new Array();
	
	for(i = 0; i<datesArray.length;i++){
		datesArray[i] = datesArray[i].split('#');
		
		//console.log('startDate: ');
		startDates[i] = convertStringToDate(datesArray[i][0]);
		
		//console.log('endDate: ');
		endDates[i] = convertStringToDate(datesArray[i][1]);

		endDates[i] = new Date(endDates[i]);
		
		var blockedDate = startDates[i];
		
		while(blockedDate < endDates[i]){
			blockedDatesArray[blockedDatesArray.length] = convertDateToString(blockedDate);
			
			blockedDate = dateAdd('d',1,blockedDate);
		}
	}
	
	for(i=0;i<fixedBlockedDates.length;i++){
		blockedDatesArray[blockedDatesArray.length] = fixedBlockedDates[i];
	}
	
	return blockedDatesArray;
}

function convertDateToString(timeStamp){
	timeStamp = new Date(timeStamp)
	timeString = timeStamp.getDate() +' '+ (timeStamp.getMonth()+1) +' '+ timeStamp.getFullYear();
	return timeString;
}

function dateAdd(unit, interval, dtDate){
	var factor;
	var myTime;
	
	if(unit == 'd') factor = 24*60*60*1000;
	if(unit == 'h') factor = 60*60*1000;
	if(unit == 'm') factor = 60*1000;
	if(unit == 's') factor = 1*1000;
	
	return dtDate + factor * interval;
}

function createWeatherSelect(position){

	$$('#competitionId option').each(function(el){el.remove();});

	emptyOption = new Element('option',{});
	emptyOption.injectInside($('competitionId'));

	for(i=0;i<trackArray[position].length;i++){
		weatherOption = new Element('option',{'value': trackArray[position][i][0]	});
		
		weatherOption.setText(trackArray[position][i][1]);
		weatherOption.injectInside($('competitionId'));
	}	
}

function showQualificationResult(levelId){
	var hasClass = $$('.level_'+levelId).hasClass('expand');
	if(hasClass[0]){
		$$('.level_'+levelId).removeClass('expand');
		$$('.level_'+levelId).addClass('shrink');
		$$('.level_'+levelId).setStyle('display', '');
		$('showBtn_'+levelId).removeClass('qualificationResults_expand');
		$('showBtn_'+levelId).addClass('qualificationResults_shrink');
	}else{
		$$('.level_'+levelId).removeClass('shrink');
		$$('.level_'+levelId).addClass('expand');
		$$('.level_'+levelId).setStyle('display', 'none');
		$('showBtn_'+levelId).removeClass('qualificationResults_shrink');
		$('showBtn_'+levelId).addClass('qualificationResults_expand');
	}
}

// ------------------------- Ranking -------------------------
function sendRankingFormCompetitionId(compOrLevelValue){

	var splittedString = compOrLevelValue.split(':');
	var compOrLevelId = splittedString[1];
		
	if(splittedString[0] == 'quali'){
		$('levelId').value = compOrLevelId; 
		$('competitionId').value = 0;
		$('seasonId').value = 0;
	}
	else if(splittedString[0] == 'season'){
		$('seasonId').value = compOrLevelId; 
		$('levelId').value = 0; 
		$('competitionId').value = 0;
		//$('locationId').value = 0;	
	}
	else{
		$('levelId').value = 0; 
		$('competitionId').value = compOrLevelId;
		$('seasonId').value = 0;
	}
	$('offset').value = 0;
	$('nick').value = '';
	$('rankingForm').action = '';
	
	document.rankingForm.submit();
}

function sendRankingFormLocationEditionId(locOrEdValue){

	var splittedString = locOrEdValue.split(':');
	var locOrEdId = splittedString[1];
		
	if(splittedString[0] == 'location'){
		$('locationId').value = locOrEdId; 
		$('editionId').value = 0;
	}
	else{
		$('locationId').value = 0; 
		$('editionId').value = locOrEdId;
	}
	$('offset').value = 0;
	//$('seasonId').value = 0;
	$('nick').value = '';
	$('rankingForm').action = '';
	document.rankingForm.submit();
}

function sendRankingFormNick(){
	$('nick').value = $('nickInput').value;
	$('rankingForm').action = '#p_' + $('nickInput').value.toLowerCase();
	document.rankingForm.submit();
}

function sendRankingFormPaging(direction){
	$('offset').value = direction;
	$('nick').value = '';
	$('rankingForm').action = '';
	document.rankingForm.submit();
}



