/**
 *
 */

var cdc = {
	
	init: function() {
		
		cdc.init_navigation();
		cdc.init_useful_links();
		cdc.init_search();
		cdc.init_external_links();
		
	}
	
	,init_navigation: function() {
		
		$('.side-navigation .navigation > li > a').click(function() {
			
			$(this).blur();
			
			if( $(this).parent().hasClass('open') ) {
				$(this).parent().removeClass('open');
				$(this).parent().find('ul').slideUp('normal');
				return false;
			} else {
			
				if( $(this).parent().find('ul').length > 0 ) {
					var navopt = $(this);
					//$(navopt).parent().addClass('open');
					
					$(this).parent().find('ul').slideDown('normal', function() {
						$(navopt).parent().addClass('open');
					});
					return false;
				} else {
					$(this).parent().addClass('selected');
				}
				
			}

			if( $(this).attr('href') == '#' ) {
				return false;
			}

		});
		
		$('#navigation > li:last').addClass('last-item');
		
	}
	
	,init_useful_links: function() {
		
		$('.useful-links li:last').addClass('last-item');
		
		$('.useful-links a').click(function() {
			if( $(this).attr('href') == '#' ) {
				return false;
			}
		});
		
	}
	
	,init_search: function() {
		
		$('#header-search-form').submit(function() {
			var q = $('#q').val();
			if(q && q != 'Enter keywords here') {
				q = q.replace(/ /g,"+");
				q = q.replace(/&/g,"+");
				q = q.replace(/\+\+/g,"+");
				q = q.replace(/\+\+/g,"+");
				q = escape(q);

				var url = "/search/" + q + ".html";
				window.location = url;
			}
			return false;
		});
		
		if( $('#header-search-form #q').val() == '' ) {
			$('#header-search-form #q').addClass('inactive').val('Enter keywords here');
		}
		
		$('#header-search-form #q').focus(function() {
			if( $(this).val() == 'Enter keywords here') {
				$(this).val('').removeClass('inactive');
			}
		}).blur(function() {
			if( $(this).val() == '' ) {
				$(this).addClass('inactive').val('Enter keywords here');
			}
		});
		
	}
	
	,init_external_links: function() {
		
		var hostname = window.location.hostname;
		
		$("a[href^='http']").click(function(e) {
			
			var url = $(this).attr('href');
			if( url.match( hostname ) ) {
				return true;
			}
			
			e.preventDefault();

			window.open( url );
			
		});
		
	}
	
};

$(document).ready(cdc.init);
