/************************************************
 * Hey!
 * Thanks for taking the time to look at our code.
 * Feel free to have a dig around; Hopefully something here can help you with
 * something you're stuck on, or inspire you to create something even better.
 * 
 * As always, please give credit where credit's due!
 *
 * littleredletter.com script by steven@littleredletter.com
 *
 ************************************************/

$(document).ready(function() {
	/**
	 * CSS Functions
	 * =============================
	 */
	
	// Make CSS aware JS is enabled
	$("body").addClass("JSOK");
	
	/*
	 * Create MSIE variables if user is running Internet Explorer.
	 * This method is more accurate than $.browser.msie
	 */
	if ($("body").hasClass("ie")) {
		var isMSIE = true;
		if ($("body").hasClass("ie6") || $("body").hasClass("ie7")) {
			var isLTIE8 = true;	// Special MSIE variable for old IEs
		}
	}
	
	// If CSS property overflow is set to hidden we know the CSS has been loaded
	if ($("#contact-form").css("overflow") === "hidden" && !isLTIE8) {
		$("#contact-form").hide().prependTo("#wrapper"); // Hide the form and move it to the top of the page
		$("#contact-form.invalid, #contact-form.review-form").show(); // Show the form if there's an error or was successful
		$("#form-content").append("<a href=\"\" id=\"form-close\">close</a>"); // Add the close button
		
		/*
		 * This browser supports our fancy form sliding, so add active class to 
		 * the nav button. If the button doesn't have this class it'll jump down
		 * to the bottom where the form is
		 */
		$("#navigation ul li:last a").addClass("active");
	}
	
	/**
	 * Navigation Functions
	 * =============================
	 */
	
	/*
	 * Redirect the browser if there are hash tags. This is required for
	 * portfolio pagination where a hash is set per each portfolio page
	 */
	if (window.location.hash) {
		var path = window.location.pathname.split("/");
		var hash = window.location.hash.substr(1);
		
		if (hash !== "contact-form") {
			window.location = "http://" + window.location.host + "/" + path[1] + "/" + window.location.hash.substr(1);
		}
	}

	/**
	 * Site Interactivity
	 * =============================
	 * Contact Form
	 * -------------------------
	 */	

	// Show the contact form
	$("#navigation ul li:last a.active").click(function() {
		$("#navigation li.on").not($(this)).addClass("semi"); // Remember the current page's button
		$(this).parent().addClass("on").siblings().removeClass("on"); // Add '.on' to Enquiries, remove from others
		$("#contact-form").slideDown(500, 'easeOutExpo');
		return false;
	});
	
	// Close the contact form
	$("#form-close, #navigation li.semi, #form-cancel").live("click", function() {
		$("#navigation li.on").removeClass("on");
		$("#navigation li.semi").addClass("on").removeClass("semi"); // Set the current page button
		$("#contact-form").slideUp(500, 'easeOutExpo');
		return false;
	});
	
	// If a valid form has been submitted, hide the "Thank You" message after 4s
	if (!isLTIE8) {
		setTimeout(function() {
			$("#contact-form.submitted.review-form").slideUp(500, 'easeOutExpo');
		}, 4000);
	}
	

	/**
	 * Services Panels
	 * -------------------------
	 */

	// Compress all 'Services' panels
	if (!isMSIE || isLTIE8) {
		$("#services .service-content").css("opacity", 0).hide();
		$("#services .service").removeClass("on");
		
		// If the user's browsed a certain service, un-hide it
		$("#services .service.current .service-content").css("opacity", 1).show();
		$("#services .service.current").addClass("on");
		
		$("#services .service a").click(function() {
			window.location.hash = $(this).attr("href"); // Add service's URL as a hash
			
			var par = $(this).closest(".service"); // Get the service's wrapper

			// If the clicked service panel is closed...
			if (!$(par).hasClass("on")) {
				$("#services :animated").stop(true, true); // Stop current animations!
				$(par).addClass("on").siblings().removeClass("on");
				$(".service-content").animate({opacity: 0}, 100).slideUp(200, function() {
					$(par).find(".service-content").slideDown(200, function() {
						$(this).animate({opacity: 1});
					});
				});
			}
			return false;
		});
	}
	

	/**
	 * Portfolio Grid
	 * -------------------------
	 */
	 
	if (!isMSIE) {
		// Fade Toggle the project info on hover
		$("#portfolio-thumbs li").hover(
			function () {
				$(this).find('.folio-over').stop().fadeTo(200, 1);
			},
			function () {
				$(this).find('.folio-over').stop().fadeTo(200, 0);
			}
		).find(".folio-over").css("opacity", 0);
	} else {
		// In IE we just use a simple slide toggle; IE no like animating opacity
		$("#portfolio-thumbs li").hover(
			function () {
				$(this).find('.folio-over').slideToggle(200);
			}
		).find(".folio-over").hide();	
	}

	
	/**
     * Form Validation
     * =============================
     */
	 
	// E-mail regex validation
	function checkEmail(email) {
		var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var emailTest = $(email).val();
		return regex.test(emailTest);
	}
	
	$("form").live("submit", function(e) {
		var form = $(this);
		var clicker = form.find("input[type=submit]");
		
		clicker.attr("disabled", "disabled"); // Disable the submit button
		
		// Run through each input to make sure it has a value
		form.find("input, textarea").each(function(){
			if (!$(this).val() && $(this).attr("name") !== "tel") { // Tel No. isn't required!
				$(this).addClass("error"); // Add the error class if it's invalid
			} else {
				$(this).removeClass("error");	
			}
			
			// Run the Email field through our e-mail validation regex
			if (!checkEmail($("#email"))) {
				$("#email").addClass("error");	
			}
		});
		
		// If there's any invalid fields; enable the button and stop submission
		if (form.find(".error").length) {
			clicker.removeAttr("disabled");
			e.preventDefault();
		} else {
			// If the form is ok; show the user it's being sent
			clicker.animate({opacity: 0.5}, 100).addClass("sending");
		}
	});

	// Once an errored field has been filled and lost focused, clear the error
	$(".error").live("blur", function() {
		if ($(this).val()) {
			$(this).removeClass("error");
		}
	});
	
	// On load, if there are values in the fields; hide the placeholders
	$("input[type=text], textarea").each(function() {
		if ($(this).val()) {
			$(this).prev("label").hide();
		}
	});

	// Some fancy placeholder stuff!
	$("input, textarea").focus(function() {
		// Make the placeholder semi-opaque when a field gets focus
		if (!isMSIE) {
			$(this).prev("label").animate({opacity: 0.3}, 200);
		} else {
			// IE doesn't like opacity on transparent backgrounds, just hide it
			$(this).prev("label").hide();
		}
	}).blur(function() {
		// Bring the placeholder back to full opacity on loss of focus
		if (!isMSIE) {
			$(this).prev("label").animate({opacity: 1}, 200);
		} else if (!$(this).val()) {
			$(this).prev("label").show();
		}
	}).keyup(function() {
		/*
		 * We don't want the labels to dissapear if a user enters space, or
		 * hits an arrow key in the field so trim whitespace from input
		 */
		var txt = jQuery.trim($(this).val());
		
		txt = txt.length;
		if (txt) {
			// If we know there's text in the field, hide the placeholder
			$(this).prev("label").hide();
		} else {
			// We're still focused in the field so semi-opaque the label
			$(this).prev("label").show().css("opacity", 0.3);
		}
	});
	
	
	/**
     * jQuery Cycle Plugin
     * =============================
     * Get it at http://jquery.malsup.com/cycle/
     */

	$("#slider-image").cycle({
		fx: 'scrollHorz',
		speed: 900,
		timeout: 4000,
		pager: '.slider-nav',
		easing: 'easeOutExpo',
		pagerAnchorBuilder: function(idx, slide) { 
			return '<li><a href="#"></a></li>';
		} 
	}).hover(function() {
    	$(this).cycle('pause'); 
	}, function() {
		$(this).cycle('resume'); 	
	});
	
	/**
	 * Projects Panels
	 * -------------------------
	 */
	var startingSlide = $("#projects .current").index();
	var cycleStarted = false;
	
	$('#projects').cycle({ 
		fx: 'scrollHorz', 
		startingSlide: startingSlide,
		timeout:  0, 
		speed:    500,
		prev:    '#last-project', 
		next:    '#next-project',
		before: function(curr, next, opts) {
			if (cycleStarted) {
				// Set the window hash to the next project's shortcode
				var thisLink = $("#projects").children().eq(opts.nextSlide).attr("data-project-link");
				window.location.hash = thisLink;
			}
			cycleStarted = true;
		},
		after:   function(curr, next, opts) {
			var id = opts.currSlide;
			var prev = id - 1;
			
			/*
			 * The previous slide's index isn't provided by Cycle
			 * If the prev counter reaches 0, set prev to the last slide index
			 */ 
			if (prev < 0) {
				prev = opts.slideCount - 1;	
			}
			
			/* Get the shortcode's from the next + previous panels and apply
			 * them to the prev/next buttons
			 */ 
			var nextLink = $("#projects").children().eq(opts.nextSlide).attr("data-project-link");
			var prevLink = $("#projects").children().eq(prev).attr("data-project-link");
			$("#last-project").attr("href", prevLink);
			$("#next-project").attr("href", nextLink);
			
			$.getJSON('/xhr.php?a=images&id='+id, displayImages);  // Grab the images associated to this project
		}			
	}); 
	
	// We get a JSON array of images to display
	function displayImages(data) {
		// If this project doesn't already have images loaded...
		if (!$(".project-wrapper:visible .project-slider-image").children().length || $(".project-wrapper:visible .project-slider-image li:first").hasClass("gen")) {
			$(".project-wrapper:visible .project-slider-image, .project-wrapper:visible .slider-nav").html("");
			
			// Parse through the array and append the images
			$.each(data.data.images, function(i, item) {
				$(".project-wrapper:visible .project-slider-image").append("<li><img src=\""+item+"\" alt=\"\" /></li>");
			});
	
			// If there's more than 1 image to display, start a new Cycle
			if (data.data.images.length > 1) {
				$(".project-wrapper:visible .project-slider-image").cycle({
					fx: 'fade',
					speed: 900,
					timeout: 4000,
					pager: $(".project-wrapper:visible .slider-nav"),
					easing: 'easeOutExpo',
					pagerAnchorBuilder: function(idx, slide) { 
						return '<li><a href="#"></a></li>';
					} 
				}).hover(function() {
					$(this).cycle('pause'); 
				}, function() {
					$(this).cycle('resume'); 	
				});
			}
	
		}
	}
});
