var s = window.s = function( string, values )
{
	// Handle complex strings
	if (values !== null)
	{
		// replace each '{key}' with 'value'
		for ( key in values ){
			var regex = new RegExp("\\{"+key+"\\}",'g');
			string = string.replace( regex, values[key] );
		}
	}

	return string;
}

$(function(){
	movies.init();
	bulletins.init();
	$(window).resize(width_check);
	width_check();
});

// width check

var width_check = function () {
	if( $(window).width() <= 800 ){
		$(document.body).addClass('thin');
	}else{
		$(document.body).removeClass('thin');
	}
}

// movie rotation

var movies = {
	// set up the movie rotation script
	init: function(){
		if($('.movie').size()>1) // if there's more than one movie
		{
			var moviecount = $('.movie').size();
			var moviepointer = 0;
			
			for(var i = 1; i<=moviecount; i++){
				$('.apollo .t').eq(0).append(' <span class="moviebull">&bull;</span>');
			}
			$('.moviebull:first').addClass('active');
	
			$('.movie').height('76px');
			setInterval(function(){
				var nextmovie = $('.movie:eq(1)');
				var lastmovie = $('.movie:last');
				var firstmovie = $('.movie:first');
				$('.movie:not(.movie:first)').hide();
				lastmovie.after(firstmovie);
				firstmovie.fadeOut(function(){
					moviepointer = (moviepointer + 1) % moviecount;
					$('.moviebull').removeClass('active');
					$('.moviebull:eq('+moviepointer+')').addClass('active');
					nextmovie.fadeIn()
				});
			},4500);
		}
	}
}
// sidebar

var bulletins = {
	getData: function(){
		var that = this;
		$.getJSON('http://xn--g6h.oberlist.com/ss/bb?callback=?',function(data){
			that.data = data;
			that.displayData();
		})
	},
	displayData: function(){
		var sidebar = document.getElementById('bulletins');
		sidebar.innerHTML = '';
		if(this.data.message==null){
			for(key in this.data){
				var div = document.createElement('div');
				div.setAttribute('class','item');
				div.innerHTML = s('<h4>{title}</h4><p class="message">{message}</p><p class="author">\&#8212; {email}</p>',{title: this.data[key].title, message: this.data[key].message, email: this.data[key].email});
				sidebar.appendChild(div);
			}
		}else{
			var p = document.createElement('p');
			p.innerHTML = this.data.message;
			sidebar.appendChild(p);
		}
	},
	init: function(){
		// make a post button
		$('#sideBar form').hide();
		$('#sideBar').append();
		var postbutton = $('<a href="#" class="postbutton">Post a note.</a>');
		$('#bulletin').append(postbutton);
		postbutton.click(function(){
			$('#sideBar form').slideToggle();
			return false;
		})
		
		document.getElementById('bulletins').innerHTML = '<p style="text-align:center;"><img src="graphics/loader-on-white.gif" class="loader" /></p>';
		this.getData();
		// refresh the data every 1 minutes
		var that=this;
		setInterval(function(){
			that.getData();
		},60000);
	}
}