var port_item_width = 335;
var offset_left;
var portCookie = 'showPortfolio';
var uri;
var port_items_html = '';
var total_port_items_width = 0;
var new_port_items_width = 0;
var scroll_px = 1000;
var html_num_added = 0;

$(document).ready(function(){
	
	// Redefine the scroll px
	scroll_px = Math.floor($(window).width() * .66);

	// Parse the URL
	get_uri_segments();

	// Open links in new window
	$('a[rel="external"]').click(function(){
		window.open($(this).attr('href'));
		return false;
	});
	
	// The homepage blog links need some reformating, else they'll break (thanks, EE for the swell pagination!)
	$('.entry-pager a').each(function() {
	    var h = $(this).attr('href');
	    var p = /[a-z]+s?:\/\/w+?\.?joshuacole\.com\/(P[0-9]+)/;
	    var r = p.exec(h);
		if(r != null && r[1]) $(this).attr('href', '/blog/'+r[1]);
	});
	
	// Do a little massaging on the entry pager
	$(".entry-pager a").each(function() {
		if($(this).html() == "&lt;") {
			$(this).html('&laquo; Previous').addClass('prev');
		} else if($(this).html() == "&gt;") {
			$(this).html('Next &raquo;').addClass('next');
		} else {
	        $(this).hide();
		}
	});
	
	$('.entry-pager strong').hide();
	
	// Work on the next/previous link text
	var next_entry_link_text = $('.bl-entry-newer a').html();
	if(next_entry_link_text !== null) {
	    var next_entry_link_text_new = (next_entry_link_text.length > 40) ? next_entry_link_text.substr(0, 37)+'... &raquo;' : next_entry_link_text;
		$('.bl-entry-newer a').html(next_entry_link_text_new);
	}
	
	var prev_entry_link_text = $('.bl-entry-older a').html();
	if(prev_entry_link_text !== null) {
	    var prev_entry_link_text_new = (prev_entry_link_text.length > 40) ? prev_entry_link_text.substr(0, 37)+'...' : prev_entry_link_text;
		$('.bl-entry-older a').html(prev_entry_link_text_new);
	}

	/************************************************
		PORTFOLIO 
	************************************************/

	$('#port-carousel-wrapper').css('width', $(window).width()+'px');	
	$('#port-imagewrapper').css('width', '80000px');

	// First off, do we show the portfolio or not? Let's check the cookie
	if(uri[1] == 'portfolio' || uri[1] == '' || getCookie(portCookie) == 1) {
		$('.wrapper-portfolio').show();
		$('#hdr-port-toggle, #port-navleft, #port-navright').removeClass('hidden');
	} else {
		$('.wrapper-portfolio').hide();
		$('#hdr-port-toggle, #port-navleft, #port-navright').addClass('hidden');
	}

	// Get the html for the portfolio items, b/c we'll need to append/prepend it when cycling
	port_items_html = $('#port-imagewrapper').html();

	// Figure out what the width of the port-imagewrapper needs to be, by 
	// calculating the widths of the inner items + the margin on those items

	setTimeout(
		function() {

			// Calculate how wide all our images are
			$('#port-imagewrapper li img').each(function() { total_port_items_width += ($(this).attr('width')) + 5; });

			// $('#port-imagewrapper').css('width', total_port_items_width+'px');
	
			// Now let's go ahead and load up some items for the "THIS WAY" button
			var new_html = '';
			for(var i = 0; i < 5; i++) {
				if(new_port_items_width == 0) new_port_items_width = total_port_items_width;
				new_port_items_width += total_port_items_width;
				new_html += port_items_html;
			}
			setTimeout(
				function() {
					// $('#port-imagewrapper').append(new_html).css('width', new_port_items_width+'px');
					$('#port-imagewrapper').append(new_html);
					$('#port-imagewrapper li').removeClass('loading').children('img').removeClass('hide');
					$('#port-imagewrapper').animate({ left: '-'+(new_port_items_width - total_port_items_width)+'px' }, 1);
				},
				350
			);
		}, 
		1500
	);

	// Toggle the view of the masthead portfolio items
	$('#hdr-port-toggle').click(function() {
		if($(this).hasClass('hidden')) {
			$('.wrapper-portfolio').slideDown();
			$(this).removeClass('hidden');
			$('#port-navleft, #port-navright').removeClass('hidden');
			setCookie(portCookie, 1, 10);
		} else {
			$('.wrapper-portfolio').slideUp();
			$(this).addClass('hidden');
			$('#port-navleft, #port-navright').addClass('hidden');
			setCookie(portCookie, 0, 10);
		}
	});

	// Custom portfolio items carousel
	$('#port-navright, #port-navleft').click(function() {
	
		if(new_port_items_width == 0) new_port_items_width = total_port_items_width;
		new_port_items_width += total_port_items_width;

		if(this.id == 'port-navright') {
			var pos = '-='+scroll_px+'px';
			html_num_added++;
			if(html_num_added < 10) {
				$('#port-imagewrapper').append(port_items_html);
				$('#port-imagewrapper li').removeClass('loading').children('img').removeClass('hide');
			}

		} else {

			var pos = '+='+scroll_px+'px';

		}

		$('#port-imagewrapper').animate(
			{ left: pos }, 
			600,
			"easeOutQuart"
		);

		return false;

	});

	// Load in all the portfolio images
	$("#port-imagewrapper li img").each(function() {
	    var img = new Image();
	    img.src = $(this).attr('src');
	    var id = this.id;
	    $(img).load(function() {
	        $('#'+id).fadeIn(250).parent().removeClass('loading');
	    });
	});

	/*******************
		END: PORTFOLIO 
	*******************/
	

	/************************************************
		FORM HANDLERS
	************************************************/
	
	// Define the default values for each field
	var def_vals = new Array();
	def_vals['name'] = 'NAME';
	def_vals['email'] = 'EMAIL ADDRESS ( not seen publicly )';
	def_vals['url'] = 'YOUR WEBSITE ( http://your-website-address.com )';
	def_vals['comments'] = 'ENTER YOUR COMMENTS HERE';
	
	// Populate the default values, if each field is blank
	if($("#form-name").val() == '') $("#form-name").val(def_vals['name']);
	if($("#form-email").val() == '') $("#form-email").val(def_vals['email']);
	if($("#form-url").val() == '' || $("#form-url").val() == 'http://') $("#form-url").val(def_vals['url']);
	if($("#form-comments").val() == '' || $("#form-comments").val() == '{comments}') $("#form-comments").val(def_vals['comments']);
	if($("#form-captcha").val() == '{captcha_word}') $("#form-captcha").val('');
	
	// Clear our the default values on focus
	$("#form-name").focus(function() { $(this).removeClass('error'); if($(this).val() == def_vals['name']) $(this).val(''); });
	$("#form-email").focus(function() { $(this).removeClass('error'); if($(this).val() == def_vals['email']) $(this).val(''); });
	$("#form-url").focus(function() { $(this).removeClass('error'); if($(this).val() == def_vals['url']) $(this).val(''); });
	$("#form-comments").focus(function() { $(this).removeClass('error'); if($(this).val() == def_vals['comments']) $(this).val(''); });
	$("#form-captcha").focus(function() { $(this).removeClass('error'); });
	
	// Repopulate the default vals on blur
	$("#form-name").blur(function() { if($(this).val() == '') $(this).val(def_vals['name']); });
	$("#form-email").blur(function() { if($(this).val() == '') $(this).val(def_vals['email']); });
	$("#form-url").blur(function() { if($(this).val() == '') $(this).val(def_vals['url']); });
	$("#form-comments").blur(function() { if($(this).val() == '') $(this).val(def_vals['comments']); });
	
	// Submit error handling
	$("#comment_form, #form").submit(function() {
		err = 0;
		if($("#form-name").val() == "" || $("#form-name").val() == def_vals['name']) {
			$("#form-name").addClass("error");
			err++;
		}
		if($("#form-email").val() == "" || $("#form-email").val() == def_vals['email']) {
			$("#form-email").addClass("error");
			err++;
		}
		if($("#form-comments").val() == "" || $("#form-comments").val() == def_vals['comments']) {
			$("#form-comments").addClass("error");
			err++;
		}
		if($("#form-captcha").val() == "") {
			$("#form-captcha").addClass("error");
			err++;
		}
		if(err > 0) {
			$("#comment-form-error-msg, #contact-form-error-msg").css('display', 'block').removeClass('hide').fadeIn();
			setTimeout(
				function() {
					$("#comment-form-error-msg").fadeOut();
					$("#contact-form-error-msg").fadeOut();
				}, 
				2000
			);
			return false;
		}
	});

	/*********************
		END: COMMENT FORM 
	*********************/

});

/*
	This function will parse the URL and set the uri segments
	into an array uri
*/

function get_uri_segments() {
	var url = document.location.href;
	var uri_raw = url.replace('http://', '');
	uri = uri_raw.split('/');
}

/************************************************
	COOKIE FUNCTIONS
************************************************/

/*
	This function sets a JS cookie. The user must have cookies
	enabled just like server-side cookies in order for this to work
*/
function setCookie(cookieName, cookieValue, expireDays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expireDays);
	document.cookie = cookieName + "=" + escape(cookieValue) +
	((expireDays == null) ? "" : ";expires=" + exdate.toGMTString());
}

/*
	This function will return the value of the cookie name it is passed
*/
function getCookie(cookieName) {
	if(document.cookie.length > 0) {
		c_start = document.cookie.indexOf(cookieName + "=");
		if(c_start != -1) {
			c_start = c_start + cookieName.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if(c_end == -1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return null;
}