var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateBooth = $("#frmCreateBooth"),
			$frmUpdateBooth = $("#frmUpdateBooth"),
			$frmCustomPrice = $("#frmCustomPrice"),
			$dialogDelete = $("#dialogDeleteImage"),
			datepicker = ($.fn.datepicker !== undefined),
			tabs = ($.fn.tabs !== undefined),
			dialog = ($.fn.dialog !== undefined),
			multiselect = ($.fn.multiselect !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
				}
			};
		
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		$(".field-int").spinner({
			min: 0
		});
		if ($frmCreateBooth.length > 0 && validate) {
			$frmCreateBooth.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
		}
		if ($frmUpdateBooth.length > 0 && validate) {
			$frmUpdateBooth.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'min_reservation_length' || element.attr('name') == 'max_reservation_length')
					{
						error.insertAfter(element.parent().parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					if (validator.numberOfInvalids()) {
				    	var index = $(validator.errorList[0].element, this).closest("div[id^='tabs-']").index();
				    	if ($tabs.length > 0 && tabs && index !== -1) {
				    		$tabs.tabs(tOpt).tabs("option", "active", index-1);
				    	}
				    };
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
		}
		if ($frmCreateBooth.length > 0 || $frmUpdateBooth.length > 0) 
		{
			if(myLabel.locale_array.length > 0)
			{
				var locale_array = myLabel.locale_array;
				for(var i = 0; i < locale_array.length; i++)
				{
					var name = $("#i18n_type_" + locale_array[i]),
						description = $("#i18n_description_" + locale_array[i]);
					name.rules('add', {
						messages: {
					    	required: myLabel.field_required
					    }
					});
					description.rules('add', {
						messages: {
					    	required: myLabel.field_required
					    }
					});
				}
			}
		}
		if ($dialogDelete.length > 0 && dialog) 
		{
			$dialogDelete.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 320,
				buttons: (function () {
					var buttons = {};
					buttons[ncbsApp.locale.button.delete] = function () {
						$.ajax({
							type: "GET",
							dataType: "json",
							url: $dialogDelete.data('href'),
							success: function (res) {
								if(res.code == 200){
									$('#image_container').remove();
									$dialogDelete.dialog('close');
								}
							}
						});
					};
					buttons[ncbsApp.locale.button.cancel] = function () {
						$dialogDelete.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		function formatImage(val, obj) {
			var src = val ? val : 'app/web/img/backend/84x56.png';
			return ['<a href="index.php?controller=pjAdminBooths&action=pjActionUpdate&id=', obj.id ,'"><img src="', src, '" style="width: 84px" /></a>'].join("");
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminBooths&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminBooths&action=pjActionDeleteBooth&id={:id}"}
				          ],
				columns: [{text: myLabel.thumb, type: "text", sortable: false, editable: false, renderer: formatImage, width: 90, align: "center"},
				          {text: myLabel.type, type: "text", sortable: true, editable: true, width: 170, editableWidth: 150},
				          {text: myLabel.capacity, type: "text", sortable: true, editable: false, width: 120, align: 'center'},
				          {text: myLabel.count, type: "text", sortable: true, editable: false, width: 100, align: 'center'},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, editableWidth: 80, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
			                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminBooths&action=pjActionGetBooth" + pjGrid.queryString,
				dataType: "json",
				fields: ['thumb', 'type', 'capacity', 'count', 'status'],
				paginator: {
					actions: [
				          {text: myLabel.delete_selected, url: "index.php?controller=pjAdminBooths&action=pjActionDeleteBoothBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBooths&action=pjActionSaveBooth&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		if ($("#price_grid").length > 0 && datagrid) 
		{
			var $price_grid = $("#price_grid").datagrid({
				buttons: [{type: "update", url: "index.php?controller=pjAdminBooths&action=pjActionUpdatePrice&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminBooths&action=pjActionDeletePrice&id={:id}"}
				          ],
				columns: [{text: myLabel.date, type: "text", sortable: true, editable: false, width: 300},
				          {text: myLabel.price, type: "text", sortable: true, editable: false, width: 300}],
				dataUrl: "index.php?controller=pjAdminBooths&action=pjActionGetPrice" + pjGrid.queryString,
				dataType: "json",
				fields: ['date', 'price'],
				paginator: {
					actions: [
				          {text: myLabel.delete_selected, url: "index.php?controller=pjAdminBooths&action=pjActionDeletePriceBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBooths&action=pjActionSavePrice&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}

		if ($frmCustomPrice.length > 0 && validate) {
			$frmCustomPrice.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				submitHandler: function(form){
					$.post("index.php?controller=pjAdminBooths&action=pjActionCustomPrice", $(form).serialize()).done(function (data) {
						if(data.code == '200')
						{
							$(form).find('input').each(function(){
								if($(this).attr('name') != 'booth_id' && $(this).attr('name') != 'save')
								{
									$(this).val('');
								}
							});
							var content = $price_grid.datagrid("option", "content"),
								cache = $price_grid.datagrid("option", "cache");
							$price_grid.datagrid("load", "index.php?controller=pjAdminBooths&action=pjActionGetPrice" + pjGrid.queryString, "date", "DESC", content.page, content.rowCount);
						}
					});
					return false;
				}
			});
		}
		
		$('#pjNcBBoothContainer').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=pjAdminBooths&action=pjActionGetBooth", "id", "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=pjAdminBooths&action=pjActionGetBooth", "id", "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=pjAdminBooths&action=pjActionGetBooth", "id", "ASC", content.page, content.rowCount);
			return false;
		});
		
		$(document).on("click", ".pj-delete-image", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDelete.data('href', $(this).data('href')).dialog("open");
		}).on("focusin", ".datepicker", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev")
			});
		}).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");
			}
			
		}).on("click", ".pj-table-icon-update", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$.get($(this).attr('href')).done(function (data) {
				if(data.code == '200')
				{
					$frmCustomPrice.find('input[name="id"]').val(data.id);
					$frmCustomPrice.find('input[name="date"]').val(data.date);
					$frmCustomPrice.find('input[name="price"]').val(data.price);
				}
			});
		});
	});
})(jQuery_1_8_2);