
var currentdate = null;


$(document).ready( function() {
	
	currentdate = Date.parseExact($('body').attr('today'), 'yyyy-MM-dd');
	
    $.ajaxSetup ({error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Server communication error: " + errorThrown)
    }});	

	targetBlank();
	
    ua = navigator.userAgent;
    ual = navigator.userAgent.toLowerCase();
	version = $.browser.version.split('.');
	
	$('#top-right').width($('#nav').width());
	$('#top-right').height(20);
		
	$('.center-if-one-line, #article.theteam h2').each(function() {
		if($(this).height() <= parseInt($(this).css('line-height'))) {
			$(this).css('text-align', 'center');
		}
	});
	
	mh = $('#nav').height()-140;

	$('body:not(.currentpage-partners-sponsors) #articles.boxes .box:first').css('padding-left', '200px');
	$('body:not(.currentpage-partners-sponsors) #articles.boxes .box:first').css('min-height', mh+'px')
	
	setupArticles();
	setSizesArticles();
	
	$('.reloadonappear').appear(function() {
		//not FF4!
		if(	
				(ual.search('firefox') > -1 && $.browser.version >= '2.0') 
			|| 	(ual.search('ipad') > -1 )
			|| 	(ual.search('ipod') > -1 )
			|| 	(ual.search('iphone') > -1 )
			|| 	(ual.search('android') > -1 )			
		
		) {

		} else {
			src = $(this).attr('src');
			$(this).attr('src', src);
		}
		
	}, {one: false})
	
	
	$('.screen img').css('cursor', 'pointer').bind('click', function(e) {
		e.preventDefault();
		scr = $(this).parent().parent().parent();
		window.location.hash = scr.attr('goto');
	});
	
	/*
	$('.screen.clicktotop img').css('cursor', 'pointer').bind('click', function() {
//		$.scrollTo(0, 1500, {axis:'y', easing: 'easeInOutCirc'})
		$.scrollTo(0, 800, {axis:'y'})		
	});
	*/
	


	$(window).bind('focus resize', function() {
		windowResized();
		

		$('#articles.boxes').masonry({ columnWidth: 5, resizeable: false });	
		$('#top-right').css('left', ($('#container').width()-$('#top-right').outerWidth())+'px')

		$('.screen').each(function() {
			scr = $(this);			
			scr.height($(window).height());
			imgh = (scr.find('img').height()/2);
			
			m = Math.abs(Math.round($(window).height()/2)-imgh);
			scr.find('.inner').css('padding-top', m+'px');
//			scr.find('.inner').css('padding-top', $(window).height()+'px')
			
		})


		/*
		posterimg = $('#poster').find('img');
		origh = parseInt($('#poster img').attr('origheight'));
		origw = parseInt($('#poster img').attr('origwidth'));


		if(origw > $(window).width()) {
			w = $(window).width();
			posterimg.width(w)		
			posterimg.css('left', '-30px');
			f = origh/origw;
			posterimg.height(Math.round(w*f))	
			$('#poster').css('height', Math.round(w*f))

			$('#poster img').height(posterimg.height());
			$('#poster img').width(posterimg.width());			
			$('#poster img').css('padding-left', '0px')
		} else {
			$('#poster img').height(origh);
			$('#poster img').width(origw);		
			$('#poster').height(origh)			

			pl = Math.round($('#content').width()/2 - (origw/2));
			$('#poster img').css('padding-left', pl+'px')
		
		}
		*/

		snapAjaxToArticle();
	});

	$(window).resize();	

	//page specific
    $('#newsletter_send').bind('click', function(e) {
        e.preventDefault();
		if($("input:radio:checked").val() == "Subscribe") {
			$.getJSON("/mail/add.php", { email: $('#newsletter_email').val(), name: $('#newsletter_name').val()  }, function(data) {
				alert(data.msg);				
	        });			
		} else {
			$.getJSON("/mail/remove.php", { email: $('#newsletter_email').val()  }, function(data) {
				alert(data.msg);				
	        });
		}
    });

	if($('#word-of-the-day').size()>0) {
		$('a.mp3').bind('click', function(e) {
			e.preventDefault();
			f = $(this).attr('mp3');
			str = '<div style="visibility:hidden;position:absolute"><embed type="application/x-shockwave-flash" flashvars="audioUrl='+f+'&autoPlay=true" src="http://www.google.com/reader/ui/3523697345-audio-player.swf" width="0" height="0" quality="best"></embed></div>';
			u = $(str);
			$('body').append(u)
			
		})
	}

	
	if($('#submit_photoform').size()>0) {
	    $('#submit_photoform').bind('click', function(e) {
	        e.preventDefault();

			$.getJSON("/mail/photo.php", { 
					firstlastname: $('#firstlastname').val(), 
					genderman: $('#genderman').is(':checked'),					
					genderwoman: $('#genderwoman').is(':checked'),
					addresshousenumber: $('#addresshousenumber').val(),	
					postcodeandcity: $('#postcodeandcity').val(),									  
					phonenumber: $('#phonenumber').val(),
					email: $('#email').val(),	
					numberwomen: $('#numberwomen').val(),									  
					numbermen: $('#numbermen').val(),
					numberkids: $('#numberkids').val(),	
					namesinphoto: $('#namesinphoto').val(),									  
					choosetime: $('#choosetime').val()								  
				}, function(data) {
				alert(data.msg);				
	        });			
	    });	
	}




    $('#legal-form a').bind('click', function(e) {
        e.preventDefault();
		
		if($("#i-have-read:checked").val()!='have-read') {
			alert('You need to comply to the rules above by checking the checkbox');				
		} else {
			url = "/mail/mail_legal.php";
			$.getJSON(url, {name : $('#legal_name').val(), date: $('#legal_date').val()} ,function(data) {
				alert(data.msg);				
	        });
		}
    });


	$('#login_press_submit').bind('click', function(e) {
		e.preventDefault();
		$('#press_form').submit();
	})
	
	$('#press_password').keypress(function(e){
		if(e.which == 13){
			$('#press_form').submit();
		}
    });


	if($('.currentpage-2011').size()>0) {
		$(window).bind('resize focus scroll', bgcolanim);
	}
	
	if($('.currentpage-participants').size() >0) {
		participants();
	}
	
	if($('.currentpage-article').size()>0) {
		$('a.ajax.participant').bind('click', function(e) {
			e.preventDefault();
			openParticipant($(this).offset().top, $(this).attr('participant-handle'), $(this).attr('href'))
		});		
	}
	
	if($('#programme').size()>0) {
		programme();
	}

	if($('#todaysprogramme').size()>0) {
		todaysprogramme($('body').attr('today'));
	}


	/*
	if(window.location.hash && $('.currentpage-participants').size()>0 != '') {
		s = window.location.hash.toString();
		$(s+'-id').trigger('click');
		setTimeout('scrollToParticipant()',250);
	}
	*/
	
	$('#nav > ul > li').has('.active').has('ul li ul li a').find('.toplevel').css('margin-bottom', '15px')
	$('#nav > ul > li:not(:eq(0)):not(:has(.active)):has(ul li a)').find('ul li').hide();
	if($('body').hasClass('style2011')) {
		$('#nav > ul > li:eq(1)').find('ul li').show();
		$('#nav > ul > li:eq(1)').find('.toplevel').css('margin-bottom', '15px')
	}
	
	if($('.currentpage-2011').size()>0) {

		if
		(
			( ual.search('android') > -1) ||		
			( ual.search('iphone') > -1 ) ||
			( ual.search('ipod') > -1 ) ||
			( ual.search('ipad') > -1 )

		) {
			$('body').css('visibility', 'visible');
			
		 } else {
			
			h = window.location.hash.substring(1);
			if(h != "maincontent" && h != '') {
				
				setTimeout("intro('"+h+"')", 200);
				
				$(window).hashchange( function() {
					h = window.location.hash.substring(1);

					if(h == 'amb') {
						

					} else {			
						if(h == ''){
							
						} else if(h == 'maincontent') {
							$.scrollTo(0, 1000, {axis:'y'});
						} else {
							$.scrollTo($('#'+h+'-id'), 250, {axis:'y'});
						}
					}				
				});
				

			} else {
				$('body').css('visibility', 'visible');
			}				
		}	
	} else {
			$('body').css('visibility', 'visible');
	}		
	
});

function intro(id) {

	$.scrollTo($('#'+id+'-id'), 0, {onAfter:bgcolanim()});				

	$('body').css('visibility', 'visible');
}

function snapAjaxToArticle() {
	w = $('#article').width();
	$('.participant-ajax').css('left', (w-130)+'px')
}

function setupArticles() {
	cuf();
//	flipSetup();	
	$(window).resize();
}

function openParticipant(offset, handle, href) {
	
//	$.scrollTo(offset, 300, {axis:'y', offset: {left: 0, top: -50}})	
	
	y = offset;

	//window.location.hash = $(this).attr('id');

	$('.participant-ajax').remove();
	
	d = $('<div class="participant-ajax"><div class="close"><a href="#" class="closebtn">Close</a><br/></div><div class="participant">...</div></div>');
	$('body').append(d)
	
	wtop = Math.round(y-30);
	d.css('top',wtop+'px');

	p = d.find('.participant');

	snapAjaxToArticle();

	p.load(href, function(responseText, textStatus) {
		$.scrollTo(d, 15, {axis:'x'})
		
		h = p.height();
		waterline = $(window).scrollTop()+$(window).height();

		if(h+wtop > waterline) {
			$.scrollTo(p, 200, {offset: {left: 0, top: -50}});
		}
		targetBlank();			

		setSizesArticles();
		flipSetup();
	})

	d.find('.closebtn').bind('click', function(e) {
		e.preventDefault();
		d.remove();
	})
	
	
}


function participants() {
	
	$(window).hashchange( function(){
		
		participant = $(window.location.hash+'-id');
		$('.participant a').removeClass('active');
		participant.addClass('active');				
		
		if(participant.size()==0) {
			$.scrollTo(0, 300, {axis:'y'});

			return;
		}		
		
		openParticipant(participant.offset().top, participant.attr('participant-handle'), participant.attr('href') );
	});
	
	
	$('a.ajax.participant').bind('click', function(e) {
		e.preventDefault();
		window.location.hash = $(this).attr('participant-handle');
		
	});
	
	$(window).hashchange();
}

function targetBlank() {
	$('a[href^="http://"], a[href^="https://"]').each(function(){
		t = $(this);
		if(t.attr('href').search(/arnhemmodebiennale.com/i) == -1 && t.attr('href').search(/localhost/i) == -1 && t.attr('href').search(/webtic.com/i) == -1 && t.attr('href').search(/10.37.129.2/i) == -1) {
			$(this).attr("target", "_blank");
		}
	});
}

function bgcolanim() {

		st = $(document).scrollTop();


		$('.bganim').each(function() {
			scr = $(this);

			if(st >= scr.offset().top && st <= scr.offset().top+scr.height()) {
				


				bcol = scr.attr('bganim-bottom');
				tcol = scr.attr('bganim-top');
				c = $.xcolor.gradientlevel(bcol, tcol, scr.offset().top+scr.height()-$(document).scrollTop(), scr.height());
				$('body').css('background-color', (c+''));
				
			}			
		})
	

}

$(window).load( function() {

	flipSetup();	
	
});

function minWidth(w) {
   	$('#content').css('min-width', w);
}
/*
function setInner() {
	$('.inner').each(function() {
		w = $(this).find('img').attr('origwidth');
		if(isNaN(w)) {
			w = $(this).find('img').attr('width');
		}
		if(isNaN(w)) {
			w = $(this).find('object').attr('width');
		}
		$(this).width(w);
		$(this).attr('w', w)
		
		alert($(this))

		h = $(this).find('img').attr('origheight');
		if(isNaN(h)) {
			h = $(this).find('img').attr('height');
		}
		if(isNaN(h)) {
			h = $(this).find('object').attr('height');
		}

		$(this).height(h);
		$(this).attr('h', h)
	});
}
*/

function flipSetup() {

	objects = $(".flip");

	objects.each(function(){
				
		words = $(this).text().split(" ");
		ww = '';
		for(word in words) {
			w = '<span y="0">' + words[word] + ' </span>';
			ww += w;
		}
		
		$(this).html(ww)
	});	


	objects.each(function() {
		line = 1;
		$(this).find("span").each(function(){
			if($(this).prev().size() >0 ) {
				if($(this).offset().top != $(this).prev().offset().top) {
					line++;
				}

				$(this).attr('y', line);				
				
			} else {
				
				$(this).attr('y', 1);			
			}
		});	
//		$(this).data('orig', $(this).html());				

	});

	objects.each(function() {
		$(this).find('span[y=1]').wrapAll('<div class="line line1"></div>');			
		$(this).find('span[y=2]').wrapAll('<div class="line line2"></div>');			
		$(this).find('span[y=3]').wrapAll('<div class="line line3"></div>');						
		$(this).find('span[y=4]').wrapAll('<div class="line line4"></div>');
		$(this).find('span[y=5]').wrapAll('<div class="line line5"></div>');			
		$(this).find('span[y=6]').wrapAll('<div class="line line6"></div>');						
		
		
	});
	
	objects.each(function() {
		$(this).data('orig', $(this).html());
	})

	cuf();

	$('.article').bind('mouseenter', function() {
		article = $(this);

		
		if(article.data('flipped') != 'yes') {
			lines = $(this).find('.flip .line');

			lines.each(function() {
					$(this).css('text-transform', 'lowercase')			
					$(this).find('span').reverseOrder()
					$(this).find('span').each(function() {
						t = $(this).text();
						$(this).text(t.split("").reverse().join(""));
					})
			});
			
			article.data('flipped', 'yes')
		}
		cuf();

	});
	
	$('.article').bind('mouseleave', function() {
		article = $(this);
		
		if(article.data('flipped') == 'yes') {
			
			$(this).find('.flip').each(function() {
				$(this).html($(this).data('orig'));
			});			

			article.data('flipped', 'no')
		}
		cuf();

	});	
	
}


function setSizesArticles() {
	

	//min w=400, pos absolute
    $('#articles .box').each(function(e) {
		imgs = $(this).find('img');
		
		imgsw = 0;
		imgs.each(function() {
			imgsw += parseInt($(this).attr('width'));

		});
		
		if(isNaN(imgsw)) {
			imgsw = parseInt($(this).find('object').attr('width'));
		}
					
		if(imgsw<380 || isNaN(imgsw)) imgsw = 380;
		$(this).width(imgsw + (imgs.size()*10));
		if($(this).hasClass('small')) {
			$(this).width(240)
		}

		
	});
	
	$('#articles #participants').width(380);
    
}

  function windowResized(boxes) {
		
		pw = $('#article p:first').width() - 40;

		
		$('#article .image').each(function() {

			img = $(this).find('img');
			ow = parseInt(img.attr('origwidth'));
			oh = parseInt(img.attr('origheight'));
			
			if(ow > pw ) {
				nw = pw;
				scale = ow/nw;
				nh = oh / scale;
			} else {
				nw = ow;
				nh = oh;					
			}

			if(nh > 230 || nw > 240) {
				img.width(nw);
				img.height(nh);			

			}
			
		});

    } //calc


function chooser(data, current) {

	var ul = $('<ul class="chooser"></ul>');
	
	for(i in data) {
		var li = $('<li></li>');
		name = data[i].name;
		id = data[i].id;
		li.append('<a>'+name+'</a>');
		if(current == id) {
			li.find('a').attr('class', 'active');
		}
		li.attr('filter-id', data[i].id);
		ul.append(li);		
	}
	ul.find('li').bind('click', function(e) {

		args = window.location.hash.substring(1).split('/');
		args[2] = $(this).attr('filter-id');
		args[4] = 'none';
		args[5] = 'none';

		url = args.join('/')

		window.location.hash = url;
	})
	
	return ul;
}

function todaysprogramme(day) {
	$.getJSON( '../../ajax-programme/',  function(data) {		
		//parse once only
		$.programme_data = data;
		
		var ev;
		for(i=0; i<data.programme.length; i++) {
			ev = data.programme[i];	
			ev.startdateobj = Date.parseExact(ev.start, 'yyyy-MM-dd HH:mm');
			ev.enddateobj = Date.parseExact(ev.end, 'yyyy-MM-dd HH:mm');
			
		}
		today = Date.parseExact(day, 'yyyy-MM-dd');
		days = expandRange( today, today  );			
		var num = showEvents(days, data, 'all-filters', true);

		
		$('#todaysprogramme #earlierday a').bind('click', function(e) {
			e.preventDefault();
			currentdate = currentdate.add({ days: -1});
			
			days = expandRange( currentdate, currentdate  );			
			var num = showEvents(days, $.programme_data, 'all-filters', true);
			
			checktodaysprogrammebuttons();
		})
		
		$('#todaysprogramme #laterday a').bind('click', function(e) {
			e.preventDefault();
			
			currentdate = currentdate.add({ days: 1});
			
			days = expandRange( currentdate, currentdate  );			
			var num = showEvents(days, $.programme_data, 'all-filters', true);
			
			checktodaysprogrammebuttons();
		})		
		
		checktodaysprogrammebuttons();
	});
}

function checktodaysprogrammebuttons() {
	start = Date.parseExact('2011-06-01', 'yyyy-MM-dd');
	end = Date.parseExact('2011-07-03', 'yyyy-MM-dd');

	if(currentdate.compareTo(start) <1) {
		$('#todaysprogramme #earlierday').css('visibility', 'hidden');
	} else {
		$('#todaysprogramme #earlierday').css('visibility', 'visible');
	}
	
	if(currentdate.compareTo(end) > -1) {
		$('#todaysprogramme #laterday').css('visibility', 'hidden');
	} else {
		$('#todaysprogramme #laterday').css('visibility', 'visible');
	}
}
	
function programme() {	
	
	$.getJSON( '../../ajax-programme/',  function(data) {		
		//parse once only
		
		for(i=0; i<data.programme.length; i++) {
			ev = data.programme[i];	
			ev.startdateobj = Date.parseExact(ev.start, 'yyyy-MM-dd HH:mm');
			ev.enddateobj = Date.parseExact(ev.end, 'yyyy-MM-dd HH:mm');

		}

		if(window.location.hash == "") {
			window.location.hash = "2011-06-01/2011-07-03/all-filters/all-locations/none/none";
		}

		/*
		if(window.location.hash.substring(0,6) == "#event") {
			var eventid = window.location.hash.substring(7,window.location.hash.length);
			window.location.hash = "2011-06-01/2011-07-03/all-filters/all-locations/" + eventid +"/none";
		}
		*/

		
		$(window).hashchange( function(){
			args = window.location.hash.substring(1).split('/');
			
			var startdate = Date.parseExact(args[0], 'yyyy-MM-dd');			
			var enddate = Date.parseExact(args[1], 'yyyy-MM-dd');
			
			var filter = args[2];
			var location = args[3];
			var ev = args[4];
			var evnum = args[5];
			
			$('#programme').html('');
			$('.event-ajax').remove();
			
			var ch = chooser(data['programme-filters'], filter);
			$('#programme').append(ch);

			days = expandRange(	startdate, enddate  );			
			var num = showEvents(days, data, filter, false);
			d= num + '/' + data.programme.length;
			$('#programme').prepend('<div id="hidden-data" style="display:none;">'+d+'</div>');
			
			if(ev != 'none') {
				openAjaxEvent(ev, evnum);
			}

		});

		

		$(window).hashchange();		
		
		/*
		$("#startdate").calendarWidget({
			month: 6,
			year: 2011						  
		 });

		$("#enddate").calendarWidget({
			month: 6,
			year: 2011						  
		 });
		
		
		$('.calendar-month .day').bind('click', function() {
			
		});
		*/
		
/*		startrange = new Date.parse('2011-06-01 10:00');
		endrange = new Date.parse('2011-07-03 22:00');

		days = expandRange(startrange, endrange);

		showEvents(days, data);*/

	});	
}

function openAjaxEvent(ev, evnum) {
	$('.event-ajax').remove();	
	var a = null;
	if(evnum == 'none') {
		a = $('a.event[eventid='+ev+']:first');		
	} else {
		a = $('a.event[eventid='+ev+'][evnum='+evnum+']:first');		
	}
	
	$('li.event').removeClass('active');
	a.parent().addClass('active');

	ot = a.offset().top;
	
	href = a.attr('href');
	//<div class="close"><a href="#" class="closebtn">Close</a><br/></div>
	d = $('<div class="event-ajax"><div class="event">...</div></div>');
	
	$('body').append(d);	
	wtop = ot-00;
	d.css('top',(wtop)+'px');
	p=d.find('.event');

	p.load(href, function(responseText, textStatus) {
	//	$.scrollTo(d, 15, {axis:'x'})

		h = $(this).height();
		waterline = $(window).scrollTop()+$(window).height();

		if(h+wtop > waterline) {
			$.scrollTo($(this), 350, {offset: {left: 0, top: -50}});
		}

		targetBlank();			

		lat = parseFloat($('.latitude:first').text())
		lng = parseFloat($('.longitude:first').text())		
		
		var latlng = new google.maps.LatLng(lat, lng);
	    var myOptions = {
	      zoom: 15,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
		  scrollwheel:false
	    };
	
	    var map = new google.maps.Map(document.getElementById("map"), myOptions);
		
		
		google.maps.event.addListener(map, 'zoom_changed', function() {
		    zoomChangeBoundsListener = 
		        google.maps.event.addListener(map, 'bounds_changed', function(event) {
		            if (this.getZoom() > 15 && this.initialZoom == true) {
		                // Change max/min zoom here
		                this.setZoom(15);
		                this.initialZoom = false;
		            }
		        google.maps.event.removeListener(zoomChangeBoundsListener);
		    });
		});		
		
		var bounds = new google.maps.LatLngBounds ();
	
		var firstinfowindow = true;
		var numplaces = 0;
		$('.event-ajax:first').find('.place').each(function() {
			lat = parseFloat($(this).find('.latitude').text())
			lng = parseFloat($(this).find('.longitude').text())		

			var myLatlng = new google.maps.LatLng(lat,lng);
  			bounds.extend (myLatlng);			

			var marker = new google.maps.Marker({
			     position: myLatlng, 
			     map: map,
			     title:$(this).find('.name').text()
			});
			
			var infowindow = new google.maps.InfoWindow({
			    content: $(this).find('.name').text() + '<br/>' + $(this).find('.description').text()
			});


			if(firstinfowindow) {
			  	infowindow.open(map,marker);
				firstinfowindow = false;
			}		

			
			google.maps.event.addListener(marker, 'click', function() {
			  infowindow.open(map,marker);
			});

			numplaces++;
		})
		
		
	
		if(numplaces>1) {
			map.initialZoom = true;				
			map.fitBounds (bounds);
		}	
		
		
		
	});

	d.find('.closebtn').bind('click', function(e) {
		e.preventDefault();
		d.remove();
	})	

}

function showEvents(days, data, filter, todayprogramme) {
	
	var evcnt = 0;
	var eventsperday = [];
	
	$('#todayprogramme_inner').html('');
	
	
	if(!todayprogramme) {
		for(i=0; i<data.programme.length; i++) {

			ev = data.programme[i];	

			if( ev['whole-month'] == 'Yes' ) {
				if((todayprogramme && ev['off-schedule']=='No') || !todayprogramme) {
					if($.inArray(filter, ev['programme-filters'])>-1) {

						eventsperday.push(ev);
						evcnt++;
					}
				}
			}		
		}	

		addDay(eventsperday, 999, $('#translations #ongoing').text(), todayprogramme, true)
	}
	
	var evnum=0;
	
	for(d in days) {

		startofday = days[d];
		endofday = startofday.clone();
		
		endofday.add({ days: 1});

					
		eventsperday = [];
		day = null;
		
		for(i=0; i<data.programme.length; i++) {
			ev = data.programme[i];	

			if(	ev['whole-month'] != 'Yes' && 
				(
					(
						ev.startdateobj.compareTo(startofday) > 0	&&
						ev.startdateobj.compareTo(endofday) < 0
					) ||
					(
						ev.enddateobj.compareTo(startofday) > 0	&&
						ev.enddateobj.compareTo(endofday) < 0
					) ||
					(
						ev.startdateobj.compareTo(startofday) < 0	&&
						ev.enddateobj.compareTo(endofday) > 0
					)					
				)
					
			) {

				if($.inArray(filter, ev['programme-filters'])>-1) {
					if( ( todayprogramme && ev['off-schedule']=='No') || !todayprogramme) {
						eventsperday.push(ev);
						evcnt++;
					}
				}
			}
		}

		if(eventsperday.length > 0 || todayprogramme) {			
			addDay(eventsperday, evnum++, days[d].toString('ddd d MMMM'), todayprogramme, false);			
		}
	}

	eventsperday =[];
	if(todayprogramme) {
		for(i=0; i<data.programme.length; i++) {

			ev = data.programme[i];	

			if( ev['whole-month'] == 'Yes' ) {
				if( ( todayprogramme && ev['off-schedule']=='No' && ev['show-ongoing-frontpage']=='Yes' ) || !todayprogramme) {
					if($.inArray(filter, ev['programme-filters'])>-1) {
						
						eventsperday.push(ev);
						evcnt++;
					}
				}
			}		
		}

		addDay(eventsperday, 999, $('#translations #ongoing').text(), todayprogramme, true)
	}
	
	if(!todayprogramme) {
		$('#programme .day').each(function(){
			$(this).find('li').wrapAll('<ul></ul>');
		})

		$('.ajax.event').bind('click', function(e) {
			e.preventDefault();

			args = window.location.hash.substring(1).split('/');
			args[4] = $(this).attr('eventid');
			args[5] = $(this).attr('evnum');
			url = args.join('/')

			window.location.hash = url;
		})
		
	} else {
		$('#todaysprogramme .day').each(function(){
			$(this).find('li').wrapAll('<ul></ul>');
		})
	
	}
	
	return evcnt;
	
}

function addDay(eventsperday, evnum, title, todayprogramme, ongoing) {

	if(eventsperday.length > 0 || todayprogramme) {
		
		day = $('<div class="day"></div>');
		day.html('<h2>' + title + '</h2>');
		if(todayprogramme) {
			$("#todaysprogramme #todayprogramme_inner").append(day);				
		} else {
			$("#programme").append(day);	
		}

		if(eventsperday.length == 0 && todaysprogramme && !ongoing) {
			day.append('<div id="noeventstoday">'+$('#translations #noeventstoday').text()+'</div>')
		}

		
		
		for(ev in eventsperday) {
			var url='';
			if(todayprogramme) {
				url = $('body').attr('root') + '/' + $('body').attr('url-language') + '/2011/programme/#2011-06-01/2011-07-03/all-filters/all-locations/' + eventsperday[ev].id + '/none/';
			} else {
				url = $('body').attr('root') + '/' + $('body').attr('url-language') + '/ajax-event/' + eventsperday[ev].id + '/' + eventsperday[ev].handle + '/';
			}

			var t = "";
			if(eventsperday[ev]['show-time'] == 'Yes') {
				d = eventsperday[ev];
				
				t = '<div class="time">';
				t += d.startdateobj.toString('HH') +':' + d.startdateobj.toString('mm');
				t += ' – ' +d.enddateobj.toString('HH') +':' + d.enddateobj.toString('mm');
				t += '</div>';
			} else {
				t = '<div class="time">–</div>';
			}

			name = t + '<div class="name"><a href="'+url+'" class="ajax event" eventid="'+eventsperday[ev].id+'" evnum="'+(eventsperday[ev].id+'-'+evnum)+'">' + eventsperday[ev].name + '</a></div>';

			c = $('<li class="event" eventid="'+eventsperday[ev].id+'">'+name+'</li>');
			day.append(c);
			if(ongoing) {
				c.addClass('ongoing');
			}
			if(eventsperday[ev]['off-schedule'] == 'Yes') {
				c.addClass('off-schedule');
			} else {
				c.addClass('on-schedule');
			}
		}	
	}
}


function expandRange(s, e) {

	var start = new Date(s);
	var end = new Date(e);	
	
	var range;
	
	start = start.clone();
	range = [];

	
	while (start.compareTo(end) < 0)
	{
	    range.push(start.clone());
	    start.addDays(1);
	}
	range.push(end.clone());
	

	return range;
}


//google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-10382711-4']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

