var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateEnquiry = $("#frmCreateEnquiry"),
			$frmUpdateEnquiry = $("#frmUpdateEnquiry"),
			validate = ($.fn.validate !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			dialog = ($.fn.dialog !== undefined),
			chosen = ($.fn.chosen !== undefined);

		if ($frmCreateEnquiry.length > 0 && validate) {
			$frmCreateEnquiry.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore"
			});
		}
		if ($frmUpdateEnquiry.length > 0 && validate) {
			$frmUpdateEnquiry.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore"
			});
			
		}

		if ($frmCreateEnquiry.length > 0 || $frmUpdateEnquiry.length > 0) {
			var $date_from = $("#date_from");
			$date_from.datepicker({
				firstDay: $date_from.attr("rel"),
				dateFormat: $date_from.attr("rev"),
				onSelect: function (dateText, inst) {
					$("#date_to").datepicker("option", "minDate", dateText);
				}
			});
			
			var $date_to = $("#date_to");
			$date_to.datepicker({
				firstDay: $date_to.attr("rel"),
				dateFormat: $date_to.attr("rev"),
				minDate: new Date()
			});
		}
		
		if (chosen) {
			$("select[name='listing_id']").chosen();
		}
		
		var $frmFilter = $(".frm-filter");
		if ($frmFilter.length > 0) {
			$frmFilter.on("change", "select[name='listing_id']", function (e) {
				$frmFilter.submit();	
			});
		}

		function formatListing (val, obj) {
			return ['<a href="index.php?controller=pjAdminListings&action=pjActionUpdate&id=', obj.listing_id,'">', $.datagrid.wordwrap(val, 40, '<br>', true), '</a>'].join("");
		}
		function formatClient (val, obj) {
			return ['<span class="bold">', obj.name, '</span><br>', obj.phone].join("");
		}
		function formatDate(val, obj) {
			return [obj.date_from, '<br>', obj.date_to].join("");
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminEnquiries&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				          {type: "delete", url: "index.php?controller=pjAdminEnquiries&action=pjActionDeleteEnquiry&id={:id}", title: myLabel.lblDelete}
				          ],
				columns: [{text: myLabel.dt, type: "text", sortable: true, editable: false, width: 100, renderer: formatDate},
				          {text: myLabel.listing, type: "text", sortable: true, editable: false, renderer: formatListing, width: 140},
				          {text: myLabel.client, type: "text", sortable: true, editable: false, renderer: formatClient, width: 130},
				          {text: myLabel.date_submitted, type: "date", sortable: true, editable: false, jqDateFormat: pjGrid.jqDateFormat, renderer: $.datagrid._formatDate, width: 110, dateFormat: pjGrid.jsDateFormat},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 110, editableWidth: 105, options: [
				                                                                                     {label: myLabel.new_stat, value: "New"}, 
				                                                                                     {label: myLabel.confirmed_stat, value: "Confirmed"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry" + pjGrid.queryString,
				dataType: "json",
				fields: ['date_from', 'listing_title', 'name', 'created', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.export_selected, url: "index.php?controller=pjAdminEnquiries&action=pjActionExportEnquiry", ajax: false},
					   {text: myLabel.confirm_selected, url: "index.php?controller=pjAdminEnquiries&action=pjActionStatusEnquiry&status=Confirmed", render: true},
					   {text: myLabel.dismiss_selected, url: "index.php?controller=pjAdminEnquiries&action=pjActionStatusEnquiry&status=New", render: true},
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEnquiries&action=pjActionDeleteEnquiryBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEnquiries&action=pjActionSaveEnquiry&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
			
			$(document).on("click", ".btn-all", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
				var content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					status: ""
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", 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=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", 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=pjAdminEnquiries&action=pjActionGetEnquiry", "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=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", content.page, content.rowCount);
				return false;
			}).on("reset", ".frm-filter-advanced", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(".pj-button-detailed").trigger("click");
				if (chosen) {
					$("select[name='listing_id']").val('').trigger("liszt:updated");
				}
				$("input[name='q']").val('');
			});
			
		}
		
		$(document).on("click", ".pj-form-field-icon-date", function (e) {
			$(this).parent().siblings("input[type='text']").datepicker("show");
		}).on("click change", "#dialog_confirm", function (e) {
			if ($(this).is(":checked")) {
				$dialogMessage.find("textarea").prop("readonly", false).removeClass("pj-form-field-readonly")
					.end().find("input[type='text']").prop("readonly", false).removeClass("pj-form-field-readonly");
			} else {
				$dialogMessage.find("textarea").prop("readonly", true).addClass("pj-form-field-readonly")
					.end().find("input[type='text']").prop("readonly", true).addClass("pj-form-field-readonly");
			}
		});
	});
})(jQuery_1_8_2);