var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var	$frmCreateSlide = $("#frmCreateSlide"),
			$frmUpdateSlide = $("#frmUpdateSlide"),
			$dialogSlideDelete = $("#dialogSlideDelete"),
			$dialogSlideCrop = $("#dialogSlideCrop"),
			$upload = $("#upload"),
			Jcrop = ($.fn.Jcrop !== undefined),
			zinoUpload = ($.fn.zinoUpload !== undefined),
			validate = ($.fn.validate !== undefined),
			dialog = ($.fn.dialog !== undefined),
			spinner = ($.fn.spinner !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (spinner) {
			$("input.spin").spinner({
				min: 0,
				step: 1
			});
		}
		
		if ($frmCreateSlide.length > 0 && validate) {
			$frmCreateSlide.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					$(".pj-multilang-wrap").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).css('display','block');
						}else{
							$(this).css('display','none');
						}
					});
					$(".pj-form-langbar-item").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).addClass('pj-form-langbar-item-active');
						}else{
							$(this).removeClass('pj-form-langbar-item-active');
						}
					});
				}
			});
		}
		
		if ($frmUpdateSlide.length > 0 && validate) {
			$frmUpdateSlide.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					$(".pj-multilang-wrap").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).css('display','block');
						}else{
							$(this).css('display','none');
						}
					});
					$(".pj-form-langbar-item").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).addClass('pj-form-langbar-item-active');
						}else{
							$(this).removeClass('pj-form-langbar-item-active');
						}
					});
				}
			});
		}
		
		function formatImage(str, obj) {
			if (str != null) {
				return ['<a href="index.php?controller=pjAdminSlides&action=pjActionUpdate&id=', obj.id, '"><img src="', str, '?', Math.floor(Math.random() * 999999), '" alt="" style="border: none; vertical-align: middle; max-width: 100px; max-height: 100px" /></a>'].join("");
			}
			
			return "---";
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminSlides&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				          {type: "delete", url: "index.php?controller=pjAdminSlides&action=pjActionDeleteSlide&id={:id}", title: myLabel.lblDelete}
				          ],
				columns: [{text: myLabel.image, type: "text", sortable: true, editable: false, width: 100, renderer: formatImage},
				          {text: myLabel.title, type: "text", sortable: true, editable: true, width: 340, editableWidth: 280},
				          {text: myLabel.sort, type: "spinner", min: 0, step: 1, sortable: true, editable: true, width: 65, editableWidth: 60},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminSlides&action=pjActionGetSlide",
				dataType: "json",
				fields: ['image_thumb', 'title', 'sort', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminSlides&action=pjActionDeleteSlideBulk",  ajax: false, render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.make_active, url: "index.php?controller=pjAdminSlides&action=pjActionStatusSlide&status=T", render: true},
					   {text: myLabel.make_inactive, url: "index.php?controller=pjAdminSlides&action=pjActionStatusSlide&status=F", render: true}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminSlides&action=pjActionSaveSlide&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$("#content").on("click", ".delete-slide", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogSlideDelete.length > 0 && dialog) {
				$dialogSlideDelete.data("id", $(this).data("id")).dialog("open");
			}
			return false;
		}).on("click", ".crop-slide", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogSlideCrop.length > 0 && dialog) {
				openCropDialog.call(null, $(this).data("id"));
			}
			return false;
		});
		
		$(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=pjAdminSlides&action=pjActionGetSlide", "sort", "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=pjAdminSlides&action=pjActionGetSlide", "sort", "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=pjAdminSlides&action=pjActionGetSlide", "sort", "ASC", content.page, content.rowCount);
			return false;
		});
		
		function getThumb(id) {
			$.get("index.php?controller=pjAdminSlides&action=pjActionImage", {
				"id": id
			}).done(function (data) {
				$("#box-slide").html(data);
			});
		}
		
		function openCropDialog(id) {
			$.get("index.php?controller=pjAdminSlides&action=pjActionCrop", {
				"id": id
			}).done(function (data) {
				$dialogSlideCrop.html(data);
				window.setTimeout(function () {
					$dialogSlideCrop.data("id", id).dialog("open");
				}, 100);
				
				$dialogSlideCrop.find("img").Jcrop({
					aspectRatio: 291/302,
					allowResize: false,
					allowSelect: false,
	                setSelect: [0, 0, 291, 302],
	                boxWidth: 800,
	                boxHeight: 600,
	                bgColor: "white",
	                onSelect: function(c) {
	                    var $frm = $dialogSlideCrop.find("form");
	                    if ($frm.length > 0) {
	                        $frm.find("input[name='x']").val(c.x);
	                        $frm.find("input[name='x2']").val(c.x2);
	                        $frm.find("input[name='y']").val(c.y);
	                        $frm.find("input[name='y2']").val(c.y2);
	                        $frm.find("input[name='w']").val(c.w);
	                        $frm.find("input[name='h']").val(c.h);
	                    }
	                }
	            }).on("load", function () {
					$dialogSlideCrop.dialog("option", "position", "center");
	            });
			});
		}
		
		if ($upload.length > 0 && zinoUpload) {
			$upload.zinoUpload({
		        url: "index.php?controller=pjAdminSlides&action=pjActionUpload",
		        method: "POST",
		        name: "image",
		        data: {
		        	"id" : $upload.data("id")
		        },
		        complete: function (event, ui) {
		            if (ui.response.status == 'OK') {
		            	getThumb.call(null, $upload.data("id"));
		            	openCropDialog.call(null, $upload.data("id"));
		            }
		        }
		    });
		}
		
		if ($dialogSlideDelete.length > 0 && dialog) {
			$dialogSlideDelete.dialog({
				autoOpen: false,
				draggable: false, 
				resizable: false,
				modal: true,
				buttons: (function () {
					var btns = {};
					btns['OK'] = function () {
						$.post("index.php?controller=pjAdminSlides&action=pjActionDeleteSlideImage", {
							"id": $dialogSlideDelete.data("id")
						}).done(function (data) {
							if (data.status == 'OK') {
								$("#box-slide").html("");
							}
						});
						$dialogSlideDelete.dialog("close");
					};
					btns['Cancel'] = function () {
						$(this).dialog("close");
					};
					return btns;
				})()
			});
		}
		
		if ($dialogSlideCrop.length > 0 && dialog) {
			$dialogSlideCrop.dialog({
				autoOpen: false,
				draggable: false, 
				resizable: false,
				modal: true,
				width: 'auto',
				buttons: (function () {
					var btns = {};
					btns['OK'] = function () {
						$.post("index.php?controller=pjAdminSlides&action=pjActionCrop", $dialogSlideCrop.find("form").serialize()).done(function (data) {
							if (data.status == 'OK') {
								getThumb.call(null, $dialogSlideCrop.data("id"));
							}
						});
						$dialogSlideCrop.dialog("close");
					};
					btns['Cancel'] = function () {
						$(this).dialog("close");
					};
					return btns;
				})()
			});
		}
	});
})(jQuery_1_8_2);