var jQuery_1_8_2 = $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateTicket = $("#frmCreateTicket"),
			$frmUpdateTicket = $("#frmUpdateTicket"),
			$frmPostReply = $('#frmPostReply'),
			chosen = ($.fn.chosen !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		function clientType(type){
			if(type == 'new')
			{
				$('#new_container').css('display', 'block');
				$('#name').addClass('required');
				$('#email').addClass('required email');
				$('#existing_container').css('display', 'none');
				$('#client_id').removeClass('required');
				$('#client_id').val('');$('#client_id').trigger("liszt:updated");
			}else if(type == 'existing'){
				$('#existing_container').css('display', 'block');
				$('#client_id').addClass('required');
				$('#new_container').css('display', 'none');
				$('#name').removeClass('required');
				$('#name').val('');
				$('#email').removeClass('required email');
				$('#email').val('');
			}else{
				$('#new_container').css('display', 'none');
				$('#name').removeClass('required');
				$('#name').val('');
				$('#email').removeClass('required email');
				$('#email').val('');
				$('#existing_container').css('display', 'none');
				$('#client_id').removeClass('required');
				$('#client_id').val('');$('#client_id').trigger("liszt:updated");
			}
		}
		if ($frmCreateTicket.length > 0 && validate) {
			$frmCreateTicket.validate({
				rules: {
					"files[]": {
						extension: "'|" + myLabel.allowed_ext + "|'"
					}
				},
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"name": {
						required: myLabel.field_required
					},
					"department_id": {
						required: myLabel.field_required
					},
					"client_id": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
			if (chosen) {
				$("#client_id").chosen();
			}
			$frmCreateTicket.on('submit', function(e) {
				if($('#client_type').val() == 'existing')
				{
					if(!$('#client_id').valid()) {
				        e.preventDefault();
				    }
				}
			}); 
			$('#client_type').on("change", function(e){
				clientType($(this).val());
			});
		}
		if ($frmUpdateTicket.length > 0 && validate) {
			$frmUpdateTicket.validate({
				
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"name": {
						required: myLabel.field_required
					},
					"department_id": {
						required: myLabel.field_required
					},
					"client_id": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					}
					
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
			if (chosen) {
				$("#client_id").chosen();
			}
			$frmUpdateTicket.on('submit', function(e) {
				if($('#client_type').val() == 'existing')
				{
					if(!$('#client_id').valid()) {
				        e.preventDefault();
				    }
				}
			}); 
			$('#client_type').on("change", function(e){
				clientType($(this).val());
			});
			$('.ticket-status').on('click', function(e){
				e.preventDefault();
				var status = $(this).attr('data-value');
				var $this = $(this);
				$( ".ticket-status" ).each(function() {
					$(this).removeClass( "status-focus" );
				});
				$('#status').val(status);
				$this.addClass("status-focus");
			});
			$('#client_id').on("change", function(e){
				var client_id = $(this).val();
				$('.pj-table-icon-edit').attr('href', 'index.php?controller=pjAdminClients&amp;action=pjActionUpdate&amp;id=' + client_id);
			});
			$('.pj-table-icon-edit').on('click', function(e){
				if($('#client_id').val() == '')
				{
					e.preventDefault();
				}
			});
			
			$("#dialogCannedMessages").dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 650
				
			});
			$('.pj-canned-messages').on("click", function(e){
				e.preventDefault();
				$("#dialogCannedMessages").dialog('open');
			});
			$('.clickable_category').on('click', function(e){
				e.preventDefault();
				var $this = $(this);
				var category_id = $(this).attr('rev');
				$.ajax({
					type: "GET",
					url: "index.php?controller=pjAdminTickets&action=pjActionGetMessages&cat_id=" + category_id,
					success: function (res) {
						$this.parent().parent().siblings().removeClass('chosen-category')
						$this.parent().parent().addClass('chosen-category');
						
						$('#message_list').html(res);
						
						$('.chosen-message').on('click', function(e){
							e.preventDefault();
							var message = $(this).text();
							$('#reply_text').val(message);
							$("#dialogCannedMessages").dialog('close');
						});
						
					}
				});
			});
			
			$("#dialogEditReply").dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 550
				
			});
			$("#dialogDeleteReply").dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				height: 160,
				close: function(){
					$('#record_id').val('');
				},
				buttons: {
					'Delete': function() {
						var id = $('#record_id').val();
						$dialog = $(this);
						$.ajax({
							type: "GET",
							dataType: "json",
							url: "index.php?controller=pjAdminTickets&action=pjActionDeleteReply&id=" + id,
							success: function (res) {
								if(res.code == 200)
								{
									$('#reply_box_' + id).remove();
									$dialog.dialog('close');
								}
							}
						});
						$(this).dialog('close');			
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
				}
			});
			$('a.edit-reply').on('click', function(e){
				var id = $(this).attr('rev');
				var reply_text = $('#reply_text_' + id).text();
				$('#edit_reply_id').val(id);
				$('#edit_reply_text').val(reply_text);
				$("#dialogEditReply").dialog('open');
			});
			$('input.update-reply').on('click', function(e){
				var $frmUpdateReply = $('#frmUpdateReply');
				var id = $('#edit_reply_id').val();
				$.ajax({
					type: "POST",
					data: $frmUpdateReply.serialize(),
					url: "index.php?controller=pjAdminTickets&action=pjActionUpdateReply",
					success: function (res) {
						$('#reply_text_' + id).html(res);
						$("#dialogEditReply").dialog('close');
					}
				});
			});
			$('a.delete-reply').on('click', function(e){
				var id = $(this).attr('rev');
				$('#record_id').val(id);
				$("#dialogDeleteReply").dialog('open');
			});
		}
		if ($frmPostReply.length > 0 && validate) {
			$frmPostReply.validate({
				rules: {
					"files[]": {extension: "'|" + myLabel.allowed_ext + "|'"}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
			$('.post-reply').on("click", function(e){
				if($frmPostReply.valid() == true)
				{
					$frmPostReply.submit();
				}
			});
		}
		
		
		if ($("#grid").length > 0 && datagrid) {
			var client_id = '';
			if(pjGrid.client_id !== undefined)
			{
				client_id = '&client_id='+pjGrid.client_id;
			}
			
			function formatDefault (str, obj) {
				if (obj.role_id == 3) {
					return '<a href="#" class="pj-status-icon pj-status-' + (str == 'F' ? '0' : '1') + '" style="cursor: ' +  (str == 'F' ? 'pointer' : 'default') + '"></a>';
				} else {
					return '<a href="#" class="pj-status-icon pj-status-1" style="cursor: default"></a>';
				}
			}
			function formatRole (str) {
				return ['<span class="label-status user-role-', str, '">', str, '</span>'].join("");
			}
			
			function onBeforeShow (obj) {
				if (parseInt(obj.id, 10) === pjGrid.currentTicketId) {
					return false;
				}
				return true;
			}
			function showClient(str, obj){
				return '<a href="index.php?controller=pjAdminClients&action=pjActionUpdate&id=' + obj.client_id + '">' + str + '</a>';
			}
			function showTicket(str, obj){
				return '<a href="index.php?controller=pjAdminTickets&action=pjActionUpdate&id=' + obj.id + '">' + str + '</a>';
			}
			function showDepartment(str, obj){
				if(obj.assigned_to != null)
				{
					if(str != null){
						return str + "<br/>" + obj.assigned_to;
					}else{
						return "--<br/>" + obj.assigned_to;
					}
				}else{
					return str;
				}
			}
			var opt_columns = [{text: myLabel.ticketid, type: "text", sortable: true, editable: false, renderer: showTicket},
						          {text: myLabel.client, type: "text", sortable: true, editable: false, renderer: showClient},
						          {text: myLabel.department, type: "text", sortable: true, editable: false, renderer: showDepartment},
						          {text: myLabel.lastreply, type: "date", sortable: true, editable: false},
						          {text: myLabel.status, type: "select", sortable: false, width: 102, editable: true, options: [
						                                                                                     {label: myLabel.New, value: "New"}, 
						                                                                                     {label: myLabel.RepliedByClient, value: "RepliedByClient"},
						                                                                                     {label: myLabel.RepliedBySupport, value: "RepliedBySupport"},
						                                                                                     {label: myLabel.InProgress, value: "InProgress"},
						                                                                                     {label: myLabel.Closed, value: "Closed"}
						                                                                                     ], applyClass: "pj-ticket-status"}];
			var opt_fields = ['ticket_id', 'client', 'department', 'last_reply', 'status'];
			if(myLabel.departments == 0)
			{
				opt_columns = [{text: myLabel.ticketid, type: "text", sortable: true, editable: false, renderer: showTicket},
						          {text: myLabel.client, type: "text", sortable: true, editable: false, renderer: showClient},
						          {text: myLabel.lastreply, type: "date", sortable: true, editable: false},
						          {text: myLabel.status, type: "select", sortable: false, width: 102, editable: true, options: [
						                                                                                     {label: myLabel.New, value: "New"}, 
						                                                                                     {label: myLabel.RepliedByClient, value: "RepliedByClient"},
						                                                                                     {label: myLabel.RepliedBySupport, value: "RepliedBySupport"},
						                                                                                     {label: myLabel.InProgress, value: "InProgress"},
						                                                                                     {label: myLabel.Closed, value: "Closed"}
						                                                                                     ], applyClass: "pj-ticket-status"}];
				
				 opt_fields = ['ticket_id', 'client', 'last_reply', 'status'];
			}
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminTickets&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminTickets&action=pjActionDeleteTicket&id={:id}", beforeShow: onBeforeShow}
				          ],
				columns: opt_columns,
				dataUrl: "index.php?controller=pjAdminTickets&action=pjActionGetTicket" + pjGrid.queryString,
				dataType: "json",
				fields: opt_fields,
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminTickets&action=pjActionDeleteTicketBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminTickets&action=pjActionExportTicket", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminTickets&action=pjActionSaveTicket&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: "",
				ticket_id: "",
				department_id: "",
				client_name: "",
				client_email: "",
				adv_status: "",
				received_after: "",
				received_after: "",
				message: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminTickets&action=pjActionGetTicket" + client_id, "t1.created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", "#filter_by_status", function (e) {
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache"),
				obj = {};
			obj.status = "";
			obj['status'] = $this.val();
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminTickets&action=pjActionGetTicket" + client_id, "t1.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=pjAdminTickets&action=pjActionGetTicket" + client_id, "t1.created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			$(".pj-button-detailed").trigger("click");

		}).on("click", ".pj-status-1", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			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(),
				ticket_id: "",
				department_id: "",
				client_name: "",
				client_email: "",
				adv_status: "",
				received_after: "",
				received_after: "",
				message: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminTickets&action=pjActionGetTicket" + client_id, "t1.created", "DESC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datepick", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev"),
				onClose: function (selectedDate) {
					var name = $this.attr("name");
					if (name == "date_from[]") {
						$this.closest("tr").find(".datepick[name='date_to[]']").datepicker("option", "minDate", selectedDate);
					} else if (name == "date_to[]") {
						$this.closest("tr").find(".datepick[name='date_from[]']").datepicker("option", "maxDate", selectedDate);
					}
				}
			});
		});
	});
})(jQuery_1_8_2);