// ==================
// = Third-Party JS =
// ==================


// pretty date

/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var newtime = time.split(" ");
	newtime = newtime[1] + " " + newtime[2] + ", " + newtime[5] + " " + newtime[3];
	var date = new Date((newtime || ""));
	var diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
		
	if ( day_diff < 0 )
		return "earlier today";
	
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff <= 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (i - 1 >= 0 && format.charAt(i - 1) == "\\") { 
			returnStr += curChar;
		}
		else if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else if (curChar != "\\"){
			returnStr += curChar;
		}
	}
	return returnStr;
};
 
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
	// Week
	W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate(); }, // Fixed now, gets #days of date
	// Year
	L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); },	// Fixed now
	o: function() { var d  = new Date(this.valueOf());  d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?
'0' : '')) + m; },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Yet Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};

/**
 * @name jQuery placehold (https://github.com/jgarber623/jquery-placehold)
 * @author Jason Garber
 * @copyright (cc) Jason Garber (http://sixtwothree.org and http://www.viget.com)
 * 
 * Licensed under the CC-GNU GPL (http://creativecommons.org/licenses/GPL/2.0/)
 */

;(function($) {
	$.fn.placehold = function( placeholderClassName ) {
		var placeholderClassName = placeholderClassName || "placeholder",
			supported = $.fn.placehold.is_supported();

		function toggle() {
			for ( i = 0; i < arguments.length; i++ ) {
				arguments[i].toggle();
			}
		}

		return supported ? this : this.each( function() {
			var $elem = $( this ),
				placeholder_attr = $elem.attr( "placeholder" );

			if ( placeholder_attr ) {
				if ( $elem.val() === "" || $elem.val() == placeholder_attr ) {
					$elem.addClass( placeholderClassName ).val( placeholder_attr );
				}

				if ( $elem.is( ":password" ) ) {
					var $pwd_shiv = $( "<input />", {
						"class": $elem.attr( "class" ) + " " + placeholderClassName,
						"value": placeholder_attr
					});

					$pwd_shiv.bind( "focus.placehold", function() {
						toggle( $elem, $pwd_shiv );
						$elem.focus();
					});

					$elem.bind( "blur.placehold", function() {
						if ( $elem.val() === "" ) {
							toggle( $elem, $pwd_shiv );
						}
					});

					$elem.hide().after( $pwd_shiv );
				}

				$elem.bind({
					"focus.placehold": function() {
						if ( $elem.val() == placeholder_attr ) {
							$elem.removeClass( placeholderClassName ).val( "" );
						}
					},
					"blur.placehold": function() {
						if ( $elem.val() === "" ) {
							$elem.addClass( placeholderClassName ).val( placeholder_attr );
						}
					}
				});

				$elem.closest( "form" ).bind( "submit.placehold", function() {
					if ( $elem.val() == placeholder_attr ) {
						$elem.val( "" );
					}

					return true;
				});
			}
		});
	};

	$.fn.placehold.is_supported = function() {
		return "placeholder" in document.createElement( "input" );
	};	
})(jQuery);


$('input, textarea').placehold('placeheld');


// ==================
// = Application JS =
// ==================

var SHRM = SHRM || {};

// Dynamic loading and filtering of listings

SHRM.listing = {
	init: function() {
		$('.content-listing .link-to-remote').bind('click', SHRM.listing.linkToRemote);
		$('.content-listing select[name=filter]').bind('change', SHRM.listing.filter);
		$('ul.content-listing li').bind('click', function() {
			window.location.href = $(this).find('a.more').attr('href');
		});
	},
	
	linkToRemote: function(e) {
		var $this = $(this);
		e.preventDefault();
		$this.animate({'opacity': 0.5});
		$this.html('Loading&hellip;');
		SHRM.listing.getContent($(this).attr('href'), function() {
			$this.animate({'opacity': 1});
			$this.html('Load More');
		});
	},
	
	filter: function(e) {
		var $this = $(this);
		$('.filter .loading').animate({'opacity': '.4'});
		SHRM.listing.getContent(document.location.pathname + "/type/" + $this.val(), function() {
			var $listing = $('ul.content-listing');
			$('.filter .loading').animate({'opacity': '.01'});
			$listing.find('li').fadeOut();
		});
	},
	
	getContent: function(url, callback, after) {
		$.ajax({
			dataType: 'html',
			type: 'get',
			url: url,
			success: function(html) {
				if(callback && typeof callback == 'function') {
					callback();
				}
				SHRM.listing.parseContent(html);
			}
		});
	},
	
	parseContent: function(html) {
		var $html = $(html),
			$listing = $html.find('.content-listing'),
			$next = $html.find('.load');
		$listing.find('li').css('opacity', 0.01).appendTo('ul.content-listing').animate({
			'opacity': 1 
		});
		if($next.length > 0) {
			var $load = $('.load');
			if($load.length > 0) {
				$('.load').attr('href', $next.attr('href'));
			} else {
				$next.appendTo('div.content-listing .inner').bind('click', SHRM.listing.linkToRemote).wrap('p');
			}
		} else {
			$('.load').remove();
		}
		
	}
};

SHRM.listing.init();

// Lightbox overlay

SHRM.lightbox = {
	template: '<div><div class="screen"></div><div class="lightbox"><span class="alt close">Close</span></div></div>',
	
	init: function() {
		this.createTemplate();
		$('.overlay').bind('click',function(e) {
			e.preventDefault();
			SHRM.lightbox.show($(this).attr('href'));
		});
	},
	
	createTemplate: function() {
		this.$template = $(this.template).css('opacity',0);
		this.$template.find('.close, .screen').bind('click', SHRM.lightbox.hide);
		$(document).bind('keyup', function(e) {
			if(e.keyCode == 27) {
				SHRM.lightbox.hide();
			}
		});
	},
	
	show: function(url) {
		var $active = this.$template.clone(true);
		var $img = $('<img />', {
			load: function() {
				$img.appendTo($active.find('.lightbox'));
				var width = $active.find('.lightbox img')[0].width > 0 ? $active.find('.lightbox img')[0].width : $active.find('.lightbox img').eq(0).attr('width');
				$active.find('.lightbox').css({
					'margin-left':  width / -2 
				}).end().appendTo('body').animate({'opacity':1});
				
			}
		});
		
		$img.attr('src', url);

	},
	
	hide: function() {
		$('.screen, .lightbox').animate({'opacity':0}, function() {
			$(this).remove();
		});
	}
};

SHRM.lightbox.init();

// Asynchronous Twitter feed

SHRM.loadTwitterStatus = function(user, scope, callback) {
	if($(scope).length > 0) {
		$.ajax({
			data: {
				count: 5
			},
			dataType: 'jsonp',
			jsonpCallback: 'callback',
			url: 'http://twitter.com/statuses/user_timeline/'+user+'.json',
			success: function(data) {
				$.each(data, function(i, item) {
					// find urls in tweets and add anchors
					var text = item.text.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'<a href="$&" target="_blank">$&</a>');
					// now find tags and add anchors
					text = text.replace(/#([a-zA-Z0-9_]*)/gim,'<a href="http://twitter.com/#search?q=$&" title="see messages tagged $& on Twitter">$&</a>');
					// now find user names and add anchors
					text = text.replace(/@([a-zA-Z0-9_]*)/gim,'<a href="http://twitter.com/$&" title="$& profile on Twitter">$&</a>');
					// fix hashes in urls
					text = text.replace(/q=#/,'q=%23');
					$(scope).append("<li><p>"+text+"</p><p class='date'>"+prettyDate(item.created_at)+"</p></li>");
					if(callback && typeof(callback) === "function") {
						callback();
					}
				});
			},
			error: function() {
				$('div.twitter').hide();
			}
		});
	}
};

SHRM.loadTwitterStatus('weknownext', 'ul.twitter');

// Sidebar Navigation Accordion

SHRM.accordion = function(scope) {
	return $(scope).each(function() {
		var $this = $(this);
		$this.children().children('a').bind('click', function(e) {
			e.preventDefault();
			$(this).parent().find('ul').slideToggle(200, 'swing', function() {
				$(this).parent().toggleClass('closed');
			});
		});
	});
};

SHRM.accordion('.accordion');

// Custom select box replacement

SHRM.selectReplace = function(selector) {
	$(selector).each(function() {
		var $this = $(this);
		$this.change(function() {
			$this.siblings('.value').html($this.find('option[value="' + $this.val() + '"]').html());
		});
	});
};

SHRM.selectReplace('select');

// Form validation

SHRM.forms = {
	errors: {
		setError: function(field) {
			var $field = $(field);
			$field.data('errors', $field.data('errors') + 1);
			$field.parent().addClass('error');
		},
		setValid: function(field) {
			var $field = $(field);
			$field.data('errors', $field.data('errors') - 1);
			if($field.data('errors') == 0) {
				$(field).parent().removeClass('error');
			}
		}
	},
	
	validators: {
		isPopulated: function(field) {
			var $field = $(field);
			if($field.val() != "" && $field.val() != field.defaultValue)
				return true;
			return false;
		},
		isValidEmail: function(email) {
			function trimString(str) { 
				return str.replace(/^\s+|\s+$/g, '');
			};
			email = trimString(email);
			emailpat = /^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
			if(!emailpat.test(email))
				return false;
			return true;
		}
	},
	
	validate: function(form) {
		var $form = $(form),
			valid = true;
		$form.find('.email').each(function() {
			if($(this).val() != "" && !SHRM.forms.validators.isValidEmail(this.value)) {
				valid = false;
				SHRM.forms.errors.setError(this);
			} else {
				SHRM.forms.errors.setValid(this);
			}
		});
		$form.find('.required').each(function() {
			if(!SHRM.forms.validators.isPopulated(this)) {
				valid = false;
				SHRM.forms.errors.setError(this);
			} else {
				SHRM.forms.errors.setValid(this);
			}
		});
		
		return valid;
	}
};

