jQuery.fn.center = function(loaded) {
    var obj = this;
    body_width = parseInt($(window).width());
    body_height = parseInt($(window).height());
    block_width = parseInt(obj.outerWidth());
    block_height = parseInt(obj.outerWidth());
    
    left_position = parseInt((body_width/2) - (block_width/2)  + $(window).scrollLeft());
    if (body_width < block_width) { left_position = 0 };
    top_position = parseInt((body_height/2) - (block_height/2) + $(window).scrollTop());
    if (body_height < block_height) { top_position = 0 };
    
    if(!loaded) {
        
        obj.css({'position': 'absolute'});
        obj.css({'left': left_position, 'top': top_position});
        $(window).bind('resize', function() { 
            obj.center(!loaded);
        });
        $(window).bind('scroll', function() { 
            obj.center(!loaded);
        });
        
    } else {
        obj.stop();
        obj.css({'position': 'absolute'});
        obj.animate({'left': left_position, 'top': top_position}, 200, 'linear');
    }
}

$(document).ready(function(){

	$("nav .login-link").click(function() {
		$("#login").slideDown();
		return false;
	});
	$("nav .section-link").click(function() {
		$("html,body").animate({
			scrollTop: $($(this).attr("href")).offset().top
		}, "slow");
		return false;
	});
	
	$("#login .close").click(function() {
		$("#login").slideUp();
		$('#login .error-message').hide();
		return false;
	});
	
	$("#contact form").jqTransform();
	
	$("#contact form").submit(function()
	{	
		// Quick and dirty validation
		if ($('#contact input[name=name]').val() == '' ||
			$('#contact input[name=email]').val() == '' ||
			$('#contact textarea[name=message]').val() == '')
		{console.log('test');
			$('#form-error').show().center();
			
			return false;
		};
		
		var postData = '';
		
		// Construct POST data dynamically
		$('#contact input, #contact select, #contact textarea').each(function(index)
		{
			if ($(this).attr('type') == 'checkbox') {
				if (!$(this).is(':checked'))
				{
					return true;
				};
			};
			
			postData += $(this).attr('name') + '=' + $(this).val() + '&';
		});
		
		// Make the POST request to the form mailer with our constructed form data
		$.ajax({
			type: 'POST',
			url: 'formmail.php',
			data: postData,
			success: function(result)
			{
				$('#form-popup').show().center();

				// Reset the form
				$('#contact input, #contact select, #contact textarea').each(function(index)
				{
					// But not the submit button
					if ($(this).attr('type') == 'submit') return true;
					
					$(this).val('');
					$(this).attr('checked', 'false');
				});
			}
		});
		
		return false;
	});
	
	$("#form-popup .close, #form-error .close").click(function() {
		$("#form-popup").fadeOut();
		$("#form-error").fadeOut();
		return false;
	});
	
	function setPortfolioActions()
	{
	
		$("#portfolio .project").hover(function() {
			if($("summary", this).is(":animated")) return;
			$("summary", this).slideDown("fast");
		},function() {
			$("summary", this).slideUp("fast");
		});
	
		$("#portfolio .project a").fancybox({
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	600, 
			'speedOut'		:	200, 
			'overlayShow'	:	true,
			'overlayOpacity':   0.75,
			'overlayColor'  :   "#000"
		});
	}
	setPortfolioActions();
	
	var projectWidth, projectMargin;	
	var normalMarginRatio = 0.12;
	var maxProjectsPerRow = 3;
	var minProjectWidth = 304;
	
	var $ta = $("#contact .form-holder .field-box .field-container textarea.field");
	var taMinW= 165;
	
	$(window).resize(function() {
		var $pp = $("#portfolio .projects li.project");
		
		var projectsPerRow =  maxProjectsPerRow;
		portfolioMarginRatio = normalMarginRatio;
		var condition = true;
		while(condition)
		{
			condition = (((1+portfolioMarginRatio)*minProjectWidth)*projectsPerRow - portfolioMarginRatio*minProjectWidth) > $("#portfolio .projects").width();
			if(condition) projectsPerRow--;
		}
		
		if(projectsPerRow > 1)
		{
			$("html").css({ overflowX: "hidden"});
			var x = projectsPerRow;
			x = $("#portfolio .projects").width() / ( x + ( portfolioMarginRatio*(x-1) ) );
			projectWidth = x;
			projectMargin = x*portfolioMarginRatio;
			$("#portfolio .group").css({ width: $("#portfolio article").width()+projectMargin+1 });
			$pp.css({ width: projectWidth, marginRight: projectMargin });
		}
		else
		{
			$("html").css({ overflowX: "auto"});
			projectWidth = $("#portfolio .projects").width() > minProjectWidth ? $("#portfolio .projects").width() : minProjectWidth;
			projectMargin = 0;
			$pp.css({ width:projectWidth, marginRight:0 });
			$("#portfolio .group").css({ width:"auto", marginRight:0 });
		}
		
		$pp.css({ height: $pp.find("div:eq(0)").height()+33+50 });
		
				
		if($(window).width()<400) $("article").addClass("tight");
		else $("article").removeClass("tight");
		
		var textareaW = $("article").width() + $("article").offset().left - $ta.offset().left - 20;
		if(textareaW<taMinW) textareaW = taMinW;
		$ta.width(textareaW);
		
		$("#contact .col").each(function(){
			var condition = $(this).prev().is(".col") && $(this).prev().offset().top == $(this).offset().top;
			
			if(!condition) $(this).addClass("single-row-col");
			else $(this).removeClass("single-row-col");
		});
	});
	$(window).resize();
	
	var $currentCat, $all = $("#portfolio ul.group").clone().removeClass("projects-all");
	$("#portfolio .legend li").click(function(){
		var catClass = this.className;
		var catClass = $(this).attr('data-id');
		
		var $new = $all.clone();
		if(catClass!='item-all')
		{
			$new.removeClass("projects-all");
			
			$new.find(".project").each(function(){
				if($(this).find("."+catClass).size()==0)
				{
					$(this).remove();
				}
			});
			
		}
		var h = $("#portfolio .project:eq(0)").height();
		$new.appendTo($("#portfolio .projects")).find(".project").css({ height: h, width:projectWidth, marginRight: projectMargin });
		$("#portfolio .projects ul.group:visible").quicksand($new.find(".project"),	function(){
			$(window).resize();
			setPortfolioActions();
		});
		return false;
	});
	
	
	$('#login form').submit(function()
	{
		$.ajax({
			type: 'POST',
			url: '/clients/process.php',
			data: 'login=' + $('#login input[name=login]').val() + '&password=' + $('#login input[name=password]').val(),
			success: function(result)
			{
				if (result == 'invalid')
				{
					$('#login .error-message').fadeIn();
				} else {
					window.location.href = "/clients/display.php";
				}
			}
		});
		
		return false;
	})
});

$(window).load(function() {
	$(window).resize();
});

function htmlLoaded()
{
	if($.browser.msie && $.browser.version.substr(0,1) == 6 ) { 
		DD_belatedPNG.fix('#logo a, #form-popup h3, #form-error h3, #contact hgroup h2');
	}
}
