var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateUser = $("#frmCreateUser"),
			$frmUpdateUser = $("#frmUpdateUser"),
			datagrid = ($.fn.datagrid !== undefined);
		
		if ($frmCreateUser.length > 0) {

			jQuery.validator.addMethod("validateUrl", function(value, element, param) {
				if(value != '')
				{
					var expression = /^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i;
				    return expression.test(value);
				}else{
					return true;
				}
			}, jQuery.validator.messages.url);
			
			$frmCreateUser.validate({
				
				rules: {
					"email": {
						required: true,
						email: true,
						remote: "index.php?controller=pjAdminUsers&action=pjActionCheckEmail"
					},
		            "contact_url":{
		            	validateUrl: true
		            }
				},
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"role_id": {
						required: myLabel.field_required
					},
					"password": {
						required: myLabel.field_required
					},
					"name": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					},
					"contact_url":{
		            	validateUrl: true
		            }
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		if ($frmUpdateUser.length > 0) {
			
			jQuery.validator.addMethod("validateUrl", function(value, element, param) {
			    var expression = /^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i;
			    return expression.test(value);
			}, jQuery.validator.messages.url);
			
			$frmUpdateUser.validate({
				rules: {
					"email": {
						required: true,
						email: true,
						remote: "index.php?controller=pjAdminUsers&action=pjActionCheckEmail&id=" + $frmUpdateUser.find("input[name='id']").val()
					}
				},
				messages: {
					"email": {
						required: myLabel.field_required,
						email: myLabel.email_invalid,
						remote: myLabel.email_taken
					},
					"role_id": {
						required: myLabel.field_required
					},
					"password": {
						required: myLabel.field_required
					},
					"name": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			function formatName(str, obj) {
				return $.datagrid.wordwrap(str, 25, '<br>', true);
			}
			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.currentUserId) {
					return false;
				}
				return true;
			}
			var gridOpts = {
				buttons: [{type: "edit", url: "index.php?controller=pjAdminUsers&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				          {type: "delete", url: "index.php?controller=pjAdminUsers&action=pjActionDeleteUser&id={:id}", beforeShow: onBeforeShow, title: myLabel.lblDelete}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: true, renderer: formatName},
				          {text: myLabel.email, type: "text", sortable: true, editable: true},
				          {text: myLabel.created, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				          {text: myLabel.role, type: "text", sortable: true, renderer: formatRole},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminUsers&action=pjActionGetUser",
				dataType: "json",
				fields: ['name', 'email', 'created', 'role', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminUsers&action=pjActionDeleteUserBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.revert_status, url: "index.php?controller=pjAdminUsers&action=pjActionStatusUser", render: true},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminUsers&action=pjActionExportUser", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminUsers&action=pjActionSaveUser&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			};
			if (pjGrid.isEditor === true) {
				function onShowEdit (obj) {
					if (parseInt(obj.id, 10) === 1 || parseInt(obj.role_id, 10) === 2) {
						return false;
					}
					return true;
				}
				
				gridOpts.buttons = [{type: "edit", url: "index.php?controller=pjAdminUsers&action=pjActionUpdate&id={:id}", beforeShow: onShowEdit}];
				gridOpts.columns = [{text: myLabel.name, type: "text", sortable: true, editable: false, renderer: formatName},
				          {text: myLabel.email, type: "text", sortable: true, editable: false},
				          {text: myLabel.created, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				          {text: myLabel.role, type: "text", sortable: true, renderer: formatRole},
				          {text: myLabel.status, type: "select", sortable: true, editable: false, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}];
				gridOpts.paginator.actions = [ {text: myLabel.exported, url: "index.php?controller=pjAdminUsers&action=pjActionExportUser", ajax: false}];
			}
			var $grid = $("#grid").datagrid(gridOpts);
		}
		
		$(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=pjAdminUsers&action=pjActionGetUser", "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=pjAdminUsers&action=pjActionGetUser", "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=pjAdminUsers&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminUsers&action=pjActionGetUser");
			});
			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=pjAdminUsers&action=pjActionGetUser", "id", "ASC", content.page, content.rowCount);
			return false;
		}).on("change", "#role_id", function (e) {
			if($(this).val() == 3)
			{
				$('.user-contact').css('display', 'block');
			}else{
				$('.user-contact').css('display', 'none');
			}
		});
	});
})(jQuery_1_8_2);