var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateEvent = $("#frmCreateEvent"),
			$frmUpdateEvent = $("#frmUpdateEvent"),
			$frmUpdateTickets = $("#frmUpdateTickets"),
			$frmUpdateDiscount = $("#frmUpdateDiscount"),
			$frmUpdateWaitlist = $("#frmUpdateWaitlist"),
			$frmUpdateMap = $("#frmUpdateMap"),
			$frmUpdateTicketp = $("#frmUpdateTicket"),
			$dialogDel = $("#dialogDelete"),
			$dialogHotspot = $("#dialogHotspot"),
			$dialogUpdate = $("#dialogUpdate"),
			$dialogDeleteTicketImage = $("#dialogDeleteTicketImage"),
			multiselect = ($.fn.multiselect !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			dialog = ($.fn.dialog !== undefined),
			tabs = ($.fn.tabs !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
				}
			},
			hotspot_width = 25,
			hotspot_height = 25;
		
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		$(".field-int").spinner({
			min: 0
		});
		if (multiselect) {
			$("#ticket_id").multiselect({noneSelectedText: myLabel.choose});
			$("#hotspot_ticket_id").multiselect({noneSelectedText: myLabel.choose});
		}
		
		if ($frmCreateEvent.length > 0 && validate) {
			$frmCreateEvent.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'start_date')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
					
				}
			});
		}
		if ($frmUpdateEvent.length > 0 && validate) {
			$frmUpdateEvent.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'start_date')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
		}
		if ($frmUpdateTickets.length > 0 && validate)
			
		{
			$.validator.addMethod('validPrice',
				function (value) { 
					if(parseFloat(value) > 9999999.99)
					{
						return false;
					}else{
						return true;
					}
				}
			);
			$frmUpdateTickets.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'sale_start' || element.attr('name') == 'sale_end')
					{
						error.insertAfter(element.parent().parent());
					}else if(element.attr('name') == 'price'){
						error.insertAfter(element.parent().parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
		}
		if ($frmUpdateDiscount.length > 0 && validate) {
			$frmUpdateDiscount.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'valid_from' || element.attr('name') == 'valid_to')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateWaitlist.length > 0 && validate) {
			$frmUpdateWaitlist.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateMap.length > 0) 
		{
			var offset = $("#map").offset(),
				dragOpts = {
					containment: "parent",
					stop: function (event, ui) {
						updateElem.apply(this, [event, ui]);
					}
				};
			$("span.empty").draggable(dragOpts).resizable({
				resize: function(e, ui) {
					var height = $(this).height();
					$(this).css("line-height", height + "px"); 
		        },
				stop: function(e, ui) {
					var height = $(this).height();
					$(this).css("line-height", height + "px");
					updateElem.apply(this, [e, ui]);
		        }
			}).bind("click", function (e) {
				$dialogUpdate.data('rel', $(this).attr("rel")).dialog("open");
				$(this).siblings(".rect").removeClass("rect-selected").end().addClass("rect-selected");
			});
			
			$("#mapHolder").click(function (e) {
				var px = $('.bsMapHolder').scrollLeft();
				var $this = $(this),
				index = getMax(),
				w = hotspot_width,
				h = hotspot_height;
				
				var t = Math.ceil(e.pageY - offset.top - (parseInt(hotspot_height / 2, 10)));
				var l = Math.ceil(e.pageX - offset.left - (parseInt(hotspot_width / 2, 10)) + px);
				var o = {top: t, left: l, width: w, height: h};
				
				if (!collisionDetect(o)) {
					index++;
					$("<span>", {
						css: {
							"top": t + "px",
							"left": l + "px",
							"width": w + "px",
							"height": h + "px",
							"line-height": h + "px",
							"position": "absolute"
						},
						html: '<span class="bsInnerRect" data-name="hidden_'+index+'">'+index+'</span>',
						rel: "hidden_" + index,
						title: index
					}).addClass("rect empty new").draggable(dragOpts).resizable({
						resize: function(e, ui) {
							var height = $(this).height();
							$(this).css("line-height", height + "px"); 
				        },
						stop: function(e, ui) {
							var height = $(this).height();
							$(this).css("line-height", height + "px"); 
							updateElem.apply(this, [e, ui]);
				        }
					}).bind("click", function (e) {
						$dialogUpdate.data('rel', $(this).attr("rel")).dialog("open");
						$(this).siblings(".rect").removeClass("rect-selected").end().addClass("rect-selected");
					}).appendTo($this);
					
					var pTicketId = $("#hotspot_ticket_id", $dialogHotspot).val();
					
					$("<input>", {
						type: "hidden",
						name: "seats_new[]",
						id: "hidden_" + index
					}).val(['x', w, h, l, t, index, '1', '1', pTicketId].join("|")).appendTo($("#hiddenHolder"));
					
				}
			});
		}
		
		if ($dialogHotspot.length > 0) {
			$dialogHotspot.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 440,
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.set] = function () {
						hotspot_width = parseInt($('#hotspot_width').val(), 10);
						hotspot_height = parseInt($('#hotspot_height').val(), 10);
						$dialogHotspot.dialog('close');
					};
					return buttons;
				})()
			});
		}
		
		if ($dialogDel.length > 0) {
			$dialogDel.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.delete] = function () {
						var event_id = $dialogDel.data('lang');
						$.ajax({
							type: "POST",
							data: {
								id: event_id
							},
							url: "index.php?controller=pjAdminEvents&action=pjActionDeleteMap",
							success: function (data) {
								$dialogDel.dialog('close');
								if(data != '100')
								{
									window.location.href = "index.php?controller=pjAdminEvents&action=pjActionMap&event_id=" + event_id
								}
							}
						});
					};
					buttons[tbsApp.locale.button.cancel] = function () {
						$dialogDel.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
		if ($dialogUpdate.length > 0) {
			var seat_id = null;
			$dialogUpdate.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 440,
				open: function () {
					var rel = $(this).data("rel"),
						arr = $("#" + rel).val().split("|");
					$("#seat_name").val(arr[5]);
					$("#seat_seats").val(arr[6]);
					seat_id = arr[0];
					
					if(arr.length == 9)
					{
						var ticket_id_arr = arr[8].split(",");
						$("#ticket_id").val(ticket_id_arr);
					}else{
						$("#ticket_id option:selected").prop("selected", false);
					}
					$("#ticket_id").multiselect('refresh');
					$dialogUpdate.find('.ui-multiselect').removeClass('error');
				},
				close: function () {
					$("#seat_name, #seat_seats").val("");
					var pTicketId = $("#ticket_id", $dialogUpdate).val();
					if(pTicketId == null || pTicketId == '')
					{
						var rel = $dialogUpdate.data('rel');
						var pHidden = $("#" + rel, $frmUpdateMap).val();
						var a = pHidden.split("|");
						if(a.length == 8)
						{
							$("#" + rel, $("#hiddenHolder")).remove();				
							$(".rect[rel='"+ rel +"']", $("#mapHolder")).remove();
						}
					}				
				},
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.save] = function () {
						var rel = $(this).data("rel"),
							pName = $("#seat_name").val(),
							pSeats = parseInt($("#seat_seats").val(), 10),
							pHidden = $("#" + rel, $frmUpdateMap).val(),
							pTicketId = $("#ticket_id", $dialogUpdate).val();
						
						if(pTicketId != null && pTicketId != '')
						{
							var a = pHidden.split("|");
							var $rect_inner = $(".bsInnerRect[data-name='" + rel + "']", $frmUpdateMap);
							$rect_inner.text(pName);
							$("#rbInner_" + rel).text(pName);
							$("#" + rel).val([seat_id, a[1], a[2], a[3], a[4], pName, pSeats, '1', pTicketId].join("|"));
							
							$dialogUpdate.find('.ui-multiselect').removeClass('error')
							$(this).dialog('close');
						}else{
							$dialogUpdate.find('.ui-multiselect').addClass('error')
						}
					};
					buttons[tbsApp.locale.button.delete] = function () {
						var rel = $(this).data('rel');
						$("#" + rel, $("#hiddenHolder")).remove();				
						$(".rect-selected[rel='"+ rel +"']", $("#mapHolder")).remove();
						
						$dialogUpdate.dialog('close');
					};
					buttons[tbsApp.locale.button.cancel] = function () {
						$dialogUpdate.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
		if ($dialogDeleteTicketImage.length > 0) {
			$dialogDeleteTicketImage.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				buttons: (function () {
					var buttons = {};
					buttons[tbsApp.locale.button.delete] = function () {
						var href = $dialogDeleteTicketImage.data('href');
						$.ajax({
							type: "GET",
							url: href,
							success: function (data) {
								$('#image_container').remove();
								$dialogDeleteTicketImage.dialog('close');
							}
						});
					};
					buttons[tbsApp.locale.button.cancel] = function () {
						$dialogDeleteTicketImage.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
		function collisionDetect(o) {
			var i, pos, horizontalMatch, verticalMatch, collision = false;
			$("#mapHolder").children("span").each(function (i) {
				pos = getPositions(this);
				horizontalMatch = comparePositions([o.left, o.left + o.width], pos[0]);
				verticalMatch = comparePositions([o.top, o.top + o.height], pos[1]);			
				if (horizontalMatch && verticalMatch) {
					collision = true;
					return false;
				}
			});
			if (collision) {
				return true;
			}
			return false;
		}
		function getPositions(box) {
			var $box = $(box);
			var pos = $box.position();
			var width = $box.width();
			var height = $box.height();
			return [[pos.left, pos.left + width], [pos.top, pos.top + height]];
		}
		
		function comparePositions(p1, p2) {
			var x1 = p1[0] < p2[0] ? p1 : p2;
			var x2 = p1[0] < p2[0] ? p2 : p1;
			return x1[1] > x2[0] || x1[0] === x2[0] ? true : false;
		}
		
		function updateElem(event, ui) {
			var $this = $(this),
				rel = $this.attr("rel"),
				$hidden = $("#" + rel),
				val = $hidden.val().split("|");		
			
			$hidden.val([val[0], parseInt($this.width(), 10), parseInt($this.height(), 10), ui.position.left, ui.position.top, $this.text(), val[6], val[7], val[8]].join("|"));
		}
		function getMax() {
			var tmp, index = 0;
			$("span.empty").each(function (i) {
				if (!isNaN(Number(this.title))) {
					tmp = Number(this.title);
				} else {
					tmp = parseInt($(this).attr("rel").split("_")[1], 10);
				}
				if (tmp > index) {
					index = tmp;
				}
			});
			return index;
		}
		
		function GetZoomFactor () {
            var factor = 1;
            if (document.body.getBoundingClientRect) {
                    
                var rect = document.body.getBoundingClientRect ();
                var physicalW = rect.right - rect.left;
                var logicalW = document.body.offsetWidth;

                factor = Math.round ((physicalW / logicalW) * 100) / 100;
            }
            return factor;
        }
		function formatTicketsSold (str, obj) {
			if (parseInt(str, 10) > 0) {
				return '<a href="index.php?controller=pjAdminEvents&action=pjActionBookings&event_id='+obj.id+'">'+str+'</a>';
			} else {
				return '0';
			}
		}
		function formatWaitlist (str, obj) {
			if (parseInt(str, 10) > 0) {
				return '<a href="index.php?controller=pjAdminEvents&action=pjActionWaitlist&event_id='+obj.id+'">'+str+'</a>';
			} else {
				return '0';
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			var buttonOpts = [{type: "view", target: 'blank', url: "preview.php?id={:id}"},
			                  {type: "edit", url: "index.php?controller=pjAdminEvents&action=pjActionUpdate&event_id={:id}"},
					          {type: "delete", url: "index.php?controller=pjAdminEvents&action=pjActionDeleteEvent&id={:id}"}
					          ];
			var columnOpts = [{text: myLabel.title, type: "text", sortable: true, editable: true, width: 170},
			                  {text: myLabel.tickets_sold, type: "text", sortable: true, editable: false, width: 50, align: "center", renderer: formatTicketsSold},
			                  {text: myLabel.avail_tickets, type: "text", sortable: true, editable: false, width: 80, align: "center"},
			                  {text: myLabel.waitlist, type: "text", sortable: true, editable: false, width: 70, align: "center", renderer: formatWaitlist},
			                  {text: myLabel.start_date, type: "text", sortable: true, editable: false, width: 90},
					          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, editableWidth: 80, options: [
							                                                                                     {label: myLabel.active, value: "T"}, 
							                                                                                     {label: myLabel.inactive, value: "F"}
							                                                                                     ], applyClass: "pj-status"}];
			
			var $grid = $("#grid").datagrid({
				buttons: buttonOpts,
				columns: columnOpts,
				dataUrl: "index.php?controller=pjAdminEvents&action=pjActionGetEvent",
				dataType: "json",
				fields: ['title', 'tickets_sold', 'available_tickets', 'cnt_subscribers', 'start_date', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEvents&action=pjActionDeleteEventBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEvents&action=pjActionSaveEvent&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		function formatSoldTickets (str, obj) {
			if (parseInt(str, 10) > 0) {
				return '<a href="index.php?controller=pjAdminBookings&action=pjActionIndex&event_id='+obj.event_id+'&status=confirmed">'+str+'</a>';
			} else {
				return '0';
			}
		}
		if ($("#ticket_grid").length > 0 && datagrid) {
			var buttonOpts = [{type: "edit", url: "index.php?controller=pjAdminEvents&action=pjActionTickets" + pjGrid.queryString + "&id={:id}"},
					          {type: "delete", url: "index.php?controller=pjAdminEvents&action=pjActionDeleteTicket&id={:id}"}
					          ];
			var columnOpts = [{text: myLabel.thumbnail, type: "text", sortable: false, editable: false, width: 90, renderer: function(val) {
			                      return val ? '<img src="' + val + '" style="max-width:60px;max-height:40px;vertical-align:middle;" />' : '';
			                  }},
			                  {text: myLabel.ticket_type, type: "text", sortable: true, editable: false, width: 300},
			                  {text: myLabel.total_tickets, type: "text", sortable: true, editable: false, width: 100, align: 'center'},
			                  {text: myLabel.sold_tickets, type: "text", sortable: true, editable: false, width: 100, align: 'center', renderer: formatSoldTickets},
			                  {text: myLabel.price, type: "text", sortable: true, editable: false, width: 80}];
			
			var $grid = $("#ticket_grid").datagrid({
				buttons: buttonOpts,
				columns: columnOpts,
				dataUrl: "index.php?controller=pjAdminEvents&action=pjActionGetTicket" + pjGrid.queryString,
				dataType: "json",
				fields: ['thumbnail', 'title', 'available_tickets', 'sold_tickets', 'price'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEvents&action=pjActionDeleteTicketBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEvents&action=pjActionSaveTicket&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		if ($("#discount_grid").length > 0 && datagrid) {
			var buttonOpts = [{type: "edit", url: "index.php?controller=pjAdminEvents&action=pjActionDiscount" + pjGrid.queryString + "&id={:id}"},
					          {type: "delete", url: "index.php?controller=pjAdminEvents&action=pjActionDeleteDiscount&id={:id}"}
					          ];
			var columnOpts = [{text: myLabel.code, type: "text", sortable: true, editable: false, width: 150},
			                  {text: myLabel.discount, type: "text", sortable: true, editable: false, width: 150},
			                  {text: myLabel.valid_from, type: "text", sortable: true, editable: false, width: 150},
			                  {text: myLabel.valid_to, type: "text", sortable: true, editable: false, width: 150}];
			
			var $grid = $("#discount_grid").datagrid({
				buttons: buttonOpts,
				columns: columnOpts,
				dataUrl: "index.php?controller=pjAdminEvents&action=pjActionGetDiscount" + pjGrid.queryString,
				dataType: "json",
				fields: ['code', 'discount', 'valid_from', 'valid_to'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEvents&action=pjActionDeleteCodeBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEvents&action=pjActionSaveCode&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		if ($("#waitlist_grid").length > 0 && datagrid) {
			var buttonOpts = [{type: "edit", url: "index.php?controller=pjAdminEvents&action=pjActionWaitlist" + pjGrid.queryString + "&id={:id}"},
			                  {type: "delete", url: "index.php?controller=pjAdminEvents&action=pjActionDeleteWaitlist&id={:id}"}
					          ];
			var columnOpts = [{text: myLabel.ticket, type: "text", sortable: true, editable: false, width: 200},
			                  {text: myLabel.name, type: "text", sortable: true, editable: false, width: 200},
			                  {text: myLabel.email, type: "text", sortable: true, editable: false, width: 200}];
			
			var $grid = $("#waitlist_grid").datagrid({
				buttons: buttonOpts,
				columns: columnOpts,
				dataUrl: "index.php?controller=pjAdminEvents&action=pjActionGetWaitlist" + pjGrid.queryString,
				dataType: "json",
				fields: ['title', 'name', 'email'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEvents&action=pjActionDeleteWaitlistBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEvents&action=pjActionSaveWaitlist&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		$(document).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: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent", "title", "ASC", 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=pjAdminEvents&action=pjActionGetEvent", "title", "ASC", 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=pjAdminEvents&action=pjActionGetEvent", "title", "ASC", content.page, content.rowCount);
			return false;
		}).on("submit", ".waitlist-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=pjAdminEvents&action=pjActionGetWaitlist" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datetimepick", function (e) {
			var minDateTime, maxDateTime,
				$this = $(this),
				custom = {},
				o = {
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev"),
					timeFormat: $this.attr("lang"),
					stepMinute: 5,
				};
			switch ($this.attr("name")) {
				case "sale_start":
					if($(".datetimepick[name='sale_end']").val() != '')
					{
						maxDateTime = $(".datetimepick[name='sale_end']").datetimepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev"),
							timeFormat: $this.attr("lang")
						}).datetimepicker("getDate");
						$(".datetimepick[name='sale_end']").datepicker("destroy").removeAttr("id");
						if (maxDateTime !== null) {
							custom.maxDateTime = maxDateTime;
						}
					}
					custom.defaultValue = $this.attr('data-default');
					break;
				case "sale_end":
					if($(".datetimepick[name='sale_start']").val() != '')
					{
						minDateTime = $(".datetimepick[name='sale_start']").datetimepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev"),
							timeFormat: $this.attr("lang")
						}).datetimepicker("getDate");
						$(".datetimepick[name='sale_start']").datepicker("destroy").removeAttr("id");
						if (minDateTime !== null) {
							custom.minDateTime = minDateTime;
						}
						custom.defaultValue = $(".datetimepick[name='sale_start']").val();
					}else{
						custom.defaultValue = $this.attr('data-default');
					}
					break;
				case "valid_from":
					if($(".datetimepick[name='valid_to']").val() != '')
					{
						maxDateTime = $(".datetimepick[name='valid_to']").datetimepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev"),
							timeFormat: $this.attr("lang")
						}).datetimepicker("getDate");
						$(".datetimepick[name='valid_to']").datepicker("destroy").removeAttr("id");
						if (maxDateTime !== null) {
							custom.maxDateTime = maxDateTime;
						}
					}
					break;
				case "valid_to":
					if($(".datetimepick[name='valid_from']").val() != '')
					{
						minDateTime = $(".datetimepick[name='valid_from']").datetimepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev"),
							timeFormat: $this.attr("lang")
						}).datetimepicker("getDate");
						$(".datetimepick[name='valid_from']").datepicker("destroy").removeAttr("id");
						if (minDateTime !== null) {
							custom.minDateTime = minDateTime;
						}
					}
					break;
			}
			$(this).datetimepicker($.extend(o, custom));
			
		}).on("focusin", ".datepick", function (e) {
			var	$this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev")
			});
		}).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 {
				$dp.trigger("focusin").datepicker("show");
			}
			
		}).on("click", ".pjTbsAddTicket", function (e) {
			
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).hide();
			$('#ticket_grid').hide();
			$frmUpdateTickets.show();
		}).on("click", ".pjTbsAddDiscount", function (e) {
			
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).hide();
			$('#discount_grid').hide();
			$frmUpdateDiscount.show();
		}).on("click", "#type", function (e) {
			var sign = $('option:selected', this).attr('data-sign');
			$('#icon_type').html(sign);
		}).on("click", ".tbHotpotSize", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogHotspot.dialog('open');
		}).on("click", ".pj-delete-map", function (e) {
			$dialogDel.data('lang', $(this).attr('lang')).dialog('open');
		}).on("change", 'input[type=radio][name=type]', function (e) {
			if (this.value == 'paid') 
			{
				$('#pjTbsPaidPrice').show();
				$('#price').addClass('required').addClass('number').addClass('validPrice');
			}else{
				$('#pjTbsPaidPrice').hide();
				$('#price').removeClass('required').removeClass('number').removeClass('validPrice');
			}
		}).on("click", ".pj-delete-image", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDeleteTicketImage.data('href', $(this).attr('data-href')).dialog('open');
		});
	});
})(jQuery_1_8_2);
		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",
				    setup: function (editor) {
				    	editor.on('change', function (e) {
				    		editor.editorManager.triggerSave();
				    	});
				    }
				};
				
				var settings = $.extend({}, defaults, options);
				
				tinymce.init(settings);
			}
		}