$(document).ready(function() {

	/* Make all links with class external open in new tab */
	$("a.external").attr('target','_blank');
	
	/* If we are in the News section */
	if ($("div.yearlyNews").length) {
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		/* Check if we clicked on a year link */
		if ( vars['year'] != null ) {
			$("a#link"+vars['year']).addClass("selected");
			$("div.yearlyNews").hide();		
			$("div#year"+vars['year']).show();
		} else {
			/* No year link was clicked on so select the first year displayed */
			$("a.year").first().addClass("selected");
		}
	} else {
		/* If we are in a News detail page, select the proper year link */
		$("a#link"+$("div#yearOfNews").html()).addClass("selected");
	}
	
	/* If there is a form on the page */
	if( $("div#formContainer").length ) {
		$("input[type='checkbox']").custCheckBox();
		$("a#showRequestForm").click(function () {
		  $("div#formContainer").slideToggle("fast");
		  trackForm();
		});
		$("a#close").click(function () {
		  $("div#formContainer").slideToggle("fast");
		});
		$('span.cust_checkbox').click(function() {
			$('p#sites').hide();
		});
		$('#submitButton').click(function() {
			var wSite = true;
			if( $("input:checkbox").length ) {
				if( $("input:checkbox:checked").length == 0 ) {
					wSite = false;
					$('p#sites').show("fast");
				}
			}
			if ($('#requestSalesCallForm').valid() && wSite ) {
			  $.ajax({ 
				type: 'POST', 
				url: '/mediagrif/sendForm', 
				data: $('#requestSalesCallForm').serialize(), 
				dataType: "xml", 
				success: function(xml) { 
						if ( $(xml).find('message').text() == 'success' ) {  
							$("div#formContainer").slideToggle("fast");
							$('p#successMsg').show("fast");
							trackSuccess();
						} else { 
							$('p#errorMsg').show("fast");
						}
					}, 
				error: function() { $('p#errorMsg').show("fast"); } });                     
			  }
		});
		$('textarea#comments').elastic();
		$("textarea#comments").counter({
			type: 'char',
			count: 'up',
			goal: 250
		}); 
	}
	
});

