/*!
 * Vacation Rental Script v3.3
 * 
 * https://www.phpjabbers.com/vacation-rental-script/
 * 
 * Copyright 2015, StivaSoft Ltd.
 * 
 */
(function (window, undefined){
	"use strict";
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined);
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnYacht(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function VacationRental(opts) {
		if (!(this instanceof VacationRental)) {
			return new VacationRental(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	VacationRental.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	VacationRental.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	VacationRental.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;			
			this.opts = {};
			
			return this;
		},
		
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("pjWrapperVacationRental");
			this.$container = pjQ.$(this.container);
			
			this.$container.on("focusin.vr", ".pjVrCalendarInput", function (e) {
				var minDate, maxDate,
					$this = pjQ.$(this),
					custom = {},
					o = {
						firstDay: $this.attr("data-fday"),
						dateFormat: $this.attr("data-dformat"),
						minDate: '0',
						dayNames: ($this.data("day")).split(","),
					    monthNames: ($this.data("months")).split(","),
					    monthNamesShort: ($this.data("shortmonths")).split(","),
					    dayNamesMin: ($this.data("daymin")).split(","),
						beforeShow: function(input, inst) {
							pjQ.$('#ui-datepicker-div').addClass("pjVrjQueryUI");
						},
						onClose: function (dateText){
							var $frm = pjQ.$('#frmVrBooking_' + self.opts.index);
							if($frm.length > 0)
							{
								if(pjQ.$(".pjVrCalendarInput[name='date_from']").val() != '' && pjQ.$(".pjVrCalendarInput[name='date_to']").val() != '')
								{
									pjQ.$("input[name='period']").valid();
								}
								pjQ.$.post(self.opts.folder + "index.php?controller=pjListings&action=pjActionGetPrice", $frm.serialize()).done(function(data) {
									pjQ.$('.pjVrPriceBox').html(data);
									var $reserved_msg = pjQ.$('#pjVrProperyReservedMsg');
									if($reserved_msg.length > 0)
									{
										$frm.find('.pjVrBtnPrimary').attr("disabled", true);
									}else{
										$frm.find('.pjVrBtnPrimary').removeAttr("disabled");
									}
								});
							}
						}
				};
				switch ($this.attr("name")) {
				case "date_from":
					if(pjQ.$(".pjVrCalendarInput[name='date_to']").val() != '')
					{
						maxDate = pjQ.$(".pjVrCalendarInput[name='date_to']").datepicker({
							firstDay: $this.attr("data-fday"),
							dateFormat: $this.attr("data-dformat")
						}).datepicker("getDate");
						pjQ.$(".pjVrCalendarInput[name='date_to']").datepicker("destroy").removeAttr("id");
						if (maxDate !== null) {
							custom.maxDate = maxDate;
						}
					}
					break;
				case "date_to":
					if(pjQ.$(".pjVrCalendarInput[name='date_from']").val() != '')
					{
						minDate = pjQ.$(".pjVrCalendarInput[name='date_from']").datepicker({
							firstDay: $this.attr("data-fday"),
							dateFormat: $this.attr("data-dformat")
						}).datepicker("getDate");
						pjQ.$(".pjVrCalendarInput[name='date_from']").datepicker("destroy").removeAttr("id");
						if (minDate !== null) {
							custom.minDate = minDate;
						}
					}
					break;
				}
				pjQ.$(this).datepicker(pjQ.$.extend(o, custom));
			}).on("click.vr", ".pjVrCalendarTrigger", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $dp = pjQ.$(this).next("input[type='text']");
				if ($dp.hasClass("hasDatepicker")) {
					$dp.datepicker("show");
				} else {
					$dp.trigger("focusin").datepicker("show");
				}
			}).on("click.vr", ".pjVrProductThumb", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('.pjVrProductThumb').removeClass('pjVrProductThumbCurrent');
			}).on("click.vr", ".pjVrCalendarInlineAction", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var get = pjQ.$(this).attr('data-get'),
					listing_id = pjQ.$(this).attr('data-listing_id'),
					cdate = pjQ.$('#pjVrViewDate_' + self.opts.index).html(),
					date = self.calendarDate.call(self, get, cdate, 2);
				
				pjQ.$.get([self.opts.folder, "index.php?controller=pjListings&action=pjActionGetAvailability", "&listing_id=", listing_id, "&get=", get, "&date=", date].join("")).done(function (data) {
				        	   
					pjQ.$('#pjVrCalendar_' + self.opts.index).html(data);
					pjQ.$('#pjVrViewDate_' + self.opts.index).html(date);
					pjQ.$('[data-toggle="tooltip"]').tooltip(); 
				}).fail(function () {
					log("Deferred is rejected");
				});
			}).on("change.vr", 'select[name="payment_method"]', function (e) {
				pjQ.$('.vrCC').hide();
				pjQ.$('.vrBank').hide();
				if(pjQ.$(this).val() == 'creditcard')
				{
					pjQ.$('.vrCC').show();
				}
				if(pjQ.$(this).val() == 'bank')
				{
					pjQ.$('.vrBank').show();
				}
			}).on("change.vr", 'select[name="bedrooms_from"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $bedrooms_to = pjQ.$('#vrSearchForm').find('select[name="bedrooms_to"]'),
						from_value = parseInt(pjQ.$(this).val(), 10);
					$bedrooms_to.find("option").prop('disabled', false);
					$bedrooms_to.find("option").each(function(e){
						var to_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("change.vr", 'select[name="bedrooms_to"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $bedrooms_from = pjQ.$('#vrSearchForm').find('select[name="bedrooms_from"]'),
						to_value = parseInt(pjQ.$(this).val(), 10);
					$bedrooms_from.find("option").prop('disabled', false);
					$bedrooms_from.find("option").each(function(e){
						var from_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("change.vr", 'select[name="bathrooms_from"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $bathrooms_to = pjQ.$('#vrSearchForm').find('select[name="bathrooms_to"]'),
						from_value = parseInt(pjQ.$(this).val(), 10);
					$bathrooms_to.find("option").prop('disabled', false);
					$bathrooms_to.find("option").each(function(e){
						var to_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("change.vr", 'select[name="bathrooms_to"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $bathrooms_from = pjQ.$('#vrSearchForm').find('select[name="bathrooms_from"]'),
						to_value = parseInt(pjQ.$(this).val(), 10);
					$bathrooms_from.find("option").prop('disabled', false);
					$bathrooms_from.find("option").each(function(e){
						var from_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("change.vr", 'select[name="adults_from"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $adults_to = pjQ.$('#vrSearchForm').find('select[name="adults_to"]'),
						from_value = parseInt(pjQ.$(this).val(), 10);
					$adults_to.find("option").prop('disabled', false);
					$adults_to.find("option").each(function(e){
						var to_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("change.vr", 'select[name="adults_to"]', function (e) {
				if(pjQ.$('#vrSearchForm').length > 0)
				{
					var $adults_from = pjQ.$('#vrSearchForm').find('select[name="adults_from"]'),
						to_value = parseInt(pjQ.$(this).val(), 10);
					$adults_from.find("option").prop('disabled', false);
					$adults_from.find("option").each(function(e){
						var from_value = parseInt(pjQ.$(this).attr('value'), 10);
						if(from_value >= to_value)
						{
							pjQ.$(this).prop('disabled', true);
						}
					})
				}
			}).on("click.vr", '.pjVrBtnSearch', function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $form = pjQ.$('#vrSearchForm');
				var serialized = $form.serializeArray();
				var dataSerialized={};
				pjQ.$.each(serialized, function (index, value) {
				    var data_name = serialized[index].name;
				    var data_value = serialized[index].value;
				    if (data_name != 'controller' && data_name != 'action') 
				    {
				    	dataSerialized[data_name] = data_value;
				    }
				});
				pjQ.$.ajax({ 
		             type: 'get',
		             url: [self.opts.folder, "index.php?controller=pjListings&action=pjActionSearch"].join(""), 
		             data: dataSerialized, 
		             success: function(data) { 
		            	 if(data == '100')
		            	 {
		            		 pjQ.$('.modal-dialog').css("z-index", "9999"); 
		            		 pjQ.$('#pjVrNoPropertiesModal').modal('show');
		            	 }else{
		            		 $form.submit();
		            	 }
		             },
		             error: function() {
		            	 log("Deferred is rejected");
		             }
		        });
				return false;
			}).on("click.vr", "#pjVrCaptchaImage", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $captcha = pjQ.$(this);
				var $form = $captcha.closest("form");
				$captcha.attr("src", $captcha.attr("src").replace(/(&rand=)\d+/g, '\$1' + Math.ceil(Math.random() * 99999)));
				$form.find('input[name="verification"]').val("").removeData("previousValue");
			});
			
			if(pjQ.$('.pjVrFancybox').length > 0)
			{
				pjQ.$(".pjVrFancybox").fancybox({
					openEffect	: 'none',
					closeEffect	: 'none'
				});
			}
			
			self.validateRequest.call(self);
			
			if(pjQ.$('#pjVrCalendar_' + self.opts.index).length > 0)
			{
				pjQ.$('[data-toggle="tooltip"]').tooltip();
			}

			if(pjQ.$('#frmVrLogin_' + self.opts.index).length > 0)
			{
				var $frm = pjQ.$('#frmVrLogin_' + self.opts.index);
				$frm.validate({
					
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'verification')
						{
							element.parent().parent().parent().parent().addClass('has-error');
							error.appendTo(element.parent().parent().next().find('ul'));
						}else{
							element.parent().addClass('has-error');
							error.appendTo(element.next().find('ul'));
						}
					},
					success: function(li, element) {
						if(li.parent().parent().hasClass('has-error'))
						{
							li.parent().parent().removeClass('has-error').addClass('has-success');
						}
						if(li.parent().parent().parent().hasClass('has-error'))
						{
							li.parent().parent().parent().removeClass('has-error').addClass('has-success');
						}
		            }
				});
			}
			
			if(pjQ.$('#frmVrRegister_' + self.opts.index).length > 0)
			{
				var $frm = pjQ.$('#frmVrRegister_' + self.opts.index);
				$frm.validate({
					rules : {
						"verification": {
							remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						},
		                "register_password_repeat" : {
		                    equalTo : "#register_password"
		                }
		            },
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'verification')
						{
							element.parent().parent().parent().parent().addClass('has-error');
							error.appendTo(element.parent().parent().next().find('ul'));
						}else{
							element.parent().addClass('has-error');
							error.appendTo(element.next().find('ul'));
						}
					},
					success: function(li, element) {
						if(li.parent().parent().hasClass('has-error'))
						{
							li.parent().parent().removeClass('has-error').addClass('has-success');
						}
						if(li.parent().parent().parent().hasClass('has-error'))
						{
							li.parent().parent().parent().removeClass('has-error').addClass('has-success');
						}
		            }
				});
			}
			if(pjQ.$('#frmVrForgot_' + self.opts.index).length > 0)
			{
				var $frm = pjQ.$('#frmVrForgot_' + self.opts.index);
				$frm.validate({
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						element.parent().addClass('has-error');
						error.appendTo(element.next().find('ul'));
					},
					success: function(li, element) {
						if(li.parent().parent().hasClass('has-error'))
						{
							li.parent().parent().removeClass('has-error').addClass('has-success');
						}
						if(li.parent().parent().parent().hasClass('has-error'))
						{
							li.parent().parent().parent().removeClass('has-error').addClass('has-success');
						}
		            }
				});
			}
		},
		validateRequest: function()
		{
			var self = this;
			if(pjQ.$('#frmVrBooking_' + self.opts.index).length > 0)
			{
				var $frm = pjQ.$('#frmVrBooking_' + self.opts.index);
				$frm.validate({
					rules:{
						"verification": {
							remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						},
						"period" : {
							required: function(){
								var from = $frm.find('input[name="date_from"]').val(),
									to = $frm.find('input[name="date_to"]').val();
								if(from == '' || to == '')
								{
									return true;
								}else{
									return false;
								}
							}
						},
						"cc_num" : {
							required: function(){
								if($frm.find('select[name="payment_method"]').val() == 'creditcard')
								{
									return true;
								}else{
									return false;
								}
							}
						},
						"cc_code" : {
							required: function(){
								if($frm.find('select[name="payment_method"]').val() == 'creditcard')
								{
									return true;
								}else{
									return false;
								}
							}
						},
						"cc_exp" : {
							required: function(){
								if($frm.find('select[name="payment_method"]').val() == 'creditcard')
								{
									return true;
								}else{
									return false;
								}
							}
						}
					},
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'verification')
						{
							error.appendTo(element.parent().parent().next().find('ul'));
						}else{
							error.appendTo(element.next().find('ul'));
						}
					},
					highlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	if(element.attr('name') == 'verification')
						{
							element.parent().parent().parent().parent().addClass('has-error');
						}else{
							element.parent().parent().addClass('has-error');
						}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	if(element.attr('name') == 'verification')
						{
							element.parent().parent().parent().parent().removeClass('has-error').addClass('has-success');
						}else{
							element.parent().parent().removeClass('has-error').addClass('has-success');
						}
		            },
		            submitHandler: function (form) {
						var $form = pjQ.$(form);
						$form.find('.btn').prop("disabled", true);
						pjQ.$.post([self.opts.folder, "index.php?controller=pjListings&action=pjActionSendRequest"].join(""), $form.serialize()).done(function (data) {
							switch (data.code) {
								case 11:
									pjQ.$.post([self.opts.folder, "index.php?controller=pjListings&action=pjActionGetPaymentForm&booking_id=" + data.booking_id].join(""), $form.serialize()).done(function (resp) {
										pjQ.$('#pjVrPaymentForm').html(resp);
										pjQ.$('html,body').animate({
									          scrollTop: pjQ.$('#pjVrBookingForm_' + self.opts.index).offset().top
									    }, 1000);
										var $paypal = self.$container.find("form[name='vrPaypal']"),
											$authorize = self.$container.find("form[name='vrAuthorize']");
										
										if ($paypal.length > 0) {
											window.setTimeout(function () {
												$paypal.trigger('submit');
											}, 2000);
										} else if ($authorize.length > 0) {
											window.setTimeout(function () {
												$authorize.trigger('submit');
											}, 2000);
										}
									}).fail(function () {
										log("Deferred is rejected");
									});
									break;
								default:
									pjQ.$.post([self.opts.folder, "index.php?controller=pjListings&action=pjActionGetRequest&status=" + data.code + '&index=' + self.opts.index].join(""), $form.serialize()).done(function (resp) {
										var html = resp.split("--LIMITER--");
										if (pjQ.$('#pjVrCalendar_' + self.opts.index).length > 0) {
											pjQ.$('#pjVrCalendar_' + self.opts.index).html(html[0]);
										}
										if (pjQ.$('#pjVrBookingForm_' + self.opts.index).length > 0) {
											pjQ.$('#pjVrBookingForm_' + self.opts.index).html(html[1]);
											self.validateRequest.call(self);
										}
										pjQ.$('[data-toggle="tooltip"]').tooltip();
									}).fail(function () {
										log("Deferred is rejected");
									});
									break;
							}
						}).fail(function () {
							log("Deferred is rejected");
						});
						return false;
					}
				});
			}
		},
		calendarDate: function (get, date, num) {
			var d = date.split("-");
			var n = new Date(d[0], d[1] - 1, d[2]);
			switch (get) {
				case 'prev':
					var newDate = new Date(new Date(n).setMonth(n.getMonth() - num));
				break;
				case 'next':
				default:
					var newDate = new Date(new Date(n).setMonth(n.getMonth() + num));
				break;
			}		
			return newDate.getFullYear() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getDate();
		}
	};
	
	window.VacationRental = VacationRental;	
})(window);