$(document).ready(function() {

	$("#s").click(function() {
		if ( $("#s").val() == 'Search...') {
			$("#s").val('');
		}
	});
	
	$("#s").blur(function() {
		if ( $("#s").val() == '') {
			$("#s").val('Search...');
		}
	});
	
	$(".tooltip .close").click(function() {
		$(this).parent().fadeOut();
		return false;
	});

	$("#social-twitter").click(function() {
		$(this).next().fadeIn();
	});
	
	$("#social-facebook").click(function() {
		$(this).next().fadeIn();
	});
	
	/*$("#social-youtube").tooltip({ 
		effect: 'slide',
		slideOffset: 20
	});
	$("#social-rss").tooltip({ 
		effect: 'slide',
		slideOffset: 20
	});*/

	$("#common-questions ul li a").click(function() {		
		searchText = $(this).text();		
		$("#ask-us-anything").val(searchText);
		performSearch();
	});
	
	if (window.location.hash) {
		
		var hashTag = window.location.hash.substr(2);

		if (hashTag.substr(0,6) == "search") {
			
			searchString = hashTag.substr(7);
			
			performSearch(searchString);
			
		} else {

			if (hashTag.substr(-1) == "/") {
				var hashTagLength = hashTag.length;
				hashTag = window.location.hash.substr(-hashTagLength);
			}

			if ( $("article#"+hashTag).length ) {
			
				var currentSlideId = $("article.active").attr('id');

				var currentSlide = $("article.active");
				var newSlide = $("article#"+hashTag);

				goto_slide(currentSlide, newSlide, currentSlideId, true);
		
			}
			
		}
		
	}
	
	function next_slide() {
		
		var currentSlideId = $("#feature-wrap article.active").attr('id');		
		var currentSlide = $("#feature-wrap article.active");
				
		var firstSlide = $("#feature-wrap article").first();
		
		var lastSlideId = $("#feature-wrap article").last().attr("id");
		
		if (lastSlideId == currentSlideId) {
			var nextSlide = $("#feature-wrap article").first();
		} else {
			var nextSlide = currentSlide.next();
		}
		
		var nextSlideId = nextSlide.attr('id');
		
		var currentLink = $("#feature-nav ul li a.active");
		var newLink = $("#feature-nav ul li a[rel="+nextSlideId+"]");
		
		currentLink.removeClass("active");
		newLink.addClass("active");

		goto_slide(currentSlide, nextSlide, currentSlideId);
		
		return false;		
		
	}
	
	function goto_slide(currentSlide, newSlide, currentSlideId, quick) {
		if (quick) {

			currentSlide.hide();
		
			currentSlide.removeClass("active");
			newSlide.fadeIn();
			newSlide.addClass("active");
		
			if (currentSlideId == "slide-1") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/demo-reel-cover.jpg" class="cover-image" id="demo-reel" />');
			} else if (currentSlideId == "slide-2") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/daod-cover.jpg" class="cover-image" id="digi" />');
			/*} else if (currentSlideId == "slide-2") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/redress_remix_cover.jpg" class="cover-image" id="redress-remix" />');*/
			} else if (currentSlideId == "slide-3") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/moderation-town-cover.jpg" class="cover-image" id="moderation-town" />');
			} else if (currentSlideId == "slide-4") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/daod-cover.jpg" class="cover-image" id="daod" />');
			} else if (currentSlideId == "slide-5") {
				currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/tedx-cover.jpg" class="cover-image" id="tedx" />');
			} 
		
		} else {
		
			currentSlide.fadeOut(function() {
		
				currentSlide.removeClass("active");
				newSlide.fadeIn();
				newSlide.addClass("active");
			
				if (currentSlideId == "slide-1") {
					currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/demo-reel-cover.jpg" class="cover-image" id="demo-reel" />');
				} else if (currentSlideId == "slide-2") {
					currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/daod-cover.jpg" class="cover-image" id="digi" />');
				/*} else if (currentSlideId == "slide-2") {
						currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/redress_remix_cover.jpg" class="cover-image" id="wma" />');*/
				} else if (currentSlideId == "slide-3") {
					currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/moderation-town-cover.jpg" class="cover-image" id="moderation-town" />');
				} else if (currentSlideId == "slide-4") {
					currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/daod-cover.jpg" class="cover-image" id="daod" />');
				} else if (currentSlideId == "slide-5") {
					currentSlide.children(".feature-item-content").html('<img src="http://www.stitchmedia.ca/assets/images/slider/tedx-cover.jpg" class="cover-image" id="tedx" />');
				}
		
			});
			
		}
		
		return false;
	}
	
    var timer = '';
	var count = '0';
	var stopTimer = false;
	
    function pauseSlider() { 
		clearInterval(timer);
    }
    function resumeSlider() { 
      	timer = setInterval(counter, 1000);
    }

    function counter() {
		var currCount = count;
      	if(currCount == 5) {
			//alert("Next Slide");
			next_slide();
        	currCount = 0;
		} else {
      		currCount++;
		}
		var progress = currCount / 5;
		progress = progress * 100;
		$('#feature #feature-nav-progress').animate({
			width: progress+'%',
		}, 750, function() {
			    // Animation complete.
		});
      	count = currCount;
    }

    window.onload = function(){
		if ( $("section#home").length ) {
      		timer = setInterval(counter, 1000);
		}
    }
	
	$(".cover-image").live('click', function() {
		
		stopTimer = true;
		
		var coverId = $(this).attr('id');
		
		if (coverId == "moderation-town") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/YVymrYjRNQs?autoplay=1" frameborder="0" allowfullscreen></iframe>');
		} else if (coverId == "digi") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/vxYdU51W0fI?autoplay=1" frameborder="0" allowfullscreen></iframe>');
		/*} else if (coverId == "wma") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/VXjH4qLKnI8?autoplay=1" frameborder="0" allowfullscreen></iframe>');*/
		} else if (coverId == "demo-reel") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/VXjH4qLKnI8?autoplay=1" frameborder="0" allowfullscreen></iframe>');
		} else if (coverId == "daod") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/vxYdU51W0fI?autoplay=1" frameborder="0" allowfullscreen></iframe>');
		} else if (coverId == "tedx") {
			$(this).parent().html('<iframe title="YouTube video player" width="570" height="351" src="http://www.youtube.com/embed/yVkW-yvWbZE?autoplay=1" frameborder="0" allowfullscreen></iframe>');
		}
		
	});		
	
	$("#feature-nav ul li a").click(function(e) {
		
		$('#timer').html(0);
		
		$('#feature #feature-nav-progress').animate({
			width: 0,
		}, 250, function() {
			    // Animation complete.
		});
      	
		if ( $(this).attr('class') != 'active') {
			var newSlideId = $(this).attr('rel');
			var currentSlideId = $("#feature-wrap article.active").attr('id');
			
			var currentSlide = $("#feature-wrap article.active");
			var newSlide = $("#feature-wrap #"+newSlideId);
			var currentLink = $("#feature-nav ul li a.active");
			var newLink = $(this);
		
			currentLink.removeClass("active");
			newLink.addClass("active");
			
			goto_slide(currentSlide, newSlide, currentSlideId);					
		}
		
		return false;
	});

	$("#team #feature-thumbs section.feature-thumb").click(function() {
		      	
		var newSlideId = $(this).attr('rel');
		var currentSlideId = $("#team article.active").attr('id');
		
		var currentSlide = $("#team article.active");
		var newSlide = $("#team #"+newSlideId);

		window.location.hash = '/'+newSlideId; 
	
		goto_slide(currentSlide, newSlide, currentSlideId);
		
	});

	$("#feature #feature-thumbs section.feature-thumb").click(function() {

		var newSlideId = $(this).attr('rel');
		var currentSlideId = $("#feature article.active").attr('id');
		
		var currentSlide = $("#feature article.active");
		var newSlide = $("#feature #"+newSlideId);
	
		goto_slide(currentSlide, newSlide, currentSlideId);

		window.location.hash = '/'+newSlideId; 
		
		return false;

	});
	
	$("#home #feature-wrap").mouseover(function() {
		pauseSlider();
	});

	$("#home #feature-wrap").mouseout(function() {
		if (stopTimer = false) {
			resumeSlider();
		}
	});
	
	$("#ask-us-anything").focus(function() {
		if ($(this).attr('value') == 'ask us anything...') {
			$(this).attr('value','');
		}
		$(this).animate({
			backgroundColor: '#ddd'
		}, 300, function() {
		    // Animation complete.
		});
	});
	$("#ask-us-anything").blur(function() {
		if ($(this).attr('value') == '') {
			$(this).attr('value','ask us anything...');
		}
		$(this).animate({
			backgroundColor: '#fff'
		}, 300, function() {
		    // Animation complete.
		});
	});
			
	$("#ask-us-anything").keypress(function(e){
		if(e.which == 13) {
			performSearch();
		}
	});
	
	$("#enter-email").live('focus', function() {
		if ($(this).attr('value') == 'Enter your email') {
			$(this).attr('value','');
		}
		$(this).animate({
			backgroundColor: '#ddd'
		}, 300, function() {
		    // Animation complete.
		});
	});
	$("#enter-email").live('blur', function() {
		
		if ($(this).attr('value') == '') {
			$(this).attr('value','Enter your email');
		}
		$(this).animate({
			backgroundColor: '#fff'
		}, 300, function() {
		    // Animation complete.
		});
	});
			
	$("#enter-email").live('keypress', function(e){
		if(e.which == 13) {
			addQuestion();
		}
	});
	
	$("#go-button").click(function() {
		performSearch();		
	});

	$("#ask-question h4 a").live('click', function() {
		$("#common-questions").slideDown();
		$("#ask-question h4").html('What are some common questions?');		
	});
	
	function urlifySearchString(string) {

		string = string.toLowerCase();
		string = string.replace(/%20/g,"-");
		
		return string;
	}
	
	/**
	 * Main search function
	 */	
	function performSearch(searchString) {
		
		/** 1. Fade out the "return to search" column, even if it doesn't exist */
		$("#search-results .carbon .content .lefter").fadeOut('fast', function() {
			
			/** 2. Get the value of the search box */
			if (searchString) {
				var searchText = searchString;
				searchText = searchText.replace(/-/g," ");
			} else {
				var searchText = $("#ask-us-anything").attr('value');
			}
			searchText = escape(searchText);
			var searchTextEscaped = searchText.replace(/<\/?[^>]+(>|$)/g, "");
			var showLeft;
		
			var urlifiedString = urlifySearchString(searchTextEscaped);
			
			window.location.hash = "/search/"+urlifiedString;
			
			/** 3. Hit this up with some Ajax */
			$.ajax({
				type: "GET",
				url: "/ajax.php",
				data: "searchText="+searchTextEscaped,
	        	dataType: "json",			
				success: function(data) {

					/** 4. If the Ajax query was successful */
					if (data.result == "success") {	
						
						/** 5. Is the content an URL? If yes, redirect the page */
						if ( CheckValidUrl(data.content) ) {
							$("#search-results .carbon .content").slideUp();
							window.location = data.content;							
						} else {					
							
							/** 5. Nope, not a URL. Let's show some content */
							$("#search-results .carbon .content .left").html(data.sidebar);
							$("#search-results .carbon .content .left").fadeIn();
							$("#search-results .carbon .content .right").html(data.content);

							/** 6. Check for sidebar content to determine page height */							 
							if ( $("#search-results .carbon .content .left").html() == "") {
								showLeft = 1;
							} else {
								showLeft = 0;
							}

							/*
							if ($('.feature-item-content').length) {
								$(".feature-item-content").hide();
							}
							*/
							
							/** 6.5? Added to make common questions slide up */							
							$("#common-questions").slideUp();
							$("#ask-question h4").html('<a href="#">What are some common questions?</a>');
							
							/** 7. Slide up the page body, and get on with the search results */
							$("#body").slideUp(500, function() {
								
								/** 8. if the content is visible, reset the height to zero so it slides properly */
								if ( !$("#search-results .carbon .content").is(":visible") ) {
									$("#search-results .carbon .content").show();
									$("#search-results .carbon .content").height('0px');
								}

								/** 9. If there is a sidebar, our height needs to be at least 350px */
								if (showLeft == 0) {						
									var newHeight = '350px';
								} else {
									var newHeight = $(".carbon .content .right").height() + 32;
								}
								
								/** 10. Let's make our search div our final height so our user can see the content */
								$("#search-results .carbon .content").animate({
									height: newHeight
								}, 500, function() {
									$('#search-results #close-search').html('Close Search &raquo;');
								    $('#search-results #close-search').fadeIn();
								});
												
							});
						}
					
					/** 4. The Ajax query was unsuccessful, show the error */					
					} else {
						showError( data.code, data.message );
					}
				}
			});
		});
	}
	
	$("#return-to-search").live('click', function() {
		performSearch();
	});
	
	$("#search-results .answered-question").live('click', function() {
		$("#search-results .carbon .content .left").fadeOut(function() {
			$("#search-results .carbon .content .lefter").html('<a id="return-to-search">&laquo; Return to search results</a>');
			$("#search-results .carbon .content .lefter").fadeIn();
		});		
		$(this).removeClass('answered-question');
		$(this).addClass('disabled-answered-question');
		var thisElement = $(this);
		var thisNextElement = $(this).parent().next();
		var questionId = $(this).attr('id');

		$("#search-results .carbon .content .right").html('');
		
			$.ajax({
				type: "POST",
				url: "/ajax.php",
				data: "questionId="+questionId,
	        	dataType: "json",
				success: function(data) {
					
					if (data.result == "success") {
						if ( CheckValidUrl(data.content) ) {
							$("#search-results .carbon .content").slideUp();
							window.location = data.content;
						} else {
							thisElement.parent().addClass('answer-header');
							$("#search-results .carbon .content .right").html(data.content);
							thisNextElement.css("opacity",0);
							thisNextElement.animate({
								height: 'toggle'
							}, 100, function() {
							    // Animation complete.					
								var newHeight = $("#search-results .carbon .content .right").height();
								newHeight = newHeight + 32;
								$("#search-results .carbon .content").animate({
									height: newHeight
								}, 300, function() {
								    // Animation complete.
									thisNextElement.animate({
										opacity: 1
									}, 300, function() {});
								});
							});
						}
					} else {
						showError( data.code );
					}
				}			
			});
		
		});
		
	});

	/**
	 * Close the search box
	 */
	$("#search-results #close-search").live('click', function() {
		/** 1. fade out clicked link */
		$('#search-results #close-search').fadeOut(function() {
			/** 2. slide up main search content box */
			$('#search-results .carbon .content').slideUp(function() {
				/** 3. Show the appropriate content */					
				$("#body").slideDown(500);
				$("#common-questions").slideDown();
			});
		});
	});

	/**
	 * Add question email form
	 */
	$("#answer-me").live('click', function() {
		addQuestion();
	});

	/**
	 * Add question function
	 */	
	function addQuestion() {
		
		var userQuestion = $('#enter-question').val();
		var userEmail = $('#enter-email').val();
		
		userEmail = escape(userEmail);
		var userEmailEscaped = userEmail.replace(/<\/?[^>]+(>|$)/g, "");

		userQuestion = escape(userQuestion);
		var userQuestionEscaped = userQuestion.replace(/<\/?[^>]+(>|$)/g, "");
		
		$.ajax({
			type: "GET",
			url: "/ajax.php",
			data: "addQuestion="+userQuestionEscaped+"&userEmail="+userEmailEscaped,
        	dataType: "json",			
			success: function(data) {

				if (data.result == "success") {
					$("#search-results .carbon .content .left").fadeOut();
					$("#search-results .carbon .content .right").html('<h2 class="answer-header">Thank you for your question!</h2><p>Our team has been notified about your question, and we&rsquo;ll get to it as soon as possible. You will be notified by email when it has been answered.</p>');
					
					var newHeight = $("#search-results .carbon .content .right").height() + 32;

					$("#search-results .carbon .content").animate({
						height: newHeight
					});
					
				} else {
					showError( data.code, data.message );
				}
				
			}
		});
		
	}

	/**
	 * Show were function
	 */		
	function showError(code, message) {
		
		$("#body").slideUp(500, function() {
			
			// if the content is already visible, no reset height
			if ( !$("#search-results .carbon .content").is(":visible") ) {
				$("#search-results .carbon .content").show();
				$("#search-results .carbon .content").height('0px');
			}
			
			if (!message) {
				message = "";
			}

			$("#search-results .carbon .content .right").html('<h2 class="answer-header">Something went wrong!</h2><p>Error Code: '+code+'</p><p>'+message+'</p>');

			var newHeight = $("#search-results .carbon .content .right").height() + 32;
			
			$("#search-results .carbon .content").animate({
				height: newHeight
			}, 500, function() {
			    $('#search-results #close-search').fadeIn();
			});

			$("#search-results .carbon .content .left").fadeOut();
			$("#search-results .carbon .content .lefter").fadeOut();
			$("#search-results .carbon .content .right").fadeIn();
			
		});
		
	}

	function CheckValidUrl(strUrl) {
		var v = new RegExp();
		v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%#&\?\/.=]+$");
		return v.test(strUrl);
	}
