(function (window, undefined){
	"use strict";
	pjQ.$.ajaxSetup({
		xhrFields: {
			withCredentials: true
		}
	});
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined),
		routes = [
		          	{pattern: /^#!\/loadTickets$/, eventName: "loadTickets"},
		          	{pattern: /^#!\/loadSeats$/, eventName: "loadSeats"},
		          	{pattern: /^#!\/loadCheckout$/, eventName: "loadCheckout"},
		          	{pattern: /^#!\/loadPreview$/, eventName: "loadPreview"},
		          	{pattern: /^#!\/loadComplete\/([A-Z]{2}\d{10})$/, eventName: "loadComplete"}
		         ];
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnProperty(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function hashBang(value) {
		if (value !== undefined && value.match(/^#!\//) !== null) {
			if (window.location.hash == value) {
				return false;
			}
			window.location.hash = value;
			return true;
		}
		
		return false;
	}
	
	function onHashChange() {
		var i, iCnt, m;
		for (i = 0, iCnt = routes.length; i < iCnt; i++) {
			m = window.location.hash.match(routes[i].pattern);
			if (m !== null) {
				pjQ.$(window).trigger(routes[i].eventName, m.slice(1));
				break;
			}
		}
		if (m === null) {
			pjQ.$(window).trigger("loadTickets");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function EventTicketing(opts) {
		if (!(this instanceof EventTicketing)) {
			return new EventTicketing(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	EventTicketing.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	EventTicketing.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	EventTicketing.prototype = {
		reset: function () {
			this.$container = null;			
			this.container = null;
			this.opts = {};
			this.booking_uuid = null;
			
			return this;
		},
		
		disableButtons: function () {
			this.$container.find(".btn").each(function (i, el) {
				pjQ.$(el).attr("disabled", "disabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".btn").removeAttr("disabled");
		},
		formatCurrency: function(price)
		{
			var self = this;
			var currency = self.opts.currency;
			var format = '---';
			price = price.toFixed(2);
			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;
		},
		calcPrice: function(){
			var self = this;
		
			var subtotal = 0;
			var total_tickets = 0;
			
			pjQ.$('.pjEtsTicketQty').each(function(){
				var count = parseInt(pjQ.$('#'+pjQ.$(this).attr('id')+' option:selected').val(), 10);
				var price = parseFloat(pjQ.$(this).attr('data-price'));
				var id = pjQ.$(this).attr('data-id');
				var type = pjQ.$(this).attr('data-type');
				total_tickets += count;
				if(type == 'donation')
				{
					var $donation_input = pjQ.$('#pjEtsDonation_' + id);
					if($donation_input.val() != '')
					{
						var donation = parseFloat($donation_input.val());
						subtotal += donation * count;
					}
				}else{
					subtotal += price * count;
				}
			});
			pjQ.$('#pjEtsSelectedTickets_' + self.opts.id).html(total_tickets);
			pjQ.$('#pjEtsPrice_' + self.opts.id).html(self.formatCurrency(subtotal));
		},
		checkTickets: function(){
			var self = this;
			var total_tickets = 0;
			pjQ.$('.pjEtsTicketQty').each(function(){
				var count = parseInt(pjQ.$(this).val(), 10);
				total_tickets += count;
			});
			if(total_tickets > 0)
			{
				return true;
			}else{
				return false;
			}
		},
		checkDonation: function(){
			var self = this;
			var donation_valid = true;
			pjQ.$('.pjEtsTicketQty').each(function(){
				var type = pjQ.$(this).attr('data-type');
				var id = pjQ.$(this).attr('data-id');
				var count = parseInt(pjQ.$(this).val(), 10);
				if(type == 'donation')
				{
					var $donation_input = pjQ.$('#pjEtsDonation_' + id);
					
					if($donation_input.val() == '' && count > 0)
					{
						donation_valid = false;
					}
				}
			});
			return donation_valid;
		},
		checkSeats: function(submit){
			var self = this;
			var valid = true;
			pjQ.$('.pjEtsTicketTitle').each(function(){
				var qty = parseInt(pjQ.$(this).attr('data-qty'), 10);
				var ticket_id = pjQ.$(this).attr('data-id');
				var number_of_seats = pjQ.$('#pjEtsHiddenSeats_' + self.opts.id).find('input.pjEtsHiddenSeat_'+ticket_id+'[type=hidden]').length;
				if(number_of_seats < qty)
				{
					valid = false;
					if(!pjQ.$('#pjEtsTicketTitle_' + ticket_id).hasClass('focus'))
					{
						if(submit == true)
						{
							pjQ.$('#pjEtsTicketTitle_' + ticket_id).addClass('seat-alert');
						}
					}
				}else{
					pjQ.$('#pjEtsTicketTitle_' + ticket_id).removeClass('seat-alert');
				}
			});
			if(valid == false)
			{
				if(submit == true)
				{
					pjQ.$('#pjEtsSeatMsg_' + self.opts.id).show();
				}
			}else{
				pjQ.$('#pjEtsSeatMsg_' + self.opts.id).hide();
			}
			return valid;
		},
		showTicketMessage: function(message){
			var self = this;
		
			pjQ.$('#pjEtsTicketMsg_' + self.opts.id).html(message).parent().show();
		},
		hideTicketMessage: function(){
			var self = this;
		
			pjQ.$('#pjEtsTicketMsg_' + self.opts.id).html('').parent().hide();
		},
		
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("pjEtsContainer_" + self.opts.id);
						
			self.$container = pjQ.$(self.container);
			
			this.$container.on("click.ets", ".pjEtsMenuItem", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var load = pjQ.$(this).attr('data-load');
				if (!hashBang("#!/" + load)) 
				{
					pjQ.$(window).trigger(load);
				}
				return false;
			}).on("click.ets", ".pjEtsJoinWaitlist", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $joinMessage = pjQ.$('#pjEtsJoinMessage_' + self.opts.id);
				var $frmJoinWaitlist = pjQ.$('#pjEtsJoinForm_' + self.opts.id);
				$frmJoinWaitlist.find('input[name="name"]').val('');
				$frmJoinWaitlist.find('input[name="email"]').val('');
				$frmJoinWaitlist.find('input[name="event_id"]').val(pjQ.$(this).attr('data-event_id'));
				$frmJoinWaitlist.find('input[name="ticket_id"]').val(pjQ.$(this).attr('data-ticket_id'));
				$joinMessage.html("");
				pjQ.$('#pjEtsModalJoinWaitlist_' + self.opts.id).modal('show');
				return false;
			}).on("keydown.ets", ".pjEtsDonation", 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(pjQ.$(this).val().indexOf('.') !== -1 && e.keyCode == 190)
				{
					e.preventDefault();
				}
			}).on("keyup.ets", ".pjEtsDonation", function (e) {
				self.calcPrice.call(self);
				if(self.checkDonation() == true)
				{
					self.hideTicketMessage.call(self);
				}
			}).on("change.ets", ".pjEtsTicketQty", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				if(pjQ.$(this).attr('data-apply') == 'F')
				{
					self.calcPrice.call(self);
				}else{
					pjQ.$('#pjEtsApplyCode_' + self.opts.id).trigger('click');
				}
				if(self.checkTickets() == true)
				{
					self.hideTicketMessage.call(self);
				}
			}).on("click.ets", "#pjEtsApplyCode_" + self.opts.id, function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $applyCode = pjQ.$(this);
				var $removeCode = pjQ.$('#pjEtsRemoveCode_' + self.opts.id);
				var discount_code = pjQ.$('#pjEtsDiscountCode_' + self.opts.id).val();
				if(discount_code != '')
				{
					var params = { "locale": self.opts.locale, "id": self.opts.id, "discount_code" : discount_code};
					if(self.opts.session_id != "")
					{
						params.session_id = self.opts.session_id;
					}
					pjQ.$.get([self.opts.folder, "index.php?controller=pjFront&action=pjActionApplyCode"].join(""), params).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 = pjQ.$('#pjEtsTicketQty_' + ticket_id);
									var qty = parseInt($ticketQty.val(), 10);
									var count = parseInt(data.count, 10);
									if(qty >= count)
									{
										$ticketQty.attr('data-price', price_arr[1]);
										pjQ.$('#pjEtsPriceLabel_' + ticket_id).html(price_arr[2]);
									}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);
										pjQ.$('#pjEtsPriceLabel_' + ticket_id).html(original_price_format);
									}
									$ticketQty.attr('data-apply', 'T');
								}
							}
							$applyCode.hide();
							$removeCode.show();
						}else{
							pjQ.$('.pjEtsTicketQty').each(function(){
								var ticket_id = pjQ.$(this).attr('data-id');
								var type = pjQ.$(this).attr('data-type');
								var original_price = pjQ.$(this).attr('data-original_price');
								var original_price_format = pjQ.$(this).attr('data-original_price_format');
								pjQ.$('#pjEtsTicketQty_' + ticket_id).attr('data-price', original_price);
								pjQ.$('#pjEtsPriceLabel_' + ticket_id).html(original_price_format);
							});
						}
						pjQ.$('#pjEtsCodeMsg_' + self.opts.id).html(data.text);
						self.calcPrice.call(self);
					});
				}
			}).on("click.ets", "#pjEtsRemoveCode_" + self.opts.id, function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $applyCode = pjQ.$('#pjEtsApplyCode_' + self.opts.id);
				var $removeCode = pjQ.$(this);
				var params = { "locale": self.opts.locale, "id": self.opts.id};
				if(self.opts.session_id != "")
				{
					params.session_id = self.opts.session_id;
				}
				pjQ.$.get([self.opts.folder, "index.php?controller=pjFront&action=pjActionRemoveCode"].join(""), params).done(function (data) {
					pjQ.$('.pjEtsTicketQty').each(function(){
						var ticket_id = pjQ.$(this).attr('data-id');
						var type = pjQ.$(this).attr('data-type');
						var original_price = pjQ.$(this).attr('data-original_price');
						var original_price_format = pjQ.$(this).attr('data-original_price_format');
						pjQ.$('#pjEtsTicketQty_' + ticket_id).attr('data-price', original_price);
						pjQ.$('#pjEtsPriceLabel_' + ticket_id).html(original_price_format);
						pjQ.$(this).attr('data-apply', 'F');
					});
					pjQ.$('#pjEtsDiscountCode_' + self.opts.id).val('');
					pjQ.$('#pjEtsCodeMsg_' + self.opts.id).html('');
					$applyCode.show();
					$removeCode.hide();
					self.calcPrice.call(self);
				});
				return false;
			}).on("click.ets", ".pjTbSeatAvailable", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				
				var number_of_seats = 0;
				var seat_id = pjQ.$(this).attr('data-id');
				var seat_name = pjQ.$(this).attr('data-name');
				var ticket_id = pjQ.$(this).attr('data-ticket_id');
				var ticket_qty = parseInt(pjQ.$('#pjEtsTicketTitle_' + ticket_id).attr('data-qty'), 10);
				var $hiddenSeats = pjQ.$('#pjEtsHiddenSeats_' + self.opts.id);
				var $mapHolder = pjQ.$('#pjEtsMapHolder_' + self.opts.id);
				var $seatsChosen = pjQ.$('#pjEtsListChosenSeats_' + self.opts.id);
				var $selectMoreSeats = pjQ.$('#pjTbSelectMoreSeats_' + self.opts.id);
				
				$mapHolder.find('.pjTbSeatChecked').each(function(){
					if(!pjQ.$(this).hasClass('pjEtsOtherTicket'))
					{
						number_of_seats++;
					}
				});
				if(number_of_seats < ticket_qty)
				{
					pjQ.$(this).removeClass('pjTbSeatAvailable').addClass('pjTbSeatChecked');
					pjQ.$('<input>').attr({
					    type: 'hidden',
					    id: 'seat_id_' + ticket_id + "_" + seat_id,
					    name: 'seat_id['+ticket_id+'][' + seat_id + ']',
					    class: 'pjEtsHiddenSeat_' + ticket_id,
					    value: seat_id
					}).appendTo($hiddenSeats);
					
					var seat_clone = pjQ.$('#pjEtsSeatClone_' + self.opts.id).html();
					seat_clone = seat_clone.replace("{NAME}", seat_name);
					seat_clone = seat_clone.replace("{TICKETID}", ticket_id);
					seat_clone = seat_clone.replace("{SEATID}", seat_id);
					$seatsChosen.append(seat_clone);
				}
				var seats_left = ticket_qty - (number_of_seats + 1);
				if(seats_left > 0)
				{
					var singular_msg = $selectMoreSeats.attr('data-singular_msg');
					var plural_msg = $selectMoreSeats.attr('data-plural_msg');
					plural_msg = plural_msg.replace("{SEATS}", seats_left);
					if(seats_left == 1)
					{
						$selectMoreSeats.html(singular_msg);
					}else{
						$selectMoreSeats.html(plural_msg);
					}
				}else{
					$selectMoreSeats.html("");
				}
				self.checkSeats(false);
				return false;
			}).on("click.ets", ".pjTbSeatChecked", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $mapHolder = pjQ.$('#pjEtsMapHolder_' + self.opts.id);
				var seat_id = pjQ.$(this).attr('data-id');
				var ticket_id = pjQ.$(this).attr('data-ticket_id');
				var $hiddenSeats = pjQ.$('#pjEtsHiddenSeats_' + self.opts.id);
				if(!pjQ.$(this).hasClass('pjEtsOtherTicket'))
				{
					pjQ.$(this).removeClass('pjTbSeatChecked').addClass('pjTbSeatAvailable');
					pjQ.$('#pjEtsSeatChosen_' + ticket_id + '_' + seat_id).remove();	
					pjQ.$('#seat_id_' + ticket_id + '_' + seat_id).remove();	
				}
				
				var $selectMoreSeats = pjQ.$('#pjTbSelectMoreSeats_' + self.opts.id);
				var number_of_seats = 0;
				var ticket_qty = parseInt(pjQ.$('#pjEtsTicketTitle_' + ticket_id).attr('data-qty'), 10);
				$mapHolder.find('.pjTbSeatChecked').each(function(){
					if(!pjQ.$(this).hasClass('pjEtsOtherTicket'))
					{
						number_of_seats++;
					}
				});
				var seats_left = ticket_qty - (number_of_seats);
				if(seats_left > 0 && number_of_seats > 0)
				{
					var singular_msg = $selectMoreSeats.attr('data-singular_msg');
					var plural_msg = $selectMoreSeats.attr('data-plural_msg');
					plural_msg = plural_msg.replace("{SEATS}", seats_left);
					if(seats_left == 1)
					{
						$selectMoreSeats.html(singular_msg);
					}else{
						$selectMoreSeats.html(plural_msg);
					}
				}else if(number_of_seats == 0){
					$selectMoreSeats.html("");
				}else{
					$selectMoreSeats.html("");
				}
				
				self.checkSeats(false);
			}).on("click.ets", ".pjEtsTicketTitle", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var ticket_id = pjQ.$(this).attr('data-id');
				pjQ.$('.pjEtsTicketTitle').removeClass('focus').removeClass('seat-alert');
				pjQ.$(this).addClass('focus');
				self.getSeats(ticket_id);		
			}).on("change.ets", "select[name='payment_method']", function () {
				self.$container.find(".pjEtsCcWrap").hide();
				self.$container.find(".pjEtsBankWrap").hide();
				switch (pjQ.$("option:selected", this).val()) {
				case 'creditcard':
					self.$container.find(".pjEtsCcWrap").show();
					break;
				case 'bank':
					self.$container.find(".pjEtsBankWrap").show();
					break;
				}
			});
			
			pjQ.$(window).on("loadTickets", this.$container, function (e) {
				self.loadTickets.call(self);
			}).on("loadSeats", this.$container, function (e) {
				self.loadSeats.call(self);
			}).on("loadCheckout", this.$container, function (e) {
				self.loadCheckout.call(self);
			}).on("loadPreview", this.$container, function (e) {
				self.loadPreview.call(self);
			}).on("loadComplete", this.container, function (e, booking_uuid) {
				self.booking_uuid = booking_uuid;
				self.loadComplete.call(self);
			});
			
			if (window.location.hash.length === 0) {
				this.loadTickets.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		getSeats: function(ticket_id){
			var self = this;
			var post_data = pjQ.$('#pjEtsHiddenSeats_' + self.opts.id).find('input[type=hidden]').serialize();
			var ajax_url =  [this.opts.folder, "index.php?controller=pjFront&action=pjActionGetSeats", '&id=', self.opts.id, '&ticket_id=', ticket_id].join("");
			if(self.opts.session_id != "")
			{
				ajax_url = [this.opts.folder, "index.php?controller=pjFront&action=pjActionGetSeats", "&session_id=", self.opts.session_id, '&id=', self.opts.id, '&ticket_id=', ticket_id].join("");
			}
			self.disableButtons.call(self);
			pjQ.$.post(ajax_url, post_data).done(function (data) {
				pjQ.$('#pjEtsSeatsSelector_' + self.opts.id).html(data);
				self.enableButtons.call(self);
			}).fail(function () {
				self.enableButtons.call(self);
			});
		},
		loadTickets: function () {
			var self = this,
				params = { "locale": this.opts.locale, "id": this.opts.id };

			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionTickets"].join(""), params).done(function (data) {
				self.$container.html(data);
				self.bindTickets.call(self);
			}).fail(function () {
				
			});
		},
		bindTickets: function(){
			var self = this;
		
			pjQ.$('.modal-dialog').css("z-index", "9999"); 
			
			if (validate) 
			{
				var $form = pjQ.$('#pjEtsJoinForm_'+ self.opts.id);
				$form.validate({
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));
					},
		            highlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	element.parent().removeClass('has-success').addClass('has-error');
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	element.parent().removeClass('has-error').addClass('has-success');
		            },
					submitHandler: function (form) {
						self.disableButtons.call(self);
						var $form = pjQ.$(form);
						var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionJoin"].join("");
						if(self.opts.session_id != "")
						{
							ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionJoin", "&session_id=", self.opts.session_id].join("");
						}
						pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
							var $joinMessage = pjQ.$('#pjEtsJoinMessage_' + self.opts.id);
							if (data.code == "200") {
								pjQ.$('#pjEtsModalJoinWaitlist_' + self.opts.id).modal('hide');
								pjQ.$('#pjEtsModalJoinWaitlistConfirm_' + self.opts.id).modal('show');
							}else{
								$joinMessage.removeClass('text-success').addClass('text-danger').html(data.text);
							}
							self.enableButtons.call(self);
						}).fail(function () {
							self.enableButtons.call(self);
						});
						return false;
					}
				});
				
				var $form = pjQ.$('#pjEtsTicketsForm_'+ self.opts.id);
				
				$form.validate({
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));
					},
					submitHandler: function (form) {
						if(self.checkTickets() == true)
						{
							if(self.checkDonation() == true)
							{
								self.disableButtons.call(self);
								var $form = pjQ.$(form);
								var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveTickets"].join("");
								if(self.opts.session_id != "")
								{
									ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveTickets", "&session_id=", self.opts.session_id].join("");
								}
								pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
									if (data.status == "OK") 
									{
										if(self.opts.has_map == true)
										{
											if (!hashBang("#!/loadSeats")) 
											{
												self.loadSeats.call(self);
											}
										}else{
											if (!hashBang("#!/loadCheckout")) 
											{
												self.loadCheckout.call(self);
											}
										}
									}
								}).fail(function () {
									
								});
								self.enableButtons.call(self);
							}else{
								self.showTicketMessage(self.opts.ticket_messages_2);
							}
						}else{
							self.showTicketMessage(self.opts.ticket_messages_1);
						}
						return false;
					}
				});
			}
		},
		loadSeats: function () {
			var self = this,
				params = { "locale": this.opts.locale, "id": this.opts.id };

			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionSeats"].join(""), params).done(function (data) {
				if (data.code != undefined && data.status == 'ERR') {
					if (!hashBang("#!/loadTickets")) 
					{
						self.loadTickets.call(self);
					}
				}else{
					self.$container.html(data);
					self.bindSeats.call(self);
				}
			}).fail(function () {
				
			});
		},
		bindSeats: function(){
			var self = this;
			var focus_ticket_id = null;
			pjQ.$('.pjEtsTicketTitle').each(function(){
				if(pjQ.$(this).hasClass('focus'))
				{
					focus_ticket_id = pjQ.$(this).attr('data-id');
				}
			});
			if(focus_ticket_id != null)
			{
				self.getSeats(focus_ticket_id);
			}
			if (validate) 
			{
				var $form = pjQ.$('#pjEtsSeatsForm_'+ self.opts.id);
				
				$form.validate({
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));
					},
					submitHandler: function (form) {
						if(self.checkSeats(true) == true)
						{
							self.disableButtons.call(self);
							var $form = pjQ.$(form);
							var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveSeats"].join("");
							if(self.opts.session_id != "")
							{
								ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveSeats", "&session_id=", self.opts.session_id].join("");
							}
							pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
								if (data.status == "OK") 
								{
									if (!hashBang("#!/loadCheckout")) 
									{
										self.loadCheckout.call(self);
									}
								}
								self.enableButtons.call(self);
							}).fail(function () {
								self.enableButtons.call(self);	
							});
						}
						return false;
					}
				});
			}
		},
		loadCheckout: function () {
			var self = this,
				params = { "locale": this.opts.locale, "id": this.opts.id};

			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionCheckout"].join(""), params).done(function (data) {
				if (data.code != undefined && data.status == 'ERR') {
					if (!hashBang("#!/loadTickets")) 
					{
						self.loadTickets.call(self);
					}
				}else{
					self.$container.html(data);
					self.bindCheckout.call(self);
				}
			}).fail(function () {
				
			});
		},
		bindCheckout: function(){
			var self = this,
				index = this.opts.index;
		
			pjQ.$('.modal-dialog').css("z-index", "9999"); 
			var $form = pjQ.$('#pjEtsCheckoutForm_'+ self.opts.id);
			if ($form.length > 0 && validate) 
			{
				var remote_url = self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha";
				if(self.opts.session_id != "")
				{
					remote_url = self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha&session_id=" + self.opts.session_id;
				}
				$form.validate({
					rules: {
						"captcha": {
							remote: remote_url
						}
					},
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'terms')
						{
							error.appendTo(element.siblings().find('ul'));
						}else{
							error.appendTo(element.next().find('ul'));
						}
					},
		            highlight: function(ele, errorClass, validClass) {
		            	var element = pjQ.$(ele);
		            	if(element.attr('name') == 'captcha')
						{
							element.parent().parent().parent().removeClass('has-success').addClass('has-error');
						}else{
							element.parent().removeClass('has-success').addClass('has-error');
						}
		            },
		            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{
							element.parent().removeClass('has-error').addClass('has-success');
						}
		            },
					submitHandler: function (form) {
						self.disableButtons.call(self);
						var $form = pjQ.$(form);
						var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckout", "&id=", self.opts.id].join("");
						if(self.opts.session_id != "")
						{
							ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckout", "&session_id=", self.opts.session_id, "&id=", self.opts.id].join("");
						}
						pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
							if (data.status == "OK") {
								if (!hashBang("#!/loadPreview")) 
								{
									self.loadPreview.call(self);
								}
							}
						}).fail(function () {
							self.enableButtons.call(self);
						});
						return false;
					}
				});
			}
		},
		loadPreview: function () {
			var self = this,
				index = this.opts.index,
				params = { "locale": this.opts.locale, "id": this.opts.id};
			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id; 
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionPreview"].join(""), params).done(function (data) {
				if (data.code != undefined && data.status == 'ERR') {
					if (!hashBang("#!/loadTickets")) 
					{
						self.loadTickets.call(self);
					}
				}else{
					self.$container.html(data);
					self.bindPreview.call(self);
				}
			}).fail(function () {
				
			});
		},
		bindPreview: function(){
			var self = this,
				index = this.opts.index;
		
			if (validate) 
			{
				var $form = pjQ.$('#pjEtsPreviewForm_'+ self.opts.id);
				$form.validate({
					onkeyup: false,
					errorElement: 'li',
					submitHandler: function (form) {
						self.disableButtons.call(self);
						var $form = pjQ.$(form);
						var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveBooking", "&id=", self.opts.id].join("");
						if(self.opts.session_id != "")
						{
							ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveBooking", "&session_id=", self.opts.session_id, "&id=", self.opts.id].join("");
						}
						pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
							if (data.code == "200") {
								hashBang("#!/loadComplete/" + data.booking_uuid);
							} else if (data.code == "119") {
								self.enableButtons.call(self);
							}else{
								var $summaryMsg = pjQ.$('#pjEtsSummaryMsg_' + self.opts.id);
								var text = data.text;
								var data_load = 'loadTickets';
								if(data.code == '101')
								{
									data_load = 'loadSeats';
								}
								text = text.replace("{STAG}", '<a href="#" class="pjEtsMenuItem" data-load="'+data_load+'">');
								text = text.replace("{ETAG}", '</a>');
								$summaryMsg.html(text).parent().show();
							}
						}).fail(function () {
							self.enableButtons.call(self);
						});
						return false;
					}
				});
			}
		},
		loadComplete: function () {
			var self = this;
			var params = {"locale": this.opts.locale, "id": this.opts.id, "booking_uuid": this.booking_uuid};
			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionComplete"].join(""), params).done(function (data) {
				self.$container.html(data);
				
				var $paypal = self.$container.find("form[name='etsPaypal']"),
					$authorize = self.$container.find("form[name='etsAuthorize']");
				
				if ($paypal.length > 0) {
					window.setTimeout(function () {
						$paypal.trigger('submit');
					}, 3000);
				} else if ($authorize.length > 0) {
					window.setTimeout(function () {
						$authorize.trigger('submit');
					}, 3000);
				}
			});
			
			return this;
		}
	};
	
	window.EventTicketing = EventTicketing;	
})(window);