/* ---------------------------------------------------------------------------------------------------- */
/* =bell-barbecue.js */
/* ---------------------------------------------------------------------------------------------------- */

var BELL = {};


/* -------------------------------------------------- */
/* =nav */

BELL.nav = {
	
	init: function () {
		this.container = $('mainnav');
		this.items = {
			mainnav: this.container.getElements('li.main')
		};
		this.items.mainnav.each(function (item, index) {
			var subnav = item.getElement('.subnav');
			if (subnav) {
				item.addEvents({
					'mouseenter': this.showSub.pass(subnav, this),
					'mouseleave': this.hideSub.pass(subnav, this)
				});
			}
		}, this);
	},
	
	showSub: function (subnav) {
		subnav.setStyle('display', 'block');
	},
	
	hideSub: function (subnav) {
		subnav.setStyle('display', 'none');
	}
	
};

window.addEvent('domready', function () {
	//BELL.nav.init();
});


/* -------------------------------------------------- */
/* =externalLinks */

window.addEvent('domready', function () {
	$$('#content a').forEach(function (anchor) {
		var href = anchor.get('href');
		if (href && (href.test(/^http:\/\//) || href.test(/^https:\/\//))) anchor.addClass('external');
	});
});


/* -------------------------------------------------- */
/* =tracking */

BELL.tracker = {

	init: function () {
		$$('a').forEach(function (anchor) {
			var href = anchor.get('href');
			if (href) {
				if (href.test(/^http:\/\//) || href.test(/^https:\/\//)) anchor.addEvent('click', this.track.pass(['outbound', '/' + href], this));
				if (href.test(/^\/_upload\//)) anchor.addEvent('click', this.track.pass(['download', href], this));
			}
		}, this)
	},
	
	track: function (type, href) {
		pageTracker._trackPageview('/' + type + href);
	}
	
};

window.addEvent('domready', function () {
	BELL.tracker.init();
});


/* -------------------------------------------------- */
/* =weather */

BELL.weather = {

	init: function () {
		$('frm-weather-submit').addEvent('click', function () {
			$('frm-weather').submit();
		});		
	}
	
};

window.addEvent('domready', function () {
	$('weather-teaser').addEvent('click', function () {
		window.location.href = '/service/wetter';
	});
});


/* -------------------------------------------------- */
/* =cup */

BELL.cup = {
	
	init: function () {
		this.input = $('fld-grillchef').addEvent('keypress', this.checkPreview.bindWithEvent(this));
		this.buttonPreview = $('cup-preview-button').addEvent('click', this.setText.bind(this));
		this.buttonSend = $('cup-order-button').addEvent('click', this.sendForm.bind(this));
		this.loadFlash();
		if (this.input.get('value').trim().length) this.checkComm();
	},
	
	loadFlash: function () {
		this.swiff = new Swiff('/_swf/cup-preview.swf', {
			width: 603,
			height: 557,
			container: 'cup-preview-container',
			vars:  {
				lang: thisUserLang
			}
		});
	},
	
	checkComm: function () {
		try {
			this.setText();
		} catch (e) {
			this.checkComm.delay(500, this);
		}
	},
	
	checkPreview: function (event) {
		if (event.key === 'enter') {
			event.stop();
			if (window.location.href.search(/#/) < 0) window.location.href = window.location.href + '#cup';
			this.setText();
		}
	},
	
	setText: function () {
		this.swiff.remote('setText', this.input.get('value').trim().toUpperCase());
	},
	
	sendForm: function () {
		$('frm-cup').submit();
	}
	
};

/* -------------------------------------------------- */
/* =PartnerSlideShow */
BELL.PartnerHandler =
{
    init: function () {
		this.loadFlash();
	},
	
	loadFlash: function () {
		this.swiff = new Swiff('/_swf/partner.swf', {
		    width:202,
		    height:160,
		    loop:false,
			container: 'RbFlashPartner'
		});
	}
};

/* -------------------------------------------------- */
/* =FireBox */
BELL.FireHandler =
{
    init: function () {
		this.loadFlash();
	},
	
	loadFlash: function () {
		this.swiff = new Swiff('/_swf/bell_flames.swf', {
		    width:1960,
		    height:150,
		    loop:false,
			container: 'fireBox'
		});
	}
};

/* -------------------------------------------------- */
/* =calculator */

BELL.calculator = {
	
	init: function () {
		//console.log('BELL.calculator.init');
	}	
	
};


/* -------------------------------------------------- */
/* =ringtones */

BELL.ringtones = {
	
	options: {
		volume: 50
		
	},
	
	init: function (data) {
		this.data = data;
		this.sounds = new Hash();
		this.data.forEach(this.createSound, this);
	},
	
	createSound: function (data) {
		this.sounds.include(data.id, soundManager.createSound({
			id: data.id,
			url: data.url,
			volume: this.options.volume,
			onfinish: this.hidePlayingIcon.pass(data.id, this)
		}));
		$('play-' + data.id).addEvent('click', this.toggle.pass(data.id, this));
	},
	
	stopAll: function () {
		this.sounds.forEach(function (obj, key) {
			this.stop(key);
		}, this);
	},
	
	stop: function (id) {
		this.sounds.get(id).stop();
		this.hidePlayingIcon(id);
	},
	
	play: function (id) {
		this.sounds.get(id).play();
		this.showPlayingIcon(id);
		pageTracker._trackPageview('/ringtones/listen/' + id);
	},
	
	toggle: function (id) {
		if (this.sounds.get(id).playState == 0) {
			this.stopAll();
			this.play(id);
		} else {
			this.stop(id);
		}
	},
	
	showPlayingIcon: function (id) {
		$('play-' + id).addClass('playing');
	},
	
	hidePlayingIcon: function (id) {
		$('play-' + id).removeClass('playing');
	}
	
}


/* -------------------------------------------------- */
/* =invitation */

BELL.invitation = {

	init: function () {
		this.tagger = new Tags('fld-email', 'recipients-output', {tagSeparators: [';', 'enter']});
		$('invitation-add-recipient').addEvent('click', this.addRecipient.bind(this));
		this.calendar = new Calendar();
		this.calendar.addEvent('select', function (date) {
			$('fld-date').set('value', date.format('%d.%m.%Y'));
		});
		$('fld-date-cal').addEvent('click', function (event) {
			this.calendar.load(event, {
				date: $('fld-date').get('value')
			});
		}.bind(this));
		
		$('frm-invitation-submit').addEvent('click', function () {
			$('frm-invitation').submit();
		});
	},
	
	addRecipient: function () {
		var input = $('fld-email');
		var value = input.get('value').trim();
		if (value.length) {
			this.tagger.addTag(value);
			input.set('value', '');
		}
		
	}
	
};



/* -------------------------------------------------- */
/* =tvspots */

BELL.tvspots = {
	
	data: {
		'hippie-de': '/_upload/tvspots/bell_grillschef_hippie_d.flv',
		'jeanclaude-de': '/_upload/tvspots/bell_grillschef_jean_claude_d.flv',
		'liebeskummer-de': '/_upload/tvspots/bell_grillschef_liebeskummer_d.flv',
		'seich-de': '/_upload/tvspots/bell_grillschef_seich_d.flv',
		
		'hippie-fr': '/_upload/tvspots/bell_grillschef_hippie_f.flv',
		'jeanclaude-fr': '/_upload/tvspots/bell_grillschef_jean_claude_f.flv',
		'liebeskummer-fr': '/_upload/tvspots/bell_grillschef_liebeskummer_f.flv',
		'seich-fr': '/_upload/tvspots/bell_grillschef_seich_f.flv',
		
		'hippie-it': '/_upload/tvspots/bell_grillschef_hippie_i.flv',
		'jeanclaude-it': '/_upload/tvspots/bell_grillschef_jean_claude_i.flv',
		'liebeskummer-it': '/_upload/tvspots/bell_grillschef_liebeskummer_i.flv',
		'seich-it': '/_upload/tvspots/bell_grillschef_seich_i.flv'
	},
	
	init: function () {
		this.container = $('spots-mediaplayer-container');
		$('spots-anchors').getElements('a').forEach(function (anchor) {
			var key = anchor.get('class');
			anchor.addEvent('click', this.loadSpot.pass(this.data[key], this));
		}, this);
	},
	
	loadSpot: function (file) {
		this.swiff = new Swiff('/_swf/mediaplayer.swf', {
			width: 480,
			height: 308,
			container: this.container,
			vars: {
				file: file,
				volume: 50,
				autostart: true
			}
		});
		pageTracker._trackPageview('/tvspots' + file);
	}
	
};


/* -------------------------------------------------- */
/* =makingof */

BELL.makingof = {

	init: function () {
		new Swiff('/_swf/slideshow.swf', {
			width: 480,
			height: 350,
			container: 'spots-makingof-container'
		});
	}

};


/* -------------------------------------------------- */
/* =knowhow */

BELL.knowhow = {
	
	init: function () {
		new Fx.Accordion($$('.knowhow-trigger'), $$('.knowhow-wrapper'), {
			display: -1,
			opacity: false
		});
	}	

};


/* -------------------------------------------------- */
/* =organizer */

BELL.organizer = {};

BELL.organizer.create = {
	
	init: function () {
		
		this.mapTypes = {
			'G_NORMAL_MAP': G_NORMAL_MAP,
			'G_PHYSICAL_MAP': G_PHYSICAL_MAP
		};
		
		this.loadMap();
		this.inputs = {
			zip: $('map-zip'),
			city: $('map-city'),
			address: $('map-address'),
			longitude: $('map-longitude'),
			latitude: $('map-latitude'),
			maptype: $('map-maptype'),
			zoomlevel: $('map-zoomlevel')
		};
		this.inputs.zip.addEvent('blur', this.checkAddress.bind(this));
		this.inputs.city.addEvent('blur', this.checkAddress.bind(this));
		this.inputs.address.addEvent('blur', this.checkAddress.bind(this));
		this.form = $('frm-organizer-new');
		this.btn = $('frm-organizer-submit');
		this.btn.addEvent('click', this.sendForm.bindWithEvent(this));
		this.geocoder = new google.maps.ClientGeocoder();
		this.zoomLevel = 7;
		this.mapType = 'G_PHYSICAL_MAP'; 
		this.isGeoCoding = false;
		this.checkAddress();
	},
	
	loadMap: function () {
		this.map = new google.maps.Map2($('organizer-map'));
    	this.map.disableDragging();
		this.map.disableDoubleClickZoom();
		this.resetMap();
	},
	
	resetMap: function () {
		this.zoomLevel = 7;
		this.mapType = 'G_PHYSICAL_MAP';
		this.map.setCenter(new google.maps.LatLng(46.7, 8.25), this.zoomLevel, this.mapTypes[this.mapType]);
		if (this.marker) {
			this.marker.remove();
			this.marker = null;
		}
	},
	
	checkAddress: function () {
		this.isGeoCoding = true;
		var address = '';
		if (this.inputs.city.get('value')) {
			address += ', ' + this.inputs.city.get('value');
			this.zoomLevel = 13;
			this.mapType = 'G_NORMAL_MAP';
		}
		if (this.inputs.zip.get('value')) {
			address += ', ' + this.inputs.zip.get('value');
			this.zoomLevel = 13;
			this.mapType = 'G_NORMAL_MAP';
		}
		if (this.inputs.address.get('value')) {
			address += ', ' + this.inputs.address.get('value');
			this.zoomLevel = 15;
			this.mapType = 'G_NORMAL_MAP';
		}
		if (address.length) {
			address = 'Switzerland' + address;
			this.geocoder.getLatLng(address, this.setLocation.bind(this));
		} else {
			this.resetMap();
			this.fillForm({lat: '', lng: '', maptype: '', zoomlevel: ''});
		}
	},
	
	setLocation: function (LatLng) {
		if (LatLng) {
			this.map.setCenter(LatLng, this.zoomLevel, this.mapTypes[this.mapType]);
			if (this.marker) {
				this.marker.setLatLng(LatLng);
			} else {
				this.marker = this.createMarker(LatLng);
				this.map.addOverlay(this.marker);
			}
			this.fillForm({lat: LatLng.lat(), lng: LatLng.lng(), maptype: this.mapType, zoomlevel: this.zoomLevel});
		} else {
			this.resetMap();
			this.fillForm({lat: '', lng: '', maptype: '', zoomlevel: ''});
		}
	},
	
	fillForm: function (values) {
		this.inputs.latitude.setProperty('value', values.lat);
		this.inputs.longitude.setProperty('value', values.lng);
		this.inputs.maptype.setProperty('value', values.maptype);
		this.inputs.zoomlevel.setProperty('value', values.zoomlevel);
		this.isGeoCoding = false;
	},
	
	createMarker: function (point) {
		var marker = new google.maps.Marker(point);
		return marker;
	},
	
	sendForm: function () {
		if (!this.isGeoCoding) {
			this.timer = $clear(this.timer);
			this.form.submit();
		} else {
			this.timer = this.checkSubmitState.periodical(50, this);
		}
	},
	
	checkSubmitState: function () {
		if (!this.isGeoCoding) this.sendForm();
	}
	
};


BELL.organizer.date = {
	
	options: {
		SelectedDates: []
	},
	
	init: function (options) {
		$extend(this.options, options);
		this.datelist = $('organizer-datelist-list');
		this.items = this.options.SelectedDates;
		this.cal = new Calendar({
			className: 'organizer-calendar',
			embed: $('calendar-container'),
			multiSelect: true,
			SelectedDates: this.options.SelectedDates,
			Months: BELL.organizer.date.Months,
			WeekDays: BELL.organizer.date.WeekDays,
			Today: BELL.organizer.date.Today,
			onSelect: function (date) {
				this.checkDate(date);
			}.bind(this)
		});
		this.updateDateList();
		$('frm-organizer-date-submit').addEvent('click', function () {
			$('frm-organizer-date').submit();	
		});
	},
	
	checkDate: function (date) {
		(this.items.contains(date.format('%d.%m.%Y'))) ? this.removeDate(date) : this.addDate(date);
	},
		
	addDate: function (date) {
		if (!this.items.contains(date.format('%d.%m.%Y'))) {
			this.items.push(date.format('%d.%m.%Y'));
			new Request({
				url: '/_service/organizer.asp?time=' + $time(),
				data: 'op=10&organizer_date=' + date.format('%Y-%m-%d'),
				onSuccess: this.updateDateList.bind(this)
			}).send();
			//this.updateDateList();
		}
	},
		
	removeDate: function (date) {
		if (this.items.contains(date.format('%d.%m.%Y'))) {
			this.items.erase(date.format('%d.%m.%Y'));
			new Request({
				url: '/_service/organizer.asp?time=' + $time(),
				data: 'op=20&organizer_date=' + date.format('%Y-%m-%d'),
				onSuccess: this.updateDateList.bind(this)
			}).send();
			//this.updateDateList();
		}
	},
	
	updateDateList: function () {
		this.datelist.empty();
		this.items.sort(this.sortDate);
		this.items.forEach(function (item) {
			new Element('li').set('text', item).injectInside(this.datelist);
		}, this);
	},
	
	sortDate: function (a, b) {
		var arrA = a.split('.'); var a = arrA[2] + arrA[1] + arrA[0];
		var arrB = b.split('.'); var b = arrB[2] + arrB[1] + arrB[0];
		return (a > b) ? 1 : -1;
	}
	
};


BELL.organizer.time = {
	
	init: function () {
		$('frm-organizer-time-submit').addEvent('click', function () {
			$('frm-organizer-time').submit();
		});
	}
	
};


BELL.organizer.send = {
	
	options: {
		Lat: 46.7,
		Lng: 8.25,
		zoomLevel: 7,
		mapType: 'G_PHYSICAL_MAP'
	},
	
	init: function (options) {
		
		$extend(this.options, options);
		
		this.mapTypes = {
			'G_NORMAL_MAP': G_NORMAL_MAP,
			'G_PHYSICAL_MAP': G_PHYSICAL_MAP
		};
		
		this.loadMap();
	},
	
	loadMap: function () {
		this.map = new google.maps.Map2($('organizer-map'));
    	this.map.disableDragging();
		this.map.disableDoubleClickZoom();
		var LatLng = new google.maps.LatLng(this.options.Lat, this.options.Lng);
		this.map.setCenter(LatLng, this.options.zoomLevel, this.mapTypes[this.options.mapType]);
		this.marker = this.createMarker(LatLng); // TODO: set marker only if options are passed
		this.map.addOverlay(this.marker);
	},
	
	createMarker: function (point) {
		var marker = new google.maps.Marker(point);
		return marker;
	}
	
};



BELL.organizer.subscribe = {
	
	options: {
		Lat: 46.7,
		Lng: 8.25,
		zoomLevel: 7,
		mapType: 'G_PHYSICAL_MAP'
	},
	
	init: function (options) {
		
		$extend(this.options, options);
		
		this.mapTypes = {
			'G_NORMAL_MAP': G_NORMAL_MAP,
			'G_PHYSICAL_MAP': G_PHYSICAL_MAP
		};
		
		this.loadMap();
		
		$('frm-subscribe-submit').addEvent('click', function (){
			$('frm-subscribe').submit();
		});
	},
	
	loadMap: function () {
		this.map = new google.maps.Map2($('organizer-map'));
    	this.map.disableDragging();
		this.map.disableDoubleClickZoom();
		var LatLng = new google.maps.LatLng(this.options.Lat, this.options.Lng);
		this.map.setCenter(LatLng, this.options.zoomLevel, this.mapTypes[this.options.mapType]);
		this.marker = this.createMarker(LatLng);
		this.map.addOverlay(this.marker);
	},
	
	createMarker: function (point) {
		var marker = new google.maps.Marker(point);
		return marker;
	}
	
};


/* -------------------------------------------------- */
/* =Prefill */

BELL.Prefill = new Class({
	initialize: function (element, defaultValue) {
		this.element = $(element);
		this.defaultValue = defaultValue;
		this.element.addEvents({
			'focus': this.clearValue.bind(this),
			'blur': this.prefillValue.bind(this)
		});
		this.prefillValue();
	},
	clearValue: function () {
		if (this.element.get('value') == this.defaultValue) this.element.setProperty('value', '');
	},
	prefillValue: function () {
		if (this.element.get('value').length == 0) this.element.setProperty('value', this.defaultValue);
	}
});
