var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmBooking,
			$frmCreateBooking = $("#frmCreateBooking"),
			$frmUpdateBooking = $("#frmUpdateBooking"),
			$dialogItemDelete = $("#dialogItemDelete"),
			$dialogItemEdit = $("#dialogItemEdit"),
			$dialogItemAdd = $("#dialogItemAdd"),
			$tabs = $("#tabs"),
			tabs = ($.fn.tabs !== undefined),
			dialog = ($.fn.dialog !== undefined),
			spinner = ($.fn.spinner !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			chosen = ($.fn.chosen !== undefined);
		
		function getBookingItems($form) {
			$.get("index.php?controller=pjAdminBookings&action=pjActionItemGet", $form.find("input[name='id'], input[name='hash']").serialize()).done(function (data) {
				$("#boxBookingItems").html(data);
			});
		}
		
		if ($frmCreateBooking.length > 0 && validate) {
			$frmBooking = $frmCreateBooking;
			$frmCreateBooking.validate({
				rules: {
					uuid: {
						remote: "index.php?controller=pjAdminBookings&action=pjActionCheckUuid"
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore",
				invalidHandler: function (event, validator) {
					$tabs.tabs("option", "active", 0);
				}
			});
			
			getBookingItems.call(null, $frmCreateBooking);
		}
		
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs();
		}
		
		if ($frmUpdateBooking.length > 0) {
			$frmBooking = $frmUpdateBooking;
			$frmUpdateBooking.on("click", ".btnCreateInvoice", function () {
				$("#frmCreateInvoice").trigger("submit");
			});
			
			if (validate) {
				$frmUpdateBooking.validate({
					rules: {
						uuid: {
							remote: "index.php?controller=pjAdminBookings&action=pjActionCheckUuid&id=" + $frmUpdateBooking.find("input[name='id']").val()
						}
					},
					errorPlacement: function (error, element) {
						error.insertAfter(element.parent());
					},
					onkeyup: false,
					errorClass: "err",
					wrapper: "em",
					ignore: ".ignore",
					invalidHandler: function (event, validator) {
						$tabs.tabs("option", "active", 0);
					}
				});
			}
			
			getBookingItems.call(null, $frmUpdateBooking);
		}
		
		function formatDateTime(str) {
			if (str === null || str.length === 0) {
				return myLabel.empty_datetime;
			}
			
			if (str === '0000-00-00 00:00:00') {
				return myLabel.invalid_datetime;
			}
			
			if (str.match(/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}/) !== null) {
				var x = str.split(" "),
					date = x[0],
					time = x[1],
					dx = date.split("-"),
					tx = time.split(":"),
					y = dx[0],
					m = parseInt(dx[1], 10) - 1,
					d = dx[2],
					hh = tx[0],
					mm = tx[1],
					ss = tx[2];
				return $.datagrid.formatDate(new Date(y, m, d, hh, mm, ss), pjGrid.jsDateFormat + ", hh:mm");
			}
		}
		
		function formatItems(str, obj) {
			var tmp,
				arr = [];
			for (var i = 0, iCnt = obj.items.length; i < iCnt; i++) {
				tmp = obj.items[i].split("~.~");
				arr.push([tmp[2], ' x ', tmp[3]].join(""));
			}
			
			return arr.join("<br>");
		}
		
		function formatDefault (str) {
			return myLabel[str] || str;
		}
		
		function formatId (str, obj) {
			return ['<a href="index.php?controller=pjAdminBookings&action=pjActionUpdate&id=', obj.id, '">', str, '</a>'].join("");
		}
		
		function formatTotal(val, obj) {
			return obj.total_formated;
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminBookings&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBooking&id={:id}"}
				          ],
				columns: [{text: myLabel.uuid, type: "text", sortable: true, editable: false, width: 90, renderer: formatId},
				          {text: myLabel.items, type: "text", sortable: true, editable: false, renderer: formatItems, width: 175},
				          {text: myLabel.from, type: "date", sortable: true, editable: false, width: 110, renderer: formatDateTime},
				          {text: myLabel.to, type: "date", sortable: true, editable: false, width: 110, renderer: formatDateTime},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, options: [
				                                                                                     {label: myLabel.confirmed, value: 'confirmed'},
				                                                                                     {label: myLabel.pending, value: 'pending'},
				                                                                                     {label: myLabel.cancelled, value: 'cancelled'}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString,
				dataType: "json",
				fields: ['uuid', 'id', 'dt_from', 'dt_to', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBookingBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBookings&action=pjActionSaveBooking&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		if ($("#grid_invoices").length > 0 && datagrid) {
			var $grid_invoices = $("#grid_invoices").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjInvoice&action=pjActionUpdate&id={:id}", title: "Edit"},
				          {type: "delete", url: "index.php?controller=pjInvoice&action=pjActionDelete&id={:id}", title: "Delete"}],
				columns: [
				    {text: myLabel.num, type: "text", sortable: true, editable: false, renderer: formatId},
				    {text: myLabel.order_id, type: "text", sortable: true, editable: false},
				    {text: myLabel.issue_date, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				    {text: myLabel.due_date, type: "date", sortable: true, editable: false, renderer: $.datagrid._formatDate, dateFormat: pjGrid.jsDateFormat},
				    {text: myLabel.created, type: "text", sortable: true, editable: false, renderer: formatDateTime},
				    {text: myLabel.status, type: "text", sortable: true, editable: false, renderer: formatDefault},	
				    {text: myLabel.total, type: "text", sortable: true, editable: false, align: "right", renderer: formatTotal}
				],
				dataUrl: "index.php?controller=pjInvoice&action=pjActionGetInvoices&q=" + $frmUpdateBooking.find("input[name='uuid']").val(),
				dataType: "json",
				fields: ['id', 'order_id', 'issue_date', 'due_date', 'created', 'status', 'total'],
				paginator: {
					actions: [
					   {text: myLabel.delete_title, url: "index.php?controller=pjInvoice&action=pjActionDeleteBulk", render: true, confirmation: myLabel.delete_body}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$("#content").on("focusin", ".datepick", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev")
			});
		}).on("click", ".item-edit", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogItemEdit.length > 0 && dialog) {
				var $this = $(this);
				$dialogItemEdit
					.data("id", $this.data("id"))
					.data("hash", $this.data("hash"))
					.data("key", $this.data("key"))
					.dialog("open");
			}
			return false;
		}).on("click", ".item-add", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogItemAdd.length > 0 && dialog) {
				$dialogItemAdd.dialog("open");
			}
			return false;
		}).on("click", ".item-delete", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogItemDelete.length > 0 && dialog) {
				var $this = $(this);
				$dialogItemDelete
					.data("id", $this.data("id"))
					.data("hash", $this.data("hash"))
					.data("key", $this.data("key"))
					.dialog("open");
			}
			return false;
		}).on("click", ".order-calc", function () {
			var $this = $(this),
				$form = $this.closest("form");
			$.post("index.php?controller=pjAdminBookings&action=pjActionGetPrice", $form.serialize()).done(function (data) {
				if (data.status == 'OK') {
					$form.find("#price").val(data.data.price.toFixed(2));
					$form.find("#security").val(data.data.security.toFixed(2));
					$form.find("#deposit").val(data.data.deposit.toFixed(2));
					$form.find("#tax").val(data.data.tax.toFixed(2));
					$form.find("#total").val(data.data.total.toFixed(2));
					$form.find("#delivery").val(data.data.delivery.toFixed(2));
					$form.find("#collection").val(data.data.collection.toFixed(2));
					
					getBookingItems.call(null, $form);
				}
			});
		}).on("change", "#payment_method", function () {
			if ($("option:selected", this).val() == 'creditcard') {
				$(".erCC").show();
			} else {
				$(".erCC").hide();
			}
		});
		
		$(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=pjAdminBookings&action=pjActionGetBooking", "id", "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=pjAdminBookings&action=pjActionGetBooking", "id", "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=pjAdminBookings&action=pjActionGetBooking", "id", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".pj-button-detailed, .pj-button-detailed-arrow", function (e) {
			e.stopPropagation();
			$(".pj-form-filter-advanced").slideToggle();
		}).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;
			}
			cache.q = "";
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking", "id", "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");
			return false;
		}).on("click", ".pj-form-field-icon-date", function (e) {
			var $dp = $(this).parent().siblings("input[type='text']");
			if ($dp.hasClass("hasDatepicker")) {
				$dp.datepicker("show");
			} else {
				$dp.trigger("focusin").datepicker("show");
			}
		});
		
		function onChange() {
			var $this = $(this),
				$option = $this.find("option:selected"),
				$form = $this.closest("form"),
				$dialog = $form.parent(),
				$details = $form.find(".item_details");
			
			$details.hide();
			destroySpinner.call(null, $form);
			if ($option.val() != "") {
				$form.find("input[name='qty']").val('1').data("max", $option.data("qty"));
				
				$details.show();
			}
			attachSpinner.call(null, $form);
			$dialog.dialog("option", "position", "center");
		}
		
		function attachSpinner($container) {
			if (!spinner) {
				return false;
			}
			
			var $qty = $container.find("input[name='qty']");
			if ($qty.length > 0) {
				$qty.spinner({
					min: 1,
					max: $qty.data("max")
				});
			}
			
			return true;
		}
		
		function destroySpinner($container) {
			if (!spinner) {
				return false;
			}
			$container.find("input[name='qty']").spinner("destroy");
			
			return true;
		}

		if ($dialogItemEdit.length > 0 && dialog) {
			var $frm = null
			if($frmCreateBooking.length > 0)
			{
				$frm = $frmCreateBooking;
			}
			if($frmUpdateBooking.length > 0)
			{
				$frm = $frmUpdateBooking;
			}
			$dialogItemEdit.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				width: 600,
				open: function () {
					$dialogItemEdit.html("");
					$.get("index.php?controller=pjAdminBookings&action=pjActionItemEdit", {
						"booking_item_id": $dialogItemEdit.data("id"),
						"hash": $dialogItemEdit.data("hash"),
						"key": $dialogItemEdit.data("key")
					}).done(function (data) {
						$dialogItemEdit.html(data);
						attachSpinner.call(null, $dialogItemEdit);
						if (chosen) {
							$dialogItemEdit.find("select.stock-product").chosen();
						}
						$dialogItemEdit.dialog("option", "position", "center");
					});
				},
				buttons: {
					"Update": function () {
						var $this = $(this);
						var post_data = $dialogItemEdit.find("form").serialize();
						post_data += "&" + $.param({ 'date_from': $frm.find('input[name="date_from"]').val() });
						post_data += "&" + $.param({ 'date_to': $frm.find('input[name="date_to"]').val() });
						post_data += "&" + $.param({ 'hour_from': $frm.find('select[name="hour_from"]').val() });
						post_data += "&" + $.param({ 'minute_from': $frm.find('select[name="minute_from"]').val() });
						post_data += "&" + $.param({ 'hour_to': $frm.find('select[name="hour_to"]').val() });
						post_data += "&" + $.param({ 'minute_to': $frm.find('select[name="minute_to"]').val() });
						$.post("index.php?controller=pjAdminBookings&action=pjActionItemEdit", post_data).done(function (data) {
							getBookingItems.call(null, $frmBooking);
							$this.dialog("close");
						});
					},
					"Cancel": function () {
						$(this).dialog("close");
					}
				}
			}).on("change", "select[name='foreign_id']", onChange);
		}
		
		if ($dialogItemAdd.length > 0 && dialog) {
			$dialogItemAdd.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				width: 600,
				open: function () {
					$dialogItemAdd.html("");
					$.get("index.php?controller=pjAdminBookings&action=pjActionItemAdd", $frmBooking.find("input[name='id'], input[name='hash'], #date_from, #hour_from, #minute_from, #date_to, #hour_to, #minute_to").serialize()).done(function (data) {
						$dialogItemAdd.html(data);
						attachSpinner.call(null, $dialogItemAdd);
						if (chosen) {
							$dialogItemAdd.find("select.stock-product").chosen();
						}
						$dialogItemAdd.dialog("option", "position", "center");
					});
				},
				buttons: {
					"Add": function () {
						var $this = $(this);
						$.post("index.php?controller=pjAdminBookings&action=pjActionItemAdd", $dialogItemAdd.find("form").serialize()).done(function (data) {
							getBookingItems.call(null, $frmBooking);
							$this.dialog("close");
						});
					},
					"Cancel": function () {
						$(this).dialog("close");
					}
				}
			}).on("change", "select[name='foreign_id']", onChange);
		}
		
		if ($dialogItemDelete.length > 0 && dialog) {
			$dialogItemDelete.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				buttons: {
					"Delete": function () {
						$.post("index.php?controller=pjAdminBookings&action=pjActionItemDelete", {
							"id": $dialogItemDelete.data("id"),
							"hash": $dialogItemDelete.data("hash"),
							"key": $dialogItemDelete.data("key")
						}).done(function (data) {
							getBookingItems.call(null, $frmBooking);
							$dialogItemDelete.dialog("close");
						});
					},
					"Cancel": function () {
						$(this).dialog("close");
					}
				}
			});
		}
	});
})(jQuery_1_8_2);