$(document).ready(function() {
	// links
	$('*[rel=external]').attr('target', '_blank');
	
	// toc
	$('.top.toc li').each(function() {
		var duration = 300;
		var delay = 100;
		
		var li = $(this);
		
		li.append('<div class="menu-over-effect"><div class="left"></div><div class="middle"></div><div class="right"></div></div>');
		li.mouseenter(function() {		
			li.find('.menu-over-effect .left').clearQueue().css('width', '0px').animate({width:35}, duration);
			li.find('.menu-over-effect .right').clearQueue().css('background-position', '-178px 0').animate({backgroundPosition:'-143px 0'}, duration);
			if (!(/MSIE\s8/.test(navigator.userAgent) || /MSIE\s7/.test(navigator.userAgent))) {
				li.find('.menu-over-effect .middle').clearQueue().css('opacity', '1').delay(delay).fadeIn(duration - delay);
			}
			li.find('a').clearQueue().css('padding', '40px 0 0').animate({paddingTop:43}, duration);
		});
		
		li.mouseleave(function() {
			li.find('.menu-over-effect .left').clearQueue().css('width', '35px').animate({width:0}, duration);
			li.find('.menu-over-effect .right').clearQueue().css('background-position', '-143px 0').animate({backgroundPosition:'-178px 0'}, duration);
			if (!(/MSIE\s8/.test(navigator.userAgent) || /MSIE\s7/.test(navigator.userAgent))) {
				li.find('.menu-over-effect .middle').clearQueue().css('opacity', '1').delay(delay).fadeOut(duration - delay);
			}
			li.find('a').clearQueue().css('padding', '43px 0 0').animate({paddingTop:40}, duration);
		});
	});
	
	// portfolio
	if ($('.portfolio li').length) {
		$('.portfolio li').mouseenter(function() { $(this).find('div').fadeIn(400); });
		$('.portfolio li').mouseleave(function() { $(this).find('div').fadeOut(200); });
		
		var ar = [];
		$('.portfolio li').each(function() {
			var i = $(this).find('img').get(0);
			var s = i.src.substring(0, i.src.lastIndexOf('.') - 3) + i.src.substring(i.src.lastIndexOf('.'), i.src.length);
			ar.push({img: s, alt: i.alt});
		});
		
		$('.portfolio li').each(function(index) { $(this).click(function() {lb(ar, index); }); });
	}
	
	// tabs
	if ($('.fat-footer .container').length) $('.fat-footer .container').dsdTabs({toc: $('.fat-footer .tabs')});
	
	// slides
	if ($('.promo .slides').length && $('.promo .toc').length) $('.promo .slides').dsdShow({effectDuration:.75, interval:7, buttons: $('.promo .toc')});
	
	// google maps
	$('.google-map').each(function() {
		var gc = new google.maps.Geocoder()
			, container = this
			, name = $(this).children('.name').text()
			, address = $(this).children('.address').text()
			, city = $(this).children('.city').text()
			, state = $(this).children('.state').text()
			, zip = $(this).children('.zip').text();
		
		gc.geocode({'address': address + ', ' + city + ', ' + state + ' ' + zip}, function(results, status) {
			var start_options = 0;
			
			if (status == google.maps.GeocoderStatus.OK) {
				map = new google.maps.Map(container, {
					zoom: 11, 
					center: new google.maps.LatLng(results[0].geometry.location.lat() + .04, results[0].geometry.location.lng()),
					mapTypeId: google.maps.MapTypeId.ROADMAP
				});
				
				var html = '<strong>' + name + '</strong><div>' + address + '<br/>' + city + ', ' + state + ' ' + zip + '</div>';
				var marker = new google.maps.Marker({map: map, position: results[0].geometry.location});
				var iw = new google.maps.InfoWindow();
				
				iw.setContent(html);
				iw.open(map, marker);
				
				google.maps.event.addListener(marker, 'click', function() {				
					iw.setContent(html);
					iw.open(map, marker);
				});
			} else {
				$(this).hide();
			}
		});
	});
	
	// forms
	$('form.ajax-me').submit(function() {
		var valid = true;
		$(this).find('.required').each(function() {
			if ($(this).val() == '') {
				valid = false;
				$(this).addClass('error');
			} else {
				$(this).removeClass('error');
			}
		});
		
		if (valid) {	
			$(this).find('input[type=submit]').attr('disabled', true);
			var data = $(this).serialize();
			$.ajax({
				url: '../form-handler.js', 
				data: data,
				type: 'POST',
				context: this,
				success: function(d, x, y) {
					$(this).next('.message').removeClass('error').removeClass('success').addClass(d.status).show().find('.text').html(d.message);
					$(this).find('input[type=submit]').attr('disabled', false);
					
					if ($(this).next('.message').hasClass('success')) {
						// reset the form
						$(this).find(':input').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
					}
				}
			});
		}
		return false;
	});
	
	$('.message .close').click(function() {
		$(this).parents('.message').hide();
	});
	
	// plus one
	$('.likes').prepend('<g:plusone count="false" href="http://www.darkstardesign.com"></g:plusone>');
	(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();
});

function lb(ar, index) {
	var w = Math.max($('body').width(), 1040);
	if (ar.length > 1 && index < ar.length && index >= 0) {
		// next, previous
		var img = $('<img alt="' + ar[index].alt + '" />');
		img.hide();
		img.load(function() {
			var ih = this.height;
			var iw = this.width;
			
			$('.lb-container').append(img);
			
			if (/MSIE/.test(navigator.userAgent)) {
				// IE - can't figure out the dimensions of a hidden image, so show the image (and possibly the container) then hide it after we get the dimensions
				img.show();
				var hide = true;
				if ($('.lb-container').is(":visible")) {
					hide = false;
				} else {
					$('.lb-container').show();
				}
				ih = this.height;
				iw = this.width;
				img.hide();
				if (hide) $('.lb-container').hide();
			}
			
			
			var map = {left: ((w/2) - (iw/2) - 10) + 'px', width: iw, height: ih};
			if ($('.lb-container').is(":visible")) {
				// transform the shape of lb container
				$('.lb-container').animate(map, 300, function() {
					$('.lb-container img').fadeIn(500);
					$('.go-left, .go-right').show();
				});
				// don't hide my close button!
				$('.lb-container').css('overflow', 'visible');
			} else {
				$('.lb-container').css(map);
				$('.lb-container img').show();
				$('.lb-container').fadeIn(500);
				$('.go-left, .go-right').show();
			}
			
		});
		if ($('.body-overlay, .lb-container').length) {
			$('.go-left, .go-right').hide();
			$('.lb-container').find('img').remove();
			$('.lb-container .go-left').unbind('click').click(function() {
				lb(ar, (index == 0 ? ar.length - 1 : index - 1));
			});
			
			$('.lb-container .go-right').unbind('click').click(function() {
				lb(ar, ((index + 1) % ar.length));
			});
		} else {
			var go_left = $('<div class="go-left"></div>');
			var go_right = $('<div class="go-right"></div>');
			
			go_left.click(function() { lb(ar, (index == 0 ? ar.length - 1 : index - 1)); });
			go_right.click(function() { lb(ar, ((index + 1) % ar.length)); });
			
			var top = $('html').scrollTop() + 50;
			
			$('body').prepend('<div class="body-overlay" style="display:none;"></div><div class="lb-container" style="display:none; top:'+top+'px;"><div class="close"></div></div>');
			$('.body-overlay, .lb-container .close').click(function() { $('.body-overlay, .lb-container').remove(); });
			$('.lb-container').append(go_left).append(go_right);
			$('.go-left, .go-right').mouseenter(function() {
				$(this).clearQueue().css('opacity', 0).animate({opacity: .5}, 200);
			});
			$('.go-left, .go-right').mouseleave(function() {
				$(this).clearQueue().css('opacity', .5).animate({opacity: 0}, 200);
			});
		}
		$('.body-overlay').fadeIn(500);
		img.attr('src', ar[index].img);
	} else if (ar.length > 0) {
		var img = $('<img alt="' + ar[0].alt + '" />');
		img.load(function() {
			$('.lb-container').append(img);
			$('.lb-container').fadeIn(500);
		});
		$('body').prepend('<div class="body-overlay" style="display:none;"></div><div class="lb-container" style="display:none;"><div class="close"></div></div>');
		$('.body-overlay, .lb-container .close').click(function() { $('.body-overlay, .lb-container').remove(); });
		$('.body-overlay').fadeIn(500);
		img.attr('src', ar[0].img);
	}
}

/**************************************************************************
* Tab switcher
*
* Switches tabs out based on a tab TOC
* Scott Wespi (scott@darkstardesign.com)
*
* Requires jQuery
**************************************************************************/
(function($){
	/* feel free to change these, but it may be easier to over-write them with options like so:
		$('#slider-container').dsdTabs({startTab: 2});
	*/
	var settings = {
		startTab: 0,
		toc: false
	};
	
	var data = {
		container: false,
		totalTabs: 0,
		index: 0,
		lastIndex: 0
	};
	
	var methods = {
		init: function(options) {
			return this.each(function() {        
				// merge options and settings
				if (options) { 
					$.extend(settings, options);
				}
				
				var $this = $(this);
				
				data.totalTabs = $this.children('.tab').length; 
				data.index = settings.startTab; 
				data.lastIndex = settings.startTab;
				data.container = $this;
				
				if (data.totalTabs > 1) {
					// hide everything besides the current slide
					$this.children('.tab').hide();
					$this.children('.tab:eq('+data.index+')').show();
				}
				
				if (settings.toc) {
					settings.toc.children('li').removeClass('active');
					settings.toc.children('li:eq('+data.index+')').addClass('active');
					
					$.each(settings.toc.children('li'), function(i, s) {
						s.onclick = function() { methods.gotoTab(i); };
					});
				}
			});
		},
		nextSlide: function() {
			data.lastIndex = data.index;
			data.index = (data.index + 1) % data.totalTabs;
			
			methods.cycleTab();
		},
		cycleTab: function() {
			var container = data.container;
			if (settings.toc) {
				settings.toc.children('li:eq('+data.lastIndex+')').removeClass('active');
				settings.toc.children('li:eq('+data.index+')').addClass('active');
			}
			container.children('.tab:eq('+data.lastIndex+')').hide();
			container.children('.tab:eq('+data.index+')').show();
		},
		gotoTab: function(index) {
			if (index != data.index) {
				data.lastIndex = data.index;
				data.index = index;
				methods.cycleTab();
				return true;
			}
			return false;
		}
	};

	$.fn.dsdTabs = function(method) {
		// generic method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dsdTabs' );
		}
	};
})(jQuery);


/**************************************************************************
* Simple Javascript Slideshow
*
* Changes slides out (crossfade)
* Scott Wespi (scott@darkstardesign.com)
*
* Requires jQuery
**************************************************************************/
(function($){
	/* feel free to change these, but it may be easier to over-write them with options like so:
		$('#slider-container').dsdShow({effectDuration:1, interval:3});
	*/
	var settings = {
		interval: 6,
		effectDuration: .5,
		buttons: false,
		autoStart: true
	};
	
	var data = {
		container: false,
		totalSlides: 0,
		index: 0,
		lastIndex: 0,
		timer: -1,
		moving: false
	};
	
	var methods = {
		init: function(options) {
			return this.each(function() {        
				// merge options and settings
				if (options) { 
					$.extend(settings, options);
				}
				
				var $this = $(this);
				
				data.totalSlides = $this.children('.slide').length; 
				data.index = 0; 
				data.lastIndex = 0; 
				data.timer = -1; 
				data.moving = false;
				data.container = $this;
				
				if (data.totalSlides > 1) {
					// hide everything besides the current slide
					$this.children('.slide').hide();
					$this.children('.slide:eq('+data.index+')').show();
				}
				
				if (settings.buttons) {
					settings.buttons.children('li').removeClass('active');
					settings.buttons.children('li:eq('+data.index+')').addClass('active');
					
					$.each(settings.buttons.children('li'), function(i, s) {
						s.onclick = function() { methods.gotoSlide(i); };
					});
				}
			
				if (settings.autoStart) {
					data.timer = window.setInterval(methods.nextSlide, settings.interval * 1000);
				}
			});
		},
		nextSlide: function() {
			if (!data.moving) {
				data.moving = true;
				data.lastIndex = data.index;
				data.index = (data.index + 1) % data.totalSlides;
				
				methods.cycleSlide();
			} else {
				window.clearInterval(data.timer);
			}
		},
		cycleSlide: function() {
			var container = data.container;
			if (settings.buttons) {
				settings.buttons.children('li:eq('+data.lastIndex+')').removeClass('active');
				settings.buttons.children('li:eq('+data.index+')').addClass('active');
			}
			if (/MSIE\s8/.test(navigator.userAgent)) {
				container.children('.slide:eq('+data.lastIndex+')').hide();
				container.children('.slide:eq('+data.index+')').show();
				data.moving = false;
			} else {
				container.children('.slide:eq('+data.lastIndex+')').fadeOut(settings.effectDuration * 1000);
				container.children('.slide:eq('+data.index+')').fadeIn(settings.effectDuration * 1000, function() {
					data.moving = false;
				});
			}
		},
		gotoSlide: function(index) {
			window.clearInterval(data.timer);
			if (!data.moving) {
				data.moving = true;
				if (index != data.index) {
					data.lastIndex = data.index;
					data.index = index;
					methods.cycleSlide();
					return true;
				}
				data.moving = false;
			}
			return false;
		}
	};

	$.fn.dsdShow = function(method) {
		// generic method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dsdShow' );
		}
	};
})(jQuery);
