$(document).ready(function() {

	// Is Homepage?
	$h = $("#homePanels").length > 0;	
	
    // Main Menu
    if ($h) {
	    $("#topBar").css("top", "-100px").animate({
		    top: 0
	    }, 1000);
	}
    $("#mainMenu li").hover( function() {
	    $(this).find("ul").show();
    }, function() {
	    $(this).find("ul").hide();
    });
    
    // Logo
    $("#logo").hoverIntent( function() {
		$(this).animate({
			marginTop: 0
		});
		/*$("#telNumber").animate({
			marginTop: 10
		});*/
    }, function() {
		$(this).animate({
			marginTop: -10
		});
		/*$("#telNumber").animate({
			marginTop: 0
		});*/
    });
    
    // Gallery
    $(".gallery a").each( function() {
	    $(this).attr("rel", "gallery");
    });
	$(".gallery a[rel=gallery]").fancybox({
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade'
    });
    
    // Input Default text
	$("input[type=text], textarea").each( function() {		
		if ($(this).val() != "") {
		    $(this).parent().find("label").hide();
		}
	});
    
   	$("input[type=text], textarea").keypress(function() {
		$(this).parent().find("label").fadeOut(300);
    });

    $("input[type=text], textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).parent().find("label").fadeIn(150);
        }
    });
    
    // Carousel
    $int2 = setInterval( "animateCarousel('next', 'auto')", 10000);
    
    
    $("#carouselContainer .scrollingContent").width("10000px");
    $("#carouselContainer .carouselItem").width($(window).width());
    $(window).resize( function() {
	    $("#carouselContainer .carouselItem").width($(window).width());
    });
    
    
    $("#carouselControls").show().find("li a").hoverIntent( function() {
		$(this).not(".disabled").animate({backgroundPosition: "0px 0px"});
    }, function() {
		$(this).not(".disabled").animate({backgroundPosition: "28px 0px"});
    }).click( function(e) {
	    e.preventDefault();
	    var $direction = $(this).parent().attr("class");
	    animateCarousel($direction, 'click');
    });
    
    disableControls();
    
    // Clients Panel (Home)
    $int = setInterval( "cycleHomeClients()", 5000);
    
    // Search Submit
    $("#searchForm").submit(function(e) {
	    e.preventDefault();
	    // hide results and show loader
		$("#searchResults li").slideUp();
		$("#searchResults li.loading").slideDown();
	    
	    // ajax call to populate results
		var $s = $("#s").val();
		var $n = 5;
		
	    $.getJSON('/getSearchResults.php', {s:$s, n:$n}, function(data){
		    $.each(data, function(i, item) {
			    $result = '<li><a href="' + item[0] + '">' + item[1] + '<span>' + item[2] + '</span></a></li>';
			    $("#searchResults li.loading").after($result);
		    });
			$("#searchResults li.end .more").attr("href", "/?s=" + $s);
	    
		    // show results and hide loader
		    $("#searchResults").slideDown(300, function() {
			    $("#searchResults li.loading").animate({ // this bit is fake
				    opacity: 1
			    }, 2000, function() {
					$("#searchResults li").slideDown();
					$("#searchResults li.loading").hide();
			    });
		    });
	    });
	    
    });
	$("#searchResults a.close").click(function(e) {
	    e.preventDefault();
		$("#searchResults:visible").slideUp(150, function() {
			//$("#searchResults").html("");
			$("#searchResults li").hide();
			$("#searchResults li.loading").show();
		});
	});
    
    // Contact Form Submit
    $("#contactForm").submit(function(e) {
	    e.preventDefault();
	    $("#contactForm .overlay").fadeIn(function() {
		    
		    // remove error styling
		    $("#contactForm input, #contactForm textarea, #contactForm label").each( function() {
			    $(this).removeAttr("style");
			    if ($(this).val() != "") {
				    $(this).parent().find("label").hide();
			    }
		    });
		    
		    // validate
		    var $errors = false;
		    var $errorDetails = new Array();
		    if (!validate_email($("#contactForm #contactEmail").val())) {
			    $errors = true;
			    $errorDetails[$errorDetails.length] = "contactEmail";
		    }
		    
		    $("#contactForm #contactName, #contactForm #contactEnquiry, #contactForm #contactEmail").each(function() {
			    if ($(this).val() == "" || $(this).val() === null) {
			    	$errors = true;		
			    	$errorDetails[$errorDetails.length] = $(this).attr("id");
			    	
			    }
		    });		    
		    
		    if ($errors) {
			    // show errors
			    $("#contactForm .overlay").fadeOut();
			    for (var $errorId in $errorDetails) {
				    $("#" + $errorDetails[$errorId]).css("color", "#c10000").parent().find("label").css("color", "#c10000");
				    //alert( $errorDetails[$errorId] );
			    }
		    } else {
		    
			    // ...ajax call to send email
			    var $n = $("#contactName").val();
			    var $e = $("#contactEmail").val();
			    var $t = $("#contactTelephone").val();
			    var $m = $("#contactEnquiry").val();
			    
			    $.getJSON('/processContactForm.php', {n:$n, e:$e, t:$t, m:$m}, function(data){
				    var $response;
				    $.each(data, function(i, item) {
					    $response = item;
				    });
			    
			    
			    
				    if ($response == "sent") {
					    // hide form
					    $("#contactForm").animate({ // this bit is fake
						    opacity: 1
						    }, 2000, function() {
						    $("#contactForm").fadeOut(500, function() {
					    		// show thank you message
						    	$("#contactForm").append("<p>Thank you for your message, we'll get back to you shortly.</p>");
						    });
					    });
				    } else {
		    			$a = $("<a />").attr("href", "#").bind("click", function(e) {
		    				e.preventDefault();
						    $("#errorPopup, #contactForm .overlay").fadeOut();
					    }).text("try again").css("color", "#c10000");
					    $errorPopup = $("<div />").attr("id", "errorPopup").append("There was an error sending your message. Please ").append($a).append(".").css({
							"width" : "250px",
							"position" : "absolute",
							"background" : "#ffffff",
							"z-index" : "9",
							"-moz-border-radius" : "5px 5px 5px 5px",
							"border-radius" : "5px 5px 5px 5px",
							"padding" : "10px 10px 10px 10px",
							"font-size" : "1.4em",
							"color" : "#C10000",
							"text-align" : "center",
							"top" : "52px",
							"left" : "177px"
					    });
					    
					    $("#contactForm form").prepend($errorPopup);
				    }
			    });
			    
			    
		    }
		    
	    });
    });
    
    // Services Scroll
     $(".servicespanel .prev a, .servicespanel .next a").click( function(e) {
	    e.preventDefault();
	    var $direction = $(this).parent().attr("class");
	    animateServices($direction);
    });
    
    // Left Right Arrows on Services
	$(document).keydown(function(e) {
		if (e.keyCode == 37) {
			animateServices("prev");
		} else if (e.keyCode == 39) {
			animateServices("next");
		} 
	});
    
    
});

function animateServices($dir) {
	$scroller = $(".servicespanel .scrollingContent");
	if (!$scroller.is(":animated")) {
		var $c_items = $scroller.find(".service").length;
		var $c_item_width = $scroller.find(".service").width() + 14;
		var $minleft = - ($c_items - 5) * $c_item_width; //-677px
		var $cur_left = parseFloat($scroller.css("left"));
		
		var $new_left;
		
		switch ($dir) {
			case "next":
				if ($cur_left == $minleft) {
					$new_left = 0;
				} else {
					$new_left = $cur_left - $c_item_width;
				}
				break;
			case "prev":
				if ($cur_left == 0) {
					$new_left = $minleft;
				} else {
					$new_left = $cur_left + $c_item_width;
				}
				break;
		}
		
		$scroller.animate({
			left: $new_left
		}, 500, 'easeInOutExpo');
		
	}
}

function animateCarousel($direction, $source) {
	$currentItem = parseFloat($("#currentItem").text());
	$lastItem = $(".carouselItem").length - 1;
	
	switch ($direction) {
		case "next":
			if ($currentItem < $lastItem) {
				$x = - ($currentItem + 1) * $(window).width();
				$i = $currentItem + 1;
			} else if ($source == 'auto') {
				$x = 0 * $(window).width();
				$i = 0;
			}
			$("#currentItem").text($i);
			$("#carouselContainer .scrollingContent").animate({
				left: $x
			}, 750, "easeInCirc", disableControls());
			break;
		case "prev":
			if ($currentItem > 0) {
				$x = - ($currentItem - 1) * $(window).width();
				$i = $currentItem - 1;
			}
			$("#currentItem").text($i);
			$("#carouselContainer .scrollingContent").animate({
				left: $x
			}, 750, "easeInCirc", disableControls());
			
			break;
	}
	if ($source == 'auto') {
		clearInterval($int2);
	    $int2 = setInterval( "animateCarousel('next', 'auto')", 10000);
	} else if ($source == 'click') {
		clearInterval($int2);
	}
	
}

function disableControls() {
	$currentItem = parseFloat($("#currentItem").text());
	$lastItem = $(".carouselItem").length - 1;
	
	if ($currentItem < 1) {
		$("#carouselControls li.prev a").css("opacity", 0.5).addClass("disabled").animate({backgroundPosition: "28px 0px"});
	} else {
		$("#carouselControls li.prev a").css("opacity", 1).removeClass("disabled");
	}
	
	
	if ($currentItem == $lastItem) {
		$("#carouselControls li.next a").css("opacity", 0.5).addClass("disabled").animate({backgroundPosition: "28px 0px"});
	} else {
		$("#carouselControls li.next a").css("opacity", 1).removeClass("disabled");
	}
}

function cycleHomeClients() {
	
	var $x = $(".clientList li.show").length;
	var $index = $(".clientList li").index($(".clientList li.show:first"));
	var $newindex = $index + $x;
	
	if ($newindex > ($(".clientList li").length - 1 )) {
		$newindex = 0;
	}
	$(".clientList li.show").fadeOut(500, function() {
		$(this).removeClass("show");
		for ($i = $newindex; $i < ($newindex + $x); $i++) {
			$(".clientList li:eq(" + $i + ")").fadeIn(500, function() {
				$(this).addClass("show");
			});
		}
	});
	
	// reset timer
	clearInterval($int);
	$int = setInterval( "cycleHomeClients()", 5000);
	
}

function validate_email(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   } else {
	   return true;
   }
}
