var $startDate, $endDate, $adults, $children;

jQuery(document).ready(function($){
	"use strict";
	
	$('.um_book').live('click',function(e){	
		e.preventDefault();
		
		$('.um_shadow').addClass('active');	
		
		var postId = $(this).data('postid');
			
		var ajaxData = {
			"action" : "um_booking",
			"post_id" : postId
		}; 
		$.post(ajax_url, ajaxData, function(data){
			if(data){
				$('body').append(data);
				$('.selectpicker').selectpicker('refresh');
				createDatePickers();
			  	
			  	$(".bookingScroll").mCustomScrollbar({
			  		 	horizontalScroll: false,
			            autoDraggerLength: true,
			            autoHideScrollbar: true,
			  		 	advanced:{ 
				  		 	autoScrollOnFocus : false,
				  		 	updateOnContentResize: true,
	                		updateOnBrowserResize: true 
                		}
			  	});
			  	
			  	positionScrollBar();
				
			  	$(".bookingScroll").mCustomScrollbar("update");
			  	
			  	$('.um_shadow').removeClass('active');	
		  	}
		});
		
	});
		
	$('.closeBtn').live('click',function(e){	
		$startDate = '';
		$endDate = '';	
		$adults = '';
		$children = '';
		$('.um_booking_lightbox').remove();
	});
	
	jQuery(window).resize(function(){
			positionScrollBar();
	});
	
	
	
	
	$('button.um_bookBtn').live('click',function(e){
		
		e.preventDefault();
			
		var return_state = validateBookingForm($);
		
		if(return_state){
			
			
			$('.um_shadow').addClass('active');	
			
			var postID = $('.um_post_id').data('um_post_id');
			
			var bookingData = getBookingData($); 
			
			$('.bookingContainer').remove();
			
			//loading..
			
			var ajaxData = {
				"action" : "um_booking_completed",
				"post_id" : postID,
				"booking_data" : bookingData
			}; 
			$.post(ajax_url, ajaxData, function(data){
				if(data){
					$('.um_lightbox .container').append(data); 
				
					$(".billScroll").mCustomScrollbar({
				  		 	horizontalScroll: false,
				            autoDraggerLength: true,
				            autoHideScrollbar: true,
				  		 	advanced:{ 
					  		 	autoScrollOnFocus : false,
					  		 	updateOnContentResize: true,
		                		updateOnBrowserResize: true 
	                		}
				  	});
				  	
			  		positionScrollBar();
					$(".billScroll").mCustomScrollbar("update");
					
					$('.um_shadow').removeClass('active');	
  				}
  			});
		}
				
	});
	
	
	$('#termsVal').live('click',function(){
	    if ($(this).attr('checked')) {
	        $(this).val('true');
	    }else{
	    	$(this).val('');
	    }
	})
		
	$('#um_adults').live('change',function(){
		$adults = $(this).val();
		$('body').trigger('calculatePrice');
	});
	$('#um_children').live('change',function(){
		$children = $(this).val();;
		$('body').trigger('calculatePrice');
	});	
	
	
	$('body').on('calculatePrice',function(){
	
		var calculateAdults = false;
		var calculateChildren = false;
		
		if($('#um_calc_adult').length > 0){
			calculateAdults = true;
		} 
		if($('#um_calc_children').length > 0){
			calculateChildren = true;
		}
		
		
		if(calculateAdults && calculateChildren){
			if($startDate != '' && $startDate != undefined){
				if($endDate != '' && $endDate != undefined){
					if($adults != '' && validateNumbers($adults))
					{
						if($children != '' && validateNumbers($children))
						{
							var $dayDifference = dayDifference(parseDate($startDate), parseDate($endDate));
							var $price = $('#um_calc_price').data('um_price');
							var $cPrice = $('#um_calc_price').data('um_children_price');
							
							var $total = $dayDifference * $price * $adults;
							var $cTotal = $dayDifference * $cPrice * $children;
							$total = $total + $cTotal;
							
							$('#um_calc_adult').text($adults);
							$('#um_calc_children').text($children);
							$('#um_calc_period').text($dayDifference);
							$('#um_calc_price').text($total);
						}
						
					}
			
				}
			}
		}
		else if(calculateAdults && (!calculateChildren)){
			
			if($startDate != '' && $startDate != undefined){
				if($endDate != '' && $endDate != undefined){
					if($adults != '' && validateNumbers($adults))
					{						
							var $dayDifference = dayDifference(parseDate($startDate), parseDate($endDate));
							var $price = $('#um_calc_price').data('um_price');
							
							var $total = $dayDifference * $price * $adults;
							$('#um_calc_adult').text($adults);
							$('#um_calc_period').text($dayDifference);
							$('#um_calc_price').text($total);

					}
			
				}
			}
			
		}
		else if((!calculateAdults) && calculateChildren){
				
				if($startDate != '' && $startDate != undefined){
					if($endDate != '' && $endDate != undefined){
						
						if($children != '' && validateNumbers($children))
						{
							var $dayDifference = dayDifference(parseDate($startDate), parseDate($endDate));
							var $price = $('#um_calc_price').data('um_children_price');
							
							var $total = $dayDifference * $price * $children;
							$('#um_calc_children').text($children);
							$('#um_calc_period').text($dayDifference);
							$('#um_calc_price').text($total);
						}
					}
				}
		}
		else{
			if($startDate != '' && $startDate != undefined){
				if($endDate != '' && $endDate != undefined){
					
					var $dayDifference = dayDifference(parseDate($startDate), parseDate($endDate));
					var $price = $('#um_calc_price').data('um_price');
					
					var $total = $dayDifference * $price;
					
					$('#um_calc_period').text($dayDifference);
					$('#um_calc_price').text($total);
					
				}	
			}
		}
	});
	
	
	
	
	
});

function add1Day(str){
	
	var mdy = str.split('/');
	var d = new Date(mdy[0], mdy[1] - 1 , mdy[2]);
	var returnDate = new Date( mdy[0], mdy[1] - 1);
	returnDate.setDate(d.getDate() + 1);
	return returnDate.getFullYear() + '/' + (returnDate.getMonth() + 1) + '/' + returnDate.getDate();
}

function parseDate(str) {
    var mdy = str.split('/');
    return new Date(mdy[0], mdy[1] - 1 , mdy[2]);
}

function dayDifference(start, end) {
    return Math.floor((end - start) / (86400000));
}

function positionScrollBar(){
	if(jQuery('.bookingContainer').length >= 1){
		var container = jQuery('.bookingContainer');
		var position = container.position();
		
		var cHeight = container.height();
		jQuery('.um_booking_lightbox .mCSB_scrollTools').css({
			'right': position.left - 15, 
			'top': position.top,
			'bottom': position.top
		});	
	}
}

function createDatePickers(){
	
	 jQuery('.um_datePicker').datetimepicker({ format:'Y/m/d', timepicker:false });
	
	  jQuery('#um_date_start').datetimepicker({
	 	 format					: 'Y/m/d',
		 scrollMonth			: false,				
		 scrollInput 			: false,
	 	 minDate				: 0,
	 	 onShow					: function( ct ){
							   		this.setOptions({
							  			  maxDate: jQuery('#um_date_end').val() ? jQuery('#um_date_end').val() : false
							  			  
									})
			
	 							}
	 	,
							 	onChangeDateTime : function(dp,$input){
							 		$startDate = $input.val();
							 		jQuery('body').trigger('calculatePrice');
							 	},	
		timepicker				: false
	});
		 
	  jQuery('#um_date_end').datetimepicker({
		format					: 'Y/m/d',
		scrollMonth				: false,				
		scrollInput 			: false,
	  	onShow					: function( ct ){
							 	  	this.setOptions({
							    			minDate: jQuery('#um_date_start').val()  ? add1Day(jQuery('#um_date_start').val()) : 0
							   		})
						  
						  		},
	  	onChangeDateTime 		: function(dp,$input){
							 			$endDate = $input.val();
							 			jQuery('body').trigger('calculatePrice');
							 	},
	 	timepicker				: false
	 });
		 
}



function getBookingData($){

	var data = [];
	
	$('.formInput').each(function(){		
	
		var innerData = [];

		var type = $(this).data('um_type');
		
		if(type == undefined){
			
			if($(this).find('input').attr('name') == "um_arival" || $(this).find('input').attr('name') == "um_departure"){
				
				innerData.push({
					type : $(this).find('input').attr('name'),
					icon : 'fa-calendar',
					label : $(this).children('label').text(),
					value : $(this).find('input').val()
				});
			}
		}
		else{
			if(type == 'area'){
				
				innerData.push({
					type : type,
					icon : $(this).find('i.fa').data('um_icon'),
					label : $(this).children('label').text(),
					value : $(this).find('textarea').val()
				});
			}
			else if(type == 'email' || type == 'number'){
				
				innerData.push({
					type : type,
					icon : $(this).find('i').data('um_icon'),
					uniqueID : $(this).find('input').data('unique_id'),
					label : $(this).children('label').text(),
					value : $(this).find('input').val()
				});
				
			}
			else if(type == "drop"){
				innerData.push({
					type : type,
					icon : $(this).find('i').data('um_icon'),
					uniqueID : $(this).find('input').data('unique_id'),
					label : $(this).children('label').text(),
					value : $(this).find('.selectpicker').find('li.selected').text()
				});
			}
			else if (type == 'check'){
				
				var values = [];
				$(this).find('input:checked').each(function(){
				  	values.push($(this).val());
				});
					
				if(values.length === 0)	{
					
					values.push("null");
				}	
							
				innerData.push({
					type : type,
					icon : $(this).find('i').data('um_icon'),
					label : $(this).children('label').text(),
					value : values 
				});	
				
			}
			else if(type == "radio"){
				innerData.push({
					type : type,
					icon : $(this).find('i').data('um_icon'),
					label : $(this).children('label').text(),
					value : $(this).find('input:checked').val() 
				});	
			}
			else{
				
				innerData.push({
					type : type,
					icon : $(this).find('i').data('um_icon'),
					label : $(this).children('label').text(),
					value : $(this).find('input').val()
				});			
			}	
		}
		data.push(innerData);
	});

	return data;
}

function validateBookingForm($){
	
	 var return_state = true;
 
	$('.formInput').each(function(){
		 $(this).removeClass('error');
		 var type = $(this).data('um_type');
		 var isMendatory = $(this).data('um_mendatory');
		 
		 if((type != "drop") && (type != 'check') && (type != "area") && (type != 'radio'))
		 {
			 if(isMendatory == true){
			 	if(type == "email"){
			 		if($(this).find('input').val().match('^$') || !validateEmail($(this).find('input').val())){
			 			return_state = false;
			 			$(this).addClass('error');
			 		}
			 	}
			 	else if(type == 'tel'){
			 		if($(this).find('input').val().match('^$') || !validatePhone($(this).find('input').val())){
			 			return_state = false;
			 			$(this).addClass('error');
			 		}
			 	}
			 	else if(type == 'number'){
			 		if($(this).find('input').attr('max') == ''){
			 			if(  $(this).find('input').val().match('^$')   || !validateNumbers($(this).find('input').val())  ) {
			 				
		 					return_state = false;
		 					$(this).addClass('error');
						}
			 			
			 		}	
		 			else if(($(this).find('input').val().match('^$') || !validateNumbers($(this).find('input').val())) ||
			 		 ($(this).find('input').val() < $(this).find('input').attr('min') || $(this).find('input').val() > $(this).find('input').attr('max'))){
	 
			 				return_state = false;
			 				$(this).addClass('error');
			 			
		 			}
			 	}
			 	else{
			 		if($(this).find('input').val().match('^$')){
			 			return_state = false;
			 			$(this).addClass('error');
			 		}	
			 	}
			 	
			 }else{
			 	if($(this).find('input').val() != ""){	
	 				if(type == "email"){
				 		if(!validateEmail($(this).find('input').val())){
				 				return_state = false;
				 				$(this).addClass('error');
			 				}
			 		}
				 	else if(type == 'tel'){
				 		if( !validatePhone($(this).find('input').val())){
				 				return_state = false;
				 				$(this).addClass('error');
				 			}
			 		}
				 	else if(type == 'number'){
				 		if(!validateNumbers($(this).find('input').val())){
				 				return_state = false;
				 				$(this).addClass('error');
			 				}
			 		}
				 }
			 }
		}
		else{
			 if(isMendatory == true){
			 	 if(type == 'area'){
			 		if($(this).find('textarea').val().match('^$')){
			 			return_state = false;
			 			$(this).addClass('error');
			 		}
			 	}
			 	
			 }
		}
	
	});
	
	return return_state;
	
	
}
