var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateTemplate = $("#frmCreateTemplate"),
			$frmUpdateTemplate = $("#frmUpdateTemplate"),
			datagrid = ($.fn.datagrid !== undefined);
		
		if ($frmCreateTemplate.length > 0) {
			$frmCreateTemplate.validate({
				rules: {
					"title": {
						remote: "index.php?controller=pjAdminTemplates&action=pjActionCheckTitle"
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateTemplate.length > 0) {
			$frmUpdateTemplate.validate({
				rules: {
					"title": {
						remote: "index.php?controller=pjAdminTemplates&action=pjActionCheckTitle&id=" + $frmUpdateTemplate.find("input[name='id']").val()
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		
		if($frmCreateTemplate.length > 0 || $frmUpdateTemplate.length > 0)
		{
			tinymce.init({
				relative_urls : false,
				remove_script_host : false,
			    selector: "textarea.mceEditor",
			    theme: "modern",
			    width: 560,
			    height: 350,
			    plugins: [
			         "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
			         "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
			         "save table contextmenu directionality emoticons template paste textcolor fileuploader"
			    ],
			    toolbar: "insertfile undo redo | styleselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image fileuploader | print preview media fullpage | forecolor backcolor emoticons",
			    setup: function (editor) {
			        editor.on('change', function () {
			            tinymce.triggerSave();
			        });
			    },
			    external_fileuploader_path: myLabel.fileuploader_url,
			    fileuploader_title: "File uploader",
			    external_plugins: {
			    	"fileuploader": "../fileuploader/" + myLabel.fileuploader_version + "/plugin.min.js"
			    }
			});
		}
		function formatDocuments (str, obj) {
			if (parseInt(str, 10) > 0) {
				return '<a href="index.php?controller=pjAdminDocuments&action=pjActionIndex&template_id='+obj.id+'">'+str+'</a>';
			} else {
				return str;
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminTemplates&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminTemplates&action=pjActionDeleteTemplate&id={:id}"}
				          ],
				columns: [{text: myLabel.title, type: "text", sortable: true, editable: false, width: 320},
				          {text: myLabel.generated_documents, type: "text", sortable: true, editable: false, align: 'center', width: 160, renderer: formatDocuments},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 120, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminTemplates&action=pjActionGetTemplate",
				dataType: "json",
				fields: ['title', 'documents', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminTemplates&action=pjActionDeleteTemplateBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminTemplates&action=pjActionSaveTemplate&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=pjAdminTemplates&action=pjActionGetTemplate", "id", "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=pjAdminTemplates&action=pjActionGetTemplate", "id", "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=pjAdminTemplates&action=pjActionGetTemplate", "id", "ASC", content.page, content.rowCount);
			return false;
		});
	});
})(jQuery_1_8_2);