$(function() {

	if(typeof dwr != "undefined"){ dwr.engine.beginBatch(); }

	$('div.related dd.rel-cinema div.remoteContent').theatre();
	$('div.related dd.rel-cinema div.remoteContent').tv();
	$('td.reservation a').ladder();
	$('h4.theatre-info').theatreInfo();
	
	/** extra community lists */
	$('#Film dt.rel-community').addTabbedMovieLists(['popular','hot','ratedOnTv','ratedInTheater',
													'popularInTheater','rated']);
		
	$('#Bioscoop dt.rel-community').addTabbedMovieLists(['ratedInTheater', 'popularInTheater']);
		
	$('dt.rel-user').one('click', function() {
		$('ul.subscribe li.subscriptions-current').subscriptions();
	});	
		/** if visible on start */
		$('dd.rel-user').each(function(){
			if($(this).css('display') == 'block'){ $('dt.rel-user').click();	}		
		});	
	if(typeof dwr != "undefined"){ dwr.engine.endBatch() };	
});

/** 
* Get tv information
* @alias jQuery.prototype.tv
* @return {jQuery}
*/
jQuery.fn.tv = function() {
	return this.each(function() {

		if(typeof movies == "undefined"){
			return;
		}	

		var el = $.create('div');1
		$(this).prepend(el);
						
		if (movies.length == 1)
			tvServiceDWR.findShowsForMovie(movies[0], stations);
		else if (movies.length > 1)
			tvServiceDWR.findShowsForMovies(movies, stations);
		
		function stations(obj) {
			if (obj.length == 0)
				return;
			
			/* kopje */
			var head = $.create('h5', {id: 'tv-stations', className: 'fg-theme-color underline-theme-color'});
			head.text('Televisie');
			el.append(head);
			head.after('<img alt="Deze week op televisie" title="Deze week op televisie" src="'+ base +'images/icons/thumbnail_tv.gif" style="float:right;" />');

			$.each(obj, function(i, o) {
				var months = ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'];
				var weekdays = ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'];
				var data = o.station;
				var movie = o.movie;
				var tvDate = '';
				var zender;
				var mins, hours, day, month, start, end, weekday, startTime, endTime, zenderInfo;
				
				startTime = o.scheduleStart;
				/** if starttime is >=00:00 < 6:00 it belongs to the day before */	
				if(startTime.getHours() >= 0 && startTime.getHours() < 6){				
					var msecs =	startTime.getTime();
						msecs = msecs - (24*60*60*1000);/** subtract 1 day */
					startTime = new Date();				
					startTime.setTime(msecs);							
				}
				weekday = weekdays[startTime.getDay()];	
				zender = data.name;
				day = startTime.getDate();
				month = startTime.getMonth()+1;
				hours = startTime.getHours();
				mins = startTime.getMinutes();
				start = hours+':'+(mins < 10 ? '0' + mins : mins);
				endTime = o.scheduleStop;
				hours = endTime.getHours();
				mins = endTime.getMinutes();
				end = hours+':'+(mins < 10 ? '0' + mins : mins);
				
				tvDate = weekday.toLowerCase() +' '+ day +' '+ months[month-1].toLowerCase();
				
				zenderInfo = $.format('{1} ({2}, {3} - {4})', zender, tvDate, start, end);
				
				var url = $.format('{1}tv/{2}/{3}/{4}', base, startTime.getFullYear(), month, day);
				var a = $.create('a', {href: url});
				var p = $.create('p', {className: 'movieTitle tv'});
				a.text(zenderInfo);
				p.append(a);
				el.append(p);
				var p = $.create('p', {className: 'movieTitle'});
				p.text(movie.title);
				el.append(p);
				var p = $.create('p', {className: 'movieData'});

				var directors = [];
				$(movie.relatedPersons).filter(function(i){return this.type == 'DIRECTOR'}).each( function(i, d){directors.push(d.roleB.fullName)})
				var director = directors.join(', ');

				if (movie.year != -1)
					director += ' ('+movie.year+')';
				p.text(director);
				el.append(p);
			});
			
			var a2 = $.create('a', {className: 'kop'});
				a2.attr('href', base + 'tv/#listing');
				a2.text('Televisie-overzicht vandaag');
			el.append(a2);
			el.append('<br />&nbsp;<br />');

			var scrollEl = el.parents('dd.related');
			var ul = el.parents('div.related').find('ul.top:first');
			$('div.rel-block').listJumpIcon(ul, 'tv', head, obj.length, scrollEl, true);
		}
	});
}


/** 
* Get theatre information
* @alias jQuery.prototype.theatre
* @return {jQuery}
*/
jQuery.fn.theatre = function() {
	return this.each(function() {

		if(typeof movies == "undefined"){
			return;
		}

		var el = $.create('div');
		$(this).prepend(el);

		showTimeServiceDWR.findCitiesForMovies(movies, cities);
		
		function cities(obj) {
			if (obj.length == 0)
				return;
			
			/* kopje */
			var head = $.create('h5', {id: 'theatre', className: 'fg-theme-color underline-theme-color'});
			head.text('Bioscoop');
			el.append(head);
			
			var toggleB = $.create('a', {className: 'togglebutton'});
				toggleB.append('<img alt="Draait nu in de bioscoop" title="Draait nu in de bioscoop" src="'+ base +'images/icons/thumbnail_bioscoop.gif" style="float:right;" />');	
			head.after(toggleB);
			/*
			if (data.length == 0) {
				toggleB.attr('href', base +'bioscoop/#listing');
				toggleB.append('<img alt="Draait nu in de bioscoop" title="Draait nu in de bioscoop" src="'+ base +'images/icons/thumbnail_bioscoop.gif" style="float:right;" />');	
			}else{
				toggleB.attr('href', '');
				toggleB.click(toggleSteden);
				toggleB.append('<img alt="Kies een stad (draait nu in '+data.length+' steden)" title="Kies een stad (draait nu in '+data.length+' steden)" src="'+ base +'images/icons/thumbnail_bioscoop.gif" style="float:right;" />');
			}*/				 
			
			$.each(obj, function(i, o) {
				var data = o.cities;
				var movie = o.movie;
				var p = $.create('p', {className: 'movieTitle bios'});
				p.text(movie.title);
				el.append(p);
				var p = $.create('p', {className: 'movieData'});

				var directors = [];
				$(movie.relatedPersons).filter(function(i){return this.type == 'DIRECTOR'}).each( function(i, d){directors.push(d.roleB.fullName)})
				var director = directors.join(', ');

				if (movie.year != -1)
					director += ' ('+movie.year+')';
				p.text(director);
				el.append(p);
	
				var a = $.create('a', {className: 'kop'});
			
				//if (data.length != 1) {
					a.attr('href', '');
					a.append('Kies een stad<br />(draait nu in '+data.length+' steden)');
					a.click(toggleSteden);			
				/*} else {				
					a.addClass('inactive');
					a.text('Draait nu in '+data[0].name);
					showTimeServiceDWR.findByCityAndMovie(movie.id, data[0].navName, toonTheater);
				}*/
				el.append(a);
				
				/* lijst van steden */
				var list = $.create('div', {className: 'steden'});
				p= $.create('p', {className: 'kiesstad'});
				p.text('Deze film is te zien in:');
				list.append(p);
				$.each(data, function(i, stad) {
					var a = $.create('a', {href: stad.navName+'/'+movie.id});
					a.text(stad.name);
					a.click(theaters)
					list.append(a);
					if (i < data.length - 1) {
						var sep = document.createTextNode(', ');
						list.append(sep);
					}
				});
				el.append(list);
				
				var info = $.create('div', {className: 'theaterInfo'});
				info.css({'display':'none'});
				el.append(info);

				if (data.length != 1) {
					el.append('<br />');
				}
				var a2 = $.create('a', {className: 'kop'});
					a2.attr('href', base + 'bioscoop/#listing');
					a2.text('Ga naar de volledige bioscoopladder');
				el.append(a2);
				el.append('<br />&nbsp;<br />');
		
				function toggleSteden() {
					
					if ($.browser.safari) {
						a.addClass('open');
						list.css('display', 'block');					
					} else {
						a.toggleClass('open');
						
						/** anim bugs in jQuery 1.1.x */	
						//list.slideToggle();
						list.css('display', (list.css('display') == 'block')? 'none':'block' );
						info.slideUp();
					}
					
					return false;
				}
				function theaters() {
					var theater = $(this);
					var theaterCity = theater.attr('href').split('/');
					showTimeServiceDWR.findByCityAndMovie(theaterCity[1], theaterCity[0], toonTheater);
					return false;
				}
				function toonTheater(data) {
					info.text('');
					var head = $.create('p', {className: 'cityName'});
					if (data.length == 0)
						head.text("Geen theaters gevonden");
					else
						head.text(data[0].theater.city.name);
					info.append(head);
		
					var list = $.create('ul');
					$.each(data, function(i, t) {
						var li = $.create('li');
						var res = $.create('a', {className: 'reserveren', href: 'http://www.belbios.nl/'});
						res.text('reserveren');
						res.click(function() {
							reservation(movie, t.theater);
							return false;
						})
						li.append(res);
		
						var name = $.create('p', {className: 'name'});
						name.text(t.theater.name);
						li.append(name);
						var time = $.create('p');
						time.text(t.times);
						li.append(time);
						list.append(li);
					});
					info.append(list);
					
		
					if ($.browser.safari) {
						info.css('display', 'block');					
					} else {
						info.css({display: 'block', height:'auto'});
						//info.slideDown();/* bugs!! */
						el.find('div.steden').slideUp();
						el.find('a.kop').removeClass('open');
					}
				}
			});

			var scrollEl = el.parents('dd.related');
			var ul = el.parents('div.related').find('ul.top:first');
			$('div.rel-block').listJumpIcon(ul, 'theatre', head, obj.length, scrollEl, true);
		}
	});
}

/** 
* Activeer reserveer-knop bioscoopladder
* @alias jQuery.prototype.ladder
* @return {jQuery}
*/
jQuery.fn.ladder = function() {
	return this.each(function() {
		var me = $(this);
		me.click(function() {
			var ids = me.siblings('span').text().split('/');
			var movie = {
				id: ids[0],
				title: me.parents('tr').find('td:nth(1) h4').text()
			};
			var th = me.parents('tr');
			while (!th.is('.title')) {
				th = th.prev();
			}
			th = th.find('td:first');
			var theatre = {
				id: ids[1],
				name: th.find('h4').text(),
				city: {name: $('#listing div.found h3.artikelen span').text()},
				phonenumber: th.find('p.meta').text()
			};
			reservation(movie, theatre);
			return false;
		});
	});
}

function reservation(movie, theatre) {
	var dark = $.darken();
	
	var box = $.create('div', {id: 'reservation'});
	box.css('top', $(document).scrollTop()+200);

	var tBalk = $.create('h1', {className: 'bar'}).text('Reserveren');
	box.append(tBalk);

	var closeBox = $.create('div', {id: 'resClose'}).text('X sluiten');
	closeBox.click(function() {
		box.remove();
		dark.cancel();
	});
	box.append(closeBox);

	var form = $.create('form');

	var theaterName = $.create('h1').text(theatre.name+' ('+theatre.city.name+')');
	form.append(theaterName);
	var title = $.create('h2').text(movie.title);
	form.append(title);
	
	var wait = $.create('p', {className: 'ajax-wait'}).text('Even geduld...');
	form.append(wait);

	box.append(form);
	box.css('height', 0);
	$('body').append(box);
	box.animate({height: 250});

	errorHandler = resvFormError;
	showTimeServiceDWR.findReservationOptionsForMovieInTheater(movie.id, theatre.id, resvForm, resvFormError);
	resvFormError = null;

	function resvForm(data) {
		wait.remove();

		var kies = $.create('p').text('Kies een tijdstip:');
		form.append(kies);
		
		var sel = $.create('select');
		$.each(data, function(i, d) {
			var opt = $.create('option');
			var date = d.date.getDate()+'-'+(d.date.getMonth()+1)+'-'+d.date.getFullYear();
			var time = d.date.getHours()+':'+d.date.getMinutes();
			var resvInfo = [d.bbCinemaId, d.bbMovieId, date, time].join(',');
			opt.attr('value', resvInfo);
			opt.text(niceDate(d.date, true));
			sel.append(opt);
		});
		form.append(sel);
		
		var button = $.create('input', {type: 'submit', value: 'Reserveer'});
			button.click(function(){
				var wait = $.create('p', {className: 'ajax-wait'}).text('Even geduld...');
				form.append(wait);
	
				var ar = sel.val().split(',');
				showTimeServiceDWR.placeReservation(ar[0], ar[1], ar[2], ar[3], getUrl);
				return false;
				
				function getUrl(url) {
					var w = window.open(url, '_blank', 'width=400,height=450');
					if (!w) {						
						
						/** popups are being blocked, show a link to open the reservation page in a new window */
						alert('Er wordt een popup geblokkeerd. \n\n' + 'Klik op de hyperlink die zo verschijnt om de reservering af te maken in een nieuw venster.');

						var or = $.create('a').text('Open de reserveringspagina in een nieuw venster.');
							or.attr('href', url);
							or.attr('target', '_blank');
							or.css({display : 'block', textDecoration: 'underline'});							
							or.click(function(){
								box.remove();
								dark.cancel();								
							});
						var p = $.create('p');																		
						wait.after(p);
						p.append(or);
						wait.remove();

					} else {
						box.remove();
						dark.cancel();
					}
				}
			});
		form.append(button);		
	}
	function resvFormError(data) {	
		wait.remove();
		var err = $.create('p').html('Op dit moment is online reserveren niet mogelijk.<p>Bel om te reserveren '+theatre.name+': '+theatre.phonenumber+'.</p>');
		form.append(err);

		var button = $.create('input', {type: 'submit', value: 'Annuleren'});
		button.click(function(){
			box.remove();
			dark.cancel();
		});		
		form.append(button);
	} 
}


/** 
* Activate button for theatre info.
* @alias jQuery.prototype.theatreInfo
* @return {jQuery}
*/
jQuery.fn.theatreInfo = function() {
	var active, open = [];
	return this.each(function(i) {
		open[i] = false;
		$(this).click(function() {
			
			var me = $(this);
			var box = $('#theatreInfo');

			if (open[active]) {
				box.animate({height: 0}, function() {
					box.remove();
					open[active] = false;
					if (active != i) {
						showInfo();
					}
				});
			} else {
				showInfo();
			}			
			
			function showInfo() {
				var box = $.create('div', {id: 'theatreInfo'});
				box.css('top', me.offset().top+35);
			
				var tBalk = $.create('h1', {className: 'bar'}).text('Adresinformatie');
				box.append(tBalk);
			
				var closeBox = $.create('div', {id: 'resClose'}).text('X sluiten');
				closeBox.click(function() {
					box.animate({height: 0}, function() {
						box.remove();
						open[i] = false;
					});
				});
				box.append(closeBox);

				var p = me.parents('td').find('p.desc').clone(true);				
				box.append(p);
				
				box.css('height', 0);
				$('body').append(box);
				box.animate({height: 250});
				open[i] = true;
				active = i;
			}
		});
	});
};


