/*!
 * Yacht Listing Website v1.0
 *
 * https://www.phpjabbers.com/yacht-listing-website/
 * 
 * Copyright 2014, PHPJabbers
 * 
 */
(function (window, undefined){
	"use strict";
	var document = window.document,
		validate = ($.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;
		},
		formatCurrency: function(price, currency)
		{
			var format = '---';
			switch (currency)
			{
				case 'USD':
					format = "$" + price;
					break;
				case 'GBP':
					format = "&pound;" + price;
					break;
				case 'EUR':
					format = "&euro;" + price;
					break;
				case 'JPY':
					format = "&yen;" + price;
					break;
				case 'AUD':
				case 'CAD':
				case 'NZD':
				case 'CHF':
				case 'HKD':
				case 'SGD':
				case 'SEK':
				case 'DKK':
				case 'PLN':
					format = price + currency;
					break;
				case 'NOK':
				case 'HUF':
				case 'CZK':
				case 'ILS':
				case 'MXN':
					format = currency + price;
					break;
				default:
					format = price + currency;
					break;
			}
			return format;
		},
		disableButtons: function () {
			$(".btn").attr("disabled", "disabled");
		},
		enableButtons: function () {
			$(".btn").removeAttr("disabled");
		},
		init: function (opts) {
			var self = this;
			this.opts = opts;
			
			$(document).on("click.yl", ".pjYlSearchType", function (e) {
				var $frm = $('#pjYlQuickSearch');
				$('.pjYlSearchType').removeClass('active');
				$(this).addClass('active');
				$frm.find("input[name='for']").val($(this).attr('data-type'));
			}).on("click.yl", ".ylNavMonth", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var month = $(this).attr('data-month'),
					id = $(this).attr('data-id');
				self.disableButtons();
				$.get(self.opts.folder + 'index.php?controller=pjWebsite&action=pjActionGetMonth&id=' + id + '&month=' + month).done(function (data) {
					$('#pjYlReservationTable').html(data);
					self.enableButtons();
				});
			}).on("click.yl", ".ylBtnReserve", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var week = null;
				week = $(this).attr('data-week');
				if(week != null)
				{
					$('#frmYlBooking').find('input[name="week"]').val(week);
					$('#frmYlBooking').submit();
				}
			}).on("change.yl", "#ylPaymentMethod", function (e) {
				
				var val = $(this).val();
				$('.ylCcWrap').hide();
				$('.ylBankWrap').hide();
				if(val == 'creditcard')
				{
					$('.ylCcWrap').show();
				}else if(val == 'bank'){
					$('.ylBankWrap').show();
				}
			});
			
			var quickPriceSlider = $("#pjYlQuickPriceSlider");
	
		 	if (quickPriceSlider.length) {
		 		var $priceLabel = $('#pjAcPriceLabel');
		 		var $frm = $('#pjYlQuickSearch');
		 		quickPriceSlider.slider({
					range: true,
					min: 0,
					max: 500000,
					step: 1000,
					values: [ 0, 500000 ],
					slide: function( event, ui ) {
						var currency = $priceLabel.attr('data-currency'),
							filter_price_from = self.formatCurrency(parseInt(ui.values[0], 10), currency),
							filter_price_to = self.formatCurrency(parseInt(ui.values[1], 10), currency);
							
						$priceLabel.html(filter_price_from + ' - ' + filter_price_to);
					},
					stop: function( event, ui ) {
						var slider_value_from = parseInt(ui.values[0], 10),
							slider_value_to = parseInt(ui.values[1], 10);
						
						$frm.find("input[name='min_price']").val(slider_value_from);
						$frm.find("input[name='max_price']").val(slider_value_to);
					}
				});
		 	};
	
		 	var slideshow = $('.slideshow');
	
		 	if (slideshow.length) {
		 		slideshow.flexslider({
		    		directionNav: false
		 		});
		 	};
	
		 	var details_slider = $('.yacht-details-slider');
	
		 	if (details_slider.length) {
		 		details_slider.flexslider({
		 			controlNav: "thumbnails",
		    		directionNav: false
		 		});
		 	};

		 	$(window).scroll(function(){
				if ($(this).scrollTop() > 80) {
					$('.scroll-to-top').addClass('active');
				} else {
					$('.scroll-to-top').removeClass('active');
				}
			});
			
			$('.scroll-to-top').click(function(){
				$('html, body').animate({scrollTop : 0},600);
				return false;
			});

		 	var $frmYLReserve = $('#frmYLReserve');
		 	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")
						},
						"c_notes": {
							required: $frmYLReserve.find("textarea[name='c_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")
						}
					},
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'captcha')
						{
							element.parent().parent().parent().addClass('has-error');
							error.appendTo(element.next().find('ul'));
						}else if(element.parent().hasClass('form-control-select')){
							element.parent().parent().addClass('has-error');
							error.appendTo(element.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');
						}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	if(element.attr('name') == 'captcha')
						{
							element.parent().parent().parent().removeClass('has-error').addClass('has-success');
						}else if(element.parent().hasClass('form-control-select')){
							element.parent().parent().removeClass('has-error').addClass('has-success');
						}else{
							element.parent().parent().removeClass('has-error').addClass('has-success');
						}
		            },
					submitHandler: function(form){
						var $form = $(form);
						$('.ylFormMessage').parent().parent().show();
						self.disableButtons();
						$.post([self.opts.folder, "index.php?controller=pjListings&action=pjActionReserve&id=" + $frmYLReserve.find("input[name='listing_id']").val()].join(""), $form.serialize()).done(function (data) {
							$('.ylFormMessage').parent().hide();
							if (!data.code) {
								return;
							}
							switch (parseInt(data.code, 10)) {
								case 100:
									$('.ylFormError').parent().parent().show();
									self.enableButtons();
									break;
								case 124:
									$('.ylFormError').html(data.text).parent().parent().show();
									self.enableButtons();
									break;
								case 200:
								case 201:
									$('.ylFormError').html("").parent().parent().hide();
									self.getPaymentForm(data);
									break;
							}
						});
						return false;
				    }
				});
			}
		 	var $frmYLLogin = $('#frmYLLogin');
		 	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")
						}
					},
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						element.parent().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');
						}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	element.parent().parent().removeClass('has-error').addClass('has-success');
		            }
				});
			}
		 	var $frmYLRegister = $('#frmYLRegister');
			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")
						}
					},
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						element.parent().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');
						}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	element.parent().parent().removeClass('has-error').addClass('has-success');
		            }
				});
			}
			var $frmYLForgot = $('#frmYLForgot');
			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")
						}
					},
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						element.parent().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');
						}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	element.parent().parent().removeClass('has-error').addClass('has-success');
		            }
				});
			}
		 	self.bindSlider();
		},
		getPaymentForm: function(obj){
			var self = this;
			var qs = {
					"id": obj.listing_id,
					"booking_id": obj.booking_id, 
					"payment_method": obj.payment
				};
			$.get([this.opts.folder, "index.php?controller=pjWebsite&action=pjActionGetPaymentForm"].join(""), qs).done(function (data) {
				$('.ylFormMessage').parent().parent().hide();
				$('.ylFormError').parent().parent().hide();
				var $msg_container = $('#ylReserveMessage');
				$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 = $('#frmYLReserve');
			
			$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); 
			$('#ylCaptchaImage').attr("src", self.opts.folder + 'index.php?controller=pjFront&action=pjActionCaptcha&rand=' + rand);
		},
		bindSlider: function()
		{
			var self = this,
				index = this.opts.index,
				$frmSearch = $('#pjYlQuickSearch');
			$( ".ylSlider" ).slider({
				range: true,
				min: 0,
				max: 150,
				values: [ 0, 150 ],
				step: 5,
				slide: function( event, ui ) {
					$(this).find( ".ui-slider-handle" ).eq(0).text( ui.values[ 0 ] );
					$(this).find( ".ui-slider-handle" ).eq(1).text( ui.values[ 1 ] );
					if($(this).hasClass('ylPowerSlider'))
					{
						$frmSearch.find("input[name='min_horse_power']").val(ui.values[ 0 ]);
						$frmSearch.find("input[name='max_horse_power']").val(ui.values[ 1 ]);
					}else if($(this).hasClass('ylLengthSlider')){
						$frmSearch.find("input[name='min_length']").val(ui.values[ 0 ]);
						$frmSearch.find("input[name='max_length']").val(ui.values[ 1 ]);
					}else if($(this).hasClass('ylBeamSlider')){
						$frmSearch.find("input[name='min_beam']").val(ui.values[ 0 ]);
						$frmSearch.find("input[name='max_beam']").val(ui.values[ 1 ]);
					}
				}
			});
			$('.ylSlider').each(function(){
				$(this).find( ".ui-slider-handle" ).eq(0).text( 0 );
				$(this).find( ".ui-slider-handle" ).eq(1).text( 150 );
			});
			
			$( ".ylYearSlider" ).slider({
				range: true,
				min: self.opts.min_year,
				max: self.opts.max_year,
				values: [ self.opts.min_year, self.opts.max_year ],
				step: 1,
				slide: function( event, ui ) {
					$(this).find( ".ui-slider-handle" ).eq(0).text( ui.values[ 0 ] );
					$(this).find( ".ui-slider-handle" ).eq(1).text( ui.values[ 1 ] );
					
					$frmSearch.find("input[name='min_year']").val(ui.values[ 0 ]);
					$frmSearch.find("input[name='max_year']").val(ui.values[ 1 ]);
				}
			});
			$('.ylYearSlider').each(function(){
				$(this).find( ".ui-slider-handle" ).eq(0).text( self.opts.min_year );
				$(this).find( ".ui-slider-handle" ).eq(1).text( self.opts.max_year );
			});
			
			$( ".ylLOASlider" ).slider({
				range: true,
				min: 0,
				max: 20,
				values: [ 0, 20 ],
				step: 1,
				slide: function( event, ui ) {
					$(this).find( ".ui-slider-handle" ).eq(0).text( ui.values[ 0 ] );
					$(this).find( ".ui-slider-handle" ).eq(1).text( ui.values[ 1 ] );
					
					$frmSearch.find("input[name='min_loa']").val(ui.values[ 0 ]);
					$frmSearch.find("input[name='max_loa']").val(ui.values[ 1 ]);
				}
			});
			$('.ylLOASlider').each(function(){
				$(this).find( ".ui-slider-handle" ).eq(0).text( 0 );
				$(this).find( ".ui-slider-handle" ).eq(1).text( 20 );
			});
		},
	};
	
	window.YachtListing = YachtListing;	
})(window);