﻿// Language
var language;
if (navigator.userLanguage)
	language = navigator.userLanguage;
else if (navigator.language)
	language = navigator.language;
else
	language = 'nl';
if (language != 'en') browserCulture = 'nl';
if (language == 'en') $('body').addClass('en');

function en() {
	language = 'en';
	$('body').addClass('en');
}

function nl() {
	language = 'nl';
	$('body').removeClass('en');
}

function isEn() { return (language == 'en'); }

$(function() {
	// Content
    var isBlackboardNews = false;
    var newsTitle = $('#newscontent .ContentItemDetailNewsItem .Title').html();
    if (newsTitle) {
        $('#_blackboard').html(newsTitle);
        isBlackboardNews = true;
    } else {
        $('#_blackboard').html('Volgende concert ' + $('#calendarcontent .DateTime').text().replace(' ', ' &nbsp;&nbsp;'));
    }
	
	// Happy little radio
	var happyRadio = function() {
		if (!isAudio) {
			var $radio = $('#_radio');
			var jumpy = function(){
				$radio.animate({
					marginBottom: '10px'
				}, 100, function() {
					$radio.animate({
						marginBottom: '0px'
					}, 100);
				});
			}
			jumpy();
			window.setTimeout(jumpy, 600);
		}
	}
	window.setInterval(happyRadio, 10000);
	window.setTimeout(happyRadio, 2000);
	
	// Click
	$('.Thingie').live('click', function() {
		switch (this.id) {
			case '_chair1':
			case '_chair2':
			case '_chair3':
			case '_chair4': $((isEn() ? '.lan_en .MenuItemTitleEnAccord a' : '.lan_nl .MenuItemTitleEnAccord a')).click(); break;
			case '_blackboard':
			    if (isBlackboardNews) { $((isEn() ? '.lan_en .MenuItemTitleEnAccord a' : '.MenuItemTitleRecensies a')).click(); break; }
			case '_calendar': $((isEn() ? '.MenuItemTitleCalendar a' : '.MenuItemTitleAgenda a')).click(); break;
			case '_books': $((isEn() ? '.MenuItemTitleProjects a' : '.MenuItemTitleProjecten a')).click(); break;
			case '_newspaper': $((isEn() ? '.lan_en .MenuItemTitleEnAccord a' : '.MenuItemTitleRecensies a')).click(); break;
			case '_radio': openAudioPlayer(); break;
			case '_drawer': $((isEn() ? '.MenuItemTitleArchive a' : '.MenuItemTitleArchief a')).click(); break;
			case '_piggybank': $((isEn() ? '.MenuItemTitleFoundation a' : '.MenuItemTitleStichting a')).click(); break;
			case '_galleryback':
			case '_videoback': activateRoom('room_default'); break;
			case '_galleryprev': galleryMove(galleryIndex - 1); break;
			case '_gallerynext': galleryMove(galleryIndex + 1); break;
			case '_videoprev': gotoVideo(videoIndex - 1); break;
			case '_videonext': gotoVideo(videoIndex + 1); break;
			case '_tv':
				prepareVideo();
				activateRoom('room_video');
				centerVideo();
				break;
			case '_picture1':
			case '_picture2':
				$('.Museum').css('visibility', 'hidden');
				activateRoom('room_gallery');
				calcGallery();
				$('.Museum').css('visibility', 'visible');
				break;
			default:
				happyObj($(this));
		}
		return false;
	});
	
	// Menu click
	$('#menu .MenuItemLabel').addClass('iframe').click(function() {
		videoHtml('');
		if ($(this).parent().hasClass('MenuItemTitleHome')) { activateRoom('room_default'); return false; } 
		if ($(this).parent().hasClass('MenuItemTitleGallery')) { $('#_picture1').click(); return false; } 
		if ($(this).parent().hasClass('MenuItemTitleVideo')) { $('#_tv').click(); return false; } 
	});
	
	$('#menu .MenuItemLabel:not(.MenuItemTitleHome a, .MenuItemTitleGallery a, .MenuItemTitleVideo a)').fancybox({
		overlayColor: '#000',
		titleShow: false,
		width: 800,
		height: 500,
		autoScale: true,
		padding: 0
	});
	
	// Menu hover
	$('#menu .MenuItem').mouseenter(function() {
		if ($(this).hasClass('MenuItemTitleVideo')) happy('#_tv');
		if ($(this).hasClass('MenuItemTitleEnAccord')) happy('#_chair1, #_chair2, #_chair3, #_chair4, #_newspaper');
		if ($(this).hasClass('MenuItemTitleCalendar')) happy('#_calendar, #_blackboard');
		if ($(this).hasClass('MenuItemTitleAgenda')) happy('#_calendar, #_blackboard');
		if ($(this).hasClass('MenuItemTitleProjects')) happy('#_books');
		if ($(this).hasClass('MenuItemTitleProjecten')) happy('#_books');
		if ($(this).hasClass('MenuItemTitleFoundation')) happy('#_piggybank');
		if ($(this).hasClass('MenuItemTitleStichting')) happy('#_piggybank');
		if ($(this).hasClass('MenuItemTitleGallery')) happy('#_picture1, #_picture2');
	});
	
	// Fancy click
	$('.ThFancy').fancybox({
		overlayColor: '#000'
	});

	// Run every minute
	updateMinute();
	window.setInterval(updateMinute, 60000);
	
	var newVideoPollInterval = 0;
	var videoCount = 0;
	// CMS: start polling when adding video
	$('.ContentItemContentGroupVideoPlayer .ContentGroupMenuItemAdd').live('click', function() {
		if (!newVideoPollInterval) {
			videoCount = $('.ContentItemDetailVideoPlayer').length;
			newVideoPollInterval = window.setInterval(function() {
				if ($('.ContentItemDetailVideoPlayer').length > videoCount) {
					clearInterval(newVideoPollInterval);
					newVideoPollInterval = 0;
					videoIndex = 0;
					prepareVideo();
				}
			}, 2000);
		}
	});
});

var months = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'spt', 'okt', 'nov', 'dec'];

function happy(selector){
	happyObj($(selector));
}

function happyObj(item) {
	item.animate({marginLeft: '-4px'}, 50);
	window.setTimeout(function() {
		item.animate({marginLeft: '4px'}, 50);
		window.setTimeout(function() {
			item.animate({marginLeft: '-2px'}, 50);
			window.setTimeout(function() {
				item.animate({marginLeft: '2px'}, 50);
				window.setTimeout(function() {
					item.animate({marginLeft: '0px'}, 50);
				}, 50);
			}, 50);
		}, 50);
	}, 50);
}

function updateMinute() {
	var now = new Date;
	$('#_calendar').html('<span class="month">' + months[now.getMonth()] + '</span><br /><span class="day">' + now.getDate() + '</span>');
}

function activateRoom(id) {
	$('.room:not(#' + id + ')').css('display', 'none');
	$('#' + id).fadeIn(1000);
}

// Index
var galleryIndex = 0;

function calcGallery() {
	var width = 0;
	$('.Museum .ContentItemGalleryImage').each(function() { width += $(this).width() + 80; });
	$('.Museum').width(width + 100);
}

function galleryMove(index) {
	var items = $('.Museum .ContentItemGalleryImage');
	if (index < 0) index = 0;
	if (index >= items.length) index = items.length - 1;
	galleryIndex = index;
	var newitem = items.eq(index);
	var newx = (newitem.position().left * -1 - (newitem.width() / 2)) + 'px';
	$('.Museum').animate({
		marginLeft: newx
	}); 
}

var videoIndex = 0;

function prepareVideo() {
	$('.ContentItemDetailVideoPlayer').css('display', 'none');
	gotoVideo(videoIndex);
}

function gotoVideo(index) {
	var items = $('.ContentItemDetailVideoPlayer');
	if (index < 0) index = 0;
	if (index >= items.length) index = items.length - 1;
	items.eq(videoIndex).css('display', 'none');
	videoIndex = index;
	var newitem = items.eq(index);
	newitem.css('display', 'block');
	videoHtml('<div class="videoEmbed"><div class="videoCenter">' + newitem.find('.FilePath').text() + '</div></div>');
	centerVideo();
}

function videoHtml(html) {
	$('#_videoscreen .screeninnercontent').html(html);
}

function centerVideo() {
	//$('.videoCenter').css('margin-left', (($('.videoEmbed').width() - $('.videoCenter').width()) / 2) + 'px');
}


var isAudio = false;

function openAudioPlayer() {
	if (!isAudio) {
		isAudio = true;
		$('#_blackboard').html($('#audiocontent').html());
		var player = new audioPlayer('#_blackboard .audioplayer');
	}
}

var audioPlayer = function(element) {
    var self = this;
    this.element = element;
    this.loadedSounds = 0;
    this.initSoundManager(function() {
        self.init();
    });
}

audioPlayer.prototype = {

    init: function() {
        var self = this;
        this.$tracks = $('.tracks li', self.element);
        $('.tracks li a', self.element).click(function() {
            self.go($(this).parent()); return false;
        });
        this.$buttonPrevious = $('.buttons .previous', self.element).click(function() {
            self.previous(); return false;
        });
        this.$buttonTogglePlay = $('.buttons .toggleplay', self.element).click(function() {
            self.togglePlay(); return false;
        });
        this.$buttonNext = $('.buttons .next', self.element).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();
                    self.goToFirst(false);
                } else {
                    // Error, disable player buttons
                    $('.buttons', self.element).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 = $('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.activeSound) this.activeSound.stop();
    },
    
    togglePlay: function() {
        if (this.isPlaying()) this.stop(); else this.play();
    },
    
    isPlaying: function() {
        return this.$buttonTogglePlay.hasClass('playing');
    }

}
