var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateEvent = $("#frmCreateEvent"),
			$frmUpdateEvent = $("#frmUpdateEvent"),
			$dialogDeleteSingle = $("#dialogDeleteSingle"),
			$dialogDeleteRecurring = $("#dialogDeleteRecurring"),
			dialog = ($.fn.dialog !== undefined),
			validate = ($.fn.validate !== undefined),
			spinner = ($.fn.spinner !== undefined),
			$tabs = $("#tabs"),
			$sub_tabs = $("#sub_tabs"),
			tipsy = ($.fn.tipsy !== undefined),			
			datagrid = ($.fn.datagrid !== undefined),
			remove_arr = new Array(),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val(ui.newPanel.attr('id'));
				}
			},
			sub_tOpt = {
					activate: function (event, ui) {
						$(":input[name='sub_tab_id']").val(ui.newPanel.attr('id'));
					}
			};
		
		if ($tabs.length > 0 && tabs) {
			var $t = $(":input[name='tab_id']");
			$tabs.tabs({
				activate: function(event, ui) {
					if ($t.length > 0) {
						$t.val(ui.newPanel.attr('id'));
						var newIndex = ui.newTab.parent().children().index(ui.newTab);
						if(newIndex > 3)
						{
							$('#button_container').css('display', 'none');
						}else{
							$('#button_container').css('display', 'block');
						}
					}
				}
			});
			var $sub_tab = $(":input[name='sub_tab_id']");
			$sub_tabs.tabs({
				activate: function(event, ui) {
					if ($sub_tab.length > 0) {
						$sub_tab.val(ui.newPanel.attr('id'));
						var newIndex = ui.newTab.parent().children().index(ui.newTab);
					}
				}
			});
		}
		if (tipsy) {
			$(".listing-tip").tipsy({
				offset: 1,
				opacity: 1,
				html: true,
				gravity: "nw",
				className: "tipsy-listing"
			});
		}
		function setPrices()
		{
			var index_arr = new Array();
				
			$('#price_container').find(".price-box").each(function (index, row) {
				index_arr.push($(row).attr('data-index'));
			});
			$('#index_arr').val(index_arr.join("|"));
		}
		if ($frmCreateEvent.length > 0 && validate) {
			$frmCreateEvent.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					$(".pj-multilang-wrap").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).css('display','block');
						}else{
							$(this).css('display','none');
						}
					});
					$(".pj-form-langbar-item").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).addClass('pj-form-langbar-item-active');
						}else{
							$(this).removeClass('pj-form-langbar-item-active');
						}
					});
				},
				submitHandler: function(form){
					var valid = true,
						localeId = null;
					
					setPrices();
					$("#frmCreateEvent .pj-positive-number").each(function() {
						if($(this).val() == '')
						{
							valid = false;
							$(this).addClass('pj-error-field');
						}else{
							if(Number($(this).val()) < 0 || $.isNumeric($(this).val()) == false)
						    {
						    	valid = false;
						    	$(this).addClass('pj-error-field');
						    }else{
						    	valid = true;
						    	$(this).removeClass('pj-error-field');
						    }
						}
					});
					$("#frmCreateEvent .ebcRequired").each(function() {
						if($(this).val() == '')
						{
							valid = false;
					    	$(this).addClass('pj-error-field');
					    	if(localeId == null)
					    	{
					    		localeId = $(this).attr('lang');
					    	}
						}else{
							$(this).removeClass('pj-error-field');
						}
					});
					if(localeId != null)
					{
						$(".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(valid == true)
					{
						form.submit();
					}
					
				}
			});
		}
		function setInstall()
		{
			var step_1 = $('#install_step_clone').text();
			var hide = $("input[name='install_hide']").is(":checked") ? "&hide=1" : "";
			step_1 = step_1.replace('{HIDE}', hide);
			$('#install_step_1').val(step_1);
		}
		if ($frmUpdateEvent.length > 0 && validate) {
			$frmUpdateEvent.validate({
				
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					$(".pj-multilang-wrap").each(function( index ) {
						if($(this).attr('data-index') == myLabel.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');
						}
					});
				},
				submitHandler: function(form){
					var valid = true,
						localeId = null;
					
					setPrices();
					$("#frmUpdateEvet .pj-positive-number").each(function() {
						if($(this).val() == '')
						{
							valid = false;
							$(this).addClass('pj-error-field');
						}else{
							if(Number($(this).val()) < 0 || $.isNumeric($(this).val()) == false)
						    {
						    	valid = false;
						    	$(this).addClass('pj-error-field');
						    }else{
						    	valid = true;
						    	$(this).removeClass('pj-error-field');
						    }
						}
					});
					$("#frmCreateEvent .ebcRequired").each(function() {
						if($(this).val() == '')
						{
							valid = false;
					    	$(this).addClass('pj-error-field');
					    	if(localeId == null)
					    	{
					    		localeId = $(this).attr('lang');
					    	}
						}else{
							$(this).removeClass('pj-error-field');
						}
					});
					if(localeId != null)
					{
						$(".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(valid == true)
					{
						form.submit();
					}
				}
			});
			tinymce.init({
			    selector: "textarea.mceEditor",
			    theme: "modern",
			    width: 530,
			    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"
			 });
			
			setInstall();
			
			$frmUpdateEvent.on("change", "input[name='install_hide']", function (e) {
				setInstall();
			});
		}
		if (spinner) {
			$(".field-int").spinner({
				min: 0
			});
		}
		
		$('#repeat-monthly-date').on('change', function(e){
			if($(this).val() == 0)
			{
				$('#repeat-monthly-each').removeAttr('disabled');
				$('#repeat-monthly-day').removeAttr('disabled');
			}else{
				$('#repeat-monthly-each').attr('disabled', 'disabled');
				$('#repeat-monthly-day').attr('disabled', 'disabled');
			}
		});
		
		$('#repeat').on('change', function(e){
			$('p[id^="repeat_"]').css('display','none');
			$('div[id^="repeat_"]').css('display','none');
			$('#repeat_' + $(this).val()).css('display','block');
			if($(this).val() == 'none')
			{
				$('#repeat_box').css('display','none');
				$('#hidden_recurring_on').removeClass('required');
			}else{
				$('#repeat_box').css('display','block');
				if($('#end_repeat_date').val() == '' && $('#end_repeat_times').val() == '')
				{
					$('#hidden_recurring_on').addClass('required');
				}
			}
			if($(this).val() == 'custom')
			{
				$('#repeat-custom-days').addClass('required');
			}else{
				$('#repeat-custom-days').removeClass('required');
			}
		});
		
		$('.delete-image').on('click', function(e){
			e.preventDefault();
			if($frmCreateEvent.length > 0)
			{
				$("#image_container").remove();
				$("#copy_image").val(0);
			}else{
				var event_id = $(this).attr('rev');
				var is_recurring = $(this).attr('data-recurring');
				$('.pjEbcDeleteImage').hide();
				if(is_recurring == 'no')
				{
					$('#pjEbcDeleteSingle').show();
					var btnOpts = {
						'Delete': function() {
							$.ajax({
								type: "POST",
								data: {
									id: event_id
								},
								dataType: 'json',
								url: "index.php?controller=pjAdminEvents&action=pjActionDeleteImage",
								success: function (res) {
									if(res.status == 1){
										$("#image_container").remove();
										$("#dialogDeleteImage").dialog('close');
									}
								}
							});
						},
						'Cancel': function() {
							$("#dialogDeleteImage").dialog('close');
						}
					}
				}else{
					$('#pjEbcDeleteAll').show();
					var btnOpts = {
						'Delete one': function() {
							$.ajax({
								type: "POST",
								data: {
									id: event_id
								},
								dataType: 'json',
								url: "index.php?controller=pjAdminEvents&action=pjActionDeleteImage",
								success: function (res) {
									if(res.status == 1){
										$("#image_container").remove();
										$("#dialogDeleteImage").dialog('close');
									}
								}
							});
						},
						'Delete all': function() {
							$.ajax({
								type: "POST",
								data: {
									id: event_id
								},
								dataType: 'json',
								url: "index.php?controller=pjAdminEvents&action=pjActionDeleteAllImages",
								success: function (res) {
									if(res.status == 1){
										$("#image_container").remove();
										$("#dialogDeleteImage").dialog('close');
									}
								}
							});
						},
						'Cancel': function() {
							$("#dialogDeleteImage").dialog('close');
						}
					}
				}
				$("#dialogDeleteImage").dialog({
					autoOpen: false,
					resizable: false,
					draggable: false,
					width: 380,
					height:150,
					modal: true,
					buttons: btnOpts
				});
				$("#dialogDeleteImage").dialog('open');
			}
		});
		
		if ($("#grid").length > 0 && datagrid) {
			function showBookings (str, obj) {
				if(obj.linked == '1')
				{
					return '<a href="index.php?controller=pjAdminBookings&action=pjActionIndex&event_id='+obj.id+'">'+str+'</a>';
				}else{
					return str;
				}
			}
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminEvents&action=pjActionUpdate&id={:id}"},
				          {type: "remove", url: "index.php?controller=pjAdminEvents&action=pjActionDeleteEvent&id={:id}"},
				          {type: "menu", url: "#", text: myLabel.more, items:[
				              {text: myLabel.copy, url: "index.php?controller=pjAdminEvents&action=pjActionCreate&id={:id}", ajax: false, render: true},
				              {text: myLabel.tickets, url: "index.php?controller=pjAdminEvents&action=pjActionUpdate&id={:id}&tab_id=tabs-6", ajax: false, render: true}
				           ]}
				          ],
				columns: [{text: myLabel.eventdate, type: "text", sortable: true, editable: false, width:220},
				          {text: myLabel.eventtitle, type: "text", sortable: true, editable: true, width: 200},
				          {text: myLabel.tickets, type: "text", sortable: true, editable: false, width:75, align: 'center', renderer: showBookings},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width:80 ,options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminEvents&action=pjActionGetEvent",
				dataType: "json",
				fields: ['event_date', 'title', 'tickets', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEvents&action=pjActionDeleteEventBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.revert_status, url: "index.php?controller=pjAdminEvents&action=pjActionStatusEvent", render: true},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminEvents&action=pjActionExportEvent", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEvents&action=pjActionSaveEvent&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
			
		$(document).on("focusin", ".textarea_install", function (e) {
			$(this).select();
		}).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("click", ".pj-status-1", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("click", ".pj-status-0", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$.post("index.php?controller=pjAdminEvents&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent");
			});
			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(),
				page: 1
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent", "title", "ASC", 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,
					onClose:function(dateTimeText){
						if($this.attr("name") == 'event_start_ts')
						{
							$(".datetimepick[name='event_end_ts']").val(dateTimeText);
						}
					}
			};
			switch ($this.attr("name")) {
			case "event_start_ts":
				if($(".datetimepick[name='event_end_ts']").val() != '')
				{
					$(".datetimepick[name='event_end_ts']").datepicker("destroy").removeAttr("id");
				}
				break;
			case "event_end_ts":
				if($(".datetimepick[name='event_start_ts']").val() != '')
				{
					minDateTime = $(".datetimepick[name='event_start_ts']").datetimepicker({
						firstDay: $this.attr("rel"),
						dateFormat: $this.attr("rev"),
						timeFormat: $this.attr("lang")
					}).datetimepicker("getDate");
					$(".datetimepick[name='event_start_ts']").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.not('.hasDatepicker').datepicker({
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev"),
					onClose:function(dateText){
						if($this.attr("name") == 'end_repeat_date')
						{
							if($('#end_repeat_date').val() != '' || $('#end_repeat_times').val() != '')
							{
								$('#hidden_recurring_on').removeClass('required').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 {
				$dp.trigger("focusin").datepicker("show");
			}
		}).on("click", "#ebc_add_price", function (e) {
			
			var len = $("#price_container > .price-box").length;
			var i = len + 1;
			var price_box_content = $('#clone_container').html();
			var index = Math.ceil(Math.random() * 999999);
			price_box_content = price_box_content.replace('{fieldint}', 'field-int');
			if (len === 1) {
				$("#price_container").append(price_box_content.replace(/{index}/g, 'ebc_' + index));
			} else {
				$("#price_container > .price-box:last").after(price_box_content.replace(/{index}/g, 'ebc_' + index));
			}
			if (spinner) {
				$(".field-int").spinner({
					min: 0
				});
			}
			
		}).on("click", ".btn-remove-price", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}

			var $price = $(this).parent().parent(),
				id = $price.attr('data-index');
			if(id.indexOf("ebc") == -1)
			{
				remove_arr.push(id);
			}
			$('#remove_arr').val(remove_arr.join("|"));
			$price.remove();
			
		}).on("keyup", '.pj-positive-number', function(e){
			if($(this).val() == '')
			{
				$(this).removeClass('pj-error-field');
			}else{
				if(Number($(this).val()) < 0 || $.isNumeric($(this).val()) == false)
			    {
			    	$(this).addClass('pj-error-field');
			    }else{
			    	$(this).removeClass('pj-error-field');
			    }
			}
			
		}).on("keyup", '.ebcRequired', function(e){
			if($(this).val() == '')
			{
				$(this).addClass('pj-error-field');
			}else{
				$(this).removeClass('pj-error-field');
			}
		}).on("click", ".pj-table-icon-remove", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tr = $(this).closest('tr');
			var id = ($tr.data('id')).replace("id_", "");
			
			$.get("index.php?controller=pjAdminEvents&action=pjActionCheckRecurring", {
				"id": id
			}).done(function (data) {
				if(data == 'true')
				{
					$dialogDeleteRecurring.data('id', id).dialog('open');
				}else{
					$dialogDeleteSingle.data('id', id).dialog('open');
				}
			});
		}).on("keydown", "#end_repeat_times", 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) {
				console.log('number');
            } else {
            	e.preventDefault();
            } 
		}).on("keyup", "#end_repeat_times", 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) {
				if($('#end_repeat_date').val() != '' || $('#end_repeat_times').val() != '')
				{
					$('#hidden_recurring_on').removeClass('required').valid();
				}
            } else {
            	e.preventDefault();
            } 
			return false;
		});
		
		if ($dialogDeleteSingle.length > 0 && dialog) 
		{
			$dialogDeleteSingle.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				
				buttons: (function () {
					var buttons = {};
					buttons[ebcApp.locale.button.delete] = function () {
						$.get("index.php?controller=pjAdminEvents&action=pjActionDeleteEvent", {
							"id": $dialogDeleteSingle.data('id')
						}).done(function (data) {
							if(data.code == '200')
							{
								$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent");
								$dialogDeleteSingle.dialog("close");
							}
						});
					};
					buttons[ebcApp.locale.button.cancel] = function () {
						$dialogDeleteSingle.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		if ($dialogDeleteRecurring.length > 0 && dialog) 
		{
			$dialogDeleteRecurring.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 450,
				buttons: (function () {
					var buttons = {};
					buttons[ebcApp.locale.button.delete_all] = function () {
						$.get("index.php?controller=pjAdminEvents&action=pjActionDeleteRecurring", {
							"id": $dialogDeleteRecurring.data('id')
						}).done(function (data) {
							$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent");
							$dialogDeleteRecurring.dialog("close");
						});
					};
					buttons[ebcApp.locale.button.delete_this] = function () {
						$.get("index.php?controller=pjAdminEvents&action=pjActionDeleteEvent", {
							"id": $dialogDeleteRecurring.data('id')
						}).done(function (data) {
							if(data.code == '200')
							{
								$grid.datagrid("load", "index.php?controller=pjAdminEvents&action=pjActionGetEvent");
								$dialogDeleteRecurring.dialog("close");
							}
						});
					};
					buttons[ebcApp.locale.button.cancel] = function () {
						$dialogDeleteRecurring.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
	});
})(jQuery_1_8_2);