// Handle login/signup links

function ajaxLink(link, target, callback) {
    $.ajax({
      url: link.attr("href"),
      success: function(data) {
          target.fadeOut(function(){
              target.html(data);
              target.fadeIn();
              
              if (callback && typeof(callback) === "function") {
                  callback();
              }
          });
      }
    });
}

function ajaxLinkAppend(link, target, callback) {
    $.ajax({
        url: link.attr("href"),
        success: function(data) {
            target.fadeOut(function(){
                $('.current-content').hide();
                target.append(data);
                target.fadeIn();
                
                if (callback && typeof(callback) === "function") {
                    callback();
                }
            });
        }
    });
}

// Waiting list form stuff

var formOptions = {
	target: '#waiting-form-response',
	beforeSubmit: disableSubmitButton,
	success: formSuccess
}

function setupForm() {
    if ($('#waiting-form').length == 0 || $('#waiting-form').hasClass('initialized')) {
		return false;
	}
    
	formValidator = $("#waiting-form").validator({
		singleError: true,
		effect: 'show-splash-error'
	});

	$("#waiting-form").ajaxForm(formOptions);

	$.tools.validator.addEffect("show-splash-error", function(errors, event) {
		// Show the error message
		$.each(errors, function(index, error) {

			var input = error.input;
			
			input.addClass('error');
			
			var errorElem = $('#waiting-form-error');
			errorElem.html('<div class="form-errors-up-arrow"></div><div class="form-errors"></div>');

			$.each(error.messages, function() {
				errorElem.find(".form-errors").append('<p>' + this + '</p>');
			});

			positionSplashError(input, errorElem);

			$(window).resize(function() {
				positionSplashError(input, errorElem);
			});

			errorElem.fadeIn();
		});

	}, function(inputs)  {
		// Hide the error message.
		inputs.removeClass('error');
		$('#waiting-form-error').fadeOut();
	});
	
	$("#waiting-form").addClass('initialized');
}

function disableSubmitButton(data, $form, opts) {

	var firstname = $('#form_firstname')[0];

	if (firstname.value == "Your name") {

		firstname.value = '';
		formValidator.data('validator').checkValidity();
		return false;
		
	}
	
    $form.find('input:submit').val("Please wait...").click(function(e){
        e.preventDefault();
        return false;
    });
}

function formSuccess() {
	$('#welcome').first().fadeOut('slow', function(){
		$('#waiting-form-response').fadeIn('slow', function(){
			$('#welcome').first().remove();
			$('#waiting-form-response').first().attr('id', '');

			if($('#waiting-form').length > 0) {
				setupForm();
			}
		});
	});
}

function positionSplashError(input, error) {
	inputPos = input.parent().position();
	error.css('position', 'absolute');
	error.css('top', inputPos.top + input.parent().height());
	error.css('left', inputPos.left + input.parent().width()/2 - error.width()/2);
}

// Fancy login links

var fancyLoginLinks = false;
var loginWidth = false;
var dotWidth = false;
var signupWidth = false;

function setLoginWidths() {
    if (typekitIsGo == false) {
        setTimeout("setLoginWidths()",500);
        return false;
    }
    
    if (fancyLoginLinks == false) {
        loginWidth = $('.login').width() + 1;
    	dotWidth = $('.dot').width();
    	signupWidth = $('.signup').width() + 1;
    	fancyLoginLinks = true;
	}
}

function loadWelcome() {
    if ($('#welcome-content').length) {
		$('.current-content').fadeOut(function(){
			$('#welcome-content').fadeIn(function(){
			    setWelcomeCurrent();
			});
		});
	} else {
		ajaxLinkAppend($('.logo'), $('#content'), setWelcomeCurrent);
	}
	
	$('#login-holder').animate({'width': loginWidth + dotWidth + signupWidth}, 'fast', function(){
            $('.login').fadeIn();
			$('.signup').fadeIn();
			$('.dot').fadeIn();
    });
	
	$('.logo').addClass('disabled');
}

function setWelcomeCurrent() {
	$('.current-content').each(function(){
		if (this.style.display == 'none') {
			$(this).removeClass('current-content');
		}
	});
	$('#welcome-content').addClass('current-content');
	
	setupForm();
}

function loadLogin() {
    if ($('#login-content').length) {
		$('.current-content').fadeOut(function(){
			$('#login-content').fadeIn(function(){
			    setLoginCurrent();
			});
		});
	} else {
		ajaxLinkAppend($('.login'), $('#content'), setLoginCurrent);
	}
	
	$('#login-holder').css({'width': $('#login-holder').width()});
	$('.login').fadeOut(function(){
		$('#login-holder').animate({'width': signupWidth}, 'fast', function(){
			$('.signup').fadeIn();
		});
	});
	$('.dot').fadeOut();
	
	$('.logo').removeClass('disabled');
}

function setLoginCurrent() {
	$('.current-content').each(function(){
		if (this.style.display == 'none') {
			$(this).removeClass('current-content');
		}
	});
	$('#login-content').addClass('current-content');
	
	setupLoginForm();
}

function loadSignup() {
    if ($('#signup-content').length) {
		$('.current-content').fadeOut(function(){
			$('#signup-content').fadeIn(function(){
			    setSignupCurrent();
			});
		});
	} else {
		ajaxLinkAppend($('.signup'), $('#content'), setSignupCurrent);
	}
	
	$('#login-holder').css({'width': $('#login-holder').width()});
	$('.signup').fadeOut(function(){
		$('#login-holder').animate({'width': loginWidth}, 'fast', function(){
			$('.login').fadeIn();
		});
	});
	$('.dot').fadeOut();
	
	$('.logo').removeClass('disabled');
}

function setSignupCurrent() {
	$('.current-content').each(function(){
		if (this.style.display == 'none') {
			$(this).removeClass('current-content');
		}
	});
	$('#signup-content').addClass('current-content');
}

$(document).ready(function(){
	
	if (typeof ie === 'undefined') {
	    setLoginWidths();
    }
    
    // Waiting list form
    
	if ($('#waiting-form').length > 0) {
		setupForm();
	}
	
	// Deal with ajax page content
	
	$('#welcome-content').addClass('current-content');
	$('.logo').addClass('disabled');
	//$('.login').addClass('disabled');
	//$('.login').attr('href', "#");
	
	$('.logo').click(function(e){
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
			return false;
		}
		
		if (fancyLoginLinks) {
			e.preventDefault();
			history.pushState({ path: this.path }, '', this.href)
			
			loadWelcome();
		}
	});
	
	$('.login').click(function(e){
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
			return false;
		}
		
		if (fancyLoginLinks) {
			e.preventDefault();
			history.pushState({ path: this.path }, '', this.href)
			
			loadLogin();
		}
	});
	
	$('.signup').click(function(e){
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
			return false;
		}
		
		if (fancyLoginLinks) {
			e.preventDefault();
			history.pushState({ path: this.path }, '', this.href)
			
			loadSignup();
		}
	});
	
	
	// Used to detect initial (useless) popstate.
    // If history.state exists, assume browser isn't going to fire initial popstate.
    var popped = ('state' in window.history), initialURL = location.href
    
    // Unbind the popstate set in base.js so we can rebind it.
    $(window).unbind('popstate');
    
    // popstate handler takes care of the back and forward buttons
    $(window).bind('popstate', function(event){
        // Ignore inital popstate that some browsers fire on page load
        var initialPop = !popped && location.href == initialURL
        popped = true
        if ( initialPop ) return
	
	    if (location.pathname.match(/login\/$/)) {
	        loadLogin();
	    }
	    else if (location.pathname.match(/invite\/$/)) {
	        loadSignup();
	    }
	    else if (location.pathname.match(/\/$/)) {
	        loadWelcome();
	    } else {
	        window.location = location.href
	    }
    });

});
