$(function(){
	$(document.body).addClass('e');
	$('input#username').focus();
	frontal
	(/item/, function(){			
		//FIRE UP OUR RATING WIDGETS
		(function(){
            if(!$.fn.rating) return;
			var ratings = $('em.rating-effectiveness'),
                ratings2 = $('em.rating-creativity'),
                options = $().data('voting_options'),
                options2 = $().data('voting_options2'),
                pass = $('#vote_form div.effectiveness'),
                pass2 = $('#vote_form div.creativity'),
                vote = $('#vote_form div.rating')
                    .data('url', $('link[rel=vote]').attr('href'))
                    .bind('update.rating', function(){
                        window.onbeforeunload = null;
                    });
			if((pass.length > 0) && !pass.find('input').is(':checked')){
				window.onbeforeunload = function(){
					return "You have not voted on this entry.";
				}
			}
			if((pass2.length > 0) && !pass2.find('input').is(':checked')){
				window.onbeforeunload = function(){
					return "You have not voted on this entry.";
				}
			}
			
			if('object' == typeof(options)){
				var rate = $('<div class="rating"></div>');

                $.each(options, function(i, v){
                    var opt = $('<label class="value_'+i+'"><span class="type">'+v+'</span><input type="radio" value="'+i+'" /></label>');
                    if(i == 0){
                        opt.addClass('abstain');
                    }
                    rate.append(opt);
                });
				rate.append('<span class="value"></span>');

                var rate2 = $('<div class="rating"></div>');
                $.each(options2, function(i, v){
                    var opt = $('<label class="value_'+i+'"><span class="type">'+v+'</span><input type="radio" value="'+i+'" /></label>');
                    if(i == 0){
                        opt.addClass('abstain');
                    }
                    rate2.append(opt);
                });
				rate2.append('<span class="value"></span>');

				rate.insertAfter(ratings).each(function(i){
					$(this)
						.find('input')
						.attr('name', 'vote_value['+i+']')
					.end()
						.find('input[value='+$.trim(ratings.eq(i).text())+']')
						.attr('checked', true);
				});
				ratings.remove();

				rate2.insertAfter(ratings2).each(function(i){
					$(this)
						.find('input')
						.attr('name', 'vote_value2['+i+']')
					.end()
						.find('input[value='+$.trim(ratings2.eq(i).text())+']')
						.attr('checked', true);
				});
				ratings2.remove();

				$('.selection div.rating').each(function(){
					var url = $(this).parent().prev('a.url').attr('href');
					url = (url)? url+'/vote' : url = vote.data('url');
					$(this).data('url', url);
				});
			}
				
			$('div.rating')
				.rating({'standalone':'label.abstain span, .yes_no label.value_1 span, .yes_no label.value_2 span'})
				.bind('update.rating', function(evt, el){
                    
                    // Start adding multi voting functionality.
                    var effectiveness = $(el).closest('div').attr('effectiveness-data-votevalueset-id');
                    var creativity = $(el).closest('div').attr('creativity-data-votevalueset-id');

                    if (!effectiveness) {
                        var effectiveness = $(el).closest('span').attr('effectiveness-data-votevalueset-id');
                    }
                    if (!creativity) {
                        var creativity = $(el).closest('span').attr('creativity-data-votevalueset-id');
                    }
                    if (effectiveness > 0) {
                        var votevaluesetid = effectiveness;
                    }
                    else if (creativity > 0) {
                        var votevaluesetid = creativity;
                    }
                    else {
                        var votevaluesetid = 'default';
                    }
                    // End adding multi voting functionality

                    try{
						var path = $(this).data('url');
						if(path){
							$.post(path, {'votevalue':$(el).attr('value'), 'votevalueset_id':votevaluesetid, 'form_name':'judge_voting_form'}, function(data, status){
								if('success' != status || true != data.result){
									throw 'Update failed';
								} else {
                                    if (data.endOfSession) {
                                        if(!$.isArray(options2)) {
                                            if (confirm('You have reached the end of this judging session. Do you wish to return to the main menu?')) {
                                                window.location.replace('http://' + window.location.hostname + '/' + data.yearId);
                                            }
                                        }
                                        else {
                                            if (votevaluesetid == 72212572) {
                                                if (confirm('You have reached the end of this judging session. Do you wish to return to the main menu?')) {
                                                    window.location.replace('http://' + window.location.hostname + '/' + data.yearId);
                                                }
                                            }
                                        }
                                    }
                                }
							}, 'json');
						}
					}catch(e){
						alert('An error occured when trying to record your vote.');
					}
				})
		}());
		
		//CREATE OUR CREDIT AND ITEMS TABS
		(function(){
			var tabs = $(document.createElement('ul')).addClass('tabs grid_6 push_1 alpha omega');
			var sections = $('section.tab');
			var active = $.fn;
			tabs.insertBefore(
				sections.each(function(i){
					var section = $(this),
					link = $(document.createElement('a')).attr('href','#'+section.attr('id')).html(section.find('h1:first').remove().html()),
					strong = $(document.createElement('strong')).html(link.html()),
					getLink = function(){
						return link.click(function(e){
							e.preventDefault();
							section.trigger('show.tabs');
						});
					},
					item = $(document.createElement('li')).addClass('tab_'+i).append('<b class="tr" /><b class="tl" />').append(getLink());
					section
						.bind('hide.tabs', function(){
							strong.replaceWith(getLink());
							item.removeClass('active');
							section.hide();
						})
						.bind('show.tabs', function(){
							link.replaceWith(strong);
							active.trigger('hide.tabs');
							active = section.show();
							item.addClass('active');
						});
					
					tabs.append(item);
				}).append('<b class="tr" /><b class="tl" /><b class="bl" /><b class="br" />').hide().eq(0).trigger('show.tabs')
			);
			if(window.location.hash){
				sections.filter('#'+window.location.hash).trigger('show.tabs');
				window.scrollTo(0,0);
			}
		}());
		
		//DIRECT SUBMITS ON OUR NOTES FORM TO XHR
		(function(){
			var note_list = $('#notes dl');
			$('#notes form').submit(function(evt){
				evt.preventDefault();
				var form = $(this);
				if('' == form.find('textarea').attr('value')) return;
				form.find('button').attr('disabled', 'disabled');
				$.post($('link[rel=new_note]').attr('href'), form.serialize(), function(data, status){
					try{
						if('success' == status && data.created){
							$('<dt>'+data.created+'</dt><dd>'+data.str_note.replace(/\n/g,'<br />')+'</dd>')
								.hide()
								.prependTo(note_list)
								.slideDown();
							form.find('textarea').attr('value','');
							form.find('button').removeAttr('disabled');
						}
					}catch(e){
						alert('An error occured when trying to save your note.')
					}
				}, 'json');
			})
		}());
		
		(function(){
			if(!$.fn.flowplayer) return;
			var domain_key = '#@2de087dca573908e21e';
			
			var controlPlugin = {
				opacity:0.8,
	      		autoHide:'always',
	            hideDelay:1000,
	            backgroundColor:'#00000',
	            buttonColor:'#000000',
	            buttonOverColor:'#333333',
	            timeColor:'#DDDDDD',
	            bufferColor:'#DDDDDD',
	            progressColor:'#FFFFFF',
	            volumeSliderColor:'#666666',
	            tooltipColor:'#000000'
			};
			
			//INITIALISE OUR VIDEO PLAYER
			$('a.video').html('').flowplayer('/swf/lib/flowplayer.commercial-3.1.5.swf',{
				key: domain_key,
				clip:{
					scaling:'fit',
					autoPlay:false,
					autoBuffering:true
				},
				plugins:{
					controls: controlPlugin
				}
			});
			
			//INITIALISE OUR AUDIO
			$('a.audio').html('').flowplayer('/swf/lib/flowplayer.commercial-3.1.5.swf',{
				key: domain_key,
				canvas: {
					backgroundColor:'#ffffff',
					backgroundGradient:'none'
				},
				clip:{
					autoPlay:false,
					autoBuffering:false
				},
				plugins:{
				    audio: { 
						url: '/swf/lib/flowplayer.audio-3.1.2.swf'
	        		},
					controls: $.extend(controlPlugin, {
						autoHide:'never',
						height:30,
						fullscreen:false
					})
				}
			});
		}());
		
		//INITIALISE THE PRINT MAGNIFIER
		$('a.image')
			.click(function(evt){
				evt.preventDefault();
			})
			.queue(function(){
				var enclosures = [];
				$('.hmedia a[rel=enclosure]').each(function(){
					var enc = $(this);
					enclosures.push({
						'src':enc.attr('href'),
						'size':[enc.find('.width').text(), enc.find('.height').text()]
					});
				});
				
				// Since we have the magnifier we will remove links to our alternate enclosures
				$('.hmedia .alternatives').remove();
				if(enclosures.length < 2) return;
				var radios = $.fn,
				labels = $.fn,
				moveHandler,
				self = $(this)
					.magnifier({
						'preview':enclosures[0].src,
						'levels':enclosures
					})
					.bind('zoom', function(evt, level){
						radios.filter('*[value='+level+']').trigger('active').get(0).checked=true;
					}),
				controls = $('<div></div>')
					.append($('<button class="zoom-in" type="button">Zoom in</button>')
						.click(function(){ self.trigger('zoomin'); })
					)
					.append($('<button class="zoom-out" type="button">Zoom out</button>')
						.click(function(){ self.trigger('zoomout'); })
					)
					.insertAfter(
						$('.magnifier-preview').addClass('grid_2 push_6 alpha')
					)
					.wrap('<form class="magnifier-controls"></form>');
				$.each(enclosures, function(i){
					$('<label></label>')
						.append(
							$('<input type="radio" name="zoom" value="'+i+'"/>')
								.change(function(){
									self.trigger('zoomto', i);
								})
								.bind('active', function(){
									labels.removeClass('active');
									$(this).closest('label').addClass('active');
								})
						)
						.bind('mousedown', function(evt){
							if($(this).hasClass('active')){
								var y = evt.pageY;
								var i = 18;
								moveHandler = function(evt){
									var diff = evt.pageY-y;
									if(diff > i){
										self.trigger('zoomout');
									}else if(diff < -i){
										self.trigger('zoomin');
									}else{
										return;
									}
									y = evt.pageY;
								}
								$(document).mousemove(moveHandler);
								controls.addClass('grabbing');
							}
						})
						.prependTo(controls);
				});
				radios = controls.find('input');
				labels = controls.find('label');
				self.trigger('zoom', 0);
				
				$((window.addEventListener|window.attachEvent)?window:document.documentElement).mouseup(function(){
					$(document).unbind('mousemove', moveHandler);
					controls.removeClass('grabbing');
				})
			});
	});
});

