var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateDocument = $("#frmCreateDocument"),
			$frmUpdateDocument = $("#frmUpdateDocument"),
			$frmSendDocument = $('#frmSendDocument'),
			$dialogView = $("#dialogView"),
			$dialogRestore = $("#dialogRestore"),
			$dialogSend = $("#dialogSend"),
			chosen = ($.fn.chosen !== undefined),
			dialog = ($.fn.dialog !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (chosen) {
			$('.pj-chosen').chosen();
		}
		if ($frmCreateDocument.length > 0) {
			$frmCreateDocument.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateDocument.length > 0) {
			$frmUpdateDocument.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		
			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 formatCustomer (str, obj) {
			if(pjGrid.isAdmin == true && obj.customer_id)
			{
				return '<a href="index.php?controller=pjAdminCustomers&action=pjActionUpdate&id='+obj.customer_id+'">'+str+'</a>';
			}else{
				return str;
			}
		}
		function formatTemplate (str, obj) {
			if(pjGrid.isAdmin == true && obj.template_id)
			{
				return '<a href="index.php?controller=pjAdminTemplates&action=pjActionUpdate&id='+obj.template_id+'">'+str+'</a>';
			}else{
				return str;
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [
				          	{type: "edit", url: "index.php?controller=pjAdminDocuments&action=pjActionUpdate&id={:id}"},
				          	{type: "delete", url: "index.php?controller=pjAdminDocuments&action=pjActionDeleteDocument&id={:id}"},
				          	{type: "view", url: "index.php?controller=pjAdminDocuments&action=pjActionPreview&id={:id}&hash={:hash}", target: '_blank'},
				          	{type: "download", url: "file.php?id={:id}&hash={:hash}"}
				         ],
				columns: [	
				          	{text: myLabel.customer, type: "text", sortable: false, editable: false, width: 125, renderer: formatCustomer},
				          	{text: myLabel.template, type: "text", sortable: false, editable: false, width: 150, renderer: formatTemplate},
				          	{text: myLabel.title, type: "text", sortable: true, editable: false, width: 150},
				          	{text: myLabel.created, type: "text", sortable: true, editable: false, width: 120}
				         ],
				dataUrl: "index.php?controller=pjAdminDocuments&action=pjActionGetDocument" + pjGrid.queryString,
				dataType: "json",
				fields: ['name', 'template', 'title', 'created'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminDocuments&action=pjActionDeleteDocumentBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminDocuments&action=pjActionSaveDocument&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		if ($("#history_grid").length > 0 && datagrid) {
			
			var gridOpts = {
				buttons: [{type: "view", url: "index.php?controller=pjAdminDocuments&action=pjActionView&id={:id}&document_id={:document_id}", title: myLabel.view},
				          {type: "edit", url: "index.php?controller=pjAdminDocuments&action=pjActionUpdate&id={:document_id}", title: myLabel.edit},
				          {type: "delete", url: "index.php?controller=pjAdminDocuments&action=pjActionDeleteHistory&id={:id}", title: myLabel.delete}
				         ],
				columns: [{text: myLabel.customer, type: "text", sortable: false, editable: false, width: 100},
				          {text: myLabel.document, type: "text", sortable: true, editable: false, width: 130},
				          {text: myLabel.datetime, type: "text", sortable: true, editable: false, width: 130},
				          {text: myLabel.user, type: "text", sortable: true, editable: false, width: 100},
				          {text: myLabel.ip, type: "text", sortable: true, editable: false, width: 90}],
				dataUrl: "index.php?controller=pjAdminDocuments&action=pjActionGetHistory" + pjGrid.queryString,
				dataType: "json",
				fields: ['name', 'title', 'modified', 'user_name','ip'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminDocuments&action=pjActionDeleteHistoryBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminDocuments&action=pjActionSaveHistory&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			};
			if(pjGrid.queryString != "")
			{
				gridOpts.buttons = [
				                    {type: "view", url: "index.php?controller=pjAdminDocuments&action=pjActionView&id={:id}&document_id={:document_id}", title: myLabel.view},
				                    {type: "edit", url: "index.php?controller=pjAdminDocuments&action=pjActionUpdate&id={:document_id}", title: myLabel.edit},
							        {type: "delete", url: "index.php?controller=pjAdminDocuments&action=pjActionDeleteHistory&id={:id}", title: myLabel.delete}
		        ];
				gridOpts.columns = [
				          {text: myLabel.customer, type: "text", sortable: false, editable: false, width: 200},
				          {text: myLabel.datetime, type: "text", sortable: true, editable: false, width: 150},
				          {text: myLabel.user, type: "text", sortable: true, editable: false, width: 120},
				          {text: myLabel.ip, type: "text", sortable: true, editable: false, width: 100}
				];
				gridOpts.fields = ['name', 'modified', 'user_name', 'ip'];
			}
			var $history_grid = $("#history_grid").datagrid(gridOpts);
		}
		
		function generateContent()
		{
			var template_id = $("select[name='template_id']").val(),
				customer_id = $("select[name='customer_id']").val();
			
			if(template_id != '' && customer_id != '')
			{
				$('.pj-loader').show();
				$.get("index.php?controller=pjAdminDocuments&action=pjActionGenerateContent&template_id=" + template_id + "&customer_id=" + customer_id).done(function (data) {
					$('#pjDmContent').html(data).parent().show();
					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"
					    }
					 });
					$('.pj-loader').hide();
				});
			}else{
				$('#pjDmContent').parent().hide();
			}
		}
		
		$(document).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=pjAdminDocuments&action=pjActionGetDocument", "id", "ASC", content.page, content.rowCount);
			return false;
		}).on("change", "#template_id", function (e) {
			generateContent.call(null);
			$(this).valid();
		}).on("change", "#customer_id", function (e) {
			generateContent.call(null);
			$(this).valid();
		}).on("click", ".pjDmSendDoc", function (e) {
			$dialogSend.dialog("open");
		});
		
		$('#history_grid').on("click", '.pj-table-icon-view', function(e){
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var i = 0;
			$(this).parent().siblings().each(function(e){
				if(i == 0)
				{
					$dialogView.data('id', $(this).find("input.pj-table-select-row").val());
				}
				if(i == 1)
				{
					$dialogView.data('datetime', $(this).find(">:first-child").html());
				}
				i++;
			});
			$dialogView.data('href', $(this).attr('href')).dialog("open");
			return false;
		});
		
		if ($dialogView.length > 0 && dialog) 
		{
			$dialogView.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 650,
				height: 450,
				open: function (event, ui) {
					$.get($dialogView.data('href')).done(function (data) {
						var title = $dialogView.attr('data-title');
						title = title.replace("{DATETIME}", $dialogView.data('datetime'));
						$dialogView.dialog('option', 'title', title);
						$dialogView.html(data);
					});
				},
				buttons: (function () {
					var buttons = {};
					buttons[dmApp.locale.button.restore] = function () {
						var restore_href = $dialogView.data('href');
						restore_href = restore_href.replace('pjActionView', 'pjActionRestore');
						$dialogRestore.data('href', restore_href).dialog("open");
					};
					buttons[dmApp.locale.button.close] = function () {
						$dialogView.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		if ($dialogRestore.length > 0 && dialog) 
		{
			$dialogRestore.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 450,
				height: 150,
				open: function () {
					
				},
				buttons: (function () {
					var buttons = {};
					buttons[dmApp.locale.button.yes] = function () {
						$.get($dialogRestore.data('href')).done(function (data) {
							$dialogRestore.dialog("close");
						});
					};
					buttons[dmApp.locale.button.no] = function () {
						$dialogRestore.dialog("close");
					};
					return buttons;
				})()
			});
		}
		
		if ($dialogSend.length > 0 && dialog) 
		{
			tinymce.init({
				relative_urls : false,
				remove_script_host : false,
			    selector: "textarea.mceMessage",
			    theme: "modern",
			    width: 510,
			    height: 200,
			    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"
			    }
			});
			
			$dialogSend.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 550,
				open: function () {
					
				},
				buttons: (function () {
					var buttons = {};
					buttons[dmApp.locale.button.send] = function () {
						$.post("index.php?controller=pjAdminDocuments&action=pjActionSend", $frmSendDocument.serialize()).done(function (data) {
							$dialogSend.dialog("close");
						});
					};
					buttons[dmApp.locale.button.cancel] = function () {
						$dialogSend.dialog("close");
					};
					return buttons;
				})()
			});
		}
	});
})(jQuery_1_8_2);