/*!
 * Yacht Listing v2.0
 * Layout 1
 * https://www.phpjabbers.com/yacht-listing-script/
 * 
 * Copyright 2014, PHPJabbers
 * 
 */
(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 YachtListing(opts) {
		if (!(this instanceof YachtListing)) {
			return new YachtListing(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	YachtListing.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	YachtListing.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	YachtListing.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;			
			this.opts = {};
			
			return this;
		},
		disableButtons: function () {
			var $el;
			this.$container.find(".ylBtn").each(function (i, el) {
				$el = pjQ.$(el).addClass('ylBtnDisabled').attr("disabled", "disabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".ylBtn").removeAttr("disabled").removeClass("ylBtnDisabled");
		},
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("ylContainer_" + this.opts.index);
			this.$container = pjQ.$(this.container);
			
			var validate = (pjQ.$.fn.validate !== undefined),
				$frmYLLogin = pjQ.$('#frmYLLogin_' + this.opts.index),
				$frmYLRegister = pjQ.$('#frmYLRegister_' + this.opts.index),
				$frmYLForgot = pjQ.$('#frmYLForgot_' + this.opts.index),
				$frmYLReserve = pjQ.$('#frmYLReserve_' + this.opts.index);
			
			this.$container.on("click.yl", ".ylNavSecondary .ylActive", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$(this).toggleClass('ylHovered').next().toggle();
				return false;
			}).on("click.yl", ".ylTypeFilter", function (e) {
				pjQ.$('#frmSearch_' + self.opts.index).submit();
			}).on("click.yl", ".ylGalleryThumbs", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('#ylDetailsImage_' + self.opts.index).attr('src', pjQ.$(this).attr('href'));
			}).on("click.yl", ".ylReservationTable tr", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('.ylReservationTable tr').removeClass('ylActiveRow');
				if(pjQ.$(this).hasClass('ylAvailable'))
				{
					pjQ.$(this).not('.ylReservationTable tfoot tr').toggleClass('ylActiveRow');
				}
			}).on("click.yl", ".ylNavMonth", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var month = pjQ.$(this).attr('data-month'),
					id = pjQ.$(this).attr('data-id');
				pjQ.$.get(self.opts.folder + 'index.php?controller=pjListings&action=pjActionGetMonth&id=' + id + '&month=' + month).done(function (data) {
					pjQ.$('#ylReservationTable_' + self.opts.index).html(data);
				});
			}).on("click.yl", ".ylBtnReserve", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var week = null;
				pjQ.$('.ylReservationTable tr').each(function(){
					if(pjQ.$(this).hasClass("ylActiveRow"))
					{
						week = pjQ.$(this).attr('data-week');
					}
				});
				if(week != null)
				{
					pjQ.$('#ylWeek_' + self.opts.index).val(week);
					pjQ.$('#frmBooking_' + self.opts.index).submit();
				}
			}).on("change.yl", "#ylPaymentMethod_" + self.opts.index, function (e) {
				
				var val = pjQ.$(this).val();
				pjQ.$('.ylCcWrap').hide();
				pjQ.$('.ylBankWrap').hide();
				if(val == 'creditcard')
				{
					pjQ.$('.ylCcWrap').show();
				}else if(val == 'bank'){
					pjQ.$('.ylBankWrap').show();
				}
			}).on("click.yl", ".ylBtnDisabled", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				return false;
			});
			
			if ($frmYLLogin.length > 0 && validate) 
			{
				$frmYLLogin.validate({
					messages: {
						"login_email": {
							required: $frmYLLogin.find("input[name='login_email']").attr("data-err"),
							email: $frmYLLogin.find("input[name='login_email']").attr("data-email")
						},
						"login_password": {
							required: $frmYLLogin.find("input[name='login_password']").attr("data-err")
						}
					},
					errorPlacement: function (error, element) {
						error.insertAfter(element);
					},
					errorClass: "err",
					wrapper: "em",
					onkeyup: false
				});
			}
			
			if ($frmYLRegister.length > 0 && validate) 
			{
				$frmYLRegister.validate({
					rules: {
						"reenter_password": {
							equalTo: $frmYLRegister.find("input[name='password']")
						},
						"captcha": {
							remote: $frmYLRegister.find("input[name='captcha']").attr("data-folder") + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						}
					},
					messages: {
						"name": {
							required: $frmYLRegister.find("input[name='name']").attr("data-err")
						},
						"email": {
							required: $frmYLRegister.find("input[name='email']").attr("data-err"),
							email: $frmYLRegister.find("input[name='email']").attr("data-email")
						},
						"password": {
							required: $frmYLRegister.find("input[name='password']").attr("data-err")
						},
						"reenter_password": {
							required: $frmYLRegister.find("input[name='reenter_password']").attr("data-err"),
							equalTo: $frmYLRegister.find("input[name='reenter_password']").attr("data-match")
						},
						"captcha": {
							required: $frmYLRegister.find("input[name='captcha']").attr("data-err"),
							remote: $frmYLRegister.find("input[name='captcha']").attr("data-captcha")
						}
					},
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'captcha')
						{
							error.insertAfter(element.parent());
						}else{
							error.insertAfter(element);
						}
					},
					errorClass: "err",
					wrapper: "em",
					onkeyup: false
				});
			}
			
			if ($frmYLForgot.length > 0 && validate) 
			{
				$frmYLForgot.validate({
					messages: {
						"email": {
							required: $frmYLForgot.find("input[name='email']").attr("data-err"),
							email: $frmYLForgot.find("input[name='email']").attr("data-email")
						}
					},
					errorPlacement: function (error, element) {
						error.insertAfter(element);
					},
					errorClass: "err",
					wrapper: "em",
					onkeyup: false
				});
			}
			
			if ($frmYLReserve.length > 0 && validate) 
			{
				$frmYLReserve.validate({
					rules: {
						"captcha": {
							remote: $frmYLReserve.find("input[name='captcha']").attr("data-folder") + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						}
					},
					messages: {
						"c_title": {
							required: $frmYLReserve.find("select[name='c_title']").attr("data-err")
						},
						"c_name": {
							required: $frmYLReserve.find("input[name='c_name']").attr("data-err")
						},
						"c_email": {
							required: $frmYLReserve.find("input[name='c_email']").attr("data-err"),
							email: $frmYLReserve.find("input[name='c_email']").attr("data-email")
						},
						"c_phone": {
							required: $frmYLReserve.find("input[name='c_phone']").attr("data-err")
						},
						"c_company": {
							required: $frmYLReserve.find("input[name='c_company']").attr("data-err")
						},
						"c_address": {
							required: $frmYLReserve.find("input[name='c_address']").attr("data-err")
						},
						"c_country": {
							required: $frmYLReserve.find("select[name='c_country']").attr("data-err")
						},
						"c_state": {
							required: $frmYLReserve.find("input[name='c_state']").attr("data-err")
						},
						"c_city": {
							required: $frmYLReserve.find("input[name='c_city']").attr("data-err")
						},
						"c_zip": {
							required: $frmYLReserve.find("input[name='c_zip']").attr("data-err")
						},
						"front_notes": {
							required: $frmYLReserve.find("textarea[name='front_notes']").attr("data-err")
						},
						"payment_method": {
							required: $frmYLReserve.find("select[name='payment_method']").attr("data-err")
						},
						"cc_type": {
							required: $frmYLReserve.find("select[name='cc_type']").attr("data-err")
						},
						"cc_num": {
							required: $frmYLReserve.find("input[name='cc_num']").attr("data-err")
						},
						"cc_code": {
							required: $frmYLReserve.find("input[name='cc_code']").attr("data-err")
						},
						"captcha": {
							required: $frmYLReserve.find("input[name='captcha']").attr("data-err"),
							remote: $frmYLReserve.find("input[name='captcha']").attr("data-captcha")
						}
					},
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'captcha')
						{
							error.insertAfter(element.parent());
						}else{
							error.insertAfter(element);
						}
					},
					errorClass: "err",
					wrapper: "em",
					onkeyup: false,
					submitHandler: function(form){
						var $form = pjQ.$(form);
						pjQ.$('.ylFormMessage').parent().show();
						self.disableButtons();
						pjQ.$.post([self.opts.folder, "index.php?controller=pjListings&action=pjActionReserve&id=" + $frmYLReserve.find("input[name='listing_id']").val()].join(""), $form.serialize()).done(function (data) {
							pjQ.$('.ylFormMessage').parent().hide();
							if (!data.code) {
								return;
							}
							switch (parseInt(data.code, 10)) {
								case 100:
									pjQ.$('.ylFormError').parent().show();
									self.enableButtons();
									break;
								case 124:
									pjQ.$('.ylFormError').html(data.text).parent().show();
									self.enableButtons();
									break;
								case 200:
								case 201:
									pjQ.$('.ylFormError').html("").parent().hide();
									self.getPaymentForm(data);
									break;
							}
						});
						return false;
				    }
				});
			}
		},
		getPaymentForm: function(obj){
			var self = this,
				index = this.opts.index;
			var qs = {
					"id": obj.listing_id,
					"booking_id": obj.booking_id, 
					"payment_method": obj.payment
				};
			pjQ.$.get([this.opts.folder, "index.php?controller=pjListings&action=pjActionGetPaymentForm"].join(""), qs).done(function (data) {
				pjQ.$('.ylFormMessage').parent().hide();
				pjQ.$('.ylFormError').parent().hide();
				var $msg_container = pjQ.$('#ylReserveMessage_' + index);
				$msg_container.html(data);
				$msg_container.css('display', 'block');
				switch (obj.payment) {
					case 'paypal':
						$msg_container.find("form[name='ylPaypal']").trigger('submit');
						break;
					case 'authorize':
						$msg_container.find("form[name='ylAuthorize']").trigger('submit');
						break;
					case 'creditcard':
					case 'bank':
					case 'cash':
						self.resetRevervationForm();
						break;
				}
			}).fail(function () {
				log("Deferred is rejected");
			});
		},
		resetRevervationForm: function(){
			var self = this,
				$frmYLReserve = pjQ.$('#frmYLReserve_' + this.opts.index);
			
			$frmYLReserve.find("select[name='c_title']").val('');
			$frmYLReserve.find("input[name='c_name']").val('');
			$frmYLReserve.find("input[name='c_email']").val('');
			$frmYLReserve.find("input[name='c_phone']").val('');
			$frmYLReserve.find("input[name='c_company']").val('');
			$frmYLReserve.find("input[name='c_address']").val('');
			$frmYLReserve.find("select[name='c_country']").val('');
			$frmYLReserve.find("input[name='c_state']").val('');
			$frmYLReserve.find("input[name='c_city']").val('');
			$frmYLReserve.find("input[name='c_zip']").val('');
			$frmYLReserve.find("textarea[name='c_notes']").val('');
			$frmYLReserve.find("select[name='payment_method']").val('');
			$frmYLReserve.find("select[name='cc_type']").val('');
			$frmYLReserve.find("input[name='cc_num']").val('');
			$frmYLReserve.find("input[name='cc_code']").val('');
			$frmYLReserve.find("input[name='captcha']").val('');
			
			var rand = Math.floor((Math.random()*999999)+1); 
			pjQ.$('#ylCaptchaImage_' + self.opts.index).attr("src", self.opts.folder + 'index.php?controller=pjFront&action=pjActionCaptcha&rand=' + rand);
		}
	};
	
	window.YachtListing = YachtListing;	
})(window);