// tracks window resizing
var width = 0, height = 0;
var $curpanel = false;
var $navitems = [];
var $window = $(window);

$(function() {
	 
	 // show browser warnings if necessary
	 verifyBrowser();
	 
	 // reset content
	 $('#content').scrollTop(0, 0);
	 
	 // set global navitems
	 $navitems = $('#nav li a');
	 
	 // update the panel widths
	 updatePanelWidth($window.width(), $window.height());
	 
	 // bind deep linking
	 deepLinking();
	 
	 // load twitter feed
	 loadTwitterFeed();
	 
	 // custom accordion
	 enableAccordion();
	 
	 // hover over image
	 photoHover();
	 
	 // handle contact form submissions
	 handleContactSubmission();

	 // track window resizing
	 $window.resize(function() {
		  var $this = $(this);
		  updatePanelWidth($this.width(), $this.height());
	 });

});

// remove preloader after content has loaded
$(window).load(function() {
	$('#loading').fadeOut(function() {
		$(this).remove();
	});
});

/**
 * Verify the user has a newer browser.
 */
function verifyBrowser() {
	var $closelink, $tooltip;
	if (!$.browser.mozilla && !$.browser.webkit) {
		$closelink = $('<a href="close" class="closeTooltip">close</a>').bind('click', function() {
			$(this).parent().fadeOut().remove();
			return false;
		});
		$tooltip = $('<div id="supportedBrowsers"><p>This site utilizes a number of CSS3 features that remain <em>unsupported in all current versions of IE</em>.  As such, it is best viewed in a newer version of Firefox, Safari, or Chrome. If you <em>must</em> use IE, please use IE8.</p></div>');
		$closelink.prependTo($tooltip);
		$tooltip.appendTo($('body'));
	}
}

/**
 * Handles changing the title bar and scrolling to the
 * proper container for navigation items.
 */
function deepLinking() {
   $.address.change(function(event) {
		var $this, value;
		$('.panel').css('overflow-y', 'hidden');
		value = event.value;
		value = value.replace('/', '');
		if (value.length == 0) return;
		$curpanel = $('#' + value);
		$navitems.filter(function(items) {
			$this = $(this);
			$this.toggleClass('selected', $this.hasClass(value));
		});
		$('#wrapper').stop().scrollTo($curpanel, 700, { axis: 'x', easing: 'linear' });
		if (value.length < 4) value = value.toUpperCase();
		else value = value.substr(0,1).toUpperCase() + value.substr(1, value.length);
		$.address.title($.address.title().split(' - ')[0] + ' - ' + value);
		if ($curpanel[0].scrollHeight > height) {
			$('.panel').css('overflow-y', 'scroll');
		}
   });

   // bind navigation to deep linking
   $('#nav').find('li a').click(function() {
		var value = $(this).attr('href');
      $.address.value(value.replace('/#/', ''));
      return false;
   });
}

/**
 * Ensures windows each have individual viewports
 * equal to the window width.
 */
function updatePanelWidth(w, h) {
	 // reference the old width
	 oldWidth = width;
	 
	 // update global width and set panels
	 width = w;
	 height = h;

	 // fix panel widths
	 if (oldWidth != width) {
		  $('#wrapper .panel').width(width);
	 }
	 
	 // ensure we don't need vertical scrolling
	 if ($curpanel !== false) {
		  if ($curpanel[0].scrollHeight > height) {
			  $('.panel').css('overflow-y', 'scroll');
		  } else {
			  $('.panel').css('overflow-y', 'hidden');
		  }
		 
		  // if the width magically decreased
		  if (oldWidth != width) {
			   $('#wraper').stop().scrollTo($curpanel, { axis: 'x', easing: 'linear' });
		  }
	 }
}

/**
 * Loads my twitter data.
 */
function loadTwitterFeed() {
    $('#twitter').tweet();
    return false;
}

/**
 * Simple accordion.
 */
function enableAccordion() {
	$('.accordion .expandable').live('click', function() {
		$(this).toggleClass('open').next('ul').slideToggle();
		return false;
	});
}

function photoHover() {
	$('.photo').hover(function() {
		$(this).find('img').stop().animate({ opacity: 1.0 }, 1000);
	}, function() {
		$(this).find('img').stop().animate({ opacity: 0.2 }, 1000);
	});
}

/**
 * Handles AJAX contact form submission.
 */
function handleContactSubmission() {
	$('#contactform').submit(function() {
		var $this, $name, $email, $subject, $message, errors = false;
		var errorstyle = {'color': '#f00'};
		$this = $(this);

		var $processing = $('<span class="loading">processing...</span>');
		$('#contactsubmit').replaceWith($processing);

		// store form fields
		$name = $this.find('#name');
		$email = $this.find('#email');
		$subject = $this.find('#subject');
		$message = $this.find('#message');

		// clear any previous errors
		$name.prev('label').css('color', 'inherit');
		$email.prev('label').css('color', 'inherit');
		$subject.prev('label').css('color', 'inherit');
		$message.prev('label').css('color', 'inherit');

		if ($name.val().length == 0) {
			$name.prev('label').css(errorstyle);
			errors = true;
		}

		if ($email.val().length == 0 || $email.val().indexOf('@') == -1) {
			$email.prev('label').css(errorstyle);
			errors = true;
		}

		if ($subject.val().length == 0) {
			$subject.prev('label').css(errorstyle);
			errors = true;
		}

		if ($message.val().length == 0) {
			$message.prev('label').css(errorstyle);
			errors = true;
		}

		// handle errors
		if (errors) {
			errors = false;
			return false;
		}

		// create a hidden input for simple spam prevention
		$('<input type="hidden" name="kapow" value="' + new Date().getTime() + '" />').appendTo($this);
		$.post('/index/contact', $this.serialize(), function(data) {
			if (data == 'success') {
				data = '<strong>Thank you!</strong><br /> Your form submission was successful. You can expect a reply within 2 business days.';
			} else {
				data = '<strong>Oh no!</strong><br />Your form submission was unsuccessful. You might be better off contacting me at corey AT coreyballou DOT com.';
			}

			$this.fadeOut('fast', function() {
				$this.html(data).fadeIn('fast');
			});
		});
		return false;
	});
}

