﻿$(function() {
	$(window).load(fillStock);

	var city;
	var hrefSplit = location.href.split('#(');
	if (hrefSplit.length > 1) city = hrefSplit[1].replace(')', '');
	goCity(city);
	$('#city a').click(function() {
		var city = $(this).closest('li').attr('id');
		if (city == 'All') city = '';
		goCity(city);
	});

    $('.ContentItemDetailVideoPlayer .FilePath').each(function() {
        var html = $(this).html();
        if (html.toLowerCase().indexOf('<embed') < 0) {
            $(this).html(getEmbed(html, 600, 400));
        }
    });
	
	$('.AppointmentHeader, .PressHeader').live('click', function() {
		var isActive = $(this).closest('.ContentItem').hasClass('active');
		$('.ContentItemDetailAppointment, .ContentItemMilestone').removeClass('active');
		if (!isActive) $(this).closest('.ContentItem').addClass('active');
	});
	
	if (typeof Cms !== 'undefined') {
		$('.allwaysvisible').prepend('<div class="CmsCityHeader">Altijd zichtbaar</div>');
		$('.allcities').prepend('<div class="CmsCityHeader">Zichtbaar onder "alle plaatsen"</div>');
		$('.leiden:not(body)').prepend('<div class="CmsCityHeader">Leiden</div>');
		$('.amsterdam:not(body)').prepend('<div class="CmsCityHeader">Amsterdam</div>');
		$('.utrecht:not(body)').prepend('<div class="CmsCityHeader">Utrecht</div>');
		$('.haren:not(body)').prepend('<div class="CmsCityHeader">Haren</div>');
	}
	
	var audio = new audioPlayer();
	
});

function getEmbed(url, w, h) {
    var regexp = new RegExp('(youtube\.com/watch.*?v=|youtu\.be/)([a-zA-Z0-9_-]*)');
    var match = regexp.exec(url);
    if (match) {
        if (match.length > 0) 
            return '<iframe title="YouTube video player" width="' + w + '" height="' + h + '" src="http://www.youtube.com/embed/' + match[2] + '" frameborder="0" allowfullscreen></iframe>';
    }
    regexp = new RegExp('vimeo\.com/([a-zA-Z0-9]*)');
    match = regexp.exec(url);
    if (match) {
        if (match.length > 0) 
            return '<iframe src="http://player.vimeo.com/video/' + match[1] + '" width="' + w + '" height="' + h + '" frameborder="0"></iframe>';
    }
    regexp = new RegExp('picasaweb.*?user/([^/]*)/albumid/([0-9]*)');
    match = regexp.exec(url);
    if (match) {
        if (match.length > 0) 
            return '<embed type="application/x-shockwave-flash" src="https://picasaweb.google.com/s/c/bin/slideshow.swf" width="' + w + '" height="' + h + '" flashvars="host=picasaweb.google.com&amp;hl=nl&amp;feat=flashalbum&amp;RGB=0x000000&amp;feed=https%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2F' + match[1] + '%2Falbumid%2F' + match[2] + '%3Falt%3Drss%26kind%3Dphoto%26hl%3Dnl" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"></embed>';
    }
    return '';
}

function goCity(city) {
	$(document.body).removeClass('leiden').removeClass('amsterdam').removeClass('utrecht').removeClass('haren');
	$('#city a').removeClass('active');
	if (city) {
		var cityLower = city.toLowerCase();
		city = cityLower[0].toUpperCase() + cityLower.slice(1);
		$(document.body).addClass(cityLower);
		$('#city #' + city + ' a').addClass('active');
	}
	else {
		$('#city #All a').addClass('active');
	}

	// Update internal links
	var newHash = (city ? '#(' + city + ')' : '');
	$('a:not(#city a)').each(function() {
		if (this.href && this.href.toLowerCase().indexOf('hortus-festival') > -1) {
			var newHref = $(this).attr('href');
			if (newHref.indexOf('#') >= 0) {
				if (newHref.indexOf('#(') < 0) return;
				newHref = newHref.slice(0, newHref.indexOf('#('));
			} 
			$(this).attr('href', newHref + newHash);
		}
	});
}

function fillStock(){
	var imageCount = 30;
	var maxHeight = $('#body').height() - $('#margin').height();
	var stock = $('#stock');
	var used = {};
	var i = 0;
	var addOne = function() {
		var image = Math.floor(Math.random() * imageCount);
		while (used['img' + image]) {
			image = Math.floor(Math.random() * imageCount);
		}
		used['img' + image] = true;
		var imageDiv = $('<div class="StockImage" />');
		imageDiv.css('background-position', (image * -200) + 'px bottom').css('display', 'none');
		stock.append(imageDiv);
		imageDiv.slideDown(500);
		i += 1;
		if (i < maxHeight / 199) { window.setTimeout(addOne, 500); }
	}
	window.setTimeout(addOne, 500);
}


var audioPlayer = function(autoPlay) {
    var self = this;
    this.autoPlay = autoPlay;
    this.loadedSounds = 0;
    if ($('.ContentItemAudioTrack').length) {
        this.initSoundManager(function() {
            self.init();
        });
    }
}

audioPlayer.prototype = {

    init: function() {
        var self = this;
        this.$tracks = $('.ContentItemAudioTrack');
        $('.ContentItemAudioTrack .FormFieldTitle a').click(function() {
            var track = $(this).closest('.ContentItemAudioTrack');
            if (track.hasClass('playing')) self.stop(); else self.go(track); return false;
        });
        this.$buttonPrevious = $('.AudioButtons .previous').click(function() {
            self.previous(); return false;
        });
        this.$buttonTogglePlay = $('.AudioButtons .toggleplay').click(function() {
            self.togglePlay(); return false;
        });
        this.$buttonNext = $('.AudioButtons .next').click(function() {
            self.next(); return false;
        });
    },
    
    initSoundManager: function(onSuccess) {
        var self = this;
        $.getScript('/js/resources/soundmanager/script/soundmanager2-jsmin.js', function() {
            soundManager.debugMode = false;
            soundManager.url = '/js/resources/soundmanager/swf/';
            soundManager.onready(function(oStatus) {
                if (oStatus.success) {
                    // Goto first track
                    onSuccess();
                    if (self.autoPlay) self.goToFirst(false);
                } else {
                    // Error, disable player buttons
                    $('.AudioButtons').css('display', 'none');
                }
            });
        });
    },
    
    go: function(elementOrPath, noPlay) {
        if (this.activeSound) this.activeSound.stop();
        if (this.activeElement) $(this.activeElement).removeClass('playing');
        if (typeof elementOrPath === "string" ) {
            this.activeElement = null;
            this.activePath = buttonOrPath;
            this.activeSound = loadSound(this.activePath);
        } else {
            this.activeElement = elementOrPath;
            this.activePath = $('.FilePath a', elementOrPath).attr('href');
            this.activeSound = $(this.activeElement).data('sound');
            if (!this.activeSound) {
                this.activeSound = this.loadSound(this.activePath);
                $(this.activeElement).data('sound', this.activeSound);
            }
        }
        if (this.activeElement) $(this.activeElement).addClass('playing');
        if (!noPlay) this.play();
    },
    
    goToFirst: function(noPlay) {
        if (this.$tracks.length > 0) this.go(this.$tracks.get(0), noPlay);
    },
    
    loadSound: function(path) {
        var self = this;
        this.loadedSounds += 1;
        return soundManager.createSound({
            id: 'sound' + this.loadedSounds,
            url: path,
            onfinish: function() {self._soundOnFinish(this)}
        });
    },
    
    _soundOnFinish: function(sound) {
        if (sound === this.activeSound) {
            this.next();
        }
    },
    
    previous: function() {
        var nextElement = $(this.activeElement).prev();
        if (nextElement.length > 0) {
            this.go(nextElement);
        } else {
            this.goToFirst();
        }
    },
    
    next: function() {
        var nextElement = $(this.activeElement).next();
        if (nextElement.length > 0) {
            this.go(nextElement);
        } else {
            this.goToFirst();
        }
    },
    
    play: function() {
        this.$buttonTogglePlay.addClass('playing');
        if (this.activeSound) this.activeSound.play();
    },
    
    stop: function() {
        this.$buttonTogglePlay.removeClass('playing');
        if (this.activeElement) $(this.activeElement).removeClass('playing');
        if (this.activeSound) this.activeSound.stop();
    },
    
    togglePlay: function() {
        if (this.isPlaying()) this.stop(); else this.play();
    },
    
    isPlaying: function() {
        return this.$buttonTogglePlay.hasClass('playing');
    }

}
