// define these out here so flash can get to them
var disableSlider, enableSlider;

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();


$(document).ready(function() {
	// get this out of the way first because it creates elements, and we want to call our PNG fix once the document is finalized
	if ($(".slider").length) {	
		var sliderEnabled = true;
		var sliderHover = false;
		
		// we need this click handler to execute before the default click, so that .active is properly set
		// jQuery will execute handlers in the order in which they were added, so quickfix is we add this first
		$(".slider .next, .slider .previous").click(function() {
			stopCarousel();
			sliderEnabled = true;
			try {
				$(".slider .active .flash")[0].pauseMovie();
			} catch (e) {}
			startCarousel();
		});		
		
		// create the carousel
		$(".slider .stage").carousel(".slider .previous", ".slider .next");
		var intCarousel = null;
		function startCarousel() {
			if (sliderHover == true) {
				return false;
			}
			clearInterval(intCarousel);
			intCarousel = setInterval(function (){
				$(".slider .next").trigger("click");
			}, 6000);
		}
		function stopCarousel() {
			clearInterval(intCarousel);
			intCarousel = null;		
		}
		
		// disable the advancing when hovering
		$(".slider").mouseover(function(){
			sliderHover = true;
			stopCarousel();
		});
		$(".slider li").mouseout(function(){
			sliderHover = false;
			if (sliderEnabled && intCarousel == null) {
				startCarousel();
			}
		});
		
		// start the auto-advancing, but give it a little extra time at the beginning
		setTimeout(function() {
			startCarousel();
		}, 2000);
		
		// this is for use with flash movies
		disableSlider = function() {
			sliderEnabled = false;
			stopCarousel();
		}
		enableSlider = function() {
			sliderEnabled = true;
			startCarousel();
		}
	}
	
	// all the dynamic items are added by this point, we can fix the PNGs
	if ((typeof(ddSelector) !== "undefined")) {
		DD_belatedPNG.fix(ddSelector);	
	}	
	
	// set up fancybox -- how we display the fancybox depends on what page we're on, so figure that out first
	var fancyClose = true;
	var fancyClickClose = false;
	
	// this allows us to filter out the border if we want
	function setFancyBorder(currentIndex) {
		if ($("a.fancyLink:eq(" + currentIndex + ")").hasClass("noFancyBorder")) {
			$("#fancybox-img").addClass("noBorder");
		} else {
			$("#fancybox-img").removeClass("noBorder");
		}
	}
	
	// we'll stop the slideshow while the fancybox is open
	function fancyStarted() {
		if (typeof(disableSlider) !== "undefined") {
			disableSlider();
		}
	}
	function fancyClosed() {
		if (typeof(enableSlider) !== "undefined") {
			enableSlider();
		}
	}
	var fancyTitle = function(title, currentArray, currentIndex, currentOpts) {
		setFancyBorder(currentIndex);
		return title;
	}
	
	if (currentPage == "work/case-studies/american-cancer-society" ||
		currentPage == "work/case-studies/comcast-espanol" ||
		currentPage == "work/case-studies/grocery-outlet" ||
		currentPage == "work/case-studies/jarden-corporation" ||
		currentPage == "work/case-studies/michael-c-fina") {
		
		fancyClose = false;
		fancyClickClose = true;
	}
		
	if (currentPage == "work") {
		fancyClose = false;
		fancyTitle = function(title, currentArray, currentIndex, currentOpts) {
	
			setFancyBorder(currentIndex);
		
			// format the title based on the fancy link's image alt
			title = $("a.fancyLink:eq(" + currentIndex + ") img").attr("alt");
			if (typeof(title) != "undefined" && title != "") {
				title = "<div>" + title + "</div>";
			} else {
				title = "";
			}
			// add the gallery index and close button
		    return title + "<div class=\"hr\"><hr /></div><div>Image " + (currentIndex + 1) + " of " + currentArray.length + "<a href=\"#\" class=\"right\" onclick=\"$.fancybox.close(); return false;\">Close</a></div>";		
		}		
	}
	
	// wire up fancybox to fancyLinks
	$("a.fancyLink").fancybox({
		padding: "12px",
		titlePosition: "inside",
		overlayColor: "#000",
		overlayOpacity: .6,
		titleFormat: fancyTitle,
		showCloseButton: fancyClose,
		hideOnContentClick: fancyClickClose,
		onClosed: fancyClosed,
		onStart: fancyStarted
	});
	
	// if there are fancybox links on the page, check the querystring to see if we're supposed to load with a fancybox opened
	if ($("a.fancyLink").length) {
		if (urlParams["fb"]) {
			$("#" + urlParams["fb"]).trigger("click");
		}
	}
	
	// little effect for thumbnail description
	$(".thumbLink").hover(function() {
		$(".desc", $(this))
			.stop(true, false).animate({"height": 30}, "fast");
	}, function() {
		$(".desc", $(this))
			.stop(false, false).animate({"height": 0}, "fast");
	});
	$(".fancyLink").click(function() {
		$(".desc", $(this))
			.stop().css({"height": "0px"});
	});
	
	// effect to cycle through a list of items	
	if ($(".fader").length) {
		var intFader = null;
		function startFader() {
			intFader = setInterval(function (){
				var current = $(".fader .active");
				var next = current.next();
				if (next.length == 0) {
					next = $(".fader li:first");
				}
				current.fadeOut("slow", function() {
					current.removeClass("active");
					next.addClass("active").fadeIn("slow");
				});
			}, 8000);
		}
		$(".fader").mouseover(function(){
			clearInterval(intFader);
			intFader = null;
		});
		$(".fader").mouseout(function(){
			if (intFader == null) {
				startFader();
			}
		});
		
		// determine the necessary height to accomodate the tallest fader item, this prevents jumping content
		var maxHeight = 0;
		$(".fader li").each(function(i, item) {
			var liHeight = $(item).outerHeight();
			if (liHeight > maxHeight) {
				maxHeight = liHeight;
			}
		});
		$(".fader").css({
			"height": maxHeight + "px"
		});
		
		var count = $(".fader li").length;
		var random = Math.floor(Math.random() * count);		
		$(".fader li:eq(" + random + ")").addClass("active");
		
		$(".fader li").not(".active").hide();
		
		startFader();
	}
	
	// wire up flash objects
	if ($("#flashHolder").length) {
	
		// add the PAL flash header to the page
		if ($(".flashAltPAL").length) {
			var flashvars = {};
			var params = {
				"allowScriptAccess": "sameDomain",
				"wmode": "transparent"
			};
			var attributes = {
				"class": "flash rawContent"
			};
			swfobject.embedSWF("/assets/flash/pal-hero.swf", "flashHolder", "950", "290", "9.0.0", "/assets/flash/expressInstall.swf", flashvars, params, attributes);
		}
	
		// add the map to the contact pages			
		if ($(".flashAltContact").length) {
			var flashvars = {};
			var params = {
				"allowScriptAccess": "sameDomain"
			};
			var attributes = {
				"class": "flash rawContent"
			};
			swfobject.embedSWF("/assets/flash/contact-hero.swf", "flashHolder", "950", "290", "9.0.0", "/assets/flash/expressInstall.swf", flashvars, params, attributes);
		}
	}
	
	
	
	if (currentPage == "about/jobs") {
		$(".more").click(function(e) {
			var moreLink = $(e.target);
			var job = moreLink.closest(".job");
			var index = $(".job").index(job);

			var fullDesc = $(".job .full:eq(" + index + ")");
			if (fullDesc.is(":visible")) {
				moreLink.html("see full listing");
				fullDesc.hide();
			} else {
				moreLink.html("hide full listing");
				fullDesc.show();
			}
			return false;
		});
		// hide the full descriptions initially
		$(".job .full").hide();
	}
	if (currentPage == "work/pal") {
		if ($(".error").length) {
			$("html").scrollTop($("#palFeedbackBlock").offset().top-20);
		}
	}
	
	if ($(".galleryWidget").length) {
	
		// height calculations don't work on objects that aren't in the document
		$(".needJS").css({
			visibility:"hidden",
			position:"absolute"
		}).show();

		// add navigation for the portfolio items
		$(".section .gallery").each(function(i, item) {
			var pager = $("<div class=\"right pager\"></div")
			var gallery = $(item);
			var childCount = gallery.children().length;
			for (var j = 0; j < childCount; j++) {
				pager.append("<img src=\"/assets/images/blank.gif\" />");
			}
			
			$("img:first", pager).addClass("active");
			pager.prepend($("<span>Sample:</span>"));
			var overviewLink = $(".overviewBase").clone().removeClass("overviewBase").addClass("overviewLink");// $("<a href=\"#\" class=\"left button overviewLink\">Full Portfolio</a>");
			var nav = $("<div class=\"nav block\"></div>");			
			nav.append(overviewLink);
			nav.append(pager);
			
			gallery.before(nav);
		});
		
		// determine the necessary height to accomodate the tallest fader item, this prevents jumping content
		var maxHeight = $(".overview").outerHeight();

		// in order to determine the max height, we'll float our items to the left 
		// rather than trying to compute the height of each and add it to the introductory paragraph
		$(".section .gallery").css({
			width:"32000px"
		});
		
		$(".section .gallery li").addClass("active").css({
			float:"left",
			position:"relative",
			overflow:"hidden"
		});
		$(".section").each(function(i, item) {
			var sectionHeight = $(item).outerHeight();
			if (sectionHeight > maxHeight) {
				maxHeight = sectionHeight;
			}
		});
		
		
		// apply the height to the main ui holder
		$(".holder").css({
			"height": maxHeight + "px"
		});
		
		// return the list items to their default
		$(".section .gallery li").removeClass("active").css({
			float:"",
			position:"",
			overflow:""
		});
		$(".section .gallery").css({
			width:""
		});
		
		$(".section .gallery li:first-child").addClass("active");		


		// wire up events
		$(".thumbLink").click(function() {
			var index = $(".thumbLink").index(this);

			$(".section:eq(" + index +")").addClass("active");

			// reset the portfolio to start at the first one
			$(".section:eq(" + index + ") .pager img").removeClass("active");
			$(".section:eq(" + index + ") .gallery li").removeClass("active").hide();
			$(".section:eq(" + index + ") .pager img:first").addClass("active");
			$(".section:eq(" + index + ") .gallery li:first").addClass("active").show();		
			
			$(".holder").animate({
				left:"-620"
			}, "slow", function() {
				//complete;
			
				
				enablePortfolio();
			});
			return false;
		});
		$(".overviewLink").click(function() {
			disablePortfolio();
			$(".holder").animate({
				left:"0"
			}, "slow", function() {
				$(".section").removeClass("active");
			});
			return false;
		});
				
		
		$(".section .pager img").click(function() {
			stopPortfolio();
			
			var selected = $(this);
			var pager = selected.closest(".pager");
			var index = $("img", pager).index(selected);

			var gallery = pager.parent().siblings(".gallery")
			var next = $(gallery.children()[index]);

			// make sure we're not animating
			if ($(".outgoing").length == 0) {
				
				var current = $(".active", gallery);
				var currentIndex = $("li", gallery).index(current);
				// make sure it's not the same link that's been clicked
				if (index != currentIndex) {

					$("img", pager).removeClass("active");
					selected.addClass("active");
		
					// perform crossfade
					next.addClass("incoming").fadeIn("slow", function() {
						$(".incoming").removeClass("incoming").addClass("active");
					});
					current.addClass("outgoing").fadeOut("slow", function() {
						$(".outgoing").removeClass("outgoing active");
					});
				}
			}

			startPortfolio();
			return false;
		});
		
		
		// create the portfolio gallery

		var intPortfolio = null;
		var portfolioEnabled = false;
		var portfolioHover = false;
		function startPortfolio() {
			if (portfolioEnabled == false || portfolioHover == true) {
				return false;
			}
			clearInterval(intPortfolio);
			intPortfolio = setInterval(function (){
				advancePortfolio();
			}, 6000);
		}
		
		function advancePortfolio() {
			var next = $(".section.active .pager img.active").next();
			if (next.length == 0) {
				next = $(".section.active .pager img:first");
			}
			
			next.trigger("click");
		}
		
		$(".gallery li img").click(function() {
			advancePortfolio();
		});		
		
		function stopPortfolio() {
			clearInterval(intPortfolio);
			intPortfolio = null;		
		}
		
		// disable the advancing when hovering
		$(".gallery").mouseover(function(){
			portfolioHover = true;
			stopPortfolio();
		});
		$(".gallery li").mouseout(function(){
			portfolioHover = false;
			if (intPortfolio == null) {
				startPortfolio();
			}
		});
		
		function enablePortfolio() {
			portfolioEnabled = true;
			startPortfolio();
		}
		function disablePortfolio() {
			portfolioEnabled = false;
			stopPortfolio();
		}

		// see if we're supposed to load with a portfolio piece selected
		if (urlParams["show"]) {
			$("#" + urlParams["show"]).addClass("active");
			
			$(".holder").css({
				left:"-620px"
			});
			enablePortfolio();
		}

		
		$(".needJS").css({
			visibility:"visible",
			position:"relative"
		});
	}
	
	$("#emailForm").submit(function(){
		var firstnameVal = $("#first_name").val();
		var lastnameVal = $("#last_name").val();
		var companyVal = $("#company").val();
		var titleVal = $("#title").val();
		var emailVal = $("#email").val();	
		var cityVal = $("#city").val();
		var stateVal = $("#state").val();
		var zipVal = $("#zip").val();
		var phoneVal = $("#phone").val();

		var valid = true;
		var errorMessage = "";
		
		var errors = {};
		
		if (firstnameVal.length == 0) {
			errors["first_name"] = "Required";
			valid = false;
		}
		
		if (lastnameVal.length == 0) {
			errors["last_name"] = "Required";
			valid = false;
		}	
		
		if (companyVal.length == 0) {
			errors["company"] = "Required";
			valid = false;
		}		

		if (titleVal.length == 0) {
			errors["title"] = "Required";
			valid = false;
		}		

		if (emailVal.length == 0) {
			valid = false;
			errors["email"] = "Required";
		} else {
			var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
			if (emailVal.search(isEmail_re) == -1) {
				valid = false;
				errors["email"] = "Invalid Email";
			}
		}
		
		if (cityVal.length == 0) {
			errors["city"] = "Required";
			valid = false;
		}
		
		if (stateVal.length == 0) {
			errors["state"] = "Required";
			valid = false;
		}
		
		if (zipVal.length == 0) {
			errors["zip"] = "Required";
			valid = false;
		}		
		
/*		
		var stripped = phoneVal.replace(/[\(\)\.\-\ ]/g, '');
		//strip out acceptable non-numeric characters
	
		if (phoneVal.length == 0 || (isNaN(parseInt(stripped))) || (!(stripped.length == 10))) {
			valid = false;
			errors["phone"] = "10 digit phone number required";
		}	
*/		
		
		if (!valid) {
			$("#errorMessage").html("<p>Please correct the errors in your form.</p>");
			$("#emailForm").addClass("error");
			
			$.each(errors, function(key, value) {
				$(".error-" + key).html(value);
			});
		}
		
		return valid;
	
	});
	
	
	$(".needJS").removeClass("needJS").addClass("hasJS");
});	

