$(function($){
	// get total price
		var $roomInput,
				$inputPrice,
				roomPrice,
				roomWeekendprice,
				roomType,
				person,
				checkinDate,
				checkoutDate,
				chekinDay,
				checkoutDay,
				checkinMonth,
				checkoutMonth,				
				night,
				totalPrice,
				daysMonth,
				checkinYear;
				
	$('#formRoomsList').delegate('input', 'click', updatePrice);
	
	function updateVars(){
		$inputPrice 		 = $('#totalprice');
		$roomInput 		   = $('#formRoomsList input:checked');
		roomPrice 			 = parseInt($roomInput.attr('data-price'));
		roomWeekendprice = parseInt($roomInput.attr('data-weekendprice'));
		roomType 				 = $roomInput.attr('data-type');
		person 					 = parseInt($('#reservationPerson').val());
		checkinDate 		 = $('#reservationDateStart').val();
		checkoutDate 		 = $('#reservationDateEnd').val();	
		person 					 = parseInt($('#reservationPerson').val());
		checkinDate 		 = $('#reservationDateStart').val();
		checkoutDate 		 = $('#reservationDateEnd').val();
		chekinDay 			 = parseInt(checkinDate.split('/')[2]);
		checkoutDay 		 = parseInt(checkoutDate.split('/')[2]);
		checkinMonth 		 = parseInt(checkinDate.split('/')[1]);
		checkoutMonth 	 = parseInt(checkoutDate.split('/')[1]);
		checkinYear 		 = parseInt(checkinDate.split('/')[0]);
		daysMonth 		   = daysInMonth(checkinMonth, checkinYear);			
	}

// date picker 
	$('.datepicker').datepicker({
		changeMonth	: true,
		changeYear	: true,
		dateFormat	: 'yy/mm/dd',
		duration		: 'fast',
		showAnim		: 'fadeIn',
		yearRange		: '0:+5',
		minDate			: 0,
		onSelect		: updatePrice,
		onClose			: updateArrivalTime
	});
	
// get days in month by month and year
	function daysInMonth(month, year) {
		return new Date(year, month, 0).getDate();
	}

	function updatePrice(){        		
		updateVars();
		
		var _checkindDate = new Date(checkinDate);
		var _checkoutDate = new Date(checkoutDate);
		var one_day=1000*60*60*24;
		var weekenddays = 0;
		var weekdays = 0;
		
		// get nights
		if( isNaN(chekinDay) && isNaN(checkoutDay) ) {
			night = 1;
		} else {
			night = ( (_checkoutDate.getTime() - _checkindDate.getTime()) / one_day );		
		}	
	
		for( var i=0; i<night; i++ ){			
			
			var milisec = ( _checkindDate.getTime() + (one_day * i) );
			var temp = new Date(milisec);
			
			if( temp.getDay() == 5 || temp.getDay() == 6 ){
				weekenddays++;
			}	
		}
		
		weekdays = night - weekenddays;

		// get total price
		if( roomType == 'room' ){
			totalPrice = (weekdays * roomPrice) + (weekenddays * roomWeekendprice);
		} else if( roomType == 'person' ){
			totalPrice = (weekdays * roomPrice * person) + (weekenddays * roomWeekendprice * person);
		}					
		
		$('#totalprice').html(totalPrice);
		$inputPrice.val(totalPrice);		
	}
	
// stepper 
	$('.stepperWrap input').attr('readonly', 'readonly');
	$('.stepperUp, .stepperDown').bind('click', function(e){
		var $this 			= $(this);		
		var $input 			= $this.parent().prev();
		var min_value 	= $input.attr('data-min');
		var max_value 	= $input.attr('data-max');
		var current_val = parseInt( $input.val() );
		
		if( $this.hasClass('stepperUp') ){
			// increment
		 if( typeof( parseInt( $input.val() ) ) === typeof(1) && !isNaN( parseInt( $input.val() ) ) ){
		 	if( parseInt( $input.val() ) < max_value ){
		 		$input.val(current_val + 1);
		 	}
		 } else {
		 	$input.val('1');
		 }
		} else {
			// decrement
			if( parseInt( $input.val() ) > min_value ) {			
				$input.val(current_val - 1);
			} else {
				$input.val(min_value);
			}
		}
		validRooms($input.val());
		updatePrice();
	});
	
// valid rooms	
	function validRooms(value){
		var rooms = [];
		rooms = $('#formRoomsList').find('input:visible');
		var $this;
		
		rooms.each(function(){
			$this = $(this);
			
			if( parseInt( $this.attr('data-max') ) < parseInt( value ) ){
				$this.attr('disabled', true);
				$this.parents('li:eq(0)').animate({ 'opacity' : 0.4 }, 200);
			} else {
				$this.attr('disabled', false);
				$this.parents('li:eq(0)').animate({ 'opacity' : 1 }, 200);
			}
		});
	}

// checkCard	
	function checkCC(){
		var type = $('#ccType option:selected').val();
		var number = $('#ccNumber').val();
		
		if( !checkCreditCard( number, type ) ){
			$('.invalidWrap').show();
			error = true;
		} else {
			$('.invalidWrap:visible').hide();
		}
	}
	
	$('#ccNumber, #ccType').live('focusout keyup change', function(e){
		if( e.type == 'focusout' && e.type == 'keyup' ){
			if( $('#ccType option:selected').val() != '' ){
				checkCC();
			}
		} else {
			if( $('#ccNumber').val() != '' ){
				checkCC();
			}
		}		
	});
	
// additional services	
	$('#additionalServices').delegate('input[type=checkbox]', 'click', function(e){
		var $this = $(this),
				date = $('#reservationDateStart').val(),
				$detailsWrap = $('#arrivalDetails');
				
		if( $this.attr('id') == 'serviceFromAirport' ){
			if( $this.is(':checked') ){
				$detailsWrap.slideDown('fast');
				$('#arrivaldate').val(date);
			} else {
				$detailsWrap.slideUp('fast');
			}
		}
		
	});
	
	function updateArrivalTime(){
	}
	
// valid email	
	function emailValidation(val){
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var address = val;
		 if(reg.test(address) == false) { 
		 	return false;
		 }
		 return true;
	}
		
// valid all required fields
	function validForm(){
		var error;
		$('.errorsWrap').hide();		
		
		$('.required').each(function(){
			var $this = $(this);
			
			if( $this.is(':text') ){
				if( $this.val() == '' ){
					error = true;
					$this.parent().find('.errorsWrap').fadeIn('fast');				
				}
			}
			
			if( $this.is('select') ){
				if( $this.val() == '' ){
					error = true;
					$this.parent().find('.errorsWrap').fadeIn('fast');
				}
			}
			
			if( $this.attr('id') == 'reservationEmail' ){
				var status = emailValidation($this.val());
				if( status != true ){
					error = true;
					$this.parent().find('.errorsWrap').fadeIn('fast');
				}
			}
			
			if( $this.attr('id') == 'reemail' ){
				if( $('#reservationEmail').val() != $this.val() || $this.val() == '' ){
					$this.parent().find('.errorsWrap').fadeIn('fast');
					error = true;
				}
			}			
			
		});
		
		if( error == true ){
			//alert('An error has occurred. Check out the form and try again.');
			return false;
		} else {
			return true;
		}
	}
	
	var buttonText;	
	
// send reservation action	
	var addServicesTemp = [];
  $(document.body).delegate('#sendReservation', 'click', function(e){
  	e.preventDefault();
  	
  	var $this = $(this),
  			nextAction = $this.attr('data-action'),
  			args = {},
  			inputs = {},
  			errors = [],
  			validEmail = /^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i,
  			error = false,
  			buttonText = $this.text();
  	
  	
  	$('.errorsWrap').hide();
  	
  	if( nextAction == 'step2' ){
  		
  		inputs = {
  			date_start 				: $('#reservationDateStart'),
  			date_end 					: $('#reservationDateEnd'),
  			reservationPerson : $('#reservationPerson'),
  			rooms 						: $('.reservationRooms:checked'),
  			totalprice 				: $('#totalprice'),
  			addServices 			: $('input[name=services]:checked'),
  			flightnumber 			: $('#flightnumber'),
  			arrivaldate 			: $('#arrivaldate'),
  			arrivaltime 			: $('#arrivalHours option:selected').val() + ':' + $('#arrivalMinutes option:selected').val()
  		}   	
			
			$.each($('input[name=services]:checked'), function(k,v){
				addServicesTemp.push($(v).val());
			});	
  		  	
  		args = {
  			action 						: nextAction,
  			date_start 				: inputs.date_start.val(),
  			date_end 					: inputs.date_end.val(),
  			reservationPerson : inputs.reservationPerson.val(),
  			rooms 						: inputs.rooms.val(),
  			totalprice 				: inputs.totalprice.val(),
  			addServices 			: addServicesTemp.toString(),
  			flightnumber 			: inputs.flightnumber.val(),
  			arrivaldate 			: inputs.arrivaldate.val(),
  			arrivaltime 			: inputs.arrivaltime			
  		}
  		
  	} else if( nextAction == 'step3' ){
  	
  		inputs = {
  			reservationFirstname 	: $('#reservationFirstname').val(),
  			reservationLastname 	: $('#reservationLastname').val(),
  			reservationAddress 		: $('#reservationAddress').val(),
  			reservationCity 			: $('#reservationCity').val(),
  			reservationZip 				: $('#reservationZip').val(),
  			reservationCountry 		: $('#reservationCountry option:selected').val(),
  			areacode 							: $('#areacode option:selected').val(),  			
  			reservationPhone 			: $('#reservationPhone').val(),
  			reservationEmail 			: $('#reservationEmail').val(),
  			reservationComment 		: $('#reservationComment').val(),
  			ccType 								: $('#ccType').val(),
  			ccNumber 							: $('#ccNumber').val(),
  			ccExpiryMonth 				: $('#ccExpiryMonth').val(),
  			ccExpiryYear 					: $('#ccExpiryYear').val(),
  			ccv 									: $('#ccv').val()
  		}		
  		
  		args = {
  			action 							 	: nextAction,
  			reservationFirstname 	: inputs.reservationFirstname,
  			reservationLastname 	: inputs.reservationLastname,
  			reservationAddress 		: inputs.reservationAddress,
  			reservationCity 			: inputs.reservationCity,
  			reservationZip 				: inputs.reservationZip,
  			reservationCountry 		: inputs.reservationCountry,
  			areacode							: inputs.areacode,
  			reservationPhone 			: inputs.reservationPhone,
  			reservationEmail 			: inputs.reservationEmail,
  			reservationComment 		: inputs.reservationComment,
  			ccType 								: inputs.ccType,
  			ccNumber 							: inputs.ccNumber,
  			ccExpiryMonth 				: inputs.ccExpiryMonth,
  			ccExpiryYear 					: inputs.ccExpiryYear,
  			ccv 									: inputs.ccv
  		}
  		
  	}		
		
		if( validForm() == false )	{
			alert('An error has occurred. Check out the form and try again.');
		} else {
			$this.attr('disabled', true);
			$this.text('Sending. Please wait...');
			//$this.hide().parent().append('<img class="ajaxLoader" src="/wp-content/themes/stock/style/css/i/ajax-loader.gif" />');
			$('#reservationFormWrap').load(window.location.href + ' #reservationFormWrap > *', args, function(){
				$this.attr('disabled', false);
				$this.text(buttonText);
			});		
		}
  });		
	
	
	
});
