$(function(){

	$('html').click(closeProject);
	
	$('#page').click(function(e){
	 e.stopPropagation();
	});

	//sorting with isotope
	$('#sort a').click(function(e){
		e.preventDefault();
		closeProject();
		var new_mode = $(this).attr("href").slice(1);
		$('body').attr('class', new_mode);
		hideLegend();
		var sortAscending = (new_mode == 'date') ? false : true;
		$('#projects').isotope({ sortBy : new_mode, sortAscending : sortAscending });
		$('#menu a.selected').removeClass('selected');
		$(this).addClass('selected');
		showLegend(new_mode);
	});
	
	//click on a new page
	$('#pages a').click(function(e){
		e.preventDefault();
		closeProject();
		var new_mode = $(this).attr("href").slice(1);
		$('body').attr('class', new_mode);
		$('#menu a.selected').removeClass('selected');
		$(this).addClass('selected');
		
		if (new_mode == 'about') {
		    $.ajax({
		        type: 'GET',
		        url: '/ajax/about.php',
				dataType: 'xml',
		        success: function(data) {
		        	$('#page .caption').html(
		        		'<div class="title">' + $(data).find('project > title').text() + '</div>' +
		        		'<div class="description">' + $(data).find('project > description').text() + '</div>' +
		        		'<div class="controls"><a class="prev">&lt;</a><a class="next">&gt;</a><a class="close">&times;</a></div>'
		        	);
		        	var images = '<ul>';
				    $(data).find('image').each(function () {
			        	images += '<li><img src="' + $(this).find('src').text() + '" width="' + $(this).find('src').text() + '" height="' + $(this).find('height').text() + '"/></li>';
				    });
				    images += '</ul>';
		        	$('#page .image').html(images);
		        	
				    //set events
				    $('#page .caption a.prev').click(prevImage);
				    $('#page .caption a.next').click(nextImage);
				    $('#page .caption a.close').click(closeProject);
				    $('#page .image img').click(nextImage);
				    
				    $('#page').show();
				    
				    //fade up first image
				    $('#page .image ul li:first').fadeIn().addClass('selected');
				}
			});
		}
	});
	    
	$('#projects').isotope({
		itemSelector : '.project',
		getSortData : {
			date : function(e) { return e.attr('data-date'); },
			format : function(e) { return e.attr('data-format'); },
			color : function(e) { return e.attr('data-color'); },
			client : function(e) { return e.attr('data-client'); }
		}
	});
	
	$('#projects img').hover(function(){
		$(this).attr('src', $(this).closest('div.project').attr('data-img'));
	}, function(){
		$(this).grayscale();
	});
	
	$('#projects a').click(function(e){
		e.preventDefault();
	    $.ajax({
	        type: 'GET',
			data : { id : $(this).parent().attr('data-id') },
	        url: '/ajax/project.php',
			dataType: 'xml',
	        success: function(data) {
	        	$('#page .caption').html(
	        		'<div class="title">' + $(data).find('project > title').text() + '</div>' +
	        		'<div class="client">' + $(data).find('project > client').text() + '</div>' +
	        		'<div class="description">' + $(data).find('project > description').text() + '</div>' +
	        		'<div class="controls"><a class="prev">&lt;</a><a class="next">&gt;</a><a class="close">&times;</a></div>'
	        	);
	        	var images = '<ul>';
			    $(data).find('image').each(function () {
		        	images += '<li><img src="' + $(this).find('src').text() + '" width="' + $(this).find('src').text() + '" height="' + $(this).find('height').text() + '"/></li>';
			    });
			    images += '</ul>';
	        	$('#page .image').html(images);
	        	
			    //set events
			    $('#page .caption a.prev').click(prevImage);
			    $('#page .caption a.next').click(nextImage);
			    $('#page .caption a.close').click(closeProject);
			    $('#page .image img').click(nextImage);
			    
			    $('#page').show();
			    
			    //fade up first image
			    $('#page .image ul li:first').fadeIn().addClass('selected');
			    
			    $('body').addClass('project');
			}
		});
	});
	
	$(document).keydown(function(e){
		//alert(e.which);
		if (e.which == 27) { //esc key
			closeProject();
		} else if (e.which == 37) { //left arrow
			prevImage();
		} else if (e.which == 39) { //right arrow
			nextImage();
		} 
	});	
});

$(window).load(function() {
	setTimeout(function(){
		$('#projects img').grayscale();
		for (i=1; i<=$("#projects a").length; i++) setTimeout("$('#projects a:hidden:random').fadeIn(400)", 50 * i-1);
		showLegend('date');	
	}, 2000);
});

function closeProject() {
	$('#page').hide();
    $('body').removeClass('project');
}

function nextImage() {
	var index = $(".image li").index($(".image li.selected")) + 1;
	var $el = $(".image li.selected").removeClass("selected").fadeOut();
	if (index == $(".image li").size()) {
		$(".image li:first").addClass("selected").fadeIn();
	} else {
		$el.next().fadeIn().addClass("selected");
	}
}

function prevImage() {
	var index = $(".image li").index($(".image li.selected"));
	var $el = $(".image li.selected").removeClass("selected").fadeOut();
	if (index == 0) {
		$(".image li:last").addClass("selected").fadeIn();
	} else {
		$el.prev().fadeIn().addClass("selected");
	}
}

function hideLegend() {
	$('#projects div.description span').hide();
	$('#projects div.bar').hide();
}

function showLegend(mode) {
	var last_desc = '';
	
	var $sortedItems = $('#projects').data('isotope').$filteredAtoms;
		
	$sortedItems.each(function(){
		var this_desc = $(this).find('div.description span.' + mode).html();
		//console.log('showing mode for ' + this_desc);
		if (last_desc != this_desc) {
			$(this).find('div.bar').fadeIn();
			$(this).find('div.description span.' + mode).fadeIn();
			last_desc = this_desc;
		}
	});
}

//grayscale thanks to alex and others at http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html
$.fn.grayscale = function() {
	return this.each(function() {
		if ($.browser.msie) {
			this.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
		} else {
			this.src = grayscaleImage(this);
		}
	});
}

function grayscaleImage(imgObj) {
    var canvas = document.createElement('canvas');
    var canvasContext = canvas.getContext('2d');
    
    var imgW = imgObj.width;
    var imgH = imgObj.height;
    canvas.width = imgW;
    canvas.height = imgH;
    
    canvasContext.drawImage(imgObj, 0, 0);
    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
    
	for (var i = 0; i < imgPixels.data.length; i=i+4){
		var avg = (imgPixels.data[i] + imgPixels.data[i+1] + imgPixels.data[i+2]) / 3;
		imgPixels.data[i] = avg;
		imgPixels.data[i+1] = avg;
		imgPixels.data[i+2] = avg;
	}
    
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    
    //console.log('ran greyscale on ' + imgObj.alt);
    return canvas.toDataURL();
}

//jquery random thanks to http://blog.mastykarz.nl/jquery-random-filter/
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
    random: function(a, i, m, r) {
        if (i == 0) jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        return i == jQuery.jQueryRandom;
    }
});

