/*global $, document, window */
Cufon.set('fontFamily', 'aqua');
Cufon.replace('.bodycontent h1');


function isNumeric(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function getUrlVars(url) {
	var obj = {},
		hashes = url.slice(url.indexOf('?') + 1).split('&'),
		hash,
		i;
	for (i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		obj[hash[0]] = (isNumeric(hash[1])) ? parseFloat(hash[1]) : hash[1];
	}
	return obj;
}

function checkImageDimensions() {
	
	var w = $(this).width(),
		h = $(this).height();

	if (w === h) {
		$(this).addClass('equal');
	} else if (w > h) {
		$(this).addClass('wide');
	} else if (w < h) {
		$(this).addClass('tall');
	}

}

function initImageSlider(properties) {

	'use strict';

	var galleryImageHolder = $(properties.elmImagesHolder),
		galleryImages = galleryImageHolder.find(properties.elmImage),
		nImageWidth = galleryImages.eq(0).width(),
		galleryImageMask = $(properties.elmSliderMask),
		nVisible = properties.nVisibleImages || 1, // how many images will be visible in the gallery
		nSpeed = properties.nAnimationSpeed || 500, // how fast the images slide
		nPadding = properties.nImagePadding || 0, // how much space between images (x2)
		activeClass = properties.strActiveClass || '.active', // if this class is found on an image it will scroll into view
		nTrueWidth = nImageWidth + (nPadding * 2);

	if (nImageWidth !== null) {

		galleryImageHolder.width(nTrueWidth * galleryImages.length);
		galleryImageMask.width(nTrueWidth * nVisible);

		galleryImages.css({
			marginLeft: nPadding,
			marginRight: nPadding
		});

		galleryImages.currIndex = 0;
		galleryImages.activeIndex = galleryImages.filter(activeClass).index();

		galleryImages.slideEvent = function (index) {
			if (this.currIndex !== index) {
				galleryImageHolder.stop(true, true).animate({ left: -(index * nTrueWidth) }, nSpeed);
			}
			this.currIndex = index;
			galleryImages.toggleNav();
		};

		galleryImages.scrollIntoView = function (index) {
			if ((galleryImages.length - index) < nVisible && nVisible <= galleryImages.length) {
				index = galleryImages.length - nVisible;
			}
			galleryImages.slideEvent(index);
		};

		galleryImages.prevIndex = function () {
			var newIndex = this.currIndex - 1;
			//return (newIndex < 0) ? this.length - nVisible : newIndex;
			return (newIndex < 0) ? 0 : newIndex;
		};

		galleryImages.nextIndex = function () {
			var newIndex = this.currIndex + 1;
			//return (newIndex > this.length - nVisible) ? 0 : newIndex;
			return (newIndex > this.length - nVisible) ? this.length - nVisible : newIndex;
		};

		galleryImages.toggleNav = function () {
			$(properties.elmBtnPrev).toggle(this.currIndex > 0);
			$(properties.elmBtnNext).toggle(this.currIndex < this.length - nVisible);
		};

		$(properties.elmBtnPrev).click(function () {
			galleryImages.slideEvent(galleryImages.prevIndex());
			return false;
		});

		$(properties.elmBtnNext).click(function () {
			galleryImages.slideEvent(galleryImages.nextIndex());
			return false;
		});

		// INIT CONFIG

		if (galleryImages.activeIndex >= 0) {
			galleryImages.scrollIntoView(galleryImages.activeIndex);
		}

		galleryImages.toggleNav();
		
	}


}


$.fn.bringToFront = function () {
	'use strict';
	return this.each(function () {
		$(this).css({
			zIndex: 1
		});
	});
};

$.fn.sendToBack = function () {
	'use strict';
	return this.each(function () {
		$(this).css({
			zIndex: 0
		});
	});
};


function doGalleryThumbs()
{

	//how many images are there?
	var numGalleryImages = $("#galthumbs li").length;
				var maxHeight = $(window).height()-100;

	$("#lightbox img").css("max-height", maxHeight);
	var currentGalleryImage = 1;

	$("#nextButton").bind('click',function(){
		// what one are we on?
		if (currentGalleryImage<numGalleryImages)
		{
			currentGalleryImage = currentGalleryImage+1;
		} else {
			currentGalleryImage = 1;
		}
			
			var maxHeight = $(window).height()-100;
			$("#lightbox img").attr("src", "/_customelements/gallery/" +$("#galthumbs li:nth-child("+currentGalleryImage+") img").attr("rel"));
			$("#lightbox img").css("max-height", maxHeight);
			
		return false;
	});

	$("#previousButton").bind('click',function(){
		// what one are we on?
		if (currentGalleryImage>1)
		{
			currentGalleryImage = currentGalleryImage-1;
		} else {
			currentGalleryImage = numGalleryImages;
		}
			
			$("#lightbox img").attr("src", "/_customelements/gallery/" +$("#galthumbs li:nth-child("+currentGalleryImage+") img").attr("rel"));

		return false;
	});
	
	
	
	$("#galthumbs img", "#majorcontent").load(checkImageDimensions);

	$(".close").bind('click',function(){
		$("#lightbox").hide();
		return false;
	});

	$("#galthumbs li a").live('click',function(){
		$("#lightbox img").attr("src", "/_customelements/gallery/" +$(this).children("img").attr("rel"));
		$("#lightbox").show();
		return false;
	});

}

$(document).ready(function () {


	'use strict';

	/*$("a[href*=.pdf]").click(function(){
		window.open(this.href);
		return false;
	});
*/
	if ($("#subnav ul li").length==0)
	{
		//$("#subnav").hide();
	}


	/* BLUE BOX HACK 
	var introQuote = $("#intro-quote");
	if (introQuote.length > 0) {
		if (introQuote.find(".pad").children().length === 0) {
			introQuote.remove();
			var masthead = $("#masthead").addClass("no-blue-box");
			masthead.find(".main-nav").addClass("inline-block").prependTo("#majorcontent");
		}
	}*/
	
	/*
	$("#link-23").bind('click',function(){
		$("#aboutnav").toggle();
		return false;
	});
	*/
	
	$("#sidebar .featured-project .featured-more").hover(function () {
		$(this).parent().addClass("more-hover");
	}, function () {
		$(this).parent().removeClass("more-hover");
	});


	

	// IF THE CONTAINER HEIGHT IS LESS THAN THE VIEWPORT HEIGHT THEN MAKE IT THE SAME HEIGHT
	/*
	$(window).resize(function () {

		var container = $("#container"),
			padding = container.css("padding-bottom"),
			borderSize = container.css("border-bottom-width"),
			minHeight = $(document).height() - parseFloat(padding) - parseFloat(borderSize);

		container.css("min-height", minHeight);

	}).trigger("resize");
	*/


	// MASTHEAD BANNER FADE IN/OUT
	var slides = $("#masthead .mast-banner img"),
		currIndex = 0;
	if (slides.length > 1) {
		//console.log("here");
		slides.hide().eq(0).show();
		window.setInterval(function () {
			var n = currIndex + 1,
				newIndex = (n > slides.length - 1) ? 0 : n,
				currSlide = slides.eq(currIndex).bringToFront(),
				nextSlide = slides.eq(newIndex).sendToBack().show();
			currSlide.fadeOut(600, function () {
				currSlide.sendToBack().hide();
				nextSlide.bringToFront();
			});
			currIndex = newIndex;
		}, 6000);
	}




	var hashes = {};
	if (document.location.href.indexOf('#') > 0) {
		$.each(document.location.href.split('#')[1].split('&'), function (index, hash) {
			var parts = hash.split("=");
			hashes[parts[0]] = parts[1];
		});
	}
	if (hashes.nProjectID) { 
		var serviceImageClass = ".project-id-" + hashes.nProjectID,
			serviceImage = $(serviceImageClass, "#servicesImageHolder");
		if (serviceImage.length > 0) {
			serviceImage.addClass("active").siblings().removeClass('active');
		}
	}
	
	$(".fig-wrapper", "#servicesImageHolder").click(function () {
		var urlparts = getUrlVars($(this).attr('href'));
		window.location.hash = "nProjectID=" + urlparts['nProjectID'];
		$(this).parent().addClass('active').siblings().removeClass('active');
		$("#services").nextAll().css('opacity', 0.5);
		$.get("/_customelements/_ajax/getProjectInfo.php", urlparts, function (data) {	
			$("#services").nextAll().remove();
			$("#services").after(data);
			$("#galthumbs img", "#majorcontent").load(checkImageDimensions);
			doGalleryThumbs();
		});
		return false;
	});

	$(".services-image.active .fig-wrapper", "#servicesImageHolder").trigger("click");
	
	/***

	desired gallery structure:
	-----------------------------------------

	<elmSliderMask>
		<elmImagesHolder>
			<elmImage class="active"><img src="image.jpg" /></elmImage>
			<elmImage><img src="image.jpg" /></elmImage>
			<elmImage><img src="image.jpg" /></elmImage>
		</elmImagesHolder>
	</elmSliderMask>
	<elmBtnPrev></elmBtnPrev>
	<elmBtnNext></elmBtnNext>

	***/



	initImageSlider({
		elmSliderMask: "#servicesImages", // mask element that encapsulates the image holder
		elmImagesHolder: "#servicesImageHolder", // element that holds all the images or image containers
		elmImage: ".services-image", // image or image container
		elmBtnPrev: "#galPrevItem", // button that will slide to previous image
		elmBtnNext: "#galNextItem", // button that will slide to next image
		nVisibleImages: 4, // how many images should be visible?
		nAnimationSpeed: 300, // transition speed in milliseconds
		nImagePadding: 3 // how many pixels of space between each image? note: this value will be doubled
	});


    $('a[href$=".pdf"]').attr('target', '_blank');
	

});


