var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	if (window.tinyMCE !== undefined) {
		tinymce.init({
		    selector: "textarea.mceEditor",
		    plugins: [
		        "advlist autolink lists link image charmap print preview anchor",
		        "searchreplace visualblocks code fullscreen",
		        "insertdatetime media table contextmenu paste"
		    ],
		    width: 550,
		    height: 350,
		    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		    setup: function (editor) {
		    	editor.on('change', function (e) {
		    		editor.editorManager.triggerSave();
		    		$(":input[name='" + editor.id + "']").valid();
		    	});
		    }
		});
	}
	$(function () {
		
		var $frmCreateListing = $("#frmCreateListing"),
			$frmUpdateListing = $("#frmUpdateListing"),
			validate = ($.fn.validate !== undefined),
			chosen = ($.fn.chosen !== undefined),
			gallery = ($.fn.gallery !== undefined),
			tabs = ($.fn.tabs !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			tipsy = ($.fn.tipsy !== undefined),
			$gallery = $("#gallery"),
			$tabs = $("#tabs"),
			tOpt = {
				select: function (event, ui) {
					$(":input[name='tab_id']").val(ui.panel.id);
				}
			};

		if ($tabs.length > 0 && tabs) 
		{
			$tabs.tabs(tOpt);
		}
		if (chosen) {
			$('#type_id').chosen();
			$('#breed_id').chosen();
			$('#address_country').chosen();
		}
		if ($frmCreateListing.length > 0 && validate) {
			$frmCreateListing.validate({
				rules: {
					"listing_refid": {
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId"
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateListing.length > 0 && validate) 
		{
			if (tipsy) {
				$(".listing-tip").tipsy({
					offset: 1,
					opacity: 1,
					html: true,
					gravity: "nw",
					className: "tipsy-listing"
				});
				$(".center-langbar-tip").tipsy({
					offset: 1,
					opacity: 1,
					html: true,
					className: "tipsy-listing-center"
				});
			}
			
			if ($gallery.length > 0 && gallery) 
			{
				$gallery.gallery({
					compressUrl: "index.php?controller=pjGallery&action=pjActionCompressGallery&foreign_id=" + myGallery.foreign_id,
					getUrl: "index.php?controller=pjGallery&action=pjActionGetGallery&foreign_id=" + myGallery.foreign_id,
					deleteUrl: "index.php?controller=pjGallery&action=pjActionDeleteGallery",
					emptyUrl: "index.php?controller=pjGallery&action=pjActionEmptyGallery&foreign_id=" + myGallery.foreign_id,
					rebuildUrl: "index.php?controller=pjGallery&action=pjActionRebuildGallery&foreign_id=" + myGallery.foreign_id,
					resizeUrl: "index.php?controller=pjGallery&action=pjActionResizeGallery&id={:id}&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash + ($frmUpdateListing.length > 0 ? "&query_string=" + encodeURIComponent("controller=pjAdminListings&action=pjActionUpdate&id=" + myGallery.foreign_id + "&tab_id=tabs-4") : ""),
					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,
					watermarkUrl: "index.php?controller=pjGallery&action=pjActionWatermarkGallery&foreign_id=" + myGallery.foreign_id
				});
			}
			$frmUpdateListing.validate({
				rules: {
					"listing_refid": {
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId&id=" + $frmUpdateListing.find("input[name='id']").val()
					}
				},
				errorPlacement: function (error, element) {
					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');
					$(".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');
						}
					});
				}
			});
		}
		
		function formatImage(val, obj) {
			var src = val ? val : 'app/web/img/backend/no-image.png';
			return ['<a href="index.php?controller=pjAdminListings&action=pjActionUpdate&id=', obj.id ,'"><img src="', src, '" style="width: 100px" /></a>'].join("");
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}"}
				          ],
				columns: [{text: myLabel.image, type: "text", sortable: false, editable: false, renderer: formatImage, width: 105},
				          {text: myLabel.ref_id, type: "text", sortable: true, editable: true, width: 105},
				          {text: myLabel.type, type: "text", sortable: true, editable: false, width: 130},
				          {text: myLabel.breed, type: "text", sortable: true, editable: false, width: 150},
				          {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=pjAdminListings&action=pjActionGetListing",
				dataType: "json",
				fields: ['image', 'listing_refid', 'type', 'breed', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminListings&action=pjActionDeleteListingBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminListings&action=pjActionSaveListing&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(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: "",
				listing_refid: "",
				type_id: "",
				breed_id: "",
				year_from: "",
				year_to: "",
				feature_age_id: "",
				feature_color_id: "",
				feature_sex_id: "",
				feature_size_id: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "created", "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=pjAdminListings&action=pjActionGetListing", "created", "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=pjAdminListings&action=pjActionGetListing", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".pj-button-detailed, .pj-button-detailed-arrow", function (e) {
			e.stopPropagation();
			$(".pj-form-filter-advanced").toggle();
		}).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;
			}
			$.extend(cache, obj, {
				q: $(".frm-filter").find("input[name='q']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			$(".pj-button-detailed").trigger("click");
			$('#listing_refid').val('');
			$('#year_from').val('');
			$('#year_to').val('');
			$('#feature_age_id').val('');
			$('#feature_color_id').val('');
			$('#feature_sex_id').val('');
			$('#feature_size_id').val('');
			if (chosen) 
			{
				$("#type_id").val('').trigger("liszt:updated");
				$("#breed_id").val('').trigger("liszt:updated");
			}
		}).on("change", "#type_id", function (e) {
			$.get(["index.php?controller=pjAdminListings&action=pjActionGetBreeds"].join(""), {type_id: $(this).val()}).done(function (data) {
				$('#pjPlBreedSelector').html(data);
				$('#breed_id').chosen();
			}).fail(function () {
				
			});
		});
	});
})(jQuery_1_8_2);