$(document).ready(function(){


	//---------------------------
	// Twitter feed
	//---------------------------
	if( $('#twitter').length ){
		
		var TwitterUsername = "R4SPO";
		$.ajax({
			url : "http://twitter.com/statuses/user_timeline/"+TwitterUsername+".json?callback=?",
			dataType : "json",
			timeout: 15000,
			
			success : function(data){
				var time = data[0].created_at,
					text = data[0].text,
					id = data[0].id_str;
					
				time = time.replace(/(\+\S+) (.*)/, '$2');
				time = $.timeago( new Date( Date.parse( time ) ) );
										
				text = text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url){
								return '<a href="'+url+'" target="_blank">'+url+'</a>'});
				text = text.replace(/@(\w+)/g, function(url){
								return '<a href="http://www.twitter.com/'+url.substring(1)+'" target="_blank">'+url+'</a>'});
				text = text.replace(/#(\w+)/g, function(url){
								return '<a href="http://twitter.com/#!/search?q=%23'+url.substring(1)+'" target="_blank">'+url+'</a>'});
				text = "<p>"+ text + "</p> <a href='http://twitter.com/"+TwitterUsername+"/status/"+id+"' class='status' target='_blank'>" +time+ "</a> ";
				$("#tweetContainer").html(text);
			},
			
			error : function(){
				$("#tweetContainer").html("There was an error connecting to your Twitter account");
			}
		});
		
	}
	
	
	//---------------------------
	// Mini-gallery hover effect
	//---------------------------
	$(".gallery").find("li").hover(function(){
		$(this).find("img").stop().animate({ "opacity": 0.5 }, 300);
	}, function(){
		$(this).find("img").stop().animate({ "opacity": 1 }, 300);
	});
	
	
	//---------------------------
	// Tooltip
	//---------------------------
	$(".browsers").find("li").hover(function(){
	
		var title = $(this).find("img").attr("alt");
			tooltip = $("<div />", {
				className	: "toolTip",
				text		: title,
				css			: {
					opacity: 0
				}
			});
		tooltip.appendTo(this).stop().animate({
			top: -30,
			opacity: 1
		}, 300);
		
	}, function(){
	
		tooltip.animate({ opacity: 0 }, 300, function(){
			$(this).remove(); 
		});
		
	});
	
	
	//---------------------------
	// Tooltip on footer
	//---------------------------
	$(".social").find("li").hover(function(){
	
		var title = $(this).find("img").attr("alt");
			tooltip = $("<div />", {
				className	: "toolTip2",
				text		: title,
				css			: {
					opacity: 0
				}
			});
		tooltip.appendTo(this).stop().animate({
			left: 40,
			opacity: 1
		}, 300);
		
	}, function(){
	
		tooltip.animate({ opacity: 0 }, 300, function(){
			$(this).remove(); 
		});
		
	});
	
	
	//---------------------------
	// adjust sidebar height
	//---------------------------
	var sidebarH = $(".sidebar").height(),
		mainH = $(".main").height();
	(sidebarH < mainH) ? $(".sidebar").height(mainH) : $(".main").height(sidebarH);
	
	
	//---------------------------
	// Homepage slider
	//---------------------------
	if( $("#slider").length){
		
		// Init
		var slider = $("#slider"),
			sliderText = $("#sliderText"),
			slidesNum = slider.find("li").length,
			running = false;
		slider.width( slidesNum*600 );
		
		// Trigger click
		$(".arrow").click(function(){
			if( !running ) {
				slide( $(this).attr("id") );
			}
			return false;
		});
		
		// Slide on
		function slide(direction){
			running = true;
			var pos = parseInt( slider.css("left") ),
				newPos = pos,
				current = sliderText.find(".current").index(),
				next = current;
			if(direction == "right") {
				newPos = pos-600;
				next = current + 1;
			}else{
				newPos = pos+600;
				next = current - 1;
			}
			
			if( next < 0 ){
				slider.animate({
					left : pos + 20
				}, 100, 'easeOutCubic' ).animate({
					left : pos
				}, 100, 'easeInCubic' , function(){
					running = false;
				});
			}else if( next == slidesNum ){
				slider.animate({
					left : pos - 20
				}, 100, 'easeOutCubic' ).animate({
					left : pos
				}, 100, 'easeInCubic' , function(){
					running = false;
				});
			}else{
				slider.animate({
					left : newPos
				},500, 'easeInCubic', function(){
					running = false;
				});
				sliderText.find("li").eq(current).fadeOut().removeClass("current");
				sliderText.find("li").eq(next).fadeIn().addClass("current");	
			}
		}
	
	}
	
	
	
	//---------------------------
	// Ajax Contact Form
	//---------------------------	
    
    if($("#contactForm").length){
    
		$("#contactForm").submit(function(){
		    
		    var ContactForm = $(this),
		    	errors = 0,
		        loader = $("#loader"),
		        result = $("#result");
		        
		    loader.fadeIn();
		    result.find(".fail, .success").hide();
		    
		    ContactForm.find(".required").each(function(){
		        var id = $(this).attr("id");
		        if($(this).hasClass("email")){
		            errors += $(this).validateEmail();
		        }if($(this).attr("id") == "captcha"){
		            errors += $(this).validateCaptcha();
		        }else{
		            //Must contain at least 3 characters
		            errors += $(this).validateLength(3);
		        }
		    });
		    
		    //If there are no errors, send the email
		    if(errors === 0){
		        var data = ContactForm.serialize(),
		            URL = ContactForm.attr("action");
				$.ajax({
					type: 'post',
					url: URL,
					data: data,
					success: function(results) {
						loader.fadeOut(function() {
							if(/email sent/.test(results)) {
								result.find(".success").fadeIn();
								ContactForm.find(".form").each(function(){
								    $(this).val("");
		                        });
							} else {
								result.find(".fail").fadeIn();
							}
						});
					},
					error: function() {
						result.find(".fail").fadeIn();
					}
				});
		    }else{
		    	// else, nudge the incorrect fields
		    	ContactForm.find(".notRight").each(function(){
		    		$(this).nudge();
		    	});
		    }
		    loader.fadeOut();     
	        return false;    
	    });
	
	    //Content length validation
	    $.fn.validateLength = function(l){
	        if( this.val().length < l ) {
	        	this.addClass("notRight");
	        	return 1;
	        } else {
	            this.removeClass('error');
	            return 0;
	        }
	    };
	
		//email validation
		$.fn.validateEmail = function(){
			var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
			if(filter.test(this.val())){
				this.removeClass("error");
				return 0;
			}else{
				this.addClass("notRight");
				return 1;
			}
		}
		
	    // Captcha validation
	    $.fn.validateCaptcha = function(){
	    	var field1 = parseInt($("#captchaField1").text()),
	    		operator = ( $("#captchaField2").text() == "+" ) ? true : false;
	    		field3 = parseInt($("#captchaField3").text()),
	    		correct = operator ? field1+field3 : field1-field3;   
	        if(this.val() != correct) {
	        	this.addClass("notRight");
	        	return 1;
	        } else {
	            this.removeClass('error');
	            return 0;
	        }
	    };
		
	    // Nudge effect
		$.fn.nudge = function(){
			$(this).animate({
				'left' : -4
			}, 80, function(){
				$(this).animate({
					'left' : 4
				}, 80, function(){
					$(this).animate({
						'left' : -4
					}, 80, function(){
						$(this).animate({
							'left' : 4
						}, 80, function(){
							$(this).animate({
								'left' : -4
							}, 80, function(){
								$(this).animate({
									'left' : 0
								}, 80, function(){
									$(this).delay(80).removeClass('notRight').addClass("error");
								});
							});
						});
					});
				});
			});
		}
			
	}	

	

});
