var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var	$frmCreateDestination = $("#frmCreateDestination"),
			$frmUpdateDestination = $("#frmUpdateDestination"),
			$dialogDestinationDelete = $("#dialogDestinationDelete"),
			$dialogDestinationCrop = $("#dialogDestinationCrop"),
			chosen = ($.fn.chosen !== undefined),
			$upload = $("#upload"),
			tipsy = ($.fn.tipsy !== undefined),
			Jcrop = ($.fn.Jcrop !== undefined),
			zinoUpload = ($.fn.zinoUpload !== undefined),
			validate = ($.fn.validate !== undefined),
			friendurl = ($.fn.friendurl !== undefined),
			dialog = ($.fn.dialog !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (tipsy) {
			$(".center-langbar-tip").tipsy({
				offset: 1,
				opacity: 1,
				html: true,
				className: "tipsy-listing-center"
			});
		}
		
		if (friendurl) {
			$("input[name$='[name]']:first").friendurl({
				id: "seo_url",
				transliterate: true
			});
		}
		
		if (chosen) {
			$("#country_id").chosen();
		}
		
		if (window.tinymce) {
			tinymce.init({
			    selector: "textarea.selector-tinymce",
			    width: 550,
			    height: 400,
			    plugins: [
			        "advlist autolink lists link image charmap print preview anchor",
			        "searchreplace visualblocks code fullscreen",
			        "insertdatetime media table contextmenu paste responsivefilemanager"
			    ],
			    toolbar: "insertfile undo redo | styleselect | fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image responsivefilemanager",
			    image_advtab: true,
			    menubar: "file edit insert view table tools",
			    setup: function (editor) {
			    	editor.on('change', function (e) {
			    		editor.editorManager.triggerSave();
			    		$(":input[name='" + editor.id + "']").valid();
			    	});
			    },
			    fontsize_formats: "8pt 9pt 10pt 11pt 12pt 13pt 14pt 15pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt 38pt 40pt 42pt",
			    content_css: "app/web/css/pjWeb.css",
			    style_formats: [
			        {title: 'Bold text', inline: 'span', styles: {"font-weight": "bold"}},
			        {title: 'Italic text', inline: 'span', styles: {"font-style": "italic"}},
			        {title: 'Black text', inline: 'span', styles: {"color": "#000"}}
			    ],
			    external_filemanager_path: "core/third-party/filemanager/",
			    filemanager_title: "Responsive Filemanager" ,
			    external_plugins: {"filemanager": "../filemanager/plugin.min.js"}
			});
		}
		
		if (validate) {
			$.validator.addMethod("seoUrl", function (value, element, params) {
				return this.optional(element) || /^[\w\-]+$/.test(value);
			}, 'Only valid characters are: a-z, 0-9, "_", "-"');
		}
		
		if ($frmCreateDestination.length > 0 && validate) {
			$frmCreateDestination.submit(function () {
				// update underlying textarea before submit validation
				tinymce.activeEditor.editorManager.triggerSave();
			}).validate({
				rules: {
					seo_url: {
						"seoUrl": true,
						"required": true,
						"remote": "index.php?controller=pjAdminDestinations&action=pjActionCheckUrl"
					}
				},
				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 ($frmUpdateDestination.length > 0 && validate) {
			$frmUpdateDestination.submit(function () {
				// update underlying textarea before submit validation
				tinymce.activeEditor.editorManager.triggerSave();
			}).validate({
				rules: {
					seo_url: {
						"seoUrl": true,
						"required": true,
						"remote": "index.php?controller=pjAdminDestinations&action=pjActionCheckUrl&id=" + $frmUpdateDestination.find("input[name='id']").val()
					}
				},
				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 ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminDestinations&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				          {type: "delete", url: "index.php?controller=pjAdminDestinations&action=pjActionDeleteDestination&id={:id}", title: myLabel.lblDelete}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: true, width: 230, editableWidth: 210},
				          {text: myLabel.seo_url, type: "text", sortable: true, editable: false, width: 170},
				          {text: myLabel.on_home, type: "select", sortable: true, editable: true, options: [
						                                                                                     {label: myLabel.yes, value: 1}, 
						                                                                                     {label: myLabel.no, value: 0}
						                                                                                     ], applyClass: "pj-status"},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminDestinations&action=pjActionGetDestination",
				dataType: "json",
				fields: ['name', 'seo_url', 'on_home', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminDestinations&action=pjActionDeleteDestinationBulk",  ajax: false, render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.make_active, url: "index.php?controller=pjAdminDestinations&action=pjActionStatusDestination&status=T", render: true},
					   {text: myLabel.make_inactive, url: "index.php?controller=pjAdminDestinations&action=pjActionStatusDestination&status=F", render: true}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminDestinations&action=pjActionSaveDestination&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$("#content").on("click", ".delete-dest", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogDestinationDelete.length > 0 && dialog) {
				$dialogDestinationDelete.data("id", $(this).data("id")).dialog("open");
			}
			return false;
		}).on("click", ".crop-dest", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogDestinationCrop.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=pjAdminDestinations&action=pjActionGetDestination", "name", "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=pjAdminDestinations&action=pjActionGetDestination", "name", "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=pjAdminDestinations&action=pjActionGetDestination", "name", "ASC", content.page, content.rowCount);
			return false;
		});
		
		function getThumb(id) {
			$.get("index.php?controller=pjAdminDestinations&action=pjActionImage", {
				"id": id
			}).done(function (data) {
				$("#box-dest").html(data);
			});
		}
		
		function openCropDialog(id) {
			$.get("index.php?controller=pjAdminDestinations&action=pjActionCrop", {
				"id": id
			}).done(function (data) {
				$dialogDestinationCrop.html(data);
				window.setTimeout(function () {
					$dialogDestinationCrop.data("id", id).dialog("open");
				}, 100);
				
				$dialogDestinationCrop.find("img").Jcrop({
					aspectRatio: 705/355,
					allowResize: false,
					allowSelect: false,
	                setSelect: [0, 0, 705, 355],
	                boxWidth: 800,
	                boxHeight: 600,
	                bgColor: "white",
	                onSelect: function(c) {
	                    var $frm = $dialogDestinationCrop.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 () {
					$dialogDestinationCrop.dialog("option", "position", "center");
	            });
			});
		}
		
		if ($upload.length > 0 && zinoUpload) {
			$upload.zinoUpload({
		        url: "index.php?controller=pjAdminDestinations&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 ($dialogDestinationDelete.length > 0 && dialog) {
			$dialogDestinationDelete.dialog({
				autoOpen: false,
				draggable: false, 
				resizable: false,
				modal: true,
				buttons: (function () {
					var btns = {};
					btns['OK'] = function () {
						$.post("index.php?controller=pjAdminDestinations&action=pjActionDeleteDestinationImage", {
							"id": $dialogDestinationDelete.data("id")
						}).done(function (data) {
							if (data.status == 'OK') {
								$("#box-dest").html("");
							}
						});
						$dialogDestinationDelete.dialog("close");
					};
					btns['Cancel'] = function () {
						$(this).dialog("close");
					};
					return btns;
				})()
			});
		}
		
		if ($dialogDestinationCrop.length > 0 && dialog) {
			$dialogDestinationCrop.dialog({
				autoOpen: false,
				draggable: false, 
				resizable: false,
				modal: true,
				width: 'auto',
				buttons: (function () {
					var btns = {};
					btns['OK'] = function () {
						$.post("index.php?controller=pjAdminDestinations&action=pjActionCrop", $dialogDestinationCrop.find("form").serialize()).done(function (data) {
							if (data.status == 'OK') {
								getThumb.call(null, $dialogDestinationCrop.data("id"));
							}
						});
						$dialogDestinationCrop.dialog("close");
					};
					btns['Cancel'] = function () {
						$(this).dialog("close");
					};
					return btns;
				})()
			});
		}
		
	});
})(jQuery_1_8_2);