var sections			= { };
var topLinkOffset		= $('#topLink').offset().top;
var contentOffsetLeft	= 0;
var offset				= 20;
var scrollOffset		= 10;
var speed				= 400;
var firstClick			= true;

function start()
{

}

function end()
{

	// Loads stuff when document ready
	documentReady();
	// Contact setup
	contactFormSetup();
	// Hover for all images
	imageHover();
	// Form validator
	validatorSetup();

	/*
		Stylesheet switching
		When clicked, switch the stylesheet, blink the label, set the button as selected,
		and then click the first item to select a default style
	*/
	$('#themeButtons li a').click(function() {

		var oldStyle = $('#themeSelected').text();
		var newStyle = this.getAttribute('title');

		switchStylesheet(newStyle);

		$('#themeSelected').fadeOut().text(newStyle).fadeIn();
		$('#themeButtons li').removeClass('sel');
		$(this).parent().addClass('sel');

		if (oldStyle != '')
		{
			$('#mainMenu li').each(function() {
				var oldHover = $('a img', this).attr('hover');
				var newHover = oldHover.replace(oldStyle.toLowerCase(), newStyle.toLowerCase());
				$('a img', this).attr('hover', newHover)
			});
		}

		return false;

	}).filter(':first').click();

}

function documentReady()
{

	$(document).ready(function() {
	
		$.preloadCssImages();

		$('#topLink').show();

		portfolio();

		// Menu & top button scrolling
		sectionScroller();
		// Section scroller link events
		sectionScrollerLinks();

		$('a[href^="http://"]')
			.attr("target", "_blank");

	});

}

var minHeight = 3000;
var diff = 80;
function portfolio()
{

	$('#portfolio ul').hide();

	$('ul.projects li a').click(function() {

		var currentHeight = $('div#sectionPortfolio .sectionWrapper').height();
		pfHeight = currentHeight;
	
		var name = $(this).siblings('span.name').text();
		var link = $(this).siblings('span.link').text();
		var linkTitle = link.replace('http://', '');

		$('ul.projects li').removeClass('sel');
		$(this).parent().addClass('sel');

		$('div#projectName h1').text(name);
		$('div#projectLink').html('<a href="' + link + '" target="_blank">' + linkTitle + '</a>');

		var img = new Image();
		$('#preview').html('').addClass('loading');
		$(img)
			.load(function () {

				var newHeight = 0;

				$(this).hide();

				$('#preview')
					.removeClass('loading')
					.html(this);
	
				var height = $(this).height();
				if ((height - minHeight) < diff)
				{
					newHeight = height + diff;
				}
				else
					newHeight = minHeight;


				$(this).fadeIn();
				$('div#sectionPortfolio .sectionWrapper').animate({
					height: newHeight + 'px'
					},
					'fast',
					function() {
						calculateOffsets()
					}
				);

			})
			.attr('src', this.href);

		return false;
	});

	$('#portfolio li a').click(function() {

		var speed = 'fast';
		if (firstClick == true)
			speed = null;
		firstClick = false;

		var checkElement = $(this).next();

		if((checkElement.is('ul')) && (checkElement.is(':visible')))
			return false;

		if((checkElement.is('ul')) && (!checkElement.is(':visible')))
		{

			$('#portfolio ul:visible').hide(speed).parent().removeClass('sel');
			checkElement.show(speed).parent().addClass('sel');
			checkElement.children(':first').children('a').click();
			return false;

		}

	}).filter(':first').click();

}

function contactFormSetup()
{

	// Hide the error message
	$('div.error').css("visibility", "hidden");

	// Show the error message, then submit
	$('.contactFormSubmit a').click(function() {
		$('div.error').css("visibility", "visible");
		$('#contactForm').submit();
		return false;
	});

}

function imageHover()
{

	$('img[hover]').hover(
		function() {
			var currentImg = $(this).attr('src');
			$(this).attr('src', $(this).attr('hover'));
			$(this).attr('hover', currentImg);
		}, function() {
			var currentImg = $(this).attr('src');
			$(this).attr('src', $(this).attr('hover'));
			$(this).attr('hover', currentImg);
		});

}

function sectionScroller()
{

	contentOffsetLeft	= $('div#content').offset().left + $('div#content').width();

	calculateOffsets();
	
	$("#topLink").css("left", contentOffsetLeft + "px");
	$("#topLink").css("top", sections['sectionHello'].newOffset.top + "px");

	$(window).wresize(function() {
		contentOffsetLeft = $('div#content').offset().left + $('div#content').width();
		$("#topLink").css("left", contentOffsetLeft + "px");
	});

	$(window).scroll(function() {

		$.each(sections, function (idx, val) {
			if (val.visible)
			{
				var top = val.newOffset.top;
				if ($(window).scrollTop() <= top - scrollOffset)
				{
					/*$('#mainMenu a').removeClass('sel');
					$('#mainMenu a[href="#' + idx + '"]').addClass('sel');*/
					$("#topLink").css("top", top + "px");
					return false;
				}
			}
		});

	});

}

function calculateOffsets()
{

	$('div#content div.scrollable').each(function(){
		sections[this.id] = {
			offset:		$(this).offset(),
			visible:	$(this).is(':visible'),
			newOffset:	{
				top:	($(this).offset().top - topLinkOffset) + offset,
				left: 	$(this).offset().left
			}
		};
	});

}

function sectionScrollerLinks()
{

	var sectionScroll = function() {
		$('html,body').animate({
				scrollTop: $(this.hash).offset().top - scrollOffset
			},
			1000
		);
		return false;
	};

	$('a[class="scrollTo"]').click(sectionScroll);

}

function validatorSetup()
{

	// Default error message suppressed
	$.validator.messages.required = "";

	$("#contactForm").validate({
		rules: {
			name: "required",
			email: {
				required: true,
				email: true
			},
			subject: "required",
			message: "required"
		},
		messages: {
			email: {
				required: "",
				email: ""
			}
		},
		// On submit hide the error placeholder, submit the form and do nothing on success
		submitHandler: function(form) {
			$('div.error').css("visibility", "hidden");
			$(form).ajaxSubmit({
				success: function() {
					$("#contactForm").fadeOut().parent().append('<p>Merci pour votre message !</p>');
				}
			});
		},
		// Show the error placeholder if any error occurs, otherwise hide it
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors)
				$('div.error').css("visibility", "visible");
			else
				$('div.error').css("visibility", "hidden");
		},
		// No standard plugin error messages
		errorElement: null,
		errorPlacement: null,
		// Do nothing on success
		success: null,
		//Flash element on error
		highlight: function(element, errorClass) {
			/*$(element).fadeOut(function() {
				$(element).fadeIn();
			})*/
		}
	});

}

function switchStylesheet(styleName)
{

	/*
		Go through every stylesheet with a title attr,
		and disable everything except the selected
	*/
	$('link[@rel*=style][title]').each(function(i)
	{
		this.disabled = true;
		if (this.getAttribute('title') == styleName)
			this.disabled = false;
	});

}

