var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
function getCsrfToken(){var m=document.querySelector('meta[name="csrf-token"]');return m?m.getAttribute('content'):''}
(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),
			spinner = ($.fn.spinner !== undefined),
			tabs = ($.fn.tabs !== undefined),
			$frmCreateListing = $("#frmCreateListing"),
			$frmUpdateListing = $("#frmUpdateListing"),
			$frmImportListing = $("#frmImportListing"),
			$dialogDeletePrice = $("#dialogDeletePrice"),
			$gallery = $("#gallery"),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
					if($(ui.newPanel).prop('id') == 'tabs-5')
					{
						if($('#lat').val() != '' && $('#lng').val() != '')
						{
							initGMap(parseFloat($('#lat').val()), parseFloat($('#lng').val()));
						}
					}
				}
			};
		
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		if (tipsy) {
			$(".listing-tip").tipsy({
				offset: 1,
				opacity: 1,
				html: true,
				gravity: "nw",
				className: "tipsy-listing"
			});
		}
		$(".field-int").spinner({
			min: 0
		});
		
		function initGMap(lat, lng)
		{
			var latlng = new google.maps.LatLng(lat, lng);
			var mapOptions = {
					  center: latlng,
					  zoom: 12,
					  mapTypeId: google.maps.MapTypeId.ROADMAP
					};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			var marker = new google.maps.Marker({
								draggable: true,
								position: latlng,
								map: map
							});
			google.maps.event.addListener(marker, 'dragend', function (event) {
			    $('#lat').val(this.getPosition().lat());
			    $('#lng').val(this.getPosition().lng());
			});
		}
		
		if ($gallery.length > 0 && gallery) {
			$gallery.gallery({
				compressUrl: "index.php?controller=pjGallery&action=pjActionCompressGallery&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				getUrl: "index.php?controller=pjGallery&action=pjActionGetGallery&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				deleteUrl: "index.php?controller=pjGallery&action=pjActionDeleteGallery&csrf_token=" + getCsrfToken(),
				emptyUrl: "index.php?controller=pjGallery&action=pjActionEmptyGallery&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				rebuildUrl: "index.php?controller=pjGallery&action=pjActionRebuildGallery&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				resizeUrl: "index.php?controller=pjGallery&action=pjActionCrop&model=pjListing&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&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash,
				watermarkUrl: "index.php?controller=pjGallery&action=pjActionWatermarkGallery&model=pjListing&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash
			});
		}
		if (spinner) {
			$(".spin").spinner({
				min: 0,
				stop: function (event, ui) {
					var $this = $(this),
						$chained = $this.closest("p").find(".spin").not(this),
						name = $this.attr("name");
					if (name.match(/_from$/) !== null) {
						$chained.spinner("option", "min", $this.val());
					} else if (name.match(/_to$/) !== null) {
						$chained.spinner("option", "max", $this.val());
					}
				}
			});
		}

		if (chosen) {
			$("#owner_id").chosen();
			$("#country_id").chosen();
			$("#category_id").chosen();
		}
		if ($frmImportListing.length > 0 && validate) {
			
			$frmImportListing.validate({
				rules: {
					csv:{
						extension: "csv"
					}
				},
				messages: {
					csv:{
						extension: "Only csv files are allowed."
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
		}
		
		if ($frmCreateListing.length > 0 && validate) {
			$frmCreateListing.validate({
				rules: {
					"listing_refid": {
						required: true,
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId"
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				onkeyup: false,
				ignore: ""
			});
		}
		
		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&csrf_token=" + (typeof myLabel !== "undefined" ? myLabel.csrf_token : getCsrfToken()), {
							id: $link.data("id")
						}).done(function () {
							$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
								$tr.remove();
								$this.dialog("close");
							});
						});
					},
					"Cancel": function () {
						$(this).dialog("close");
					}
				}
			});
		}
		
		if ($("#grid").length > 0 && datagrid) {
			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("");
			}
			
			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);
			}
			var buttonOpts = [{type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}"},
					          {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}&csrf_token=" + myLabel.csrf_token},
					          {type: "menu", url: "#", text: myLabel.more, items:[
					              {text: myLabel.exp_date_plus_30, url: "index.php?controller=pjAdminListings&action=pjActionExpireListing&id={:id}", ajax: true, render: true}
					           ]}];
			if (pjGrid.isEditor === true) {
				buttonOpts = [{type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}"},
					          {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}&csrf_token=" + myLabel.csrf_token},
					        ];
			}
			var gridOpts = {
				buttons: buttonOpts,
				columns: [{text: myLabel.image, type: "text", sortable: false, editable: false, renderer: formatImage, width: 110},
				          {text: myLabel.ref_id, type: "text", sortable: true, editable: true, renderer: formatRefid, width: 100},
				          {text: myLabel.owner, type: "text", sortable: true, editable: false, renderer: formatOwner, width: 180},
				          {text: myLabel.expire, type: "text", sortable: true, editable: false, width: 80},
				          {text: myLabel.publish, type: "select", sortable: true, editable: true, editableWidth: 95, width: 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_refid', 'owner_name', 'expire', 'status'],
				paginator: {
					actions: [
						{text: myLabel.delete_selected, url: "index.php?controller=pjAdminListings&action=pjActionDeleteListingBulk&csrf_token=" + myLabel.csrf_token, render: true, confirmation: myLabel.delete_confirm},
						{text: myLabel.exp_date_plus_30, url: "index.php?controller=pjAdminListings&action=pjActionExpireListing", render: true, confirmation: myLabel.extend_confirm},
						{text: myLabel.published, url: "index.php?controller=pjAdminListings&action=pjActionStatusListing&status=T&csrf_token=" + myLabel.csrf_token, render: true},
						{text: myLabel.not_published, url: "index.php?controller=pjAdminListings&action=pjActionStatusListing&status=F&csrf_token=" + myLabel.csrf_token, render: true},
						{text: myLabel.exported, url: "index.php?controller=pjAdminListings&action=pjActionExportListing", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminListings&action=pjActionSaveListing&id={:id}&csrf_token=" + myLabel.csrf_token,
				select: {
					field: "id",
					name: "record[]"
				}
			};
			if (pjGrid.isOwner === true) {
				function formatExtend(val, obj) {
					return ['<a class="pj-button" href="index.php?controller=pjAdminListings&action=pjActionPayment&id=', val, '">', myLabel.extend_exp_date, '</a>'].join("");
				}
				
				gridOpts.buttons = [
				    {type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}"},
				    {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}&csrf_token=" + myLabel.csrf_token}
				];
				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: 240},
				    {text: myLabel.expire, type: "text", sortable: true, editable: false, width: 80},
					{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&csrf_token=" + myLabel.csrf_token, render: true, confirmation: myLabel.delete_confirm},
				                              {text: myLabel.exported, url: "index.php?controller=pjAdminListings&action=pjActionExportListing", ajax: false}
				                              ];
			}
			
			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: "",
					q: "",
					listing_refid: "",
					country_id: "",
					category_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[$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");
					$("#category_id").val('').trigger("liszt:updated");
					$("#country_id").val('').trigger("liszt:updated");
				}
				$('#listing_refid').val('');
				$('#keyword').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: "",
					owner_id: "",
					category_id: "",
					country_id: "",
					keyword: "",
					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;
			});
		}
		
		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(){
							if($('#status').val() == 'E')
							{
								return true;
							}else{
								return false;
							}
						}
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'expire')
					{
						error.insertAfter(element.parent().parent());
					}else{
						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);
				    		$("a.pj-form-langbar-item:first").trigger("click");
				    	}
				    };
				    $(".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({
				relative_urls : false,
				remove_script_host : false,
			    selector: "textarea.mceEditor",
			    theme: "modern",
			    browser_spellcheck : true,
			    contextmenu: false,
			    width: 570,
			    height: 350,
		    	plugins: [
			         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
			         "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
			         "save table contextmenu directionality emoticons template paste textcolor"
		        ],
		        toolbar: "insertfile undo redo | styleselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l      ink image | print preview media fullpage | forecolor backcolor emoticons"
			});
				
			$("a.fancybox").fancybox();
			
			if (chosen) {
				$("#owner_id").chosen();
				$("#country_id").chosen();
			}
			
		}
		
		$("#content").on("change", "#make_id", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var make_id = $(this).val();
			$.ajax({
				type: "GET",
				dataType: 'html',
				url: 'index.php?controller=pjAdminListings&action=pjActionGetModels&id=' + make_id,
				success: function (res) {
					$('#model_container').html(res);
					$("#model_id").chosen();
				}
			});
		}).on("focusin", ".datepick", 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-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("change", "#status", function (e) {
			if($(this).val() == 'E')
			{
				$('#expiration_container').css('display', 'block');
			}else{
				$('#expiration_container').css('display', 'none');
			}
		}).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("");
					initGMap(parseFloat(data.lat), parseFloat(data.lng));
				} else {
					$this.siblings("span").html("<br>" + myLabel.address_not_found).show();
				}
			});
		}).on("click", ".btnListingPaymentRenew", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $listing_id = $(this).attr('data-listing_id'),
				$period_id = $(this).attr('data-period_id');
			$('.paypalPaymentForm').html('');
			$.get("index.php?controller=pjAdminListings&action=pjActionGetPaymentForm&listing_id=" +$listing_id + "&period_id=" + $period_id).done(function (data) {
				$('.paypalPaymentForm').html(data);
				$('.modal-dialog').css("z-index", "9999");
			});
		});
		
		if($frmUpdateListing.length > 0)
		{
			var input = document.getElementById('address_content');         
		    var autocomplete = new google.maps.places.Autocomplete(input, {
		        types: ["geocode"]
		    });
		    
		    $frmUpdateListing.on("keypress", function(e) {
				var code = e.keyCode || e.which; 
				if (code  == 13) {
					var $focused = $(':focus');
					if($focused.attr('name') == 'address_content' )
					{
						e.preventDefault();
						return false;
					}
				}
			});
			
		    google.maps.event.addListener(autocomplete, 'place_changed', function() {
		        fillInAddress();
		    });	
		    function fillInAddress() 
		    {
		    	var place = autocomplete.getPlace();

		    	var address_arr = [];
		    	for (var i = 0; i < place.address_components.length; i++) 
		    	{
		    	    var addressType = place.address_components[i].types[0];
	    	    	if(addressType == 'administrative_area_level_1')
	    	    	{
	    	    		$('#address_state').val(place.address_components[i]['short_name']);
	    	    	}
		    	    if(addressType == 'locality')
			    	{    
	    	    		$('#address_city').val(place.address_components[i]['long_name']);
	    	    	}
			    	if(addressType == 'postal_code')
			    	{    
	    	    		$('#address_postcode').val(place.address_components[i]['short_name']);
	    	    	}
				    if(addressType == 'street_number')
				    {    
				    	address_arr.push(place.address_components[i]['short_name']);
			    	}
					if(addressType == 'route')
					{    
						address_arr.push(place.address_components[i]['long_name']);
			    	}
					if(addressType == 'country')
					{    
						var country = place.address_components[i]['long_name']; 
						$("#country_id").find("option:contains('"+country+"')").each(function(){
							if( $(this).text() == country ) {
								$(this).attr("selected","selected");
								$(this).trigger("liszt:updated");
							}
						});
			    	}
		    	}
		    	$('#lat').val(place.geometry.location.lat());
		    	$('#lng').val(place.geometry.location.lng());
		    	initGMap(parseFloat(place.geometry.location.lat()), parseFloat(place.geometry.location.lng()));
		    }
		}
	});
})(jQuery_1_8_2);