var rel_pathname;
var animating = false;
var loader_timer;
var resize_timer;
var active_page;
var page_url;
var first_load = true;
var debug_box;
var splat_markup = '<div class=\"splat\"><div class=\"inner\"></div></div>';
var ios = false;
var viewer;
var shift;
var thumb_width = 95;

if (window.location.host=="localhost" || window.location.host=="dev.theycreate.co.uk") {
	rel_pathname = "/lcm/";
}
else {
	rel_pathname = "/";
}

function debug(string) {
	if (debug_box.length) {
		debug_box.html(string + " " + String(Math.floor(Math.random()*101)));
	}
}

function showLoader(area) {

    loader_timer = setTimeout(function() {
    	area.append('<div id=\"loader\"></div>');
        $('#loader', area).stop().animate({'opacity':'1'}, 200);
    }, 300);
    
}

function hideLoader(area) {

    clearTimeout(loader_timer);
    loader_timer = null;
    $('#loader', area).stop().animate({'opacity':'0'}, 200, function() {
    	$(this).remove();
    });
    
}

function aboutSwitch(new_info) {

	$('.about_us_nav').removeClass('active');
	$('.text_pane .colset').css({'visibility':'hidden'});
	
	var new_parent = new_info.parent();
	new_info.addClass('active');
	$('.colset', new_parent).css({'visibility':'visible'});
	
	animating = false;
	
}

function viewerSwitch(new_viewer) {

	viewer = new_viewer.attr('id').replace("_nav","");

	$('.viewer_nav .active').removeClass('active');
	var active_content = $('.viewer .content > .active');
	active_content.css({'display':'none'}).removeClass('active');
	$('.carousel_window .active').removeClass('active').css({'visibility':'hidden'});
	
	new_content = $("#" + viewer + "_content");
	new_carousel = $("#" + viewer + "_roller");
	new_viewer.addClass('active');
	new_content.css({'display':''}).addClass('active');
	new_carousel.addClass('active');
	new_carousel.css({'visibility':'visible'});
	animating = false;
	shift = 0;
	embedPause($('.active', active_content));
}

function embedPause(content_item) {
	if ($('iframe', content_item).length) {
		var embedded = $('iframe', content_item).filter(":eq(0)");
		$f(embedded[0]).api('api_pause');
	}
}

function longPage() {

	var page_array = new Array();
	var nav_height = 99;
	var	window_middle;
	var autoscroll = false;
	
	var container;
	
	if (navigator.userAgent.indexOf("Firefox")!=-1) {
		container = $('html');
	}
	else {
		container = $('body');
	}
	
	$('body').css({'opacity':'0', 'visibility':'visible'});
	
	$('.page').each(function() {
		page_array.push($(this));
	});

	var url = window.location.pathname;
	page_url = url.substring(0, url.indexOf('/', 5)).replace(rel_pathname,"");
	
	function refreshValues() {
		$.each(page_array, function(index, item) {
			var top = item.offset().top;
			var height = item.outerHeight();
			item.data('top', top);
			item.data('bottom', top+height);
			if (first_load && $(this).index() == page_array.length-1) {
				$('body').animate({'opacity':'1'}, function() {
					scrollToPage(page_url);
				});
			}
		});
	}
	
	var disableScroll = function() {
		return false;
	}
	
	function scrollToPage(destination) {
	
		$(window).bind('mousewheel', disableScroll);
	
		var duration = 300;
	
		if (destination) {
			destination = "#" + destination;
			target = $(destination).data('top') - nav_height;
		}
		else {
			destination = "#home";
			target = 0;
			if (first_load) {
				duration = 0;
			}
		}
		autoscroll = true;
		container.animate({scrollTop : target}, duration, 'easeInOutQuad', function() {
			active_page = $(destination);
			changeURL(active_page);
			autoscroll = false;
			first_load = false;
			$(window).unbind('mousewheel', disableScroll);
		});
		
	}
	
	function changeURL(new_page) {
	
		active_page = new_page;
		var history_url;
		if (active_page.attr('id')=="home") {
			history_url = " ";
		}
		else {
			history_url = active_page.attr('id') + "/";
		}
		history.replaceState(null, null, history_url);
		document.title = active_page.attr('title');
		
	}
	
	function changeNav(new_page) {
	
		$('.page_nav .active').removeClass('active');
		$('.splat').remove();
		
		if (new_page!="home") {
			var nav = "#nav_" + new_page;
			$(nav).addClass('active').prepend(splat_markup);
            $('.splat').css('left', Math.floor($(nav).width()/2) + 'px');
		}
		
	}
	
	$(window).scroll(function() {
		
		if (container.scrollTop() > 166) {
			$('.page_nav').css({'position':'fixed','top':'0','bottom':''});
		}
		else {
			$('.page_nav').css({'position':'','top':''});
		}
		
		if (!autoscroll) {
		
			scroll_offset = container.scrollTop() + window_middle;
			
			if (active_page.data('bottom') < scroll_offset) {
				changeURL(active_page.next());
				changeNav(active_page.attr('id'));
			}
			if (active_page.prev().length && active_page.prev().data('bottom') > scroll_offset) {
				changeURL(active_page.prev());
				changeNav(active_page.attr('id'));
			}
		}
		
	}).resize(function() {
		window_middle = $(window).height()/2;
		clearTimeout(resize_timer);
		resize_timer = setTimeout(refreshValues, 500);
	}).trigger('resize');
	
	$('.page_nav a').click(function() {
		this_href = $(this).attr('href').replace("/","");
		scrollToPage(this_href);
		changeNav(this_href);
		return false;
	});
	
	$('.viewer_nav div').livequery('click', function() {
		viewerSwitch($(this));
	});
	
}

function pageLoaded() {

	if (ios) {
		var main = $('.page').offset().top;
		$('body').delay(500).animate({scrollTop : main - 18}, 300);
	}
	
	$('.about_us_nav').livequery('click', function() {
		if (!animating) {
			animating = true;
			aboutSwitch($(this));		
		}
	});
	
	$('.carousel_nav').livequery('click', function() {
		if (!animating) {
			animating = true;
			var current_roller = $("#" + viewer + "_roller");
			var current_position = current_roller.position().left;
			var roller_width = current_roller.data('this_width');
			var window_width = $('.carousel_window:eq(0)').width();
			if ($(this).attr('id')=="cnav_left") {
				shift = -thumb_width;
				if (current_position>=0) {
					animating = false;
					return false;
				}
			}
			else {
				shift = +thumb_width;
				if (current_position<=-(roller_width-window_width-thumb_width)) {
					animating = false;
					return false;
				}
			}
			current_roller.animate({'left':current_position-shift+"px"}, 100, function() {
				animating = false;
			});
		}
	});
	
	$('.carousel_roller .thumb').livequery('click', function() {
		var this_roller = $(this).parent();
		$('.thumb.t_active', this_roller).removeClass('t_active');
		$(this).addClass('t_active');
		var this_index = $(this).index();
		var current_content = $("#" + viewer + "_content");
		var active_content_item = $('.active', current_content);
		active_content_item.removeClass('active').css({'display':'none'});
		var new_content = $('.content_item', current_content).filter(":eq(" + this_index + ")");
		new_content.addClass('active');
		new_content.css({'display':''});
		embedPause(active_content_item);
	});
	
	$('.inputfield').livequery('focus', function() {
		var parent = $(this).parent();
		$('label', parent).css({'visibility':'hidden'});
		$(this).parentsUntil('.input_wrapper').addClass('focussed');
	}).livequery('blur', function() {
		if ($(this).val()=="") {
			var parent = $(this).parent();
			$('label', parent).css({'visibility':'visible'});
			$(this).parentsUntil('.input_wrapper').removeClass('focussed');
		}
	});
	
	var submitted = false;
	
	$('.secret_email').each(function() {
		var this_id = $(this).attr('id');
		var email_address;
		switch (this_id) {
			case 'simonecrofton':
				email_address = "simone.crofton@londonchildrensmuseum.org.uk";
				break;
			case 'garethbinns':
				email_address = "gareth.binns@londonchildrensmuseum.org.uk";
				break;
		}
		$(this).wrap('<a href="mailto:' + email_address + '" />');
	});
	
	$('#send').livequery('click', function() {
		if (submitted) {
			return false;
		}
		$('label').css({'color':''});
		var name = $('input#name').val();
		var email = $('input#email').val();
		var message = $('textarea#message').val();
		var emailRegExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
		if (name == "") {
			var label = $('input#name').parent().find('label');
			label.css({'color':'red'});
			label.html("Please provide a name");
			return false;
		}
		if (email == "") {
			var label = $('input#email').parent().find('label');
			label.css({'color':'red'});
			label.html("Please provide an email address");
			return false;
		}
		if (emailRegExp.test(email) === false) {
			$('input#email').val("").trigger('blur');
			var label = $('input#email').parent().find('label');
			label.css({'color':'red'});
			label.html("Please provide a valid email address");
			return false;
		}
		if (message == "") {
			var label = $('textarea#message').parent().find('label');
			label.css({'color':'red'});
			label.html("Please provide an enquiry");
			return false;
		}
		// Submission
        $.ajax({
            url: 'contact-us/submit/',
            cache: false,
            type: 'post',
            dataType: 'json',
            data: {
                name: name,
                email: email,
                message: message
            },
            success: function(data, textStatus, jqXHR){
                $('#contact_form .inner').fadeOut(300, function() {
                	$('#contact_form').append('<div class=\"inner\"><blockquote><p>Thank you!</p></blockquote></div>')
                });
                submitted = true;
            },
            error: function(jqXHR, textStatus, errorThrown){
                var label = $('#form_error');
                label.html("The server failed to process your request - please try again.");
            }
        });
		return false;
	});
	
	if ($('.about_us_nav').length) {
		aboutSwitch($('#patrons .about_us_nav'));
	}
	
	if ($('#childrens-ideas').length) {
		$('.viewer').noSelect();
		$('.viewer .content_panel').css({'display':'none'});
		$('.carousel_roller').css({'visibility':'hidden'}).each(function() {
			var this_width = $('.thumb', this).length * thumb_width;
			$(this).css({'width': this_width+"px"}).data('this_width',this_width);
			$('.viewer .content_item').each(function() {
				if($(this).index() > 0) {
					$(this).css({'display':'none'});
				}
				else {
					$(this).addClass('active');
				}
			});
			$('.thumb', this).filter(":eq(0)").trigger('click');
		});
		viewerSwitch($('#images_nav'));
	}
		
}

$('document').ready(function() {

    $('body').addClass('has_js');
    
	active_page = $('.page').filter(':eq(0)');
	
	if (navigator.userAgent.match(/like Mac OS X/i)) {
		ios = true;
	};
	
	if (ios) {
		$('body').addClass('responsive');
		if ($('.viewer').length) {
			$('.viewer').remove();
		}
	}
	
	$('.page_nav .active').prepend(splat_markup);
    $('.splat').css('left', Math.floor($('.page_nav .active').width()/2) + 'px');
	
	if (Modernizr.history &! ios) {
		$('body').css({'visibility':'hidden'});
		$(window).load(function() {
			$.get('longpage/', function(return_data) {
				$('body').addClass('long_page');
				$('.wrapper').html(return_data);
				pageLoaded();
				longPage();
			});	
		});
	}
	else {
		pageLoaded();
	}

});

