$(document).ready(function() {
	//-----------------------------------------------------------------//
	//                                                                 //
	//                         VARIABLE INIT                           //
	//                                                                 //
	//-----------------------------------------------------------------//
	var numMonthsAhead = 18;
	var numSBSChosen = 0;
	var pickupDate = pickupDateBackend = dropoffDate = '';
	// number of days from pickupDate that X number of side by sides can be rented
	var numAvailDays = 0;
	var totalDays = price = 0;
	var firstDayOfMonth = $.datepicker.formatDate('yy-mm', new Date()) + '-01';
	var frontendDateFormat = 'mm/dd/yy';

	//-----------------------------------------------------------------//
	//                                                                 //
	//                           FUNCTIONS                             //
	//                                                                 //
	//-----------------------------------------------------------------//

	function getDirLvls() {
		numDirLvls = window.location.pathname.split( '/' ).length - 2;
		var lvlString = '';
		for(var i = 0; i < numDirLvls; i++)
			lvlString += '../';
		return lvlString;
	}

	function errorCheckForm() {
		if(
			$('#numSBS').val() == 0 ||
			$('#pickupDate').val() == '' ||
			$('#pickupTime').val() == 0 ||
			$('#dropoffDate').val() == '' ||
			$('#dropoffTime').val() == 0
			)
			return false;
		else
			return true;
	}
	function flashError() {
		$('#errorContainer').slideDown('slow');
		$('.errorTxt').effect("pulsate", { times:3 }, 2700, function() { $('#errorContainer').slideUp(); });
	}

	function formatCurrency(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
			num = '0';

		sign = 	(num == (num = Math.abs(num)));
		num = 	Math.floor(num * 100 + 0.50000000001);
		cents = num % 100;
		num = 	Math.floor(num / 100).toString();
		if(cents < 10)
			cents = '0' + cents;

		for(var i = 0; i < Math.floor( (num.length - (1 + i)) / 3); i++)
			num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));

		return ( ((sign) ? '' : '-' ) + num + '.' + cents);
	}

	// NOTE: only works for single dimension json obj
	function inJSON(needle, jsonObj) {
		for(var index in jsonObj) {
			if(jsonObj[index] == needle)
				return true;
		}
		return false;

	}
	function getBarrierDays(numSBSChosen, f) {
		if(typeof numSBSChosen == 'function') numSBSChosen();
		// console.log('barrierDays['+numSBSChosen+'] = '+barrierDays[numSBSChosen]);
		if(barrierDays[numSBSChosen] == undefined) {
			// console.log('calling .ajax()');
			$.ajax({
				url: dirLvls+'wp-content/themes/allterrainrentals/scripts/php/ajax.getBarrierDays.php',
				type: 'POST',
				data: ({numSBSChosen: numSBSChosen}),
				dataType: 'json',
				success: function(data) {
					// console.log('.ajax() success!');
					barrierDays[numSBSChosen] = data;
					// console.log('barrierDays['+numSBSChosen+'] = '+barrierDays[numSBSChosen]);
				}
			});
		}
		if(typeof f == 'function') f();
	}

	function getNumAvailDays(f) {
		$.ajax({
			url: dirLvls+'wp-content/themes/allterrainrentals/scripts/php/ajax.getNumAvailDays.php',
			type: 'POST',
			data: ({pickupDate:pickupDateBackend, numSBSChosen:numSBSChosen}),
			dataType: 'text',
			success: function(data) {
				if(data > 1000)
					numAvailDays = numMonthsAhead * 30;
				else
					numAvailDays = data - 1;

				// we need to wait until we have the total number of days
				// available for this reservation before we init the 2nd calendar
				if(typeof f == "function") f();
			}
		});
	}

	function getPriceSBS(totalDays, SBSPrice) {
		var price = minDays = maxDays = '';
		for(var index in SBSPrice) {
			if(totalDays >= SBSPrice[index].minDays && totalDays <= SBSPrice[index].maxDays)
				return SBSPrice[index].price;
		}
	}

	function checkReserved(date) {
		// console.log('checkReserved: '+date);
		ISODate = $.datepicker.formatDate('yy-mm-dd', date);
		for(var day in allReservedDays) {
			if(allReservedDays.hasOwnProperty(day)) {
				if(ISODate == day) {
					// allReservedDays[day] is the number of side by sides rented on that day
					if( (numSBSAvail - allReservedDays[day]) < numSBSChosen)
						return [false];
				}
			}
		}
		return [true];
	}

	function setPickupDate(date) {
		pickupDate = date;
		var dateObj = 		$.datepicker.parseDate(frontendDateFormat, date);
		$('#chosenPickupDate').html($.datepicker.formatDate('DD, MM d yy', dateObj));
		pickupDateBackend = $.datepicker.formatDate('yy-mm-dd', dateObj);

		$('#pickupTime').val(0).removeAttr('disabled');
		clearDisableDropoff();

		// get the last possible day for this reservation
		// based on the pickupDay & number of vehicles they picked
		getNumAvailDays();
	}
	function setDropoffDate(date) {
		dropoffDate = date;

		var dateObj = 		$.datepicker.parseDate(frontendDateFormat, date);
		$('#chosenDropoffDate').html($.datepicker.formatDate('DD, MM d yy', dateObj));

		$('#dropoffTime').removeAttr('disabled');
	}

	function initPickupDatepicker() {
		$('#pickupDatepicker').datepicker({
			changeYear: true,
			numberOfMonths: 2,
			minDate: new Date(),
			maxDate: '+'+numMonthsAhead+'m',
			dateFormat: frontendDateFormat,
			altFormat: 'yy-mm-dd',  // back-end formatted date
			altField: '#pickupDate', // hidden field for back-end use
			hideIfNoPrevNext: true,
			onSelect: setPickupDate,
			beforeShowDay: checkReserved
		}).removeAttr('disabled');
	}
	function initDropoffDatepicker() {
		var maxDateObj = $.datepicker.parseDate(frontendDateFormat, pickupDate);
		maxDateObj.setDate(maxDateObj.getDate() + numAvailDays);
		var maxDate = $.datepicker.formatDate(frontendDateFormat, maxDateObj);

		$('#dropoffDatepicker').datepicker({
			changeYear: true,
			numberOfMonths: 2,
			minDate: pickupDate,
			maxDate: maxDate,
			dateFormat: frontendDateFormat,
			altFormat: 'yy-mm-dd',
			altField: '#dropoffDate',
			hideIfNoPrevNext: true,
			onSelect: setDropoffDate
		}).removeAttr('disabled');
	}

	function resetPickup() {
		// destroy datepicker
		$('#pickupDatepicker').datepicker('hide');
		$('#pickupDatepicker').datepicker('destroy');
		initPickupDatepicker();
		// clear pickupDate
		$('#pickupDatepicker, #pickupDate').val('');
		$('#chosenDropoffDate').html('&nbsp;');
		// clear & disable #pickupTime
		$('#pickupTime').val(0).attr('disabled', 'disabled');
	}
	function clearDisablePickup() {
		// destroy datepicker
		$('#pickupDatepicker').datepicker('hide');
		$('#pickupDatepicker').datepicker('destroy');
		$('#pickupDatepicker').attr('disabled', 'disabled');
		// clear pickupDate
		$('#pickupDatepicker, #pickupDate').val('');
		$('#chosenPickupDate').html('&nbsp;');
		// clear & disable pickupTime
		$('#pickupTime').val(0).attr('disabled', 'disabled');
	}
	function clearDisableDropoff() {
		// destroy datepicker
		$('#dropoffDatepicker').datepicker('hide');
		$('#dropoffDatepicker').datepicker('destroy');
		$('#dropoffDatepicker').attr('disabled', 'disabled');
		// clear dropoffDate
		$('#dropoffDatepicker, #dropoffDate').val('');
		$('#chosenDropoffDate').html('&nbsp;');
		// disable datepicker
		$('#dropoffDatepicker').attr('disabled', 'disabled');
		// clear & disable dropoffTime
		$('#dropoffTime').val(0).attr('disabled', 'disabled');
	}

	function countTotalDays(pickupDate, dropoffDate) {
		if(pickupDate == dropoffDate)
			return 1;

		var nextDayDateObj = $.datepicker.parseDate(frontendDateFormat, pickupDate);
		var count = 1;
		var nextDay = '';
		while(nextDay != dropoffDate) {
			nextDayDateObj.setDate(nextDayDateObj.getDate() + 1);
			nextDay = $.datepicker.formatDate(frontendDateFormat, nextDayDateObj);
			count += 1;
			if(count > 1000) // sanity check
				break;
		}
		return count;
	}


	// split into 2 functions because both require ajax data
	// that needs to be grabbed before the function is run,
	// so we call them from a callback inside the ajax
	function rebuildPage() {
		if($('#pickupDatepicker').val().length != 0) {
			pickupDate = $('#pickupDatepicker').val();
			var dateObj = 		$.datepicker.parseDate(frontendDateFormat, pickupDate);
			pickupDateBackend = $.datepicker.formatDate('yy-mm-dd', dateObj);
			initPickupDatepicker();
			$('#pickupDatepicker').datepicker('setDate', pickupDate).removeAttr('disabled');
			$('#chosenPickupDate').html($.datepicker.formatDate('DD, MM d yy', dateObj));
			getNumAvailDays(rebuildPage2);
		}
		else
			initPickupDatepicker();
	}
	function rebuildPage2() {
		if($('#pickupTime').val() != 0) {
			$('#pickupTime').removeAttr('disabled');

			if($('#dropoffDatepicker').val().length != 0) {
				dropoffDate = $('#dropoffDatepicker').val();
				var dateObj = $.datepicker.parseDate(frontendDateFormat, dropoffDate);
				initDropoffDatepicker();
				$('#dropoffDatepicker').datepicker('setDate', dropoffDate);
				$('#chosenDropoffDate').html($.datepicker.formatDate('DD, MM d yy', dateObj));
				totalDays = countTotalDays(pickupDate, dropoffDate);
				price = getPriceSBS(totalDays, SBSPrice);

				if($('#dropoffTime').val() != 0) {
					$('#dropoffTime').removeAttr('disabled');
					$('#reserveBtn').removeAttr('disabled');
				}
			}
		}

	}

	//-----------------------------------------------------------------//
	//                                                                 //
	//                     INITAL PAGE SETUP                           //
	//                                                                 //
	//-----------------------------------------------------------------//

	var dirLvls = getDirLvls();

	// if the user comes from a page past this, show what they have selected
	if($('#numSBS').val() != 0) {
		numSBSChosen = parseInt($('#numSBS').val());
		//getBarrierDays(numSBSChosen, rebuildPage);
		rebuildPage();
	}
	else {
		clearDisablePickup();
		clearDisableDropoff();
	}

	//-----------------------------------------------------------------//
	//                                                                 //
	//                       EVENT HANDLERS                            //
	//                                                                 //
	//-----------------------------------------------------------------//
	$('#numSBS').change(function() {
		if($(this).val() > 0) {
			numSBSChosen = $(this).val();
			getBarrierDays(numSBSChosen, resetPickup);
			// clear & disable dropoffDatepicker
			clearDisableDropoff();
			// disable reserve button
			$('#reserveBtn').attr('disabled', 'disabled');
		}
		else {
			clearDisablePickup();
			clearDisableDropoff();
			$('#reserveBtn').attr('disabled', 'disabled');
		}
	});

	$('#pickupTime').change(function() {
		if($(this).val() != 0)
			initDropoffDatepicker();
		else {
			clearDisableDropoff();
			$('#reserveBtn').attr('disabled', 'disabled');
		}
	});
	$('#dropoffTime').change(function() {
		if($(this).val() == 0)
			$('#reserveBtn').attr('disabled', 'disabled');
		else
			$('#reserveBtn').removeAttr('disabled');
	});


	$('#datepickerForm').submit(function() {
		if(errorCheckForm()) {
			return true;
		}
		else {
			//flashError();
			return false;
		}
	});

});

