var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var datagrid = ($.fn.datagrid !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			gallery = ($.fn.gallery !== undefined),
			chosen = ($.fn.chosen !== undefined),
			dialog = ($.fn.dialog !== undefined),
			validate = ($.fn.validate !== undefined),
			tipsy = ($.fn.tipsy !== undefined),
			$frmCreateListing = $("#frmCreateListing"),
			$frmUpdateListing = $("#frmUpdateListing"),
			$dialogDeletePrice = $("#dialogDeletePrice"),
			$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 ($frmCreateListing.length > 0 && validate) {
			$frmCreateListing.validate({
				rules: {
					"listing_refid": {
						required: true,
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId"
					},
					"expire": {
						required: function(e){
							if($('#status').val() == 'E'){
								return true;
							}else{
								return false;
							}
						}
		            }
				},
				messages: {
					"listing_refid": {
						required: myLabel.field_required
					},
					"type_id": {
						required: myLabel.field_required
					},
					"status": {
						required: myLabel.field_required
					},
					"expire": {
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				onkeyup: false,
				ignore: ""
			});
		}
		
		if (chosen) {
			$("#user_id").chosen();
		}
		
		if($('.frm-filter-advanced').length > 0)
		{
			$("#country_id").chosen();
			$("#owner_id").chosen();
		}
		
		if ($dialogDeletePrice.length > 0 && dialog) {
			$dialogDeletePrice.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				buttons: {
					"Delete": function () {
						var $this = $(this),
							$link = $this.data("link"),
							$tr = $link.closest("tr");
						$.post("index.php?controller=pjAdminListings&action=pjActionDeletePrice", {
							id: $link.data("id")
						}).done(function () {
							$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
								$tr.remove();
								$this.dialog("close");
							});
						});
					},
					"Cancel": function () {
						$(this).dialog("close");
					}
				}
			});
		}
				
		$("#content").on("click", ".btnDeletePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			if ($dialogDeletePrice.length > 0 && dialog) {
				$dialogDeletePrice.data('link', $(this)).dialog("open");
			}
			return false;
		}).on("click", ".btnRemovePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tr = $(this).closest("tr");
			$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
				$tr.remove();
			});
			return false;
		}).on("click", "input[name='o_allow_paypal']", function (e) {
			if ($(this).is(":checked")) {
				$(".PayPal").show();
				$(".PayPal input").addClass('email required');
			} else {
				$(".PayPal").hide();
				$(".PayPal input").removeClass('email required');
			}
		}).on("click", "input[name='o_allow_authorize']", function (e) {
			if ($(this).is(":checked")) {
				$(".AuthorizeNet").show();
				$(".AuthorizeNet input").addClass('required');
			} else {
				$(".AuthorizeNet").hide();
				$(".AuthorizeNet input").removeClass('required');
			}
		}).on("click", "input[name='o_allow_bank']", function (e) {
			if ($(this).is(":checked")) {
				$(".BankAccount").show();
				$(".BankAccount textarea").addClass('required');
			} else {
				$(".BankAccount").hide();
				$(".BankAccount textarea").removeClass('required');
			}
		}).on("click", "#btnAddPrice", function (e) {
			var $tr,
				$tbody = $("#tblPrices tbody"),
				h = $tbody.find("tr:last").find("td:first").html(),
				i = (h === null) ? 0 : parseInt(h, 10);
			i = !isNaN(i) ? i : 0;
			$tr = $("#tblPricesClone").find("tbody").clone();
			$tbody.find(".notFound").remove();
			$tbody.append($tr.html().replace(/\{INDEX\}/g, i + 1));
		}).on("focusin", ".datepick", function (e) {
			var minDate, maxDate,
				$this = $(this),
				custom = {},
				o = {
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev")
			};
			switch ($this.attr("name")) {
			case "date_from[]":
				maxDate = $this.closest("tr").find(".datepick[name='date_to[]']").datepicker({
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev")
				}).datepicker("getDate");
				$this.closest("tr").find(".datepick[name='date_to[]']").datepicker("destroy").removeAttr("id");
				if (maxDate !== null) {
					custom.maxDate = maxDate;
				}
				break;
			case "date_to[]":
				minDate = $this.closest("tr").find(".datepick[name='date_from[]']").datepicker({
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev")
				}).datepicker("getDate");
				$this.closest("tr").find(".datepick[name='date_from[]']").datepicker("destroy").removeAttr("id");
				if (minDate !== null) {
					custom.minDate = minDate;
				}
				break;
			}
			$this.not('.hasDatepicker').datepicker($.extend(o, custom));
		}).on("click", ".btnGoogleMapsApi", function (e) {
			var $this = $(this);
			$.post("index.php?controller=pjAdminListings&action=pjActionGetGeocode", $(this).closest("form").serialize()).done(function (data) {
				if (data.code !== undefined && data.code == 200) {
					$("#lat").val(data.lat);
					$("#lng").val(data.lng);
					$this.siblings("span").hide().html("");
				} else {
					$this.siblings("span").html("<br>" + myLabel.address_not_found).show();
				}
			});
		}).on("click", ".pj-checkbox", function () {
			var $this = $(this);
			if ($this.find("input[type='checkbox']").is(":checked")) {
				$this.addClass("pj-checkbox-checked");
			} else {
				$this.removeClass("pj-checkbox-checked");
			}
		}).on("click", ".listing-tip", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("change", "input[name='is_best_deal']", function (e) {
			if ($(this).val() == '0') {
				$(".boxBd").hide();
			} else {
				$(".boxBd").show();
			}
		});
		
		if ($frmUpdateListing.length > 0 && validate) {
			$frmUpdateListing.validate({
				rules: {
					"listing_refid": {
						required: true,
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId&id=" + $frmUpdateListing.find("input[name='id']").val()
					},
					"expire": {
						required: function(e){
							if($('#status').val() == 'E'){
								return true;
							}else{
								return false;
							}
						}
		            }
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				onkeyup: false,
				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);
				    	}
				    }
				    $(".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');
						}
					});
				}
				
			});

			tinyMCE.init({
				// General options
				mode : "textareas",
				theme : "advanced",
				editor_selector : "mceEditor",
				editor_deselector : "mceNoEditor",
				plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

				// Theme options
				theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,cleanup",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				width: "570"
			});
	
			$("a.fancybox").fancybox();
			
			$(".field-int").spinner({
				min: 0
			});
			$('.pj-button-save').click(function() {
				tinyMCE.triggerSave();
			});
			if (chosen) {
				$("#owner_id").chosen();
				$("#country_id").chosen();
				$("#month").chosen();
			}
			
			if($('#flight_included').val() == 'F')
			{
				$('.flight-detail').css('display', 'none');
			}else{
				$('.flight-detail').css('display', 'block');
			}
			
			$('#flight_included').change(function(e){
				if($(this).val() == 'F')
				{
					$('.flight-detail').css('display', 'none');
				}else{
					$('.flight-detail').css('display', 'block');
				}
			});	
		}
		
		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 + "&query_string=" + encodeURIComponent("controller=pjAdminListings&action=pjActionUpdate&id=" + myGallery.foreign_id + "&tab_id=tabs-5"),
				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
			});
		}
		
		$(".spin").spinner({
			min: 0
		});
		
		if ($("#grid").length > 0 && datagrid) {
			
			function formatImage(val, obj) {
				var src = val ? val : 'app/web/img/backend/no_img.png';
				return ['<a href="index.php?controller=pjAdminListings&action=pjActionUpdate&id=', obj.id ,'"><img src="', src, '" style="width: 100px" /></a>'].join("");
			}
			
			function formatOwner(val, obj) {
				return ['<a href="index.php?controller=pjAdminUsers&action=pjActionUpdate&id=', obj.owner_id, '">', $.datagrid.wordwrap(obj.owner_name, 20, '<br>', true), '</a>'].join("");
			}
			
			function formatRefid(val, obj) {
				return $.datagrid.wordwrap(val, 25, '<br>', true);
			}
			function _formatDate(val, obj) {
				if(obj.added_by == 'owner')
				{
					if(obj.status == 'F')
					{
						return '';
					}else if(obj.status == 'E'){
						if(obj.is_expired == 1)
						{
							return '<span class="color-red">'+val+'</span>';
						}else{
							return val;
						}
					}else{
						return myLabel.unlimited;
					}
				}else{
					if(obj.status == 'E'){
						if(obj.is_expired == 1)
						{
							return '<span class="color-red">'+val+'</span>';
						}else{
							return val;
						}
					}
				}
			}
			var menuOpts = [  
			                  {text: myLabel.exp_date_plus_30, url: "index.php?controller=pjAdminListings&action=pjActionExpireListing&id={:id}", ajax: true, render: true},
				              {text: myLabel.view_enquiries, url: "index.php?controller=pjAdminEnquiries&action=pjActionIndex&listing_id={:id}"}
				           ];
			if (pjGrid.isEditor === true) {
				menuOpts = [  
				              {text: myLabel.view_enquiries, url: "index.php?controller=pjAdminEnquiries&action=pjActionIndex&listing_id={:id}"}
				           ];
			}
			var gridOpts = {
				buttons: [{type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				          {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}", title: myLabel.lblDelete},
				          {type: "menu", url: "#", text: myLabel.more, items:menuOpts}],
				columns: [{text: myLabel.image, type: "text", width: 110, sortable: false, editable: false, renderer: formatImage},
				          {text: myLabel.title, type: "text", sortable: true, width: 70, editable: true, renderer: formatRefid},
				          {text: myLabel.type, type: "text", sortable: true, editable: false},
				          {text: myLabel.owner, type: "text", sortable: true, editable: false, renderer: formatOwner, width: 100},
				          {text: myLabel.expire, type: "text", sortable: true, editable: false, width: 80, renderer: _formatDate
				          },
				          {text: myLabel.publish, type: "select", width: 80, sortable: true, editable: true, editableWidth: 80, options: [
					                                                                                     {label: myLabel.active, value: "T"}, 
					                                                                                     {label: myLabel.inactive, value: "F"},
					                                                                                     {label: myLabel.exp_date, value: "E"}
					                                                                                     ], applyClass: "pj-status"}
				          ],
				dataUrl: "index.php?controller=pjAdminListings&action=pjActionGetListing" + pjGrid.queryString,
				dataType: "json",
				fields: ['image', 'listing_title', 'type_title', 'owner_name', 'expire', 'status'],
				paginator: {
					actions: [
						{text: myLabel.delete_selected, url: "index.php?controller=pjAdminListings&action=pjActionDeleteListingBulk", render: true, confirmation: myLabel.delete_confirmation},
						{text: myLabel.published, url: "index.php?controller=pjAdminListings&action=pjActionStatusListing&status=T", render: true},
						{text: myLabel.not_published, url: "index.php?controller=pjAdminListings&action=pjActionStatusListing&status=F", render: true}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminListings&action=pjActionSaveListing&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			};
			if (pjGrid.isOwner === true) {
				function formatExtend(val, obj) {
					if(obj.status == 'F')
					{
						return ['<a class="pj-button" href="index.php?controller=pjAdminListings&action=pjActionPayment&id=', val, '">', myLabel.publish, '</a>'].join("");
					}if(obj.status == 'T'){
						return '';
					}else{
						return ['<a class="pj-button" href="index.php?controller=pjAdminListings&action=pjActionPayment&id=', val, '">', myLabel.extend_exp_date, '</a>'].join("");
					}
				}
				function _formatDate(val, obj){
					if(obj.status == 'F')
					{
						return myLabel.inactive;
					}if(obj.status == 'T'){
						return myLabel.unlimited;
					}else{
						if(obj.is_expired == 1)
						{
							return '<span class="color-red">'+val+'</span>';
						}else{
							return val;
						}
					}
				}
				gridOpts.buttons = [
				    {type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}", title: myLabel.lblEdit},
				    {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}", title: myLabel.lblDelete}
				];
				gridOpts.columns = [
				    {text: myLabel.image, type: "text", sortable: false, editable: false, renderer: formatImage, width: 100},
				    {text: myLabel.ref_id, type: "text", sortable: true, editable: true, width: 265},
					{text: myLabel.expire, type: "text", sortable: true, editable: false, renderer: _formatDate, width: 70},
					{text: "", type: "text", sortable: false, editable: false, renderer: formatExtend, width: 165}
				];
				gridOpts.fields = ['image', 'listing_refid', 'expire', 'id'];
				gridOpts.paginator.actions = [{text: myLabel.delete_selected, url: "index.php?controller=pjAdminListings&action=pjActionDeleteListingBulk", render: true, confirmation: myLabel.delete_confirm}];
			}
			
			var $grid = $("#grid").datagrid(gridOpts);
			
			$(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: "",
					is_featured: "",
					is_best_deal: "",
					listing_refid: "",
					country_id: "",
					type_id: "",
					owner_id: "",
					keyword: "",
					address_state: "",
					address_city: ""
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "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.is_featured = "";
				obj.is_best_deal = "";
				obj[$this.data("column")] = $this.data("value");
				$.extend(cache, obj);
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "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").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);
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "id", "ASC", content.page, content.rowCount);
				return false;
			}).on("reset", ".frm-filter-advanced", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(".pj-button-detailed").trigger("click");
				if (chosen) {
					$("#owner_id").val('').trigger("liszt:updated");
					$("#country_id").val('').trigger("liszt:updated");
				}
				$('#listing_refid').val('');
				$('#keyword').val('');
				$('#type_id').val('');
				$('#address_state').val('');
				$('#address_city').val('');
			}).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(),
					listing_refid: "",
					keyword: "",
					type_id: "",
					owner_id: "",
					country_id: "",
					address_state: "",
					address_city: ""
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminListings&action=pjActionGetListing", "id", "ASC", content.page, content.rowCount);
				return false;
			});
			
		}
		
		$(document).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("focusin", ".datetimepick", function (e) {

			var $this = $(this),
				o = {
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev"),
					timeFormat: $this.attr("lang"),
					stepMinute: 5
			};
			
			$(this).datetimepicker(o);
			
		}).on("change", "#status", function (e) {
			if($(this).val() == 'E')
			{
				$('#expiration_container').css('display', 'block');
			}else{
				$('#expiration_container').css('display', 'none');
			}
		}).on("change", "#owner_id", function (e) {
			if($(this).val() != '')
			{
				$('#show_contact').css('display', 'block');
				$('#owner_show').val('');
			}else{
				$('#show_contact').css('display', 'none');
			}
		});
	});
})(jQuery_1_8_2);