(function($){
	
	$.fn.setupNews = function() {
		var index = 0;
		
		return this.each(function(){
			var newsBox = $(this);
			
			setInterval(function(){
			$.getJSON($.getUrl() + '/services/get_announcement', {index: index}, function(data){
				if (data) {
					index = parseInt(data[0].index) + 1;
					newsBox.find('div').html("<span>" + data[0].title + "</span> - " + data[0].message);
				}
			});
			}, 15000);
		});
	};
	
	$.fn.artworkHover = function(){
		var cont, contID = 'artwork_cont';
		var contDim = {height: 0, width: 0};
		var port = {height: 0, width: 0};
		
		function getCont(){
			cont = cont ? cont : $('#' + contID);
			if (cont.length == 0){
			cont = $('<div id="' + contID + '"><img src=""/></div>').appendTo('body');
			}
			return cont;
		};
		
		return this.mouseover(function(e){
			var src = $(this).attr('artwork');
			var c = getCont().show().find('img').attr('src', src);
			
			// get dimensions
			var win = $(window);
			port.height = win.height(), port.width = win.width();
			contDim.height = c.height(), contDim.width = c.width();
			}).mouseout(function(e){
				getCont().hide();
			}).mousemove(function(e){
				var top = e.pageY + 4, left = e.pageX + 6;
				left =  left + contDim.width > port.width ? left - contDim.width - 4 : left;
				getCont().css({top: top, left: left});
			});
	};
	
	var AudioPlayer = {
		dialog: null,
		frame: null,
		playFile: null,
		init: function() {
			var details = $('#details');
			this.playFile = $('a[playFile]', details).bind('click', function() { AudioPlayer.open(); return false; }).attr('playFile');
			this.frame = $('#audioFrame', details);
			this.dialog = this.frame.dialog({
					autoOpen: false,
					buttons: { Close: AudioPlayer.close },
					draggable: false,
					height: 300,
					width: 300,
					overlay: { opacity: 0.5, background: 'black' },
					resizable: false,
					modal: true
				});
		},
		close: function() {
			AudioPlayer.frame.attr('src', 'javascript:false');
			AudioPlayer.dialog.dialog('close');
		},
		open: function() {
			AudioPlayer.dialog.dialog('open');
			AudioPlayer.frame.attr('src', AudioPlayer.playFile);
			AudioPlayer.dialog.dialog('moveToTop');
		}
	};
	
	/* ---------------------------------------------- */
	$(function(){
		$('#announcements').setupNews();
		
		// setup sort on search fields
		$('#search_box select').bind('change', function(){
			$('#search_box form')[0].submit();
		});
		
		$('a[artwork]').artworkHover();
		
		// setup embed link
		$('#embed_code').bind('click', function(){
			this.focus();
			this.select();
		});
		
		AudioPlayer.init();
	});

})(jQuery);