var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
function getCsrfToken(){var m=document.querySelector('meta[name="csrf-token"]');return m?m.getAttribute('content'):''}
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateItem = $("#frmCreateItem"),
			$frmUpdateItem = $("#frmUpdateItem"),
			$dialogDeletePrice = $("#dialogDeletePrice"),
			$gallery = $("#gallery"),
			$tabs = $("#tabs"),
			gallery = ($.fn.gallery !== undefined),
			dialog = ($.fn.dialog !== undefined),
			tabs = ($.fn.tabs !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			validate = ($.fn.validate !== undefined),
			spinner = ($.fn.spinner !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			tOpt = {
				select: function (event, ui) {
					$("input[name='tab']").val(ui.index);
				}
			};
		
		if (spinner) {
			$(".spinner").spinner({
				min: 0,
				step: 1
			});
		}
		
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
			
			var m = window.location.href.match(/&tab=(\d+)/);
			if (m !== null) {
				$tabs.tabs("option", "selected", m[1]);
			}
		}
		
		if ($frmCreateItem.length > 0 && validate) {
			$frmCreateItem.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		if ($frmUpdateItem.length > 0 && validate) {
			$frmUpdateItem.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		
		if ($dialogDeletePrice.length > 0 && dialog) {
			$dialogDeletePrice.dialog({
				modal: true,
				draggable: false,
				resizable: false,
				autoOpen: false,
				buttons: {
					'Delete': function () {
						var $link = $dialogDeletePrice.data("link"),
							$tr = $link.closest("tr");
						$.post("index.php?controller=pjAdminItems&action=pjActionDeletePrice&csrf_token=" + getCsrfToken(), {
							"id" : $link.data("id")
						}).done(function (data) {
							if (data.status === "OK") {
								$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
									$tr.remove();
								});
							}
							$dialogDeletePrice.dialog("close");
						});
					},
					'Cancel': function () {
						$(this).dialog("close");
					}
				}
			});
		}
		
		if ($gallery.length > 0 && gallery) {
			$gallery.gallery({
				compressUrl: "index.php?controller=pjGallery&action=pjActionCompressGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				getUrl: "index.php?controller=pjGallery&action=pjActionGetGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				deleteUrl: "index.php?controller=pjGallery&action=pjActionDeleteGallery",
				emptyUrl: "index.php?controller=pjGallery&action=pjActionEmptyGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				rebuildUrl: "index.php?controller=pjGallery&action=pjActionRebuildGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				resizeUrl: "index.php?controller=pjGallery&action=pjActionCrop&model=pjItem&&id={:id}&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash + ($frmUpdateItem.length > 0 ? "&query_string=" + encodeURIComponent("controller=pjAdminItems&action=pjActionUpdate&id=" + myGallery.foreign_id + "&tab=1") : ""),				
				rotateUrl: "index.php?controller=pjGallery&action=pjActionRotateGallery",
				sortUrl: "index.php?controller=pjGallery&action=pjActionSortGallery",
				updateUrl: "index.php?controller=pjGallery&action=pjActionUpdateGallery",
				uploadUrl: "index.php?controller=pjGallery&action=pjActionUploadGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				watermarkUrl: "index.php?controller=pjGallery&action=pjActionWatermarkGallery&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash
			});
		}
		
		function formatImage(path, obj) {
			if (path !== null && path.length > 0) {
				return '<a href="index.php?controller=pjAdminItems&action=pjActionUpdate&id='+obj.id+'"><img src="' + path + '" alt="" class="thumb-img" /></a>';
			}
			return '<a href="index.php?controller=pjAdminItems&action=pjActionUpdate&id='+obj.id+'"><img src="app/web/img/frontend/er-noimage.png" alt="" class="thumb-img" /></a>';
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminItems&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminItems&action=pjActionDeleteItem&id={:id}&csrf_token=" + myLabel.csrf_token}
				          ],
				columns: [{text: myLabel.image, type: "text", sortable: true, editable: false, renderer: formatImage, align: "center"},
				          {text: myLabel.title, type: "text", sortable: true, editable: false, width: 190},
				          {text: myLabel.category, type: "text", sortable: true, editable: false, width: 160},
				          {text: myLabel.cnt, type: "spinner", min: 0, step: 1, sortable: true, editable: true, width: 60, editableWidth: 65},
				          {text: myLabel.is_active, type: "select", sortable: true, editable: true, width: 100, options: [
			     				       {label: myLabel.active, value: 1}, 
			     				       {label: myLabel.inactive, value: 0}
			     				       ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminItems&action=pjActionGetItem" + pjGrid.queryString,
				dataType: "json",
				fields: ['image', 'title', 'category_title', 'cnt', 'is_active'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminItems&action=pjActionDeleteItemBulk&csrf_token=" + myLabel.csrf_token, render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminItems&action=pjActionSaveItem&id={:id}&csrf_token=" + myLabel.csrf_token,
				select: {
					field: "id",
					name: "record[]"
				},
				onRender: function () {
					var $dialogDelBulk = $("div[id^='pj-dialog-action-" + $grid.data("datagrid").uid + "']");
					if ($dialogDelBulk.length > 0 && dialog) {
						$dialogDelBulk.dialog("option", {
							"open": function () {
								var bookings = 0;
								$grid.find(".pj-table-select-row:checked").closest("tr").each(function (i) {
									bookings += $(this).data("object").bookings;
								});
								
								if (bookings > 0) {
									$dialogDelBulk.html(myLabel.delete_inactivate);
								} else {
									$dialogDelBulk.html(myLabel.delete_confirmation);
								}
							}, 
							"close": function () {
								$dialogDelBulk.html(myLabel.delete_confirmation);
							}
						});
					}
				}
			});
			
			var $dialogDel = $("div[id^='pj-dialog-delete-']");
			if ($dialogDel.length > 0 && dialog) {
				$dialogDel.dialog("option", {
					"open": function () {
						var row = $(this).data("row"),
							data = $(row).data();
						
						if (data.object.bookings > 0) {
							$dialogDel.html(myLabel.delete_inactivate);
						}
					}, 
					"close": function () {
						$dialogDel.html(myLabel.delete_confirmation);
					}
				});
			}
		}
		
		$(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, {
				is_active: "",
				q: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminItems&action=pjActionGetItem", "title", "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.is_active = "";
			obj[$this.data("column")] = $this.data("value");
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminItems&action=pjActionGetItem", "title", "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=pjAdminItems&action=pjActionGetItem", "id", "ASC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datepick", function () {
			if (datepicker) {
				var $this = $(this);
				$this.datepicker({
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev")
				});
			}
		});
		
		$("#content").on("click", ".btnDeletePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogDeletePrice.length > 0 && dialog) {
				$dialogDeletePrice.data("link", $(this)).dialog("open");
			}
			return false;
		}).on("click", ".btnRemovePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).closest("tr").remove();
			return false;
		}).on("click change", "input.rent_by", function () {
			var $rent_by_hour = $("input[name='rent_by_hour']"),
				$rent_by_day = $("input[name='rent_by_day']"),
				$price_per_hour = $("input[name='price_per_hour']"),
				$price_per_day = $("input[name='price_per_day']");
			
			if ($rent_by_hour.is(":checked") && $rent_by_day.is(":checked")) {
				$(".pHours, .pDays").hide();
				$(".pPeriod").show().trigger("change");
				$price_per_hour.closest("p").show();
				$price_per_day.closest("p").show();
			} else if (!$rent_by_hour.is(":checked") && !$rent_by_day.is(":checked")) {
				$(".pPeriod, .pHours, .pDays, .pHour, .pDay").hide();
				$price_per_hour.closest("p").hide();
				$price_per_day.closest("p").hide();
			} else {
				$(".pPeriod").hide();
				
				if ($rent_by_hour.is(":checked")) {
					$(".pHours, .pHour").show();
					$(".pDays, .pDay").hide();
					$price_per_hour.closest("p").show();
					$price_per_day.closest("p").hide();
				} else if ($rent_by_day.is(":checked")) {
					$(".pHours, .pHour").hide();
					$(".pDays, .pDay").show();
					$price_per_hour.closest("p").hide();
					$price_per_day.closest("p").show();
				}
			}
		}).on("click", ".btnAddPrice", function () {
			var $clone = $("#boxClonePrices tbody").clone(),
				index = Math.ceil(Math.random() * 999999),
				$tbody = $("#tblPrices").find("tbody"),
				html = $clone.html().replace(/\{INDEX\}/g, 'x_' + index);
			
			$(html).appendTo($tbody);
			$tbody.find("tr:last").find(".spin").spinner({
				min: 0,
				step: 1
			});
			
		}).on("change", "select.pPeriod", function () {
			var $this = $(this);
			switch ($this.find("option:selected").val()) {
			case "hour":
				$this.closest("tr").find(".pHour").show().end().find(".pDay").hide();
				break;
			case "day":
				$this.closest("tr").find(".pHour").hide().end().find(".pDay").show();
				break;
			}
		}).on("click", ".btnAddAvail", function () {
			var $clone = $("#boxCloneAvail tbody").clone(),
				index = Math.ceil(Math.random() * 999999),
				$tbody = $("#tblAvailability").find("tbody"),
				html = $clone.html().replace(/\{INDEX\}/g, 'x_' + index);
			
			$(html).appendTo($tbody);
			$tbody.find("tr:last").find(".spin").spinner({
				min: 0,
				step: 1
			});
			
		}).on("click", ".btnRemoveAvail", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).closest("tr").remove();
			return false;
		});
	});
})(jQuery_1_8_2);