function relative_time(time_value) {
	var newtime = time_value.replace(',','');
	var values = newtime.split(" ");
	time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	
	if (delta < 60) {
		return 'il y a moins d\'une minute';
	} else if(delta < 120) {
		return 'il y a une minute';
	} else if(delta < (60*60)) {
		return ('il y a ' + parseInt(delta / 60)).toString() + ' minutes';
	} else if(delta < (120*60)) {
		return 'il y a une heure';
	} else if(delta < (24*60*60)) {
		return 'il y a ' + (parseInt(delta / 3600)).toString() + ' heures';
	} else if(delta < (48*60*60)) {
		return 'il y a un jour';
	} else {
		return ('il y a ' + parseInt(delta / 86400)).toString() + ' jours';
	}
}

// WINDOWS LOAD 
$(window).load(function() {
	/* Slider */
	$('#slider').nivoSlider({
		effect:'fade', //Specify sets like: 'fold,fade,sliceDown'
		slices:1,
		animSpeed:300, //Slide transition speed
		pauseTime:5000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:false, //Only show on hover
		controlNav:false, //1,2,3...
		controlNavThumbs:false, //Use thumbnails for Control Nav
		controlNavThumbsFromRel:false, //Use image rel for thumbs
		controlNavThumbsSearch: '.jpg', //Replace this with...
		controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
		keyboardNav:true, //Use left & right arrows
		pauseOnHover:true, //Stop animation while hovering
		manualAdvance:false, //Force manual transitions
		captionOpacity:1 //Universal caption opacity
	});
	
	//Adjusts work_slider width
	if(document.getElementById("work_screen")){
		var ul = $('#work_screen');
		var lastLi = ul.find('li:last-child');
		var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth();
		ul.css({'width' : ulWidth});
	}
});

// DOCUMENT READY
$(document).ready(function(){ 	
	// Twitter
	// Thanks to : http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/
	var username = 'derenkeskin';
	$.get('/lib/proxy.php?url=http://twitter.com/statuses/user_timeline/' + username + '.rss?count=1', function(tweets) { 
		$(tweets).find('item').each(function() {
			var tweet = $(this);
			var pattern = new RegExp("^"+username+": ","g");
			var status = tweet.find('description').text().replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
				return '<a href="'+url+'">'+url+'</a>';
			}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
				return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
			}).replace(pattern,'');
			var tweetDate = relative_time(tweet.find('pubDate').text());
			var link = tweet.find('link').text();
			$('#tweet .loading').fadeOut(750, function() {
				$("#tweet blockquote .loading").removeClass('loading').html(status).hide().fadeIn(750);
				$("#tweet .pubdate").html('<a href="'+link+'">'+tweetDate+'</a>').hide().fadeIn(1000);								
			});
		});
	});
	
	//Works Filter
	$('#works_filter li a').click(function() {
		$(this).css('outline','none');
		$('#works_filter li a').removeClass('current');
		$(this).addClass('current');
	
		var filterVal = $(this).text().toLowerCase().replace(' ','-');
			
		if(filterVal == 'tout') {
			$('#works_list li.noactif').fadeTo('slow',1).removeClass('noactif');
		} else {
			$('#works_list li').each(function() {
				if(!$(this).hasClass(filterVal)) {
					$(this).fadeTo('slow', 0.2).addClass('noactif');
				} else {
					$(this).fadeTo('slow',1).removeClass('noactif');
				}
			});
		}
		return false;
	});
	
	//FadeIn works and scroll To
	$("#work_content").hide().fadeIn("slow", function() {
		$.scrollTo('#main', 700);
	});
	
	//Scrollable Work_slider
    $('#work_slider').mousedown(function (event) {
        $(this)
            .data('down', true)
            .data('x', event.clientX)
            .data('scrollLeft', this.scrollLeft);
        return false;
    }).mouseup(function (event) {
        $(this).data('down', false);
    }).mousemove(function (event) {
        if ($(this).data('down') == true) {
            this.scrollLeft = $(this).data('scrollLeft') + $(this).data('x') - event.clientX;
        }
    }).css({
        'overflow' : 'hidden',
        'cursor' : 'e-resize'
    });
    $(window).mouseout(function (event) {
        if ($('#work_slider').data('down')) {
            try {
                if (event.originalTarget.nodeName == 'BODY' || event.originalTarget.nodeName == 'HTML'){
                    $('#work_slider').data('down', false);
                }                
            } catch (e) {}
        }
    });
		
	//Contact Form
	$("#contact_form").validate({
		errorElement: "span",
		messages: {
			nom: "Veuillez entrer votre nom",
			suj: "Veuillez remplir ce champ",
			email: "Veuillez entrer un mail valide",
			msg: "Et le message?"
		},
		errorPlacement: function(error, element) {
			error.appendTo(element.prev("label"));
		},
		success: function(label) {
			label.parent().next().addClass("success");
		},
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit({
				target: "#result_form",
			    success:    function() { 
			        $('input#nom, input#email, input#url, input#suj, textarea#msg').attr("disabled", "disabled");  
			        $('input.submit').fadeOut("slow");
			        $('#result_form').hide().fadeIn("slow");
			    } 
			});
		}
	});
});

// LOLILOL
(function ($) {
    $.fn.konami = function (callback, code) {
        if (code == undefined) code = "38,38,40,40,37,39,37,39,66,65";
        return this.each(function () {
            var kkeys = [];
            $(this).keydown(function (e) {
                kkeys.push(e.keyCode);
                if (kkeys.toString().indexOf(code) >= 0) {
                    $(this).unbind('keydown', arguments.callee);
                    callback(e);
                }
            }, true);
        });
    }
    $(window).konami(function () {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = 'http://erkie.github.com/asteroids.min.js';
        document.body.appendChild(s); 
    });
})(jQuery);

