/*# Metadata ################################### Header v.2
# $URL: http://gt-nas-1/svn/gamebase.frontend/trunk/xsl_gamebase/_magic/data/classes.js $
# $Rev: 6469 $
# $Date: 2012-01-17 14:02:43 +0100 (Di, 17 JÃ¤n 2012) $
# $Author: pmang $
### TOC ###################################################
# =HandleGroupRace
# =SkiSettings
# =CountdownBin
# =PeriodicalPool
### Description ###########################################
#	info: adapt detach() and attach() (line: 566) when mootools 1.3 update
#########################################################*/


/*
=HandleGroupRace
*/
var HandleGroupRace = new Class({
	Implements: [Options], 
	options: {
		levels: [], 
		skiSettingsContainer: false
	}, 
	initialize: function (options) {
		this.setOptions(options);
		
		this.controlData = $H({
			skiSettings: false,
			maxStarts: false,
			extremeMode: false,
			date: false,
			time: false,
			duration: false,
			levelId: false,
			weatherId: false,
			competitionId: false
		});

		this.levels = this.options.levels;
		this.sortLevels();

		this.createDateTimePicker();
		
		// create SKISETTINGS
		if(this.options.skiSettingsContainer) {
			this.groupRaceSkiSettings = new SkiSettings({
				container:this.options.skiSettingsContainer, 
				onSelect: function(settingsValues){
					this.controlData.skiSettings = (settingsValues != 0)?settingsValues[0]+'x'+settingsValues[1]+'x'+settingsValues[2]:false;											
				}.bind(this)
			});
		}

		$('submitButton').addEvent('click', function (e) {
			e.preventDefault();
			this.controlData.competitionId = this.getCompetitionId(this.levels, $('levelId').value, $('weatherId').value);
			
			this.createCheckForm();

		}.bind(this));
		
	}, 
	sortLevels: function () {
		this.levels.each(function(el, index){
			el[1].startTime = this.createTimestamp(el[1].startTime);
		}, this);
		
		this.levels.sort(this.compareStartimes);
	}, 
	compareStartimes: function(a, b){
		return a[1].startTime - b[1].startTime;
	}, 
	createTimestamp:function (time) {
		time = time.split('T');
		time[0] = time[0].split('-');
		time[1] = time[1].split(':');

		var date = new Date(time[0][0],(time[0][1]-1),time[0][2],time[1][0],time[1][1],time[1][2]);
		return date.getTime();
	}, 
	setTheTracks: function(time){

		var trackSelect = $('levelId');
		trackSelect.getChildren('option').destroy();
		
		this.levels.each(function(el, index) {
			
			var levels = $H(el[1].competitions);
			var printKey = false;
			var currKey = el[0];
			
			levels.map(function(value, key) {
				if(time > el[1].startTime && !printKey){
					printKey = currKey;
				}
			});
			
			if(printKey){
				var track = new Element('option', {
					text: el[1].levelName, 
					value: el[0]
				});
				
				$('levelId').setProperty('disabled', false);						
				$('levelId').grab(track);
			};
		});

		if($$('#levelId option').length > 0) $$('#levelId option').getLast().setProperty('selected','selected'); // damit wird immer die aktuelle Strecke vorselektiert
		
		this.setWeathers(this.levels, trackSelect.value);
	}, 
	setWeathers: function (array, levelId) {
		//$('weatherId').getChildren('option:not[value]').destroy(); // löscht alle Einträge ausser dem leeren
		$('weatherId').getChildren('option').destroy();
		
		for(var i=0; i < array.length;i++){
			var competitions = $H(array[i][1].competitions);
			if(array[i][0] == levelId){
				competitions.map(function(value, key) {
					var weather = new Element('option', {
						text: value.weatherName, 
						value: value.weatherId
					});
					$('weatherId').setProperty('disabled', false);						
					$('weatherId').grab(weather);
				});
			}
		}
	},
	createDateTimePicker: function () {
		this.dp = new DatePicker('#date_f',{
			days: dayNames,
			months: monthNames,
			prevChar: prevChar,
			nextChar: nextChar,
			format: 'Y-m-d',
			toggleElements: '#dateBtn',
			positionOffset: {x: 335, y:-25},
			/* NOT NECESSARY ANYMORE.
			unavailableDates: ['2011-12-02','2011-12-03','2011-12-04',
							   '2011-12-09','2011-12-10','2011-12-11',
							   '2011-12-16','2011-12-17','2011-12-18',
							   '2011-12-28','2011-12-29','2011-12-30',
							   '2012-01-13','2012-01-14','2012-01-15',
							   '2012-01-20','2012-01-21','2012-01-22'],
							   */
			minDate: {date: nowString, format: 'Y-m-d'},
			maxDate: {date: '2012-03-31', format: 'Y-m-d'}, 
			addTimeToInitTime: 1000*60*5
		});
		
		this.controlData.date = $('date_f').getNext('.ffInput').value;
		
		this.setTheTracks(this.dp.options.minDate.getTime());

		this.dp.options.onSelect = (function(date) {
			this.setTheTracks(date.getTime());
		}).bind(this);
		
		this.tp = new DatePicker('#time_f',{
			timePicker: true,
			timePickerOnly: true,
			format: 'H:i',
			toggleElements: '#timeBtn',
			addTimeToInitTime: 1000*60*5,
			positionOffset: {x: 335, y:-55}
		});
		this.controlData.time = $('time_f').getNext('.ffInput').value;
	}, 
	getCompetitionId: function (array, levelId, weatherId){
		var competitionId;

		for(var i=0; i < array.length;i++){
			var competitions = $H(array[i][1].competitions);
			if(array[i][0] == levelId){
				competitions.map(function(value, key) {
					if(value.weatherId == weatherId) {
						competitionId = key;
					}
				});
			}
		}
		return competitionId;
	}, 
	createCheckForm: function () {
		this.fillControlData();

		if(!this.controlData.duration || !this.controlData.competitionId){
			this.setErrors();
		} else {
			$('competitionId').value = this.controlData.competitionId;
			
			$('time').value = this.controlData.time;
			$('date').value = this.controlData.date;
			$('duration').value = this.controlData.duration;
			
			// we need the properties to be sent in the form of: 1,###;2,0/1;3##x##x##
			// this is what composes the needed properties
			var propertiesString = '';
			if(this.controlData.maxStarts) propertiesString += '1,'+this.controlData.maxStarts+';';
			if(this.controlData.extremeMode) propertiesString += '2,'+this.controlData.extremeMode+';';
			if(this.controlData.skiSettings) propertiesString += '3,'+this.controlData.skiSettings+';'
			
			$('properties').value = propertiesString;
			
			
			var checkFormContainerList;
			if($('checkFormContainer').getElement('div').getElement('dl')) {
				$('checkFormContainer').getElement('div').getElement('dl').destroy();
			}
			checkFormContainerList = new Element('dl');
			
			$$('#createRaceFakeForm ul li label').each(function(el, index) {
				var dt =  new Element('dt');
				var dd =  new Element('dd');
				//console.log(el);
				//var dlText = el.get('text');
				var dlText = el.innerHTML;
				//console.log(dlText);
				
				dlText = dlText.replace(/\*/g,'');
				dt.set('text',dlText);
				
				var outputValue;
				
				if (index <= 1) {
					outputValue = $(el.get('for')).getNext().value;
					dd.set('text',outputValue);
					checkFormContainerList.grab(dt);
					checkFormContainerList.grab(dd);
				} else if (index >= 2 && index <= 4) {
					var optIndex = $(el.get('for')).selectedIndex;
					//outputValue = $(el.get('for')).options[optIndex].get('text');
					outputValue = $(el.get('for')).options[optIndex].innerHTML;
					dd.set('text',outputValue);
					checkFormContainerList.grab(dt);
					checkFormContainerList.grab(dd);
				} else if (index == 5 && this.controlData.maxStarts && this.controlData.maxStarts != 'error') {
					dd.set('text', this.controlData.maxStarts);
					checkFormContainerList.grab(dt);
					checkFormContainerList.grab(dd);
				} else if (index == 6 && this.controlData.extremeMode) {
					var checkedInput =  new Element('input', {
						'type': 'checkbox', 
						'checked':'checked', 
						'readonly':'readonly'
					});
					dd.grab(checkedInput);
					checkFormContainerList.grab(dt);
					checkFormContainerList.grab(dd);
				} else if (index == 7 && this.controlData.skiSettings) {
					dd.set('text', this.controlData.skiSettings);
					checkFormContainerList.grab(dt);
					checkFormContainerList.grab(dd);
				}
			}, this);

			checkFormContainerList.inject($('checkFormContainer').getElement('div'),'top');
			
			$('checkFormContainer').setStyle('display','block');
			
			if(!$('closeCheckFormContainer')) {
				this.createCheckFormCloseBtn();
			}
			
			$('finishCreateRace').addEvent('click', function(evt) {
				evt.preventDefault();
				document.createRace.submit();
			});
		}
	}, 
	createCheckFormCloseBtn: function () {
		var closeBtn = new Element('a', {
			'text': 'x', 
			'id': 'closeCheckFormContainer', 
			'href': 'javascript: void(0)'
		});
		closeBtn.inject($('checkFormContainer').getElement('div'),'top');
		
		closeBtn.addEvent('click', function(evt) {
			evt.preventDefault();
			$('checkFormContainer').setStyle('display','none');
			$('checkFormContainer').getElement('dl').destroy();
		});
	},
	setErrors: function(){
		if(!this.controlData.duration){
			$('duration_f').setStyle('background-color', '#f7e3e3');
		}else{
			$('duration_f').setStyle('background-color', '#ffffff');
		}
		
		if(this.controlData.maxStarts == 'error'){
			$('maxStarts').setStyle('background-color', '#f7e3e3');
		}else{
			$('maxStarts').setStyle('background-color', '#ffffff');
		}
	},
	fillControlData: function () { 
		this.controlData.skiSettings = (this.controlData.skiSettings)?this.controlData.skiSettings:false;
		if($('extremMode')){
			this.controlData.extremeMode = ($('extremMode').checked)?1:false;
		}
		this.controlData.date = (this.controlData.date)?$('date_f').getNext('.ffInput').value:false;
		this.controlData.time = (this.controlData.time)?$('time_f').getNext('.ffInput').value:false;
		this.controlData.duration = ($('duration_f').value)?$('duration_f').value:false;
		this.controlData.levelId = ($('levelId').value)?$('levelId').value:false;
		this.controlData.weatherId = ($('weatherId').value)?$('weatherId').value:false;
		this.controlData.competitionId = (this.controlData.competitionId)?this.controlData.competitionId:false;

		if($('maxStarts') && $('maxStarts').value.length > 0){
			this.controlData.maxStarts = (Number($('maxStarts').value))?$('maxStarts').value:'error';
		} else {
			this.controlData.maxStarts = false;
		}
	}
});


/*
=SkiSettings
*/
var SkiSettings = new Class ({
	Implements: [Options], 
	options: {
		container: 'container', 
		numberOfSliders: 3, // sliders that are used to adjust the settings  
		sliderDepiction: [langTemp_skiSettings_carve, langTemp_skiSettings_grip, langTemp_skiSettings_speed],
		overallSliderValue: 100, // this value is choped up into the amount of Sliders
		defaultSettings: [
			{
				name: 'Beginner',
				values: [74,26,0]
			},{
				name: 'Classic',
				values: [35,50,15]
			},{
				name: 'Extreme', 
				values: [25,15,60]
			},{
				name: 'Custom', 
				values: [33,33,34]
			}], 
		onSelect: $empty
	}, 
	initialize: function (options) {
		this.setOptions(options);
		this.container = $$(this.options.container)[0];
		this.createDefaultSettings();
		this.createSlider();
		
		this.setDefaultSettings(this.settingsLinks[0], this.options.defaultSettings[0].values);
		this.createDisable();
		this.disableSlider();
	}, 
	createSlider: function () {
		var sliderList = new Element('ul');
		sliderList.addClass('sliderList');
		this.container.grab(sliderList);
		
		this.sliderArray = [];
		for (i=0; i<this.options.sliderDepiction.length; i++){
			var sliderContainer = new Element('li');
			sliderList.grab(sliderContainer);
			
			var sliderDepiction = new Element('div',{
				text: this.options.sliderDepiction[i],
				'class': 'sliderDepiction'
			});
			var sliderArea = new Element('div', {
				id: 'area'+i, 
				'class': 'area' 
			});
			var sliderKnob = new Element('div', {
				id: 'knob'+i, 
				'class': 'knob'
			});
			var sliderPos = new Element('div', {
				id: 'sliderPos'+i,
				'class': 'sliderPos'
			});

			sliderContainer.grab(sliderDepiction);
			sliderContainer.grab(sliderPos);
			sliderContainer.grab(sliderArea.grab(sliderKnob));
		
			var sliderObj = {
				valueContainer: sliderPos,
				currentStep:false,
				previousStep:false,
				mouseIsDown: false,
				slider:	new Slider(sliderArea, sliderKnob, {})
			};
			sliderObj.valueContainer.set('text', sliderObj.slider.options.initialStep);
			
			this.sliderArray.push(sliderObj);
		}
		this.sliderArray.each(function(item, index){
			item.slider.addEvents({
				change: function(pos) {
					item.valueContainer.set('html', pos);
					
					item.previousStep = item.currentStep;
					item.currentStep = pos;
					
					if(item.slider.isDragging == true) {
						this.oldScFunction(index, item.previousStep);
					}
				}.bind(this)
			});
			
			item.slider.element.removeEvent('mousedown', item.slider.clickedElement);
		}, this);
	},
	select: function(values) {
		this.options.onSelect(values);
	},
	oldScFunction: function(index, prevStep) {
		
		this.sliderArray.each(function (el) {
			if(el.currentStep < 0) el.currentStep = 0;
			if(el.currentStep > 100) el.currentStep = 100;
		});
			
		if (prevStep == null) {
			return;
		}

		var p = [];
		this.sliderArray.each(function (el) {
			p.push(el.currentStep);
		});
	
		var other1 = (index + 1)%3;
		var other2 = (index + 2)%3;
	
		if (prevStep != null)	{
			var prevArray = [];
			
			this.sliderArray.each(function(el) {
				prevArray.push(el.previousStep);
			});		
			
			var percent1 = prevArray[other1];
			var percent2 = prevArray[other2];
	
			// prevent division by zero
			if (percent1 + percent2 <= 0) {
				percent1 = 1;
				percent2 = 1;
			}
	
			var change = (prevArray[index] - p[index]);
	
			var delta1 = parseInt(change * percent1 / (percent1 + percent2));
			var delta2 = parseInt(change * percent2 / (percent1 + percent2));

			p[other1] = prevArray[other1] + delta1;
			p[other2] = prevArray[other2] + delta2;
	
			// correct rounding error
			if (p[index] + p[other1] + p[other2] != 100) {
				var correct = (prevArray[other1] >= prevArray[other2]) ? other1 : other2;
				
				p[correct] += 100 - p[index] - p[other1] - p[other2];
			}
		}
		
		//check for < 0
		if (p[other1] < 0) {
			p[other2] += p[other1];
			p[other1] = 0;
		}
		else if (p[other2] < 0)	{
			p[other1] += p[other2];
			p[other2] = 0;
		}
		
		p.each(function(el, ix) {
			this.sliderArray[ix].currentStep = p[ix];
			this.sliderArray[ix].slider.set(p[ix]);
		}, this);
		
		this.select(p);

	}, 	
	createDefaultSettings: function () {
	
		var settingsList = new Element('ul');
		settingsList.addClass('settingsList');
		this.container.grab(settingsList);
		
		this.settingsLinks = [];
		
		this.options.defaultSettings.each(function(value, key) {
			var defaultSettingContainer = new Element('li', {
				'class': 'defaultSetting'
			});
			var defaultSettingLink = new Element('a',{
				href: 'javascript:void(0);'
			});
			var defaultSettingName = new Element('span');
			defaultSettingName.set('html', value.name);
			
			defaultSettingLink.grab(defaultSettingName);
			defaultSettingContainer.grab(defaultSettingLink);
			settingsList.grab(defaultSettingContainer);

			if(key == this.options.defaultSettings.length-1) {
				defaultSettingContainer.addClass('last');	
			}
			
			var setSettings = function(e){
				e.preventDefault();
				this.setDefaultSettings(defaultSettingLink, value.values); 
			}
			defaultSettingLink.boundSetSettings = setSettings.bind(this);
			defaultSettingLink.addEvent('click', defaultSettingLink.boundSetSettings);

			this.settingsLinks.push(defaultSettingLink);

		}, this);
	}, 
	setDefaultSettings: function (element, values) {
		
		values.each(function (pos, index) {
			this.sliderArray[index].slider.set(pos);
			this.sliderArray[index].previousStep = pos;
			this.sliderArray[index].currentStep = pos;
		}, this);
		
		this.setActiveDefaultSetting(element);
		
		var currSliderValues = this.getCurrSliderValues();
		//this.select(currSliderValues);

	}, 
	setActiveDefaultSetting: function (element) {
		
		this.settingsLinks.each(function(el){
			if(el.hasClass('active')) el.removeClass('active');
		})
		element.addClass('active');
		
	}, 
	createDisable: function () {
		
		var disableCheckBox = new Element('input', {
			type: 'checkbox', 
			checked: '', 
			'class': 'checkbox',
			name: 'disableSettings'
		});

		disableCheckBox.inject(this.container, 'top');

		disableCheckBox.addEvent('click', function (e) {
			if(!disableCheckBox.checked) {
				this.disableSlider();
			} else {
				this.enableSlider();
			}
		}.bind(this));
		
	}, 
	disableSlider: function() {

		this.sliderArray.each(function(item, index) {
			
			//item.slider.detach();
			item.slider.element.getElement('div.knob').setStyle('display', 'none');
			this.container.addClass('disabled');
		}, this);

		this.settingsLinks.each(function(el) {
			el.removeEvent('click', el.boundSetSettings);
		}, this);
		this.select(0);
	},
	enableSlider: function() {
		this.sliderArray.each(function(item, index) {
			item.slider.element.getElement('div.knob').setStyle('display', 'block');
			//item.slider.attach();
			this.container.removeClass('disabled');
			item.slider.element.removeEvent('mousedown', item.slider.clickedElement);
		}, this);
		
		this.settingsLinks.each(function(el) {
			el.addEvent('click', el.boundSetSettings);
			//el.removeClass('disabledLink');
		}, this);
		
		// sets the current values of the 3 sliders
		var currSliderValues = this.getCurrSliderValues();
		this.select(currSliderValues);
		
	}, 
	getCurrSliderValues: function() {
		var v = [this.sliderArray[0].currentStep,this.sliderArray[1].currentStep,this.sliderArray[2].currentStep];
		return v;
	}
});














/*
=CountdownBin
*/
var CountdownBin = new Class ({
	Implements: [Options,Events], 
	options: {
		container: false, 
		registerTo: false
	}, 
	initialize: function (registerTo, options) {
		this.setOptions(options);
		this.registerTo = registerTo;
		this.registerTo.keepRunning++; // increment keepRunning of PeriodicalPool
		this.isOver = false;
		
		this.container = this.options.container;
		
		//var containerText = this.container.get('text').split('#');
		var containerText = this.container.innerHTML.split('#');
		
		var startTime = containerText[0];
		this.duration = containerText[1];
		this.pdId = containerText[2];
		this.groupName = containerText[3];
		this.startTimestamp = this._formTimeStamp(startTime);
		this.endTimestamp = new Date(this.startTimestamp.getTime() + (this.duration * 1000));
		
		this._countDown(this.startTimestamp, this.endTimestamp);
		
		this.registerTo.addEvent('periodic', function () {
			if(!this.isOver){									   
				this._countDown(this.startTimestamp, this.endTimestamp);
			}
		}.bind(this));
	}, 
	_countDown: function (startTime, endTime) {
		var now = new Date();
		var startDiff = startTime.getTime() - now.getTime();
		var endDiff = endTime.getTime() - now.getTime();
		
		if(endDiff > 1000 && startDiff < 1000) { 								// running
			var waitingTime = this._waitingTime(endDiff);
			
			this.container.set('text',waitingTime[3]+'h '+waitingTime[2]+'min '+waitingTime[1]+'s');
			this.createAction('ranking');
			this.createPlayLink();
		} else if(startDiff > 1000){											// upcoming
			if(startDiff < 1000*60*60*24){ 										// starts in the next 24hours
				var waitingTime = this._waitingTime(startDiff);
				this.container.set('text',waitingTime[3]+'h '+waitingTime[2]+'min '+waitingTime[1]+'s');
				this.createAction('countdown');	
			} else { 															// starts before the next 24 hours
				var waitingTime = this._formatUpcoming(startTime)
				this.container.set('text', waitingTime);
				//this.createAction('fix date');
			}
			this.createAction('inactiveRanking');
			this.createInactivePlayLink();
		} else { 																// over
			this.container.set('text',langTemp_completed);
			this.createAction('ranking');
			this.createInactivePlayLink();
			if(!this.isOver) {
				this.registerTo.keepRunning--;									// decrement keepRunning of PeriodicalPool
				this.isOver = true;
			}
		}	
	},
	_formTimeStamp:function (timeString){
		var tArr = timeString.split('T');
		tArr[0] = tArr[0].split('-');
		tArr[1] = tArr[1].split(':');
		var date = new Date(tArr[0][0],(tArr[0][1]-1),tArr[0][2],tArr[1][0],tArr[1][1],tArr[1][2]);
		return date;
	}, 
	_waitingTime: function (ms) {
		var rf = new Array();
		
		rf.push(ms % 1000);
		rf.push(Math.floor(ms / 1000) % 60);
		rf.push(Math.floor(ms / 60000) % 60);
		rf.push(Math.floor(ms / 3600000));
		
		for(i=0;i<rf.length;i++) {
			rf[i] = (rf[i] < 10)?'0'+rf[i]:rf[i];
		}
		
		return rf;
	}, 
	_formatUpcoming: function(date) {
		var year = date.getFullYear();
		var month = ((date.getMonth()+1) > 9)?date.getMonth()+1:'0'+(date.getMonth()+1);
		var day = (date.getDate() > 9)?date.getDate():'0'+date.getDate();
		var hours = (date.getHours() > 9)?date.getHours():'0'+date.getHours(); 
		var minutes = (date.getMinutes() > 9)?date.getMinutes():'0'+date.getMinutes(); 
		
		return year+'-'+month+'-'+day+' | '+hours+':'+minutes;
	},
	createAction: function (action) {
		var action;
		if(action == 'ranking') {
			action = new Element('a', {
				href: '/webmagic/GroupProfile?groupName='+this.groupName+'&ptid='+this.pdId+'&m=private', 
				'class': 'rankIco'
			});		
		} else if(action == 'inactiveRanking') {
			action = new Element('span', {
				'class': 'inactiveRankIco'
			});	
		} else {
			action = new Element('span', {
				text: action, 
				styles: {
					'margin-left': '5px'
				}
			});	
		}
		this.container.grab(action);
	}, 
	createPlayLink: function () {
		var playLink = new Element('a', {
			href: '/webmagic/GroupRaceStart?ptId='+this.pdId, 
			'class': 'playIco'
		});
		
		var playLinkText = new Element('span', {
			text: 'play'
		});
		
		playLink.grab(playLinkText);
		this.container.grab(playLink);
	}, 
	createInactivePlayLink: function () {
		var inactivePlayLink = new Element('span', {
			'class': 'inactivePlayIco'
		});
		
		var playLinkText = new Element('span', {
			text: 'play'
		});
		
		inactivePlayLink.grab(playLinkText);
		this.container.grab(inactivePlayLink);
	}
});

/*
=PeriodicalPool
*/
var PeriodicalPool = new Class ({
	Implements: [Options, Events], 
	options: {
		period: 1000
	},
	initialize: function (options) {
		this.setOptions(options);

		this.counter = 0;
		this.keepRunning = false;

		var periodicalFunction = (function() {
			this.counter++;
			this.doStuff()

		}.bind(this));
		
		this.period = periodicalFunction.periodical(this.options.period, counter);
	},
	doStuff: function () {
		this.fireEvent('periodic');

		if($type(this.keepRunning) == 'number' && this.keepRunning <= 0){
			$clear(this.period);
		} 
	}
});

