/**
 * Mutes firebug console code and errors on browsers where firebug is not installed
 */
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", 
	"groupCollapsed", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
	}
}

/*	FUNCTIONS THAT CAN BE CALLED
-------------------------------------------------------------- */

	// Other Functions (must be called from DOM Ready or Window.load)

/*	DOM-READY FUNCTION
-------------------------------------------------------------- */
$(function() {
	
	// Insert IE6 Warning
	if ($.browser.className == "msie6") {
		$.ajax({
			url: '/assets/xhr/ie6-warning.html',
			success: function(html){
				$('body').prepend(html);
			}
		});
	}
	
	//Goulet!
	var goulet = $('#goulet');
	$('#content').append(goulet);
	goulet.show();
	
	// Goulet read-more link
	var ginner = $('#goulet .inner')
	ginner.hide();
	$('#gouletMore a').click( function() {
		ginner.toggle();
		if ( ginner.is(':visible') ) {
			$(this).text('read less')
		} else {
			$(this).text('read more')
		}
		return false;
	});
	
		
	$(".pagePrev").click(
	    function (){ 
	        var pge = parseInt($("#pge").val());
	        $("#pge").val(pge-1).get(0).form.submit();
	        return false;

	});
	
	$(".pageNxt").click(
	    function (){ 
	        var pge = parseInt($("#pge").val());
	        $("#pge").val(pge+1).get(0).form.submit();
	        return false;

	});
	
	//Equal column heights
	$('.result').each( function() {
		$(this).find('.theTruck, .thePrice, .theDetails').equalHeights();
	})
	$('.profileHead div').equalHeights();
	// $('.customerReview').each( function() {
	// 		$(this).find('.reviewLeft, .reviewRight').equalHeights();
	// 	})
	
	
	// Directions field interactions
	function showDirections(that) {
		$('#callToAction .directions div:visible').hide();
		that.closest('td').next('td').find('div').fadeIn('fast');
	}
	function hideDirections(that) {
		that.closest('td').next('td').find('div').fadeOut('fast');
	}
	$('#callToAction input, #callToAction select').focus( function() {
		$('#getStarted').css('opacity',.4);
		showDirections($(this));
	}).blur( function() {
		$('#getStarted').css('opacity',1);
		hideDirections($(this));
	});
	$('.samePickup').hover(function() {
		$('#callToAction .directions div:visible').addClass('wasVisible').hide();
		showDirections($(this));
	}, function() {
		$('#callToAction .directions div.wasVisible').fadeIn('fast').removeClass('wasVisible')
		hideDirections($(this));
	});
	
	// Handle the "same as pickup" functionality
	function dupDropOff() {
		//$('.txtDateEnd').val($('.txtDateStart').val()).attr("disabled", true).next('img').hide()
		$('.txtZipcodeEnd').val($('.txtZipcode').val()).attr("disabled", true);
	}
	function activeDupDropOff() {
		if ( $('.chkSamePickup input').is(':checked') ) {
			dupDropOff();
		}
	}
	
	// When the page loads, check to see if the box is checked:
	activeDupDropOff();
	
	// Do it when the checkbox is checked
	$('.chkSamePickup input').change( function() {
		if ( $(this).is(':checked') ) {
			dupDropOff();
		} else {
			$('.txtDateEnd, .txtZipcodeEnd').removeAttr("disabled"); 
			$('.txtDateEnd').next('img').show()
		}
	}).click( function() {
		if ( $(this).is(':checked') ) {
			dupDropOff();
		} else {
			$('.txtDateEnd, .txtZipcodeEnd').removeAttr("disabled"); 
			$('.txtDateEnd').next('img').show()
		}
	})
	// ...or when the values for the "Pick Up" section change.
	$('.txtZipcode').keyup( function() {
		activeDupDropOff();
	}).blur( function() {
		activeDupDropOff();
	}).click( function() {
		activeDupDropOff();
	})
	
	// Calendar Widgets
	$('.dateInput').datepicker({
		showOn: 'button',
		buttonImage: '/assets/images/calendar.png',
		buttonImageOnly: true,
		onSelect: function() { activeDupDropOff() }
		});
		
	$('.txtmiles').valueHold();
	
	// Form Validation
	$('.txtDateStart, .txtDateEnd, .txtZipcode, .txtZipcodeEnd, .txtmiles, .ddlTruckType').focus( function() {
		$(this).removeClass('invalid')
	})
	
	function validateCallToAction() {
		
		//Reset the errors
		$('.callToActionErrors').hide().children().remove();
		$('.txtDateStart, .txtDateEnd, .txtZipcode, .txtZipcodeEnd, .txtmiles, .ddlTruckType').removeClass('invalid');
		
		// Set the validator to true by default
		var validForm = true;
		
		var numOnly = /^[0-9]+$/;
		
		//Check for empty fields:
		//$('.txtDateStart, .txtDateEnd, .txtZipcode, .txtZipcodeEnd').
		var errorForm = $('.callToActionErrors')
		
		// Validate the date
		if ( $('.txtDateStart').val().length == 0 ) {
			errorForm.append('<li>Doh! You need to pick a <strong>Pick Up Date</strong></li>')
			$('.txtDateStart').addClass('invalid')
			validForm = false;
		}
		var d1,d2
		d1=new Date($('.txtDateStart').val())
		d2=new Date($('.txtDateEnd').val())
		var tD =new Date(now.getMonth() + "/" + now.getDay() + "/" + now.getFullYear())
		// Validate the date
		if ( d1=tD ) {
			errorForm.append('<li>Whops! Most carriers won\'t let you book online for same day!</li>')
			$('.txtDateStart').addClass('invalid')
			validForm = false;
		}
		
		// Validate the zip
		if ( $('.txtZipcode').val().length == 0 ) {
			errorForm.append('<li>Wait! You need to pick a <strong>Zip Code</strong> where you\'ll pick this thing up.</li>')
			$('.txtZipcode').addClass('invalid')
			validForm = false;
		}
		if ( !numOnly.test( $('.txtZipcode').val() ) ) {
		   	errorForm.append('<li>Err. <strong>A zip code</strong> can only contain numbers. 5 digits to be precise.</li>')
			$('.txtZipcode').addClass('invalid')
			validForm = false;
		}
		
		// Validate the date
		if ( $('.txtDateEnd').val().length == 0 ) {
			errorForm.append('<li>Hey! You have to pick a <strong>Drop Off Date</strong></li>')
			$('.txtDateEnd').addClass('invalid')
			validForm = false;
		}
		
		
		
		// Validate the date
		if ( d1>d2) {
			errorForm.append('<li>Hey! The <strong>Drop Off Date</strong> is before the <strong>Pick Up Date</strong>!</li>')
			$('.txtDateEnd').addClass('invalid')
			validForm = false;
		}
		
		// Validate the zip
		if ( $('.txtZipcodeEnd').val().length == 0 ) {
			errorForm.append('<li>Hold on! You need to pick a <strong>Zip Code</strong> where you\'ll drop the truck off.</li>')
			$('.txtZipcodeEnd').addClass('invalid')
			validForm = false;
		}
		if ( !numOnly.test( $('.txtZipcodeEnd').val() ) ) {
		   	errorForm.append('<li>Err. <strong>A zip code</strong> can only contain numbers. 5 digits to be precise.</li>')
			$('.txtZipcodeEnd').addClass('invalid')
			validForm = false;
		}
		
		// Validate the txtmiles
		if ( ($('.txtmiles').val().length == 0) || ( $('.txtmiles').val() == 'number of miles' ) ) {
			errorForm.append('<li>Not so fast! <strong>How many miles</strong> will you drive the truck (including to/from the rental location)?</li>')
			$('.txtmiles').addClass('invalid')
			validForm = false;
		}
		if ( !numOnly.test( $('.txtmiles').val() ) ) {
		   	errorForm.append('<li>Please put the number of miles. <strong>Numbers only</strong> please.</li>')
			$('.txtmiles').addClass('invalid')
			validForm = false;
		}
		
		// Validate the size truck
		if ( $('.ddlTruckType').val() == '-1' ) {
			errorForm.append('<li><strong>What size of truck</strong> do you want to search for?</li>')
			$('.ddlTruckType').addClass('invalid')
			validForm = false;
		}
		
		// See if the form is valid
		if ( validForm ) {
			// Submit it
			console.log('Form is valid')
		} else {
			console.log('Form is invalid');
			$('.callToActionErrors').fadeIn('fast')
		}
		return validForm;
		
	}
	
	// Call to action button
	$('.ctaSubmit').click( function() {
		return validateCallToAction();
	});
	
	/*
	// Truck size modal
	$("#dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		//height: 140,
		width: 500,
		modal: true
	});
	
	$('.truckSizeModal').click(function() {
		$("#dialog").dialog('open')
		return false;
	});
	*/
	
	$('.inputReview').growfield().maxlength({   
		//events: [], // Array of events to be triggerd    
		maxCharacters: 3000, // Characters limit   
		//status: true, // True to show status indicator bewlow the element    
		statusClass: "charCount", // The class on the status div  
		statusText: "characters left", // The status text  
		notificationClass: "lengthInvalid"	// Will be added when maxlength is reached  
		//showAlert: false, // True to show a regular alert message    
		//alertText: "You have typed too many characters.", // Text in alert message   
		//slider: true // True Use counter slider    
	}); 
  
	function validateReview() {
		
		//Reset the errors
		$('.reviewErrors').hide().children().remove();
		$('.inputFirstName, .inputLastName, .inputEmail, .inputCity, .inputState, .inputProMover, .inputStarRating, .inputReview').removeClass('invalid').focus( function() {
			$(this).removeClass('invalid');
		})
		
		// Set the validator to true by default
		var validReviewForm = true;
		
		var emailFormat = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		
		//Check for empty fields:
		//$('.txtDateStart, .txtDateEnd, .txtZipcode, .txtZipcodeEnd').
		var errorForm = $('.reviewErrors')
		
		// Validate First name
		if ( $('.inputFirstName').val().length == 0 ) {
			errorForm.append('<li>Doh! You didn\'t fill out your <strong>First Name</strong></li>')
			$('.inputFirstName').addClass('invalid')
			validReviewForm = false;
		}
		
		// Validate Last name
		if ( $('.inputLastName').val().length == 0 ) {
			errorForm.append('<li>Hey! You need to fill in your <strong>Last Name</strong></li>')
			$('.inputLastName').addClass('invalid')
			validReviewForm = false;
		}
		
		// Validate email
		if ( $('.inputEmail').val().length == 0 ) {
			errorForm.append('<li>Err... You need to fill in your <strong>Email Address</strong></li>')
			$('.inputEmail').addClass('invalid')
			validReviewForm = false;
		}
		if ( !emailFormat.test( $('.inputEmail').val() ) ) {
		   	errorForm.append('<li>Please put a <strong>valid Email Address</strong></li>')
			$('.inputEmail').addClass('invalid')
			validReviewForm = false;
		}
		
		// Validate the city
		if ( $('.inputCity').val().length == 0 ) {
			errorForm.append('<li>Hey! You have to pick a <strong>Zip Code</strong></li>')
			$('.inputCity').addClass('invalid')
			validReviewForm = false;
		}
		
//		// Validate the state
//		if ( $('.inputState').val() == 'none' ) {
//			errorForm.append('<li>Hold on! You need to pick a <strong>State</strong></li>')
//			$('.inputState').addClass('invalid')
//			validReviewForm = false;
//		}
		
		// Validate the star rating
		if ( $('.inputStarRating').val() == '0' ) {
			errorForm.append('<li>Wait wait wait! You did not choose a <strong>Star Rating</strong></li>')
			$('.inputStarRating').addClass('invalid')
			validReviewForm = false;
		}
		
		// Validate the review
		if ( $('.inputReview:eq(1)').val().length == 0 ) {
			errorForm.append('<li>Wait! Don\'t you want to <strong>Leave A Review</strong>?</li>')
			$('.inputReview:eq(1)').addClass('invalid')
			validReviewForm = false;
		}
		
		// See if the form is valid
		if ( validReviewForm ) {
			// Submit it
			console.log('Form is valid')
		} else {
			console.log('Form is invalid');
			$('.reviewErrors').fadeIn('fast')
		}
		return validReviewForm;
		
	}
	
	// Call to action button
	$('.ctaReviewSubmit').click( function() {
		return validateReview();
	});
	
});


	$('.result').each( function() {
		var conversionCompany = $(this).find('h4').text();
		var conversionButton = $(this).find('.bookOnline a');
		if ( conversionCompany.match('Budget') ) {
			conversionButton.click( function() {
				pageTracker._trackEvent('button', 'click', 'Budget Conversion');
				pageTracker._trackPageview('/bookonline/budget')
			})
		}
		if ( conversionCompany.match('Ryder') ) {
			conversionButton.click( function() {
				pageTracker._trackEvent('button', 'click', 'Ryder Conversion');
				pageTracker._trackPageview('/bookonline/ryder')
			})
		}
		if ( conversionCompany.match('Penske') ) {
			conversionButton.click( function() {
				pageTracker._trackEvent('button', 'click', 'Penske Conversion');
				pageTracker._trackPageview('/bookonline/penske')
			})
		}
	})
	
	
function doPoll(reviewid,type){
    
    
        $.ajax({
              type: "POST",
              contentType: "application/json; charset=utf-8",
              url: "/_ws/poller.asmx/LogAction",
              data: "{'reviewID':'" + reviewid +"','logtype':" + type + "}",
              dataType: "json",
              success: function(msg){
                cb(msg)
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('There was a problem submitting your ping, sorry!')
                //alert(XMLHttpRequest);
                //alert(textStatus);
              }//,
              //complete: function() {$("#ajaxLoader").remove();}
            });
            
       $("#r" + reviewid + "-" + type).html('Thanks!');
            
    
}


/*	WINDOW LOADED FUNCTION
-------------------------------------------------------------- */
// $(window).load(function () {
// 	
// 	// Page loaded stuff here
// 
// });
