// 2010.05.28 KJD: Document created

var goodUsername	= false;

// 2011.01.06 KJD: Set a dummy cookie
$.cookie( 'cookieset', true );

$( document ).ready(function(){

	// 2010.06.09 KJD: Table sorting
	$("table.list").tablesorter();
	
	// 2010.06.09 KJD: Set up the links for numbers
	$( 'table.list tfoot td.total' ).each(function(){
		var thisTotal	= 0;
		var theseRows	= $( this ).parents('table').find('tbody tr');
		
		$( theseRows ).each(function(){
			var thisCount	= parseInt( $( this ).find('td:last').text() ) || 0;
			thisTotal += thisCount;
		});

		$( this ).html( thisTotal );
	});
	
	// 2010.06.09 KJD: Remove rows with no numbers
	$( 'table.noempty tbody tr' ).each(function(){
		var thisSum	= 0;
		$( this ).find('td').each(function(){
			var thisValue	= getDigits( $( this ).text() );
			thisSum += (thisValue)?parseInt( thisValue ):0;
		});
		
		if( !thisSum ){	$( this ).addClass('hidden');	}
		
	});

	$("#mycarousel").jcarousel({
        scroll: 1,
        itemLoadCallback: mycarousel_itemLoadCallback,
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
	
	$('.gallery .toolbar .perpage').change(function(){
		myCarousel.reset();
		return false;
	});
	
	// 2010.06.12 KJD: Create the ride image links
	$('.rideinfo .photocount').each(function(){
		var photoinfo	= eval('(' + $(this).attr('rel') + ')');
		for(var i=1;i<=photoinfo['totalphotos'];i++){
			$(this).find('ul').append("<li><A href='" + photoinfo['ridesfolder'] + photoinfo['id'] + "_" + i + ".jpg' rel='ridephoto'>" + i + "</a></li>");
		}
		
		$(this).find('a').colorbox({
			width: "640px"
		});
	});
	
	// 2010.06.12 KJD: Check for empty tables
	if( !$('table.list a').length ){
		$('table.list')
			.after("no items currently available for this search.")
			.hide();
	}
	
	// 2010.06.13 KJD: Show state image or interactive map
	if( $('td.city a:visible').length ){
		initialize( $('#map_canvas').attr('rel') );
	}
	
	// 2010.06.13 KJD: Get directions
	$('.directions a').click(function(){
		$( ".googleMapForm .endAddress" ).val(
			$('.locationinfo .address1').text() + " " +
			$('.locationinfo .location').text()
		);
		$( ".googleMapForm FORM" ).submit();
	});
	
	// 2010.06.14 KJD: Check for comment form
	$('form.comment')
		.validate({
			submitHandler:function(form){
				$('.commententry').fadeOut(500);
				
				$.ajax({
					type: 'POST',
					url: thisfilename,
					data: $(form).serialize(),
					success: function(thisResponse){
						$( '.commentlist' ).append( thisResponse );
					}
				});
			}
		});
	
	// 2010.06.14 KJD: Check for label overs
	$('label.labelOver').labelOver();
	
	$( '.reportabuse a, a.reportabuse').click(function(){
		$.ajax({
			type: 'POST',
			url: thisfilename,
			data:{
				'page'	: 'reportabuse',
				'id'	: location.href
			},
			success: function(){
				alert( 'Thank you telling us about this page.');
			}
		});
	});
	
	// 2010.06.14 KJD: Contact user
	$('.rideinfo div.contact a').click(function(){
		
		// 2011.01.06 KJD: Only show if cookie available
		if( $.cookie( 'cookieset' ) ){
			$( 'form.contactuser').fadeIn(500);
			$( this ).hide(0);
		}
		
	});
	
	$('form.contactuser')
		.validate({
		submitHandler:function( form ){
			$('form.contactuser').fadeOut(500);
			
			if( $.cookie( 'cookieset' ) ){
				$.ajax({
					type: 'POST',
					url: thisfilename,
					data: $( form ).serialize() + "&ridelocation=" + escape( location.href ),
					success: function(thisResponse){
						$('div.contactuser .messagesent').fadeIn(500);
					}
				});
			}
		}
	});
	
	$('form.myridelogin')
	.validate({
		submitHandler:function( form ){
			$('form.contactuser').fadeOut(500);
			
			$.ajax({
				type: 'POST',
				url: thisfilename,
				data: $( form ).serialize(),
				success: function(data){
					var myObject = eval('(' + data + ')');
					if( myObject['status'] == 'success' ) {
						location.href= "myride.php";
					} else {
						$( '.myrides_login .loginerror' ).show(500);
					}
				}
			});
		}
	});
	
	// 2010.07.13 KJD: Separate each required
	// $('form.submitevent, form.submitrace, form.searchform').validate();
	$('form.submitevent').validate();
	$('form.submitrace').validate();
	$('form.searchform').validate();
	
	// 2010.07.28 KJD: Set to real
	$( "form.submitevent input[name='isReal'], form.submitrace input[name='isReal']" ).val('yes');
	
	$('form.submitclub, form.submitcruisein, form.submitracetrack, form.contactus').validate({
		submitHandler:function( form ){
			$.ajax({
				type: 'POST',
				url: thisfilename,
				data: $( form ).serialize(),
				success: function(response){
					alert(response);
					$( form ).find('.reset').click();
				}
			});
		}
	});
	

	// 2010.10.15 KJD: Create the makes and models
	// 2011.05.04 KJD: try it if exists
	try{
		createmakemodels();	
	} catch( e ){}
	
	
	// 2010.06.16 KJD: Do label overs
	$( 'label.labelOver' ).labelOver();
	
	// 2010.06.17 KJD: Set up the date picker
	$(".datepicker").datepicker({ 
		dateFormat: 'yy-mm-dd',
		changeYear: true,
		changeMonth: true
	});

	// 2010.06.17 KJD: When start changes, change ending date
	$('form .start input').change(function(){
		if( $('form .end input').length ){
			$('form .end input').val($(this).val() );
		}
	});
	
	// 2010.06.24 KJD: Check upcoming events
	$("div.events div.EventListItem").click(function(){
		gotoUrl( $(this).attr('rel') );
	});
	
	// 2010.06.25 KJD: Do gas buddy
	if( $('div.gasbuddy').length ){
		if( !$('div.gasbuddy .imagelink img').width() ){

			$( '.gasbuddy .gasform').show(500);
			$('div.gasbuddy .imagelink').hide(500);
		}
	}
	
	// 2010.06.29 KJD: Check for headlines
	$( '.headlines .items ul li' ).click(function(){
		//alert("go to:" + $(this).attr('rel'));
		$('.headlineform')
			.attr('action',$(this).attr('rel'))
			.submit();
	});
	
	$( "form.myridecreate input[name='username']").blur(function(){

		$.ajax({
			type: 'POST',
			url: thisfilename,
			data: {
				'page':		'checkusername',
				'username': $(this).val()
			},
			success: function(data){
				var myObject = eval('(' + data + ')');
				if( myObject['status'] == 'available' ) {
					goodUsername = true;
				} else {
					goodUsername = false;
					alert('Sorry, this username is already taken.\nPlease enter a different username.');
				}
			}
		});
	});

	// 2010.08.09 KJD: Submit the form
	$('form.myridecreate')
		.attr({'action':thisfilename})
		.validate({
			submitHandler:function(thisForm){
				if( goodUsername ){
					thisForm.submit();
				} else {
					alert( 'Please select a different username.' );
					$( "form.myridecreate input[name='username']").focus();
					return false;
				}
			}
		});
	
	// 2010.08.10 KJD: forgot password link
	$( 'a.forgotpassword').click(function(){
		var thisusername	= prompt("Enter your username and we will send your password reset to the email address you have provided:");
		
		if( thisusername ){
			$.ajax({
				type: 'POST',
				url: thisfilename,
				data: {
					'page':		'resetpassword',
					'username': thisusername
				},
				success: function(data){
					var myObject = eval('(' + data + ')');
					if( myObject['status'] == 'success' ) {
						alert("Please check your email for your new password");
					} else {
						alert('Sorry, that username was not found.');
					}
				}
			});
		}
	});

	// 2010.09.27 KJD: look for years drop-down
	$( 'select.years' ).each(function(){
		var lowYear		= 1880;
		var thisDate	= new Date();
		var highYear	= thisDate.getFullYear() + 2;
		var thisHtml	= "";
		
		for( var i = highYear; i >= lowYear; i--){
			thisHtml	+= "<option value=" + i + ">" + i + "</option>";
		}
		
		$( this ).append( thisHtml );
	});
		
	// 2011.05.31 KJD: columnize the state links
	if( jQuery.isFunction(jQuery.fn.columnize ) ){
		$( 'ul.statelist' ).columnize({ columns:3 });
	}
	
});




