function auto() {
	if ( jQuery('#teamrefresh').length != 0 ) {
		jQuery('#teamrefresh').click();
	}
}

jQuery.noConflict();
(function($) {

	$.fn.fieldHolder = function() {
		return this.each(function() {
			var holder = $(this).find('label').hide().text(),
				field = $(this).find('input');
			field.blur(function() {
				if (this.value == '') {
					$(this).val(holder).addClass('holder');
				}
			}).blur();
			field.focus(function() {
				if (this.value == holder) {
					$(this).val('').removeClass('holder');
				}
			});
		});
	};

	// Creating custom :external selector
	$.expr[':'].external = function(obj) {
		return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
	};

	function format_links() {
		$('a:external').addClass('external').click(function() {
			return recordOutboundLink(this, 'Outbound Links', this.href);
		});
	}

	/**
	 * This function is in accordance with Googles recommendations for recording external link clicks:
	 * https://www.google.com/support/googleanalytics/bin/answer.py?hl=en-uk&answer=55527
	 * @param {Object} link
	 * @param {Object} category
	 * @param {Object} action
	 */
	function recordOutboundLink(link, category, action) {
		try {
			pageTracker._trackEvent(category, action);
			setTimeout('document.location = "' + link.href + '"', 100)
		} catch(err) {}
	}

	// Daily Countdown timer
	$.fn.countDown = function(time) {
		return this.each(function() {
			now = new Date();
			var days,day,output = '';
			midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // Otherwise days are out of wack if checking in PM
			time = time.split('-');
			time[1] = time[1] - 1; // 0 based months
			end = new Date(time[0], time[1], time[2]);
			diff = end.getTime() - midnight.getTime();
			days = Math.floor(diff / (1000 * 60 * 60 * 24) );

			if (days < -3) {
				output = '<span>Tuff Truck is coming again next year!</span>';
				vis = 'past';
			} else if ( (days > -4) && (days < 1) ) {
				output = '<span><a href="/location/">Tuff Truck is on right now. GET THERE!</a>	</span>';
				vis = 'now';
			} else {
				days = days.toString();
				for (var i = 0; i < days.length; i++) {
					day = parseInt( days.charAt(i) ); // turn the string back to a number
					var padding = '';
					if (i === 0) {
						padding = (4 - days.length) * 25;
						padding = ';margin-left:' + padding + 'px';
					}
					output += '<strong style="background-position:0 ' + (day * -100) + 'px'+padding+'">' + day + '</strong>';
				}
				output += '<span> Days</span>';
				vis = 'soon';
			}
			return $(this).prepend(output).addClass(vis);
		});
	}

	// Entrant JSON fetch
	function getEntrant() {
		$_entantmod = $('#teamprofile');

		// add refresh button
		$('<a href="#" id="teamrefresh" class="refresh" title="Random Refresh">Refresh</a>').insertBefore('#teamprofile dl').bind('click', function() {
			var refresh = $(this),
				event = 'TTC2012',
				teamno = '000'; // trigger 'random craziness' mode
			refresh.addClass('loading');
			$.getJSON('/entrants/' + event + '/team/' + teamno + '/?json=?', function(data) {
				if (data.teamname) { // quick check
					$_entantmod.find('.media a').attr('href', data.link);
					$_entantmod.find('.media img').attr('src', data.img_m).attr('alt', data.teamname + ' vehicle photo').load(function() {
							refresh.removeClass('loading'); // stop loading animation
							clearTimeout(t);
							t = setTimeout('auto()', 5000);
						});
					$_entantmod.find('dd.teamname a').attr('href', data.link).text(data.teamname);
					$_entantmod.find('dd.carmake').text(data.carmake + ' ' + data.carmodel);
				}
			});
			
			return false;
		}).click(); // run onload
	}

	var t = setTimeout('auto()', 5000);
	
	$(function() {
		format_links();
		$('form div.holder').fieldHolder();

		$('<span id="togo"></span>')
			.insertAfter($('#countdown h3'))
			.countDown( $('.dtstart').attr('title') );

		if ( $('.alt1')[0] ) {
			// adds higher up than description for full body style
			$('#page').addClass('alt1');
		}

		if ($(':input').length != 0) {
			getEntrant();
		}
	});

})(jQuery);
