var jQuery_1_8_2 = $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateClient = $("#frmCreateClient"),
			$frmUpdateClient = $("#frmUpdateClient"),
			$dialogMessage = $("#dialogMessage"),
			dialog = ($.fn.dialog !== undefined),
			validate = ($.fn.validate !== undefined),
			chosen = ($.fn.chosen !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if ($frmCreateClient.length > 0 && validate) {
			$frmCreateClient.validate({
				rules: {
					"email": {
						required: true,
						email: true,
						remote: "index.php?controller=pjAdminClients&action=pjActionCheckEmail"
					}
				},
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"name": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					},
					"client_since": {
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
			if (chosen) {
				$("#country_id").chosen();
			}
		}
		if ($frmUpdateClient.length > 0 && validate) {
			$frmUpdateClient.validate({
				rules: {
					"email": {
						required: true,
						email: true,
						remote: "index.php?controller=pjAdminClients&action=pjActionCheckEmail&id=" + $frmUpdateClient.find("input[name='id']").val()
					}
				},
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"name": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					},
					"client_since": {
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				submitHandler: function(form)
				{
					var show_dialog = false;
					if($frmUpdateClient.find('input[name="old_status"]').val() == 'F' && $frmUpdateClient.find('select[name="status"]').val() == 'T')
					{
						show_dialog = true;
					}
					if(show_dialog == true)
					{
						if (dialog && $dialogMessage.length > 0) 
						{
							$dialogMessage.data('form', form).dialog('option', 'position', 'top');
							$dialogMessage.dialog("open");
						}
					}else{
						form.submit();
					}
					return false;
				}
			});
			if (chosen) {
				$("#country_id").chosen();
			}
			
			if ($dialogMessage.length > 0 && dialog) {
				
				var buttons = {};
				buttons[myLabel.btn_send] = function() {
					var $this = $(this);
					var $frmMessage = $('#frmSendMessage');
					var dialogButtons = $('.ui-dialog-buttonpane button');
					dialogButtons.prop('disabled', true).addClass("ui-state-disabled");
					$.post("index.php?controller=pjAdminClients&action=pjActionSendMessage", $frmMessage.serialize()).done(function (data) {
						$dialogMessage.html("");
						if (tinymce.editors.length > 0) 
						{
					        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
					    }
						$this.dialog('close');
						dialogButtons.prop('disabled', false).removeClass("ui-state-disabled");
						$dialogMessage.data('form').submit();
					});
				};
				buttons[myLabel.btn_cancel] = function() {
					$dialogMessage.html("");
					if (tinymce.editors.length > 0) 
					{
				        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
				    }
					$(this).dialog('close');
					$dialogMessage.data('form').submit();
				};
				
				$dialogMessage.dialog({
					autoOpen: false,
					resizable: false,
					draggable: false,
					modal: true,
					width: 600,					
					buttons: buttons,
					close: function(event, ui){
						if (tinymce.editors.length > 0) 
						{
					        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
					    }
						$dialogMessage.data('form').submit();
					},
					open: function( event, ui ) {
						$dialogMessage.html("");
						$.get(["index.php?controller=pjAdminClients&action=pjActionGetContent"].join(""), {id: $frmUpdateClient.find("input[name='id']").val()}).done(function (data) {
							$dialogMessage.html(data);
							tinymce.init({
							    selector: "textarea#mceEditor",
							    plugins: [
							        "advlist autolink lists link image charmap print preview anchor",
							        "searchreplace visualblocks code fullscreen",
							        "insertdatetime media table contextmenu paste"
							    ],
							    width: 550,
							    height: 250,
							    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
							    setup: function (editor) {
							    	editor.on('change', function (e) {
							    		editor.editorManager.triggerSave();
							    	});
							    }
							});
							if (tinymce.editors.length > 0) 
							{							
								tinymce.execCommand('mceAddEditor',true, "mceEditor");
							}
						}).fail(function () {
							
						});
					},
				});
			}
		}
		
		if ($("#grid").length > 0 && datagrid) {
			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.currentClientId) {
					return false;
				}
				return true;
			}
			function numTickets(str, obj)
			{
				if(str == '0')
				{
					return 0;
				}else{
					return '<a href="index.php?controller=pjAdminTickets&action=pjActionIndex&client_id='+obj.id+'">'+str+'</a>';
				}
			}
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminClients&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminClients&action=pjActionDeleteClient&id={:id}", beforeShow: onBeforeShow}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: false, width: 130},
				          {text: myLabel.email, type: "text", sortable: true, editable: true, width: 180},
				          {text: myLabel.last_login, type: "date", sortable: true, editable: false, width: 130},
				          {text: myLabel.tickets, type: "text", sortable: false, editable: false, width: 60, align: 'center', renderer: numTickets},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminClients&action=pjActionGetClient",
				dataType: "json",
				fields: ['name', 'email', 'last_login', 'tickets', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminClients&action=pjActionDeleteClientBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.revert_status, url: "index.php?controller=pjAdminClients&action=pjActionStatusClient", render: true},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminClients&action=pjActionExportClient", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminClients&action=pjActionSaveClient&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=pjAdminClients&action=pjActionGetClient", "name", "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=pjAdminClients&action=pjActionGetClient", "name", "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=pjAdminClients&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminClients&action=pjActionGetClient");
			});
			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=pjAdminClients&action=pjActionGetClient", "id", "ASC", 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);
					}
				}
			});
		}).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");
			}
		});
	});
})(jQuery_1_8_2);