var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var 
			$frmCreateBooking = $('#frmCreateBooking'),
			$frmUpdateBooking = $('#frmUpdateBooking'),
			$frmBookingResend = $('#frmBookingResend'),
			$dialogSelect = $("#dialogSelect"),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			spinner = ($.fn.spinner !== undefined),
			chosen = ($.fn.chosen !== undefined),
			tabs = ($.fn.tabs !== undefined),
			$tabs = $("#tabs"),
			tOpt = {
				select: function (event, ui) {
					$(":input[name='tab_id']").val(ui.panel.id);
				}
			};
	
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		$(".field-int").spinner({
			min: 1,
			stop: function( event, ui ) {
				if($('#line_id').val() != '')
				{
					calPrice();
				}
			}
		});
		if (chosen) {
			$("#location_id").chosen();
			$("#dropoff_id").chosen();
			$("#pickup_id").chosen();
			$("#search_dropoff_id").chosen();

			$("#c_country").chosen();
			$("#client_id").chosen();
		}
		if ($frmBookingResend.length > 0) 
		{
			tinymce.init({
			    selector: "textarea.mceEditor",
			    theme: "modern",
			    width: 550,
			    plugins: [
			         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
			         "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
			         "save table contextmenu directionality emoticons template paste textcolor"
			   ],
			   toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l      ink image | print preview media fullpage | forecolor backcolor emoticons"
			 });
		}
		if ($frmCreateBooking.length > 0 || $frmUpdateBooking.length > 0) 
		{
			jQuery.validator.addMethod("pjNumber", function(value, element) {
				var currency_format = parseInt($(element).attr('data-currency_format'), 10);
				var regex = /^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{1,2}|)$/;
				if(currency_format == 1)
				{
					regex = /^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{1,2}|)$/;
				}else if(currency_format == 2){
					regex = /^((\d+)|(\d{1,3})(\ \d{3}|)*)(\.\d{1,2}|)$/;
				}else if(currency_format == 3){
					regex = /^((\d+)|(\d{1,3})(\.\d{3}|)*)(\,\d{1,2}|)$/;
				}else if(currency_format == 4){
					regex = /^((\d+)|(\d{1,3})(\ \d{3}|)*)(\,\d{1,2}|)$/;
				}
				if(regex.test(value))
				{
					return true;
				}else{
					if(currency_format == 3 || currency_format == 4)
					{
						regex = /^((\d+)|(\d{1,3})(\\d{3}|)*)(\.\d{1,2}|)$/;
						if(regex.test(value))
						{
							return true;
						}else{
							return false;
						}
					}else{
						return false;
					}
				}
			});
			$.validator.addMethod('positiveNumber', function (value) { 
				return Number(value) >= 0;
			}, myLabel.positive_number);
			
			$.validator.addMethod('maximumNumber', function (value, element) { 
				var data = parseInt($(element).attr('data-value'), 10);
				if(Number(value) > data)
				{
					return false;
				}else{
					return true;
				}
			}, myLabel.max_number);
			if($('.timepick').length > 0)
			{
				$('.timepick').timepicker({
					showPeriod: myLabel.showperiod,
					defaultTime: ''
				});
			}
			if($('#client_id').length == 0)
			{
				$('.clientRequired').addClass('required');
			}
			$frmCreateBooking.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'booking_date' || element.attr('name') == 'passengers' || element.attr('name') == 'luggage')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
				    if (validator.numberOfInvalids()) {
				    	var index = $(validator.errorList[0].element, this).closest("div[id^='tabs-']").index();
				    	if ($tabs.length > 0 && tabs && index !== -1) {
				    		$tabs.tabs(tOpt).tabs("option", "active", index-1);
				    	}
				    };
				}
			});
			$frmUpdateBooking.validate({
				rules:{
					uuid: {
						required: true,
						remote: "index.php?controller=pjAdminBookings&action=pjActionCheckID&id=" + $frmUpdateBooking.find("input[name='id']").val()
					}
				},
				messages:{
					uuid: {
						remote: myLabel.duplicated_id
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'return_date' || element.attr('name') == 'passengers' || element.attr('name') == 'luggage')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
				    if (validator.numberOfInvalids()) {
				    	var index = $(validator.errorList[0].element, this).closest("div[id^='tabs-']").index();
				    	if ($tabs.length > 0 && tabs && index !== -1) {
				    		$tabs.tabs(tOpt).tabs("option", "active", index-1);
				    	}
				    };
				}
			});
		}
		
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminBookings&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBooking&id={:id}"}
						  ],
				columns: [
				          {text: myLabel.client, type: "text", sortable: false, width:160},
				          {text: myLabel.transfer_date_time, type: "text", sortable: false, width:170},
				          {text: myLabel.transfer_destinations, type: "text", sortable: false, width:160},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, options: [
				                                                                                     {label: myLabel.pending, value: "pending"}, 
				                                                                                     {label: myLabel.confirmed, value: "confirmed"},
				                                                                                     {label: myLabel.cancelled, value: "cancelled"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString,
				dataType: "json",
				fields: ['client', 'date_time', 'pickup_dropoff', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBookingBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminBookings&action=pjActionExportBooking", render: false, ajax: false},
					   {text: myLabel.print, url: "javascript:void(0);", render: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBookings&action=pjActionSaveBooking&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(document).on("focusin", ".datepick", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev"),
				onSelect: function (dateText, inst) {
					if($this.attr('name') == 'booking_date')
					{
						getAvailTimes();
						$this.valid();
					}
					if($this.attr('name') == 'return_date')
					{
						getReturnAvailTimes();
						$this.valid();
					}
				}
			});
		}).on("click", ".pj-form-field-icon-date", function (e) {
			var $dp = $(this).parent().siblings("input[type='text']");
			if ($dp.hasClass("hasDatepicker")) {
				$dp.datepicker("show");
			} else {
				if(!$dp.is('[disabled=disabled]'))
				{
					$dp.trigger("focusin").datepicker("show");
				}
			}
		}).on("click", ".pj-button-detailed, .pj-button-detailed-arrow", function (e) {
			e.stopPropagation();
			$(".pj-form-filter-advanced").toggle();
		}).on("submit", ".frm-filter-advanced", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var obj = {},
				$this = $(this),
				arr = $this.serializeArray(),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			for (var i = 0, iCnt = arr.length; i < iCnt; i++) {
				obj[arr[i].name] = arr[i].value;
			}
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(".pj-button-detailed").trigger("click");
			if (chosen) {
				$("#pickup_id").val('').trigger("liszt:updated");
				$("#search_dropoff_id").val('').trigger("liszt:updated");
			}
			$('#date').val('');
			$('#email').val('');
			$('#name').val('');
			$('#phone').val('');
			var content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				status: "",
				q: "",
				date: "",
				dropoff_id: "",
				location_id: "",
				name: "",
				phone: "",
				email: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".btn-all", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).addClass("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			var content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				status: "",
				q: "",
				date: "",
				dropoff_id: "",
				location_id: "",
				name: "",
				phone: "",
				email: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".btn-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache"),
				obj = {};
			$this.addClass("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			obj.status = "";
			obj[$this.data("column")] = $this.data("value");
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("submit", ".frm-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				q: $this.find("input[name='q']").val(),
				date: "",
				dropoff_id: "",
				location_id: "",
				name: "",
				phone: "",
				email: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("change", "#location_id", function (e) {
			getDropoff();
			if($(this).val() != '')
			{
				$(this).valid();
			}
		}).on("change", "input[name='traveling']", function (e) {
			getLines();
			var traveling = $('input[name=traveling]:checked' ).val();
			$('.trLocationLabel').hide();
			$('.trLocation-'+traveling).show();
			if($('#has_return').is(':checked'))
			{
				getReturnLines();
			}
		}).on("change", "#dropoff_id", function (e) {
			getLines();
			if($('#has_return').is(':checked'))
			{
				getReturnLines();
			}
			if($(this).val() != '')
			{
				$(this).valid();
			}
		}).on("change", "#line_id", function (e) {
			getAvailTimes();
			if($(this).val() != '')
			{
				$(this).valid();
			}
		}).on("change", "#return_line_id", function (e) {
			if($('#has_return').is(':checked'))
			{
				getReturnAvailTimes();
			}
			if($(this).val() != '')
			{
				$(this).valid();
			}
		}).on("click", "#has_return", function (e) {
			if($(this).is(':checked'))
			{
				$('#trReturnWrapper').show();
				$('#return_date').addClass('required');
				$('#return_line_id').addClass('required');
				$('#return_booking_time').addClass('required');
				getReturnLines();
			}else{
				$('#trReturnWrapper').hide();
				$('#return_date').val("").removeClass('required');
				$('#return_line_id').val("").removeClass('required');
				$('#return_booking_time').val("").removeClass('required');
				$('#sub_total').attr("data-return_price", '0');
			}
			calPrice();
		}).on("change", "#client_id", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if($(this).val() != '')
			{
				$('#pjFdEditClient').css('display', 'block');
				var href = $('#pjFdEditClient').attr('data-href');
				href = href.replace("{ID}", $(this).val());
				$('#pjFdEditClient').attr('href', href);
				$('#pjSbNewClientWrapper').hide();
				$('#pjSbNewClientWrapper').find('.clientRequired').removeClass('required');
			}else{
				$('#pjFdEditClient').css('display', 'none');
				$('#pjSbNewClientWrapper').show();
				$('#pjSbNewClientWrapper').find('.clientRequired').addClass('required');
				$('#pjSbNewClientWrapper').find('input').val("");
				$('#pjSbNewClientWrapper').find('select').val("");
			}
		}).on("change", "#pickup_id", function (e) {
			$.get("index.php?controller=pjAdminBookings&action=pjActionGetDropoff", {
				location_id: $(this).val(),
				for_search: 1
			}).done(function (data) {
				$("#trDropoffContainer").html(data);
				$("#search_dropoff_id").chosen();
			});	
		});
		
		$("#grid").on("click", 'a.pj-paginator-action:last', function (e) {
			e.preventDefault();
			var booking_id = $('.pj-table-select-row:checked').map(function(e){
				 return $(this).val();
			}).get();
			if(booking_id != '' && booking_id != null)
			{
				window.open('index.php?controller=pjAdminBookings&action=pjActionPrint&record=' + booking_id,'_blank');
			}	
			return false;
		});
		function getDropoff()
		{
			$.get("index.php?controller=pjAdminBookings&action=pjActionGetDropoff", {
				location_id: $('#location_id').val()
			}).done(function (data) {
				$("#trDropoffContainer").html(data);
				$("#dropoff_id").chosen();
				getLines();
				if($('#has_return').is(':checked'))
				{
					getReturnLines();
				}
			});	
		}
		function getLines()
		{
			if($('#dropoff_id').val() != '')
			{
				var opts = {
						location_id: $('#location_id').val(),
						dropoff_id: $('#dropoff_id').val(),
						passengers: $('#passengers').val()
					};
				$.get("index.php?controller=pjAdminBookings&action=pjActionGetLines", opts).done(function (data) {
					$('#trLineWrapper').html(data);
					getAvailTimes();
				});	
			}
		}
		function getAvailTimes()
		{
			var $form = $('#location_id').closest('form');
			var id = null;
			if($form.find('input[name="id"]').length > 0)
			{
				id = $form.find('input[name="id"]').val();
			}
			var opts = {
					location_id: $('#location_id').val(),
					dropoff_id: $('#dropoff_id').val(),
					line_id: $('#line_id').val(),
					booking_date: $('#booking_date').val(),
					passengers: $('#passengers').val(),
					traveling: $('input[name=traveling]:checked').val(),
					id: id
				};
			$.get("index.php?controller=pjAdminBookings&action=pjActionGetTimes", opts).done(function (data) {
				$('#trTimeWrapper').html(data.timetable);
				$('#sub_total').attr('data-price', data.price_per_person);
				if(parseInt(data.duration, 10) > 0)
				{
					$('#tr_duration').html(data.duration_text);
				}else{
					$('#tr_duration').html("");
				}
				if(parseFloat(data.price_per_person) > 0)
				{
					$('#tr_price_per_person').html(data.price_per_person_format).parent().parent().show();
				}else{
					$('#tr_price_per_person').html("").parent().parent().hide();
				}
				calPrice();
			});	
		}
		function getReturnLines()
		{
			if($('#dropoff_id').val() != '')
			{
				var opts = {
						location_id: $('#location_id').val(),
						dropoff_id: $('#dropoff_id').val(),
						has_return: 1
					};
				$.get("index.php?controller=pjAdminBookings&action=pjActionGetLines", opts).done(function (data) {
					$('#trReturnLineWrapper').html(data);
					getReturnAvailTimes();
				});	
			}
		}
		function getReturnAvailTimes()
		{
			var $form = $('#location_id').closest('form');
			var id = null;
			if($form.find('input[name="id"]').length > 0)
			{
				id = $form.find('input[name="id"]').val();
			}
			var opts = {
					location_id: $('#location_id').val(),
					dropoff_id: $('#dropoff_id').val(),
					line_id: $('#return_line_id').val(),
					booking_date: $('#return_date').val(),
					passengers: $('#passengers').val(),
					traveling: $('input[name=traveling]:checked').val() == 'from' ? 'to' : 'from',
					has_return: 1,
					id: id
				};
			$.get("index.php?controller=pjAdminBookings&action=pjActionGetTimes", opts).done(function (data) {
				$('#trReturnTimeWrapper').html(data.timetable);
				$('#sub_total').attr('data-return_price', data.price_per_person);
				if(parseInt(data.duration, 10) > 0)
				{
					$('#tr_return_duration').html(data.duration_text);
				}else{
					$('#tr_return_duration').html("");
				}
				if(parseFloat(data.price_per_person) > 0)
				{
					$('#tr_return_price_per_person').html(data.price_per_person_format).parent().parent().show();
				}else{
					$('#tr_return_price_per_person').html("").parent().parent().hide();
				}
				calPrice();
			});	
		}
		function calPrice()
		{
			var sub_total = 0,
				tax = 0,
				total = 0,
				deposit = 0;
			if($('#line_id').val() != '')
			{
				var passengers = parseInt($('#passengers').val(), 10);
				var price_per_person = parseFloat($('#sub_total').attr('data-price'));
				var return_price_per_person = parseFloat($('#sub_total').attr('data-return_price'));
				var tax_percentage = parseFloat($('#tax').attr('data-tax'));
				var deposit_percentage = parseFloat($('#deposit').attr('data-deposit'));
				
				if(price_per_person > 0)
				{
					sub_total = (price_per_person + return_price_per_person) * passengers;
					tax = (sub_total * tax_percentage) / 100;
					total = sub_total + tax;
					deposit = (total * deposit_percentage) / 100;
					
					$('#sub_total').val(convertToCurrencyFormat(sub_total.toFixed(2))).valid();
					$('#tax').val(convertToCurrencyFormat(tax.toFixed(2))).valid();
					$('#total').val(convertToCurrencyFormat(total.toFixed(2))).valid();
					$('#deposit').val(convertToCurrencyFormat(deposit.toFixed(2))).valid();
				}else{
					$('#sub_total').val("");
					$('#tax').val("");
					$('#total').val("");
					$('#deposit').val("");
				}
			}else{
				$('#sub_total').val("");
				$('#tax').val("");
				$('#total').val("");
				$('#deposit').val("");
			}
		}
		function convertToCurrencyFormat(input)
		{
			var number = input;
			switch(myLabel.currency_format) {
			    case 1:
			    	number = $.number( input, 2, '.', ',' );
			        break;
			    case 2:
			    	number = $.number( input, 2, '.', ' ' );
			        break;
			    case 3:
			    	number = $.number( input, 2, ',', '.' );
			        break;
			    case 4:
			    	number = $.number( input, 2, ',', ' ' );
			        break;
			}
			return number;
		}
	});
})(jQuery_1_8_2);