//Splash page
PageLoader.register(function(){
	if ($("#splashOverlay").length) {
		
		//$("body").css('overflow','hidden');
		$("#splashOverlay, #splashOverlay *").show();
		
		if ($.browser.msie) {
			$(".video-thumb > object").click();
		}

		$("#splashOverlaySelect select").change(function () {
			var flagImage = "/images/splash/" + $(this).val() + ".gif";
			$("#splashOverlaySelect img").attr("src",flagImage);
			var landingLink = "http://www.thebeatles.com/boxset/" + $(this).val() + "/index.html";
			$("#splashOverlayLandingLink").attr("href",landingLink);
		});
		$("#splashOverlaySiteLink").click(function (e) {
			e.stopImmediatePropagation(); //stops event bubbling to ajax page reload
			//if ($.browser.msie) {
			//	$(".video-thumb").show();
			//}
			$("body").css("overflow","visible");
			$("#splashOverlay").hide();
			return false;
		});
		// Sniff platform for mac specific style
		var userOSAgent = navigator.userAgent.toLowerCase();
		if (/mac os x/.test(userOSAgent)) $("#splashOverlaySelect select").css("top","3px");
	}

	if ($("#boxsetSidebar").length) {
		$("#boxsetSidebar select").change(function () {
			var flagImage = "/images/splash/" + $(this).val() + ".gif";
			$("#boxsetSidebarFlag").attr("src",flagImage);
			var landingLink = "http://www.thebeatles.com/boxset/" + $(this).val() + "/index.html";
			$("#boxsetSidebarLink").attr("href",landingLink);
		});
	}
	if ($("#boxsetSidebarStores").length) {
		$("#boxsetSidebarStores select").change(function () {
			var ukLink = 'http://www.thebeatlesonline.co.uk/home.jsp?Category=remasters';
			var usLink = 'http://beatles.fanfire.com/cgi-bin/WebObjects/Store.woa/wa/artist?sourceCode=BEAWEB&categoryName=Remasters&artistName=Beatles.com';
			var jpLink = 'http://www.thebeatles-store.jp/products/list.php?category_id=4';
			
			var flagImage = "/images/splash/" + $(this).val() + ".gif";
			$("#boxsetSidebarFlag").attr("src",flagImage);
			if ($(this).val() == 'uk') { landingLink = ukLink; }
			if ($(this).val() == 'us') { landingLink = usLink; }
			if ($(this).val() == 'jp') { landingLink = jpLink; }
			$("#boxsetSidebarLink").attr("href",landingLink);
		});
	}
	
	if ($("#loveBanner").length) {
		swfobject.embedSWF("/frontend/images/home/loveBanner.swf", "loveBanner", "230", "192", "9.0.0", "/frontend/images/home/expressInstall.swf");
	}
});	

//Magic classnames that add special behaviour to elements.
PageLoader.register(function() {
	this.find('.datepicker').datepicker({dateFormat: 'yy-mm-dd', yearRange: '-100:+0', changeFirstDay: false});
	this.find('.sortable').sortable();
});

//Make logout button a link.
PageLoader.register(function() {

	//Logout link
	this.find('.user-logout-link').click(function(e){
		var nav = $(this).parent();
		
		var validation = {};
		$('input[type=hidden]').each(function(){
			validation[this.name] = this.value;
		});

		if (PageLoader.post(this.href, validation))
		{
			e.stopImmediatePropagation();
			return false;
		}
	});
	
	//Login link
	var form = this.find('.user-login');
	var link = this.find('.user-login-link');
	var shown = false;
	
	var applyLabelActions = function(name) {
		var label = form.find('label[for=' + name + ']');
		var input = form.find('#' + name);
		var type = "input";
		
		if(input.attr("type") == "password")
		{
			type = "password";
		}
		
		var new_id = 'generated_'+label.text().replace(/[ ]/g, "_");
		var new_input = $('<input type="text" value="'+label.text()+'" id="'+new_id+'">');
		new_input.insertAfter(input);
		new_input = $('#' + new_id);
		
		new_input.css({ width: input.width(), color: '#777' });
		
		new_input.show();
		input.hide();

		label.hide();
		
		if (input.val() != "") {
			new_input.hide();
			input.show();
			input.focus();
		}

		
		new_input.
			focus(function(){
				new_input.hide();
				input.show();
				input.focus();
			});
		
		input.
			blur(function(){
				if (input.val() == '') {
					input.hide();
					new_input.show();
				}
			});

	};

	link.click(function(event){
		if (!shown) {
			shown = true;
			form.css('display', 'inline');
			applyLabelActions('login-name');
			applyLabelActions('login-password');
			
			event.stopImmediatePropagation();
			return false;
		}
	});
});

//Collapse links.
PageLoader.register(function() {
	this.find('.collapse').each(function(){
		var list = $(this);
		var items = list.children();
		
		if (items.length > 1) {
			//Items
			var collapsed = false;
			var heading = list.parent().find('.section-head');
			
			//Elements we are adding
			var link = $('<a href="#"></a>');
			var item = $('<li class="expand"></li>').html(link);
			var more = $(this).parent().find('.more');
			more = more.length > 0 ? more : $('<ul class="more"></ul>');
			more.prepend(item);

			//Labels
			var moreLabel = "More";
			var lessLabel = "Less";
			if (!$(this).hasClass('wikipedia'))
			{
				moreLabel += " (" + (items.length - 1) + ")";
				lessLabel += " (" + (items.length - 1) + ")";
			}
			
			var toggle = function(animate){
				var height = null;
				var first = $(items.get(0));
				var second = $(items.get(1));
				var last = $(items.get(items.length - 1));
				
				if (collapsed) {
					height = last.height() + last.offset().top - first.offset().top + parseInt(last.css('marginBottom'), 10);
					link.text(lessLabel).addClass("less");
					heading.removeClass('section-collapsed');
				} else {
					height = first.height();
					link.text(moreLabel).removeClass("less");
					heading.addClass('section-collapsed');
				}
				
				if (animate) {
					list.stop();
					list.animate({height : height}, 200 + 200 * (items.length - 1));				
				} else {
					list.css('height', height);
				}
				collapsed = !collapsed;
			};
			
			link.click(function(e){
				toggle(true);
				e.stopImmediatePropagation();
				return false;
			});
			
			//If an image has just loaded then the we need to 
			//resize the container, because the box isn't going to
			//reflow itself
			list.find('img').load(function(e){
				collapsed = !collapsed;
				toggle(false);
			});
			
			list.css('overflow', 'hidden').	after(more);
			toggle(false);
		}
	});
});


//Collapse text list.
PageLoader.register(function() {
	this.find('.collapse-text').each(function(){
		var list = $(this);
		var items = list.children();
		if (items.length > 0) {
			//Items
			var collapsed = false;
			var heading = list.parent().find('.text-head');
			
			//Elements we are adding
			var link = $('<a class="text-more" href="#"></a>');
			var item = $('<li class="expand-text"></li>').html(link);
			var more = $(this).parent().find('.more');
			var alt_link = $(this).parent().find('.alt-link');
			more = more.length > 0 ? more : $('<ul class="more"></ul>');
			more.append(item);
			$(this).parent().prepend(link);
			
			//Labels
			var moreLabel = "SHOW";
			var lessLabel = "HIDE";
			
			var toggle = function(animate){
				var height = null;
				var first = $(items.get(0));
				var second = $(items.get(1));
				var last = $(items.get(items.length - 1));
				
				if (collapsed) {
					height = last.height() + last.offset().top - first.offset().top + parseInt(last.css('marginBottom'), 10);
					link.text(lessLabel).addClass("less");
					heading.removeClass('section-collapsed');
				} else {
					height = 0;
					link.text(moreLabel).removeClass("less");
					heading.addClass('section-collapsed');
				}
				
				if (animate) {
					list.stop();
					list.animate({height : height}, 300 + 30 * (items.length - 1));				
				} else {
					list.css('height', height);
				}
				collapsed = !collapsed;
			};
			
			link.click(function(e){
				toggle(true);
				e.stopImmediatePropagation();
				return false;
			});

			alt_link.click(function(e){
				toggle(true);
				e.stopImmediatePropagation();
				return false;
			});
			
			//If an image has just loaded then the we need to 
			//resize the container, because the box isn't going to
			//reflow itself
			list.find('img').load(function(e){
				collapsed = !collapsed;
				toggle(false);
			});
			
			list.css('overflow', 'hidden').	after(more);
			toggle(false);

			var first_pass = $(this).parent().find('.first');

			if (first_pass.length > 0)
			{
				toggle(false);
			}
		}
	});
});

//Object
PageLoader.register(function(){
	//Create info box
	var info = $(
			'<div class="object-info">' +
				'<h3 class="section"></h3>' + 
				'<p class="title"></p>' +
			'</div>').
		css('height', 'auto').
		hide();
	
	//Remove old boxes
	$('.object-info').remove();
	$('#body').append(info);
	
	//Move the info box
	var alignInfo = function(e){
		info.
			css('left', (e.pageX + 5) + 'px').
			css('top', (e.pageY + 5)  + 'px');
	};

	//Objects
	var activeObject = null;
	
	this.find('.object-tooltip').mousemove(alignInfo);
	
	this.find('.object-tooltip .object').each(function(){
		var title = this.title;
		var type = 'The Beatles';
		var object = this;
		this.title = '';

		var parts = title.match(/(.*)\((.*)\)$/);	
		if (parts) {
			title = parts[1];
			type = parts[2];
		}
		
		$(this).
			mouseenter(function(e){
				if (activeObject != object) {
					alignInfo(e);
					activeObject = object;
					info.find('h3').text(type);
					info.find('p').text(title);
					info.show();
				}
			}).
			mouseleave(function(e){
				window.setTimeout(function(){
					if (activeObject == object) {
						activeObject = null;
						info.hide();
					}
				}, 100);
			});

	});
	
	/*Social link
	window.addthis_pub="49edd6a34f4f45f7";
	this.find('.social-bookmark').
		show().
		mouseover(function(){
			addthis_open(this, '', window.location.href, document.title);
		}).
		mouseout(function(){
			addthis_close();
		}).
		click(function(){
			addthis_sendto();
		});
*/
});

//Comment AJAX
PageLoader.register(function(){
	var actions = {
		'delete': {
			confirm: "Are you sure you want to delete this comment?",
			error: "The comment could not be deleted.",
			success: function(){
				var options = $(this).parent().parent();
				options.parent().find('.message').fadeOut();
				options.find('li').remove();
				options.prepend('<li><strong>Deleted</strong></li>');
			}
		},
		'report': {
			confirm: "Are you sure you want to report this comment?",
			error: "The comment could not be reported.",
			success: function(){
				$(this).parent().parent().prepend("<li><strong>Reported</strong></li>");
				$(this).remove();
			}
		}
	};

	this.find('.comments .actions a').each(function(){
		var action = actions[this.className];
		if (typeof action != 'undefined') {
			var href = this.href;
			$(this).click(function(event){
				if (confirm(action.confirm)) {
					var data = {};
					var that = this;
					
					//We include come special 
					$('.comments input[name^=validation]').each(function(){
						data[this.name] = this.value;
					});
					
					$.ajax({
						type: 'post',
						url: href,
						data: data,
						dataType: 'json',
						success: function(data) {
							if (data.success) {
								action.success.apply(that);
							} else {
								alert(data.message ? action.error + "\n\n" + data.message : action.error);
							}
						},
						error: function(state, e) {
							alert(action.error);
						}					
					});
				}
				event.stopImmediatePropagation();
				return false;
			});
		}		
	});
});

//User JS
PageLoader.register(function(){
	this.find('.avatar-selection .avatars').hide();
	this.find('.avatar-selection .avatar').
		show().
		after($('<button type="button">Change Avatar</button>').
			show().
			click(function(){
				$('.avatar-selection .avatars').slideToggle();
			})
		);
	
	//Remove items from collection
	this.find('.collection-edit a.delete').click(function(e){
		$(this).parent().fadeOut(function(){
			$(this).remove();
		});
		e.stopImmediatePropagation();
		return false;
	});

	//Listen for clicks on each element
	this.find('.avatars label').each(function(){
		var element = $(this);
		
		var changeSelect = function()  {
			if (element.find('input').attr('checked')) {
				$('.avatar-selection .avatar img').attr('src', element.find('.panel').attr('value'));
			}
		};
		
		element.css('cursor', 'pointer').click(changeSelect);
		element.find('input').bind('change click', changeSelect).hide();
		element.click(function(){
			element.find('input').attr('checked', true);
			changeSelect();
		});
	});
	
	//Network inputs
	var placeholder = '...';
		
	this.find('.networks input').
		bind('focus', function(e){
			$(this).removeClass('default');
			
			var idx = -1;
			var length = 0;
			var txt = this;
			
			//User has entered their own value?
			if (this.value.indexOf(placeholder) == -1) {
				//Try and highlight the text that is where the placeholder would normally be.
				var prefix = this.title.replace(placeholder, '');
				if (this.value.indexOf(prefix) != -1) {
					idx = this.value.indexOf(prefix) + prefix.length;
					length = this.value.length - idx;					
				}
			} else {
				//Highlight the placeholder
				idx = this.value.indexOf(placeholder);	
				length = placeholder.length;
			}
						
			if (idx >= 0) {
				//Setting focus does a select all for some browsers
				//Set timeout to run immediately after this focus event 
				//is handled (and therefore after the select all).
				window.setTimeout(function(){				
				    if (txt.createTextRange) {
				        var range = txt.createTextRange();
				        
				        range.collapse(true);
				        range.moveStart('character', idx);
				        range.moveEnd('character', idx + length);
				        range.select();
				    } else if (txt.selectionEnd) {
				        txt.selectionStart = idx;
				        txt.selectionEnd = idx + length;
				    }
				}, 0);
			};
		}).blur(function(){
			
			if (this.value == this.title) {
				//Just the default value.
				$(this).addClass('default');
			} else if (this.value == '' || this.title.replace(placeholder, '').indexOf(this.value) == 0) {
				//Value is empty OR the user just deleted some of the default value
				$(this).addClass('default').val(this.title);
			} else {
				//Custom value
				$(this).removeClass('default');
			}
		});
	
});


//Disable right-click on content images
PageLoader.register(function() {
	
	$('#body img').each(function() { //global context or different scope on first-run
		
		this.oncontextmenu = function() {return false};
		
	});
	
});

//IE flicker fix
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) { }

//Disable document.write. 
document.write = function() {
	debug("Document.write called", arguments);
}
