$(function () {
	
	/*
	 * UVW lightbox
	 */
	uvwLightbox = {	
	
		// init
		init: function(obj) {
			var self = this;
			var u = $('<div class="uvw_lbox""><div class="uvwlb_cover"><div class="uvwlb_throbber"></div></div><div class="uvwlb_window"></div></div>').clone();
			if($('.uvw_lbox').length==0) $('body').prepend(u);
			this.cover = $('.uvwlb_cover').hide();
			this.win = $('.uvwlb_window').hide();
			this.throbber = $('.uvwlb_cover .uvwlb_throbber');
			if(obj) var el = obj;
			else var el = $('body');
			$(document).delegate('a.uvw_lb', 'click', function(e) {
				e.preventDefault();
				self.open(this.href, $(this));
			});
			this.throbber.bind('click', function(e) {
				e.preventDefault();
				self.ajax.abort();
				self.close();
			});
			// if reference in hash, open (only when initiated on page tier)
			// URL#uvw_lb=[URI]
			if(!obj) {
				var hash = document.location.hash;
				if(hash && hash.indexOf('#uvw_lb=') == 0) {
					var url = hash.split('#uvw_lb=');
					var ref = $('body>form');
					this.open(url[1], ref);
				}
			}
			
			this.cover2 = $('<div class="uvwlb_cover2"><div class="uvwlb_throbber"></div></div>');
			$('.uvwlb_throbber', this.cover2).bind('click', function(e) {
				e.preventDefault();
				self.ajax.abort();
				self.cover2.fadeOut();				
			});
		},
		
		// open box
		open: function(url, ref) {
			var self = this;
			this.ref = ref;
			this.url = url;
			this.throbber.show();
			this.cover.fadeIn();
			this.ajax = $.ajax({
			  url: url,
			  success: function(data){			  					
				self.throbber.hide();
			  	self.win.html(data);
				
				var hash = self.url.split('#')[1];	
				var id = (hash != undefined) ? '#' + hash : false;
				var args = {
					views: {
						activeID: id
					}	
				}
				
				self.initBox(args);				
				self.center();
				self.win.prepend(self.cover2.hide());
				self.win.fadeIn();													    
			  },
			  error: function() { 
			  	return;
			  }
			});
		},
		
		// update an existing box with new content
		update: function(url) {
			var self = this;
			this.url = url;
			this.cover2.fadeIn();
			this.ajax = $.ajax({
			  url: url,
			  success: function(data){		  					
			  	self.win.html(data);
								
				var hash = self.url.split('#')[1];	
				var id = (hash != undefined) ? '#' + hash : false;
				var args = {
					views: {
						activeID: id
					}	
				}
				
				self.initBox(args);			
				self.center();									    
			  },
			  error: function() {
			  	return;
			  }
			});
		},
		
		// close box
		close: function() {	
			$('.playing', this.win).trigger('click'); // stop preview
			this.cover.fadeOut();
			this.win.fadeOut();		
		},
		
		// vertically center box
		center: function() {
			var box = this.win.outerHeight();
			var vPort = $(window).height();
			var scrollY = $(window).scrollTop();
			var y = vPort/2 - box/2 + scrollY;
			if(y < 10) y = 10;
			this.win.css({ top: y + 'px' });
		},
		 
		// init functions inside box
		initBox: function(args) {
			var self = this;
			var close = function(e) {
				e.preventDefault();
				self.close();
			}
			$('.uvwlb_close', this.win).bind('click', close);
			$('.but_cancel', this.win).bind('click', close);
			$('.but_uvwlb', this.win).bind('click', function(e) {
				e.preventDefault();
				var data = self.forms.collectFormData();
				if(data) data = '?' + data;
				self.update(this.href + data);
			});
			this.views.init(args.views.activeID);
			this.navigator = new uvwNavigator($('.uvw_navigator', this.win));	
			this.forms.init(this); 
			
			$('a.listen', this.win).audioPlayer('/swf/audio-player.swf');
		},
		
		// view switch
		views: {
			init: function(activeID) {
				var self = this;
				this.root = $('.uvw_views');
				if(this.root.length == 0) return;
				this.nav = $('.uvwv_nav', this.root);
				// show a view
				if(activeID) {
					// show view activeID
					this.show(activeID);
				} else {
					// show first view per default
					var id = '#' + $('.uvwv_view:first-child', this.root).attr('id');
					this.show(id);
				}
				// init nav
				$('a', this.nav).bind('click', function(e) {
					e.preventDefault();
					var id = '#' + $(this).attr('href').split('#')[1];
					self.show(id);
				});
			},
			show: function(id) {
				$('.uvwv_view', this.root).removeClass('active');
				$('li', this.nav).removeClass('active');
				$(id).addClass('active');		
				$('a[href*=' + id + ']', this.nav).parent().addClass('active');	
			}				
		},
		
		/* 
		 * Lightbox: forms
		 */
		forms: {
			init: function(box) {
				var self = this;
				this.box = box;
				this.storedData = new Array();
				this.root = $('form', box.win);
				if(this.root.length == 0) return;
				//this.seedForm(this.collectPackagedData());
				// collect and package selection on 'submit'
				$('.but_submit', this.root).bind('click', function(e) {
					e.preventDefault();
					self.packageFormData(self.collectFormData());
					self.box.close();
				});
				// toggle checked class on items
				$('input:radio:checked, input:checkbox:checked', this.root).parent().addClass('checked');
				$('input:radio, input:checkbox', this.root).bind('click', function() {
					$(this).parent().toggleClass('checked');
				});
				
			},
			// collect any packaged form data
			collectPackagedData: function() {
				var data = new Array();
				var string = $('input:hidden.uvw_package', this.box.ref.parent()).val();
				if(string == '' || !string) return data;
				var nvPairs = string.split('&');
				for(var i = 0; i < nvPairs.length; i++) {
					var nv = nvPairs[i].split('=');
					var name = nv[0];
					var value = nv[1];
					data[data.length] = {
						'name': name,
						'value': value	
					}
				}
				return data;	
			},
			// seed form with data
			seedForm: function(data) {
				// storedData can be accessed by dedicated scripts to do stuff with
				this.storedData = data;	
				// reset all form controls
				$('select, textarea, input[type=text], input[type=password], input[type=file]', this.root).val('');
				$('input[type=radio], input[type=checkbox]', this.root).attr({ checked: false });
				// now set using data object
				for(var i = 0; i < data.length; i++) {
					var name = data[i].name;
					var value = decodeURIComponent(data[i].value.replace(/\+/g, ' '));
					var el = $('*[name=' + name + ']', this.root);
					if(el.attr('type') == 'radio') {
						el.filter('[value=' + value + ']').attr({
							checked: true
						});
					} else {
						el.val(value).attr({
							checked: true
						}); 
					}
				}
			},
			// collect form data
			collectFormData: function() {
				var results = this.root.serialize();
				return results;				
			},
			// drop results back into the ref element's container
			packageFormData: function(results) {
				// stick results into hidden inputs
				c = this.box.ref.parent();
				var hInput = $('input:hidden.uvw_package', c);				
				hInput.attr({ value: results });
				c.append(hInput);
				// if a selection was made, check option if there is any
				var cb = $('input[type=checkbox]', c);
				if(cb.length > 0 && results.length == 0) {
					cb.removeAttr('checked');
				} else if(results.length > 0) {
					cb.attr({ checked: true });	
				}
				
				if($('.uvwlb_top50', this.box.win)) uvwSheet.music.top50ToList();
			}
		}	
	}
	
	
	
	/*
	 * UVW sheet
	 */
	uvwSheet = {
	
		// init
		init: function() {
			var self = this;
			var wide = $('<div class="uvw_sheet"><div class="uvws_cover"><div class="uvws_throbber"></div></div><div class="uvws_window"></div></div>').clone();
			$('body').prepend(wide);			
			this.cover = $('.uvws_cover').hide();
			this.win = $('.uvws_window').hide();
			this.throbber = $('.uvws_throbber');
			$(document).delegate('a.uvw_sheet', 'click', function(e) {
				e.preventDefault();
				self.open(this.href, $(this));
			});
			$(document).delegate('a.uvw_sheet_narrow', 'click', function(e) {
				e.preventDefault();
				self.open(this.href, $(this), 1);
			});
			// any checkboxes...
			$(document).delegate('input[type=checkbox].uvw_sheet', 'click', function(e) {
				if(this.checked) {
					var anchor = $('a.uvw_sheet', $(this).parent());
					self.open(anchor.attr('href'), anchor);	
				} 
			});
			this.throbber.bind('click', function(e) {
				e.preventDefault();
				self.ajax.abort();
				self.close();
			});
			
			// if reference in hash, open overview
			// URL#overview
			var hash = document.location.hash;
			if(hash && hash.indexOf('#overzicht') == 0) {
			    $('.uvw_navigation .uvw_sheet_narrow').trigger('click');
			}
		},
		
		// open sheet
		open: function(url, ref, narrowWin) {
			var self = this;
			this.ref = ref;
			self.cover.fadeIn();
			this.throbber.show();
			this.cover.fadeIn();
			if(narrowWin) this.win.addClass('uvws_narrow');
			else this.win.removeClass('uvws_narrow');
			this.ajax = $.ajax({
			  url: url,
			  success: function(data){
								
			  	self.win.html(data);
				self.throbber.hide();
				self.initSheet();
				self.slideIn();				
				
			  }
			});
		},
		
		// close sheet
		close: function() {
			this.cover.fadeOut();
			this.slideOut();
		},
		
		// slide in
		slideIn: function() {
			this.win.css({
				marginTop: '-100px',
				opacity: 0
			});
			this.win.show();
			this.win.animate({
				marginTop: 0,
				opacity: 1
			});
		},
		
		// slide out
		slideOut: function() {
			var self = this;
			this.win.css({
				marginTop: 0,
				opacity: 1
			});
			this.win.animate({
				marginTop: '-100px',
				opacity: 0
			}, function() {
				self.win.hide();
			});
		},
		 
		// init functions inside sheet
		initSheet: function() {
			var self = this;
			var close = function(e) {
				e.preventDefault();
				self.close();
			}
			$('.uvws_close', this.win).bind('click', close);
			$('.but_cancel', this.win).bind('click', close);
			this.navigator = new uvwNavigator($('.uvw_navigator', this.win));	
			this.forms.init(this);
			if($('.uvws_music_form', this.win).length > 0) this.music.init(this);
			uvwPrint.init(this.win);
		},
		
		/* 
		 * Sheet: forms
		 */
		forms: {
			init: function(sheet) {
				var self = this;
				this.sheet = sheet;
				this.storedData = new Array();
				this.root = $('form', sheet.win);
				if(this.root.length == 0) return;
				this.seedForm(this.collectPackagedData());
				// collect and package selection on 'submit'
				$('.but_submit', this.root).bind('click', function(e) {
					e.preventDefault();
					self.packageFormData(self.collectFormData());
					self.sheet.close();
				});
				// toggle checked class on items
				$('input:radio:checked, input:checkbox:checked', this.root).parent().addClass('checked');
				$('input:radio, input:checkbox', this.root).bind('click', function() {
					$(this).parent().toggleClass('checked');
				});
				this.choices = new choicesBlock(this.root, $('.uvwf_choices', this.root));
			},
			// colect any packaged form data
			collectPackagedData: function() {
				var data = new Array();
				var string = $('input:hidden.uvw_package', this.sheet.ref.parent()).val();
				if(string == '') return data;
				var nvPairs = string.split('&');
				for(var i = 0; i < nvPairs.length; i++) {
					var nv = nvPairs[i].split('=');
					var name = nv[0];
					var value = nv[1];
					data[data.length] = {
						'name': name,
						'value': value	
					}
				}
				return data;	
			},
			// seed form with data
			seedForm: function(data) {
				// storedData can be accessed by dedicated scripts to do stuff with
				this.storedData = data;	
				// reset all form controls
				$('select, textarea, input[type=text], input[type=password], input[type=file]', this.root).val('');
				$('input[type=radio], input[type=checkbox]', this.root).attr({ checked: false });
				// now set using data object
				for(var i = 0; i < data.length; i++) {
					var name = data[i].name;
					var value = decodeURIComponent(data[i].value.replace(/\+/g, ' '));
					var el = $('*[name=' + name + ']', this.root);
					if(el.attr('type') == 'radio') {
						el.filter('[value=' + value + ']').attr({
							checked: true
						});
					} else {
						el.val(value).attr({
							checked: true
						}); 
					}
				}
			},
			// collect form data
			collectFormData: function() {
				var results = this.root.serialize();
				return results;				
			},
			// drop results back into the ref element's container
			packageFormData: function(results) {
				if(!results.split('=')[1]) results = '';
				// stick results into hidden inputs
				c = this.sheet.ref.parent();
				var hInput = $('input:hidden.uvw_package', c);				
				hInput.attr({ value: results });
				c.append(hInput);
				// if a selection was made, check option if there is any
				var cb = $('input[type=checkbox]', c);
				if(cb.length > 0 && results.length == 0) {
					cb.removeAttr('checked');
					cb.trigger('change');
				} else if(results.length > 0) {
					cb.attr({ checked: true });	;
					cb.trigger('change');
				}
			}
		},
		
		/*
		 * Sheet: music selection
		 */
		music: {
			init: function(sheet) {
				var self = this;
				this.sheet = sheet;
				this.root = $('form', sheet.win);
				
				this.listIndex = 0;
				this.list = $('.uvws_music_list .uvw_list', this.root);
				this.item = $('<li><strong class="title"></strong><span class="artist"></span><input type="hidden" name="" value="" /><a href="#" class="uvwl_remove" title="Verwijder uit lijst">verwijder</a></li>');
				this.populateList();
				
				// set event listeners
				this.list.delegate('li .uvwl_remove', 'click', function(e) {
					e.preventDefault();
					self.removeFromList($(this).parent());
				});
				$('#uvwm_addmymusic').bind('click', function(e) {
					e.preventDefault();
					self.addMyMusic();
				});				
				$('#uvwm_addlivemusic').bind('click', function(e) {
					e.preventDefault();
					self.addLiveMusic();
				});
				
				
				
				Helpers.doPlaceHolderTexts($('input[title]', this.win));
				
			},
			// create a list item
			createItem: function(artist, song) {
				var c = this.item.clone();
				$('.title', c).text(song);
				$('.artist', c).text(artist);
				$('input:hidden', c).val(artist + '_' + song);
				return c;
			},
			// add item to music list
			addToList: function(artist, song, animate) {
				// check list is a duplicate exists
				var r = false;
				$('li', this.list).each(function() {
					var a = $('.artist', this).text();
					var s = $('.title', this).text();
					if(artist == a && song == s) r = true;
				});
				if(r) return;
				// create a new item
				var c = this.createItem(artist, song);
				$('input:hidden', c).attr({ name: 'item' });
				this.listIndex++;		
				this.list.prepend(c);	
				if(animate) {
					c.hide();	
					c.slideDown();
				}				
			},
			// populate list from stored data, if any, call this.addToList
			populateList: function() {
				this.list.html('');
				var d = this.sheet.forms.storedData;
				for(var i = 0; i < d.length; i++) {	
					var item = d[i];
					if(item.name.indexOf('item') != 0) continue;
					var v = decodeURIComponent(item.value.replace(/\+/g, ' '));
					var artist = v.split('_')[0];
					var song = v.split('_')[1];
					this.addToList(artist, song, false);
				}
			},
			// remove item from music list
			removeFromList: function(listItem) {
				listItem.slideUp(function() {
					$(this).remove();
				});
			},
			// add my own music
			addMyMusic: function() {
				var s = $('#uvwm_addsong', this.root);
				var a = $('#uvwm_addartist', this.root);
				var song = s.val();
				var artist = a.val();
				if(song && artist && song != s.attr('title') && artist != a.attr('title')) {
					this.addToList(artist, song, true);
					s.val(s.attr('title')).addClass('placeholder');
					a.val(a.attr('title')).addClass('placeholder');
				}
			},
			// add live music
			addLiveMusic: function() {
				var a = $('#uvwm_addband', this.root);
				var artist = a.val();
				if(artist && artist != a.attr('title')) {
					this.addToList(artist, 'Live muziek', true);
					a.val(a.attr('title')).addClass('placeholder');
				}				
			},
			// drop top 50 data into list
			top50ToList: function() {
				// retrieve and split
				var data = new Array();
				var inp = $('#uvws_top50 input:hidden.uvw_package');
				var string = inp.val();
				if(string == '') return;
				var nvPairs = string.split('&');
				for(var i = 0; i < nvPairs.length; i++) {
					var nv = nvPairs[i].split('=');
					var name = nv[0];
					var value = nv[1];
					data[data.length] = {
						'name': name,
						'value': value	
					}
				}
				// stuff into list
				for(var i = 0; i < data.length; i++) {	
					var item = data[i];
					var v = decodeURIComponent(item.value.replace(/\+/g, ' '));
					var artist = v.split('_')[0];
					var song = v.split('_')[1];
					this.addToList(artist, song, true);
				}
				// finish up
				inp.val('');
			}
		}
	}	
	
	
	/*
	 * Choices block
	 */
	function choicesBlock(obj, box) {
		this.root = obj; // monitor this section
		this.box = box; // report to box
		this.targets = 'input:text, input:password, input:radio, input:checkbox, select, textarea';
		this.init();
	}
	choicesBlock.prototype = {
		init: function() {
			var self = this;
			this.root.delegate(this.targets, 'change', function(e) {
				self.update();
			});
			this.update();	
		},
		// update box
		update: function() {
			this.box.html('<em>Nog geen keuze gemaakt</em>').removeClass('modified');
			var content = '';
			$(this.targets, this.root).each(function() {
				var el = $(this);
				switch(el.attr('type')) {
					case 'text':
						var v = el.val();
						if(v && v != el.attr('title')) {
							content = content + v + '; ';
						}
						break;
					case ('checkbox'):
					case ('radio'):
						if(el.attr('checked')) {
							var id = el.attr('id');
							var v = $('label[for=' + id + ']').text();
							content = content + v + '; ';
						}
						break;
					default:
						if(el.get(0).nodeName.toUpperCase() == 'SELECT' && el.val() != -1) {
							var s = el.get(0).selectedIndex;
							var v = $(el.get(0).options[s]).text();
							content = content + v + '; ';
						}
						if(el.get(0).nodeName.toUpperCase() == 'TEXTAREA' && el.val() && el.val() != el.attr('title')) {
							content = content + 'Opmerkingen' + '; ';	
						}
				}
			});
			if(content != '') {
				this.box.addClass('modified');
				content = content.substring(0, content.length-2);
				$('em', this.box).html(content);
			}
		}
	}
	
	
	/*
	 * UVW Navigator
	 */
	function uvwNavigator(obj){
		this.root = obj;	
		this.init();
	}
	uvwNavigator.prototype =  {
		init: function() {
			var self = this;		
			this.canvas = $('.uvwn_canvas', this.root);
			this.prev = $('.uvwn_prev', this.root);
			this.next = $('.uvwn_next', this.root); 
			this.items = $('>ul>li', this.canvas);
			this.itemWidth = this.items.eq(0).outerWidth();
			this.itemCurrent = 0;
			
			/*this.items.css({
				opacity: 0.25
			});*/
			this.scroll();
			
			this.prev.bind('click', function(e) {
				e.preventDefault();
				if(!$(this).hasClass('inactive')) self.backward();
			});
			this.next.bind('click', function(e) {
				e.preventDefault();
				if(!$(this).hasClass('inactive')) self.forward();
			});
			
			this.check();
		},
		// backward
		backward: function() {
			/*this.items.eq(this.itemCurrent).animate({
				opacity: 0.25
			});*/
			this.itemCurrent--;
			this.scroll();
			this.check();
		},
		// forward
		forward: function() {
			/*this.items.eq(this.itemCurrent).animate({
				opacity: 0.25
			});*/
			this.itemCurrent++;
			this.scroll();
			this.check();
		},
		scroll: function() {
			var posY = this.itemCurrent * this.itemWidth;
			this.canvas.animate({ scrollLeft: posY }, 'slow');		
			/*this.items.eq(this.itemCurrent).animate({
				opacity: 1
			}, 'slow');	*/
		},
		// check limits
		check: function() {
			if(this.itemCurrent == 0) this.prev.addClass('inactive'); else this.prev.removeClass('inactive'); 
			if(this.itemCurrent+1 == this.items.length) this.next.addClass('inactive'); else this.next.removeClass('inactive');
		}
	}
	
	/*
	 * Printing
	 */
	uvwPrint = {
		init: function(obj) {
			if(!obj) obj = document;
			var self = this;
			this.iframe = $('<iframe name="printFrame"></iframe>');
			this.iframe.attr({
				src: (window.uvwPrintURL || "/html/uvw/ajax/_f93_print.html")
			}).css({
				width: 0,
				height: 0
			});
			$('.uvwu_print', obj).bind('click', function(e) {
				e.preventDefault();
				self.print();
			});
		},
		print: function() {
			this.iframe.remove();
			$('body').append(this.iframe);
		}	
	}
	
	/*
	 * Init everything on load
	 */
	
	uvwSheet.init();
	uvwLightbox.init();
	uvwPrint.init();
	
	$('.uvw_navigator').each(function(i) {
		new uvwNavigator($(this));
	});
	var c = $('.uvwf_choices');
	if(c.length > 0) var choices = new choicesBlock($('.uvwb_right'), c);
	
});
