/* Define NEA namespace */
if( typeof NEA == "undefined" || !NEA ) { var NEA = {}; }
NEA.namespace = function() {
	var a=arguments, o=null, i, j, d;
	for (i=0; i<a.length; i=i+1) {
		if( typeof(a[i]) !== 'string' ) { continue; }
		d=a[i].split(".");
		o=window;
		for (j=0; j<d.length; j=j+1) {
			o[d[j]]=o[d[j]] || {};
			o=o[d[j]];
		}
	}
	return o;
};

NEA.define = function( a ) {
	return NEA.namespace( "NEA." + a );
};



/* Placeholder Text Attribute */
/* Placeholder Text Helper */
NEA.define( 'Placeholder' );
NEA.Placeholder = function() {

	function testPlaceholder() {
		var i = document.createElement( 'input' );
		return 'placeholder' in i;
	}

	var hasPlaceholder = testPlaceholder();
	if( hasPlaceholder ) {
		return;
	} else {
		/* This doesn't address the issue with password field being unable to show
		   placeholder text as a readable word. It will show up as **** per usual.
		*/
		$( 'input[placeholder], textarea[placeholder]' ).each( function() {
			var $elem = $(this),
				$elValue = $elem.val(),
				placeholder = $elem.attr( 'placeholder' );
			if( $elValue !== placeholder ) {
				$elem.val( placeholder ).addClass('placeholder');
				$elValue = $elem.val();
			}

			$elem.focus( function() {
				var $el = $(this);
				$el.removeClass('placeholder');
				if( $elValue == placeholder ) {
					$el.val( '' );
				}
				$elValue = $el.val();
			});

			$elem.blur( function() {
				$elValue = $(this).val();
				if( $elValue == placeholder || $elValue == '' ) {
					$(this).val( placeholder ).addClass('placeholder');
				} else {
					$(this).val( $elValue );
				}
				$elValue = $(this).val();
			});
		});
	}
};


/* Dropdown Menu */
NEA.define( 'Menu' );
NEA.Menu = function() {

	// Add toggle class to drop-down menus
	$('.util-nav > li').each(function() {
		var $tab = $(this);
		if( $tab.find('ul').length ) {
			$tab.find('a:first').addClass('toggle');
		}
	});

	function showMenu() {
		$(this).addClass('hover').find('.submenu').fadeIn(200);
	}

	function hideMenu() {
		$(this).removeClass('hover').find('.submenu').fadeOut(200);
	}

	$('.util-nav .toggle').parent().hoverIntent({
	     over: showMenu, // function = onMouseOver callback (REQUIRED)
	     timeout: 300, // number = milliseconds delay before onMouseOut
	     out: hideMenu // function = onMouseOut callback (REQUIRED)
	});
};


/* Topic Filter */
NEA.define( 'TopicFilter' );
NEA.TopicFilter = function() {

	var $filter = $('#topicfilter');

	$filter.change(function() {
		if ($filter.val() != "") {
			var sr = "?topic=" + $filter.val();
			window.location.search = sr;
		}
		else {
			window.location = window.location.href.split("?")[0];
		}
	});

};


/* Billboard */
NEA.define( 'Billboard' );
NEA.Billboard = function( config ) {

	var config = {
		'wrapper': config.wrapper || '.billboard',
		'rotatingArea': config.rotatingArea || config.wrapper + ' .billboard-body',
		'slides': config.slides || config.wrapper + ' li'
	};

	config.slidesLen = $(config.slides).length;

	var self=this;
	if( config.slidesLen > 1 ) {
		self.init( config );
	}
};

NEA.Billboard.prototype = {

	init: function( config ) {
		var self = this;
		if( $('body').width() >= 960 ) {
			$.getScript('/wp-content/themes/nea/js/libs/jquery.cycle.custom.min.js', function() {
				self.cycleBillboard( config );
				$( config.wrapper ).addClass( 'billboard-cycle' );
			});
		}
	},

	cycleBillboard: function( config ) {
		$( config.rotatingArea ).before('<div id="controls" />').cycle({
			fx:					'scrollHorz',
			speed:				'500', // Transition speed
			timeout: 			neaSliderOptions['timeout'],
			cleartype:			true,
			cleartypeNoBg:		true,
			activePagerClass:	'on',
			pager:				'#controls',
			startingSlide:      neaSliderOptions['startingSlide'],
			pause:              neaSliderOptions['pause']
		});
	}

};


/* Convert Email Addresses */
NEA.define( 'EmailAddress' );
NEA.EmailAddress = function() {

	$('.email').each(function() {
		var $email = $(this),
			$emailParts = $email.text().split(' ');

		if( $emailParts.length === 3 ) {

			var person = $emailParts[0],
			    domain = $emailParts[2],
			    fullEmail = person + '@' + domain;

			// create email mailto & insert email mailto after original span
			var $mailto = $( '<a />' )
			                 .attr( 'href', 'mailto:' + fullEmail )
			                 .text( fullEmail )
			                 .insertAfter( $email );

			// remove original email span
			$email.remove();

		}
	});
};


/* Comment Ratings */
NEA.define('CommentRatings');
NEA.CommentRatings = function() {
	if( $('.comment-list').length ) {
		$('.like a, .dislike a').click(function(e) {
			e.preventDefault();
			var neaClicked = $(this);
			$.get(this.href, function(data, status, jqXHR) {
				if( data.accepted === true ) {
					neaClicked.html(data.rating);
					var note = "";
					if( neaClicked.parent().hasClass('like') ) {
						note = "You like.";
					}
					else if( neaClicked.parent().hasClass('dislike') ) {
						note = "You don't like.";
					}
					neaClicked.parent().parent().children('.label').text(note);
				} else {
					neaClicked.parent().parent().children('.label').text("You can't vote on this comment again.");
				}
			});
		});	
	}
};


/* IE Polyfill Items */
NEA.define( 'IE' );
NEA.IE = function() {
	if( $.browser.version < 7 ) {
		// Add value text back to search button
		$('#search-submit').val('Go');
	}

	if( $.browser.version < 9 ) {
		// Input types and buttons
		$('input:text').addClass('input-text');
		$('input:checkbox, input:radio').addClass('input-check');
		$('input[type="submit"], input[type="button"]').addClass( 'btn-submit' );
		$('input[type="search"]').addClass('input-search');
		$('input[type="email"]').addClass('input-email');

		// Children
		$( '.util-bar li:first-child, .aside li:first-child, .breadcrumbs a:first-child, .footer li:first-child, .breadcrumbs li:first-child, .blockquote p:first-child').addClass('first-child');
		$('.aside > div').addClass('widget');
		$('.primary-nav li:last-child, .util-nav li:last-child, .breadcrumbs li:last-child').addClass('last-child');

		// Table classes
		$('.main-content tbody').each(function() {
			$(this)
				.find('tr:first').addClass('first-child').end()
				.find('tr:last').addClass('last-child').end()
				.parent().find('tfoot td:first').addClass('first-child')
			;
		});

	}
};


$(document).ready(function() {
	var $body = $('body');
	$body.removeClass('no-js');
	if( $body.width() >= 960 ) {
		$body.addClass('wide-view');
		// Initialize billboard
		var billboard = new NEA.Billboard(config = { 'wrapper': '.billboard' });
	}
	
	if( $.browser.msie ) {
		var ie = new NEA.IE();
	}
	
	// Add class to external links
	$('.content a').filter(function() {
		return this.hostname.replace('www.','') && this.hostname.replace('www.','') !== location.hostname.replace('www.','');
	}).addClass('external');
	
	// Add utility classes to table cells
	$('.main-content tbody').each(function() {
		$(this)
			.find('tr:first').addClass('first').end()
			.find('tr:last').addClass('last').end()
			.parent().find('tfoot td:first').addClass('first')
		;
	});
	
	// Validate Comment Form
	if($('#comment-form').length) {
		Modernizr.load({
			both : [ '/wp-content/themes/nea/css/validationEngine.min.css', '/wp-content/themes/nea/js/libs/languages/jquery.validationEngine-en.js', '/wp-content/themes/nea/js/libs/jquery.validationEngine.min.js' ],
			complete : function () {
				$("#comment-form").validationEngine();
			}
		});
	}
	
	var dropdowns = new NEA.Menu();
	var placeholders = new NEA.Placeholder();
	var topicfilter = new NEA.TopicFilter();
	var emails = new NEA.EmailAddress();
	var ratings = new NEA.CommentRatings();

});
