var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateBooking = $("#frmCreateBooking"),
			$frmUpdateBooking = $("#frmUpdateBooking"),
			$frmWaitList = $("#frmWaitList"),
			$dialogSelect = $("#dialogSelect"),
			$dialogJoinWaitList = $("#dialogJoinWaitList"),
			$dialogConfirmation = $("#dialogConfirmation"),
			$dialogPayment = $("#dialogPaymentConfirm"),
			$dialogTicketConfirmation = $('#dialogTicketConfirmation'),
			validate = ($.fn.validate !== undefined),
			chosen = ($.fn.chosen !== undefined);
			dialog = ($.fn.dialog !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			tabs = ($.fn.tabs !== undefined),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
				}
			};
			
		if ($tabs.length > 0 && tabs) 
		{
			$tabs.tabs(tOpt);
		}
		if (chosen) 
		{
			$("#event_id").chosen();
			$("#c_country").chosen();
		}
		if($('#barcode_label').length > 0)
		{
			$('#barcode_label').focus();
		}
		if ($frmCreateBooking.length > 0 && validate) {
			$frmCreateBooking.validate({
				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);
				    	}
				    };
				},
				submitHandler: function(form)
				{
					if(checkSeats(true) == true)
					{
						form.submit();
					}else{
						$tabs.tabs(tOpt).tabs("option", "active", 0);
					}
					return false;
				}
			});
			
		}
		if ($frmUpdateBooking.length > 0 && validate) {
			$frmUpdateBooking.validate({
				errorPlacement: function (error, element) {
					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);
				    	}
				    };
				},
				submitHandler: function(form)
				{
					if(checkSeats(true) == true)
					{
						form.submit();
					}else{
						$tabs.tabs(tOpt).tabs("option", "active", 0);
					}
					return false;
				}
			});
		}
		
		if($dialogSelect.length > 0)
		{
			var $frm = null;
			if ($frmCreateBooking.length > 0) 
			{
				$frm = $frmCreateBooking;
			}
			if ($frmUpdateBooking.length > 0) 
			{
				$frm = $frmUpdateBooking;
			}	
			$dialogSelect.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 850,
				open: function (){
					if($('#reload_map').val() == '1')
					{
						$.post("index.php?controller=pjAdminBookings&action=pjActionGetSeats", $frm.serialize()).done(function (data) {
							$dialogSelect.html(data);
							adviseToSelectSeats();
						});
					}else{
						adviseToSelectSeats();
					}
				},
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.ok] = function () {
						$('#tbCopiedSeats').html($('#tbSelectedSeats').html());
						if ($frmUpdateBooking.length > 0){
							$('#reload_map').val(0);
						}
						$dialogSelect.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		
		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.name, type: "text", sortable: true, editable: false, width: 160},
				          {text: myLabel.event, type: "text", sortable: true, editable: false, width: 160},
				          {text: myLabel.tickets, type: "text", sortable: true, editable: false, width: 70, align: 'center'},
				          {text: myLabel.price, type: "text", sortable: true, editable: false, width: 80},
				          {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: ['c_name', 'title', 'cnt_tickets', 'total', '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", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBookings&action=pjActionSaveBooking&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}	
		if ($("#grid_invoices").length > 0 && datagrid) 
		{
			function formatTotal(val, obj) {
				return obj.total_formated;
			}
			function formatDefault (str) {
				return myLabel[str] || str;
			}
			function formatId (str) {
				return ['<a href="index.php?controller=pjInvoice&action=pjActionUpdate&id=', str, '">#', str, '</a>'].join("");
			}
			function formatCreated(str) {
				if (str === null || str.length === 0) {
					return myLabel.empty_datetime;
				}
				
				if (str === '0000-00-00 00:00:00') {
					return myLabel.invalid_datetime;
				}
				
				if (str.match(/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}/) !== null) {
					var x = str.split(" "),
						date = x[0],
						time = x[1],
						dx = date.split("-"),
						tx = time.split(":"),
						y = dx[0],
						m = parseInt(dx[1], 10) - 1,
						d = dx[2],
						hh = tx[0],
						mm = tx[1],
						ss = tx[2];
					return $.datagrid.formatDate(new Date(y, m, d, hh, mm, ss), pjGrid.jsDateFormat + ", hh:mm:ss");
				}
			}
			var $grid_invoices = $("#grid_invoices").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjInvoice&action=pjActionUpdate&id={:id}", title: "Edit"},
				          {type: "delete", url: "index.php?controller=pjInvoice&action=pjActionDelete&id={:id}", title: "Delete"}],
				columns: [
				    {text: myLabel.num, type: "text", sortable: true, editable: false, renderer: formatId},
				    {text: myLabel.order_id, type: "text", sortable: true, editable: false},
				    {text: myLabel.issue_date, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				    {text: myLabel.due_date, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				    {text: myLabel.created, type: "text", sortable: true, editable: false, renderer: formatCreated},
				    {text: myLabel.status, type: "text", sortable: true, editable: false, renderer: formatDefault},	
				    {text: myLabel.total, type: "text", sortable: true, editable: false, align: "right", renderer: formatTotal}
				],
				dataUrl: "index.php?controller=pjInvoice&action=pjActionGetInvoices&q=" + $frmUpdateBooking.find("input[name='uuid']").val(),
				dataType: "json",
				fields: ['id', 'order_id', 'issue_date', 'due_date', 'created', 'status', 'total'],
				paginator: {
					actions: [
					   {text: myLabel.delete_title, url: "index.php?controller=pjInvoice&action=pjActionDeleteBulk", render: true, confirmation: myLabel.delete_body}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				select: {
					field: "id",
					name: "record[]"
				}
			});
			$frmUpdateBooking.on("click", ".btnCreateInvoice", function () {
				$("#frmCreateInvoice").trigger("submit");
			});
		}
		$(document).on("click", ".btn-all", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
			var content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				status: "",
				q: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString, "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" + pjGrid.queryString, "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()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).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" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			$(".pj-button-detailed").trigger("click");
			if (chosen) {
				$("#event_id").val('').trigger("liszt:updated");
			}
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("change", "#event_id", function (e) {
			var event_id = $(this).val();
			var has_code = $('option:selected', this).attr('data-code');
			$('.pj-loader').css('display', 'block');
			$.get("index.php?controller=pjAdminBookings&action=pjActionGetTickets&event_id=" + event_id).done(function (data) {
				$('#pjTbsTicketList').html(data);
				$('#discount_code').val('');
				if(has_code == 'T')
				{
					$('#pjEtsCodeWrapper').show();
				}else{
					$('#pjEtsCodeWrapper').hide();
				}
				$('.pj-loader').css('display', 'none');
			});	
		}).on("click", ".pjTbsJoinWaitlist", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogJoinWaitList.data('event_id', $(this).attr('data-event_id')).data('ticket_id', $(this).attr('data-ticket_id')).dialog('open');
		}).on("change", ".pjTbsTicketQty", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var qty = parseInt($(this).val(), 10);
			var id = $(this).attr('data-id');
			var total_qty = 0;
			var has_map = $(this).attr('data-map');
			var require_attendee = $(this).attr('data-attendee');
			var $seatTableCell = $('#pjTbsHiddenSeats_' + id);
			var number_of_seats = $seatTableCell.find('.pjTbsHiddenSeat').length;
			
			if(has_map == 'T')
			{
				if(qty > 0)
				{
					$('#pjTbsSelectSeatsLabel_' + id).show();
					$('#pjTbsNoneLabel_' + id).hide();
				}else{
					$('#pjTbsSelectSeatsLabel_' + id).hide();
					$('#pjTbsNoneLabel_' + id).show();
				}
			}
			
			$('.pjTbsTicketQty').each(function(){
				total_qty += parseInt($(this).val(), 10);
			});
			
			if(total_qty == 0)
			{
				$('#pjTbsTotalTickets').val('');
			}else{
				$('#pjTbsTotalTickets').val(total_qty).valid();
			}
			if($('#discount_code').val() == '')
			{
				calcPrice();
			}else{
				$('.pjTbsApplyCode').trigger('click');
			}
			
			if(qty < number_of_seats)
			{
				$seatTableCell.find('.pjTbsHiddenSeat').each(function(){
					if(qty >= number_of_seats)
					{
						return false;
					}else{
						$(this).remove();
						number_of_seats--;
					}
				});
			}
			
			if(require_attendee == 'yes')
			{
				var $attendBox = $('#pjEtsAttendee_' + id);
				if(qty == 0)
				{
					$attendBox.remove();
				}else{
					var append = 1;
					if($attendBox.length > 0)
					{
						append = 0;
					}
					$.post("index.php?controller=pjAdminBookings&action=pjActionGetAttendees&ticket_id=" + id + "&qty=" + qty + "&append=" + append, $('#pjEtsAttendee_' + id).find('input').serialize()).done(function (data) {
						if(append == 0)
						{
							$('#pjEtsAttendee_' + id).html(data);
						}else{
							$('#pjEtsAttendeeList').append(data);
						}
					});	
				}
			}
			updateSeatNames(id);
		}).on("click", ".pjTbsSelectSeatsLabel", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogSelect.data('event_id', $(this).attr('data-event_id')).data('ticket_id', $(this).attr('data-ticket_id')).dialog('open');
		}).on("keydown", ".pjTbsDonation", function (e) {
			if (e.shiftKey == true) {
                e.preventDefault();
            }
			if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 46 || e.keyCode == 190) {
				
            } else {
            	e.preventDefault();
            } 
			if($(this).val().indexOf('.') !== -1 && e.keyCode == 190)
			{
				e.preventDefault();
			}
		}).on("keyup", ".pjTbsDonation", function (e) {
			calcPrice();
		}).on("click", ".tbSeatAvailable", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var number_of_seats = 0;
			var seat_id = $(this).attr('data-id');
			var seat_name = $(this).attr('data-name');
			var ticket_id = $(this).attr('data-ticket_id');
			var ticket_qty = parseInt($('#pjTbsTicketQty_' + ticket_id).val(), 10);
			var $seatTableCell = $('#pjTbsHiddenSeats_' + ticket_id);
			var $mapHolder = $('#tbMapHolder');
			
			$mapHolder.find('.tbSeatSelected').each(function(){
				if(!$(this).hasClass('pjTbsOtherTicket'))
				{
					number_of_seats++;
				}
			});
			
			if(number_of_seats < ticket_qty)
			{
				$(this).removeClass('tbSeatAvailable').addClass('tbSeatSelected');
				$('<input>').attr({
				    type: 'hidden',
				    id: 'seat_id_' + ticket_id + "_" + seat_id,
				    name: 'seat_id['+ticket_id+'][' + seat_id + ']',
				    class: 'pjTbsHiddenSeat',
				    "data-name": seat_name,
				    value: seat_id
				}).appendTo($seatTableCell);
			}
			updateSeatNames(ticket_id);
			checkSeats(false);
		}).on("click", ".tbSeatSelected", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var seat_id = $(this).attr('data-id');
			var ticket_id = $(this).attr('data-ticket_id');
			var $seatTableCell = $('#pjTbsHiddenSeats_' + ticket_id);
			if(!$(this).hasClass('pjTbsOtherTicket'))
			{
				$(this).removeClass('tbSeatSelected').addClass('tbSeatAvailable');
				$('#seat_id_' + ticket_id + '_' + seat_id).remove();
				checkSeats(false);
			}
		}).on("click", ".pjTbsApplyCode", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var event_id = $('#event_id').val();
			var discount_code = $('#discount_code').val();
			if(event_id != '' && discount_code != '')
			{
				$.get("index.php?controller=pjAdminBookings&action=pjActionApplyCode&event_id=" + event_id + "&discount_code=" + discount_code).done(function (data) {
					if(data.status == 'OK')
					{
						if(data.ticket_id_arr != '')
						{
							var ticket_arr = data.ticket_id_arr.split("~|~");
							for(var i = 0; i < ticket_arr.length; i++)
							{
								var price_arr = ticket_arr[i].split("~:~");
								var ticket_id = price_arr[0];
								var $ticketQty = $('#pjTbsTicketQty_' + ticket_id);
								var qty = parseInt($ticketQty.val(), 10);
								var count = parseInt(data.count, 10);
								if(qty >= count)
								{
									$ticketQty.attr('data-price', price_arr[1]);
									$('#pjTbsCellPrice_' + ticket_id).html(price_arr[2]);
									$('#pjTbsUnitPrice_' + ticket_id).val(price_arr[1]);
								}else{
									var original_price = $ticketQty.attr('data-original_price');
									var original_price_format = $ticketQty.attr('data-original_price_format');
									$ticketQty.attr('data-price', original_price);
									$('#pjTbsUnitPrice_' + ticket_id).val(original_price);
									$('#pjTbsCellPrice_' + ticket_id).html(original_price_format);
								}
							}
						}
					}else{
						$('.pjTbsTicketQty').each(function(){
							var ticket_id = $(this).attr('data-id');
							var type = $(this).attr('data-type');
							var original_price = $(this).attr('data-original_price');
							var original_price_format = $(this).attr('data-original_price_format');
							$('#pjTbsTicketQty_' + ticket_id).attr('data-price', original_price);
							$('#pjTbsUnitPrice_' + ticket_id).val(original_price);
							$('#pjTbsCellPrice_' + ticket_id).html(original_price_format);
						});
						$('#discount_code').val('');
					}
					calcPrice();
				});
			}
		}).on("click", ".pjEtsSendConfirm", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogConfirmation.data('id', $(this).attr('data-id')).dialog('open');
		}).on("click", ".pjEtsSendPayment", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogPayment.data('id', $(this).attr('data-id')).dialog('open');
		}).on("click", "#use_ticket", function(e){
			$dialogTicketConfirmation.data('id', $(this).attr('lang')).dialog('open');
		});
		
		function updateSeatNames(ticket_id)
		{
			var $seatTableCell = $('#pjTbsHiddenSeats_' + ticket_id);
			var seat_name_arr = [];
			if($seatTableCell.length == 0)
			{
				$('#pjTbsSeatNames_' + ticket_id).html("").hide();
			}else{
				$seatTableCell.find('.pjTbsHiddenSeat').each(function(){
					seat_name_arr.push($(this).attr('data-name'));
				});
				$('#pjTbsSeatNames_' + ticket_id).html(seat_name_arr.join("; ")).show();
			}
		}
		
		function checkSeats(submit)
		{
			var valid = true;
			$('.pjTbsTicketQty').each(function(){
				var ticket_qty = parseInt($(this).val(), 10);
				var ticket_id = $(this).attr('data-id');
				var $seatTableCell = $('#pjTbsHiddenSeats_' + ticket_id);
				var number_of_seats = $seatTableCell.find('.pjTbsHiddenSeat').length;
				console.log(number_of_seats);
				console.log(ticket_qty);
				if(number_of_seats < ticket_qty && $seatTableCell.length > 0)
				{
					valid = false;
					if(submit == true)
					{
						$seatTableCell.closest('tr').addClass('pjTbsTableRowError');
					}
				}else{
					$seatTableCell.closest('tr').removeClass('pjTbsTableRowError');
				}
			});
			if(valid == false)
			{
				if(submit == true)
				{
					$('.pjTbsSeatErrorMsg').css('display', 'block');
				}
			}else{
				$('.pjTbsSeatErrorMsg').css('display', 'none');
			}
			return valid;
		}
		
		function calcPrice()
		{
			var subtotal = 0,
				tax = 0,
				total = 0,
				deposit = 0,
				total_qty = 0;
			
			$('.pjTbsTicketQty').each(function(){
				var count = parseInt($(this).val(), 10);
				var price = parseFloat($(this).attr('data-price'));
				var id = $(this).attr('data-id');
				var type = $(this).attr('data-type');
				total_qty += count;
				if(type == 'donation')
				{
					var $donation_input = $('#pjTbsDonation_' + id);
					if($donation_input.val() != '')
					{
						var donation = parseFloat($('#pjTbsDonation_' + id).val());
						subtotal += donation * count;
					}
				}else{
					subtotal += price * count;
				}
			});
			
			var tax_percentage = parseFloat($('#tax').attr('data-tax'));
			var deposit_percentage = parseFloat($('#deposit').attr('data-deposit'));
			
			tax = subtotal * tax_percentage / 100;
			total = subtotal + tax;
			deposit = total * deposit_percentage / 100;
			
			if(total_qty > 0)
			{
				$('#sub_total').val(subtotal.toFixed(2));
				$('#tax').val(tax.toFixed(2));
				$('#total').val(total.toFixed(2));
				$('#deposit').val(deposit.toFixed(2));
			}else{
				$('#sub_total').val('');
				$('#tax').val('');
				$('#total').val('');
				$('#deposit').val('');
			}
		}
		
		if ($dialogJoinWaitList.length > 0) {
			
			if ($frmWaitList.length > 0 && validate) {
				$frmWaitList.validate({
					errorPlacement: function (error, element) {
						error.insertAfter(element.parent());
					},
					onkeyup: false,
					errorClass: "err",
					wrapper: "em",
					ignore: ""
				});
			}
			$dialogJoinWaitList.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 450,
				open: function () {					
					$frmWaitList.find("input[name='event_id']").val($dialogJoinWaitList.data('event_id'));
					$frmWaitList.find("input[name='ticket_id']").val($dialogJoinWaitList.data('ticket_id'));
					$frmWaitList.find("input[name='name']").val('');
					$frmWaitList.find("input[name='email']").val('');
				},
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.send] = function () {
						if($frmWaitList.valid())
						{
							$.post("index.php?controller=pjAdminBookings&action=pjActionJoin", $frmWaitList.serialize()).done(function (data) {
								$dialogJoinWaitList.dialog('close');
							});	
						}
					};
					buttons[tbsApp.locale.button.cancel] = function () {
						$dialogJoinWaitList.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
		
		if($dialogSelect.length > 0)
		{
			$dialogSelect.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 850,
				open: function (){
					var loader_url = $dialogSelect.attr('data-loader');
					var post_data = $('#pjTbsTicketTable').find('input.pjTbsHiddenSeat[type=hidden]').serialize();
					if($frmUpdateBooking.length > 0)
					{
						post_data += "&id="+$frmUpdateBooking.find("input[name='id']").val();
					}
					$dialogSelect.html('<img src="'+loader_url+'" />');
					$.post("index.php?controller=pjAdminBookings&action=pjActionGetSeats&event_id=" + $dialogSelect.data('event_id') + "&ticket_id=" + $dialogSelect.data('ticket_id'), post_data).done(function (data) {
						$dialogSelect.html(data);
					});
				},
				close: function () {
					$dialogSelect.html('');				
				},
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.ok] = function () {
						
						$dialogSelect.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		
		if ($dialogConfirmation.length > 0 && dialog) {
			$dialogConfirmation.dialog({
				autoOpen: false,
				draggable: false,
				resizable: false,
				modal: true,
				width: 640,
				open: function () {
					$dialogConfirmation.html("");
					$.get("index.php?controller=pjAdminBookings&action=pjActionConfirmation", {
						"booking_id": $dialogConfirmation.data('id')
					}).done(function (data) {
						$dialogConfirmation.html(data);
						validator = $dialogConfirmation.find("form").validate({
							
						});
						$dialogConfirmation.dialog("option", "position", "center");
						attachTinyMce.call(null);
					});
				},
				buttons: {
					'Send': function () {
						if (validator.form()) {
							if(window.tinymce !== undefined) 
							{
								tinymce.triggerSave()
							}
							$("#dialogConfirmation").next(".ui-dialog-buttonpane").find(".ui-button").attr("disabled", true).addClass("ui-state-disabled");
							$.post("index.php?controller=pjAdminBookings&action=pjActionConfirmation", $dialogConfirmation.find("form").serialize()).done(function (data) {
								$("#dialogConfirmation").next(".ui-dialog-buttonpane").find(".ui-button").removeAttr("disabled").removeClass("ui-state-disabled");
								$dialogConfirmation.dialog("close");
							})
						}
					},
					'Cancel': function () {
						$(this).dialog("close");
					}
				}
			});
		}
		if ($dialogPayment.length > 0 && dialog) {
			$dialogPayment.dialog({
				autoOpen: false,
				draggable: false,
				resizable: false,
				modal: true,
				width: 640,
				open: function () {
					$dialogPayment.html("");
					$.get("index.php?controller=pjAdminBookings&action=pjActionSendPayment", {
						"booking_id": $dialogPayment.data('id')
					}).done(function (data) {
						$dialogPayment.html(data);
						validator = $dialogPayment.find("form").validate({
							
						});
						$dialogPayment.dialog("option", "position", "center");
						attachTinyMce.call(null);
					});
				},
				buttons: {
					'Send': function () {
						if (validator.form()) {
							if(window.tinymce !== undefined) 
							{
								tinymce.triggerSave()
							}
							$("#dialogPaymentConfirm").next(".ui-dialog-buttonpane").find(".ui-button").attr("disabled", true).addClass("ui-state-disabled");
							$.post("index.php?controller=pjAdminBookings&action=pjActionSendPayment", $dialogPayment.find("form").serialize()).done(function (data) {
								$("#dialogPaymentConfirm").next(".ui-dialog-buttonpane").find(".ui-button").removeAttr("disabled").removeClass("ui-state-disabled");
								$dialogPayment.dialog("close");
							})
						}
					},
					'Cancel': function () {
						$(this).dialog("close");
					}
				}
			});
		}
		if ($dialogTicketConfirmation.length > 0 && dialog) {
			$dialogTicketConfirmation.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 380,
				height:150,
				modal: true,
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.yes] = function () {
						$.ajax({
							type: "POST",
							data: {
								id: $dialogTicketConfirmation.data('id')
							},
							dataType: 'json',
							url: "index.php?controller=pjAdminBookings&action=pjActionSetUseTicket",
							success: function (res) {
								if(res.status == 1){
									$('#use_ticket').attr("disabled", true);
								}
							}
						});
						$dialogTicketConfirmation.dialog('close');
					};
					buttons[tbsApp.locale.button.no] = function () {
						$('#use_ticket').removeAttr('checked');
						$dialogTicketConfirmation.dialog('close');
					};
					return buttons;
				})()
			});
		}
		function attachTinyMce(options) {
			if (window.tinymce !== undefined) {
				tinymce.EditorManager.editors = [];
				var defaults = {
					selector: "textarea.mceEditor",
					theme: "modern",
					width: 610,
					height: 330,
					plugins: [
				         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
				         "searchreplace 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 | link image | print preview media fullpage | forecolor backcolor emoticons"
				};
				
				var settings = $.extend({}, defaults, options);
				
				tinymce.init(settings);
			}
		}
	});
})(jQuery_1_8_2);