var 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: 530,
		    height: 250,
		    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();
		    	});
		    }
		});
		
		tinymce.init({
		    selector: "textarea.mceTermsEditor",
		    plugins: [
		        "advlist autolink lists link image charmap print preview anchor",
		        "searchreplace visualblocks code fullscreen",
		        "insertdatetime media table contextmenu paste"
		    ],
		    width: 700,
		    height: 250,
		    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();
		    	});
		    }
		});
	}
	$(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"),
			$dialogDeletePrice = $("#dialogDeletePrice"),
			$dialogCopyBookings = $("#dialogCopyBookings"),
			$dialogCopyTerms = $("#dialogCopyTerms"),
			$dialogCopyEmails = $("#dialogCopyEmails"),
			$gallery = $("#gallery"),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
					if($(ui.newPanel).prop('id') == 'tabs-6')
					{
						if($('#lat').val() != '' && $('#lng').val() != '')
						{
							initGMap(parseFloat($('#lat').val()), parseFloat($('#lng').val()));
						}
					}
				}
			};
		
		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"
					}
				},
				messages: {
					"listing_refid": {
						remote: myLabel.vr_duplicate_ref_id
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				onkeyup: false,
				ignore: ".ignore"
			});
			
			if (chosen) {
				$("#owner_id").chosen();
			}
		}
		
		if (chosen) {
			$("#user_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");
					}
				}
			});
		}
		
		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());
			});
		}
		
		$("#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"),
					dayNames: ($this.data("day")).split(","),
				    monthNames: ($this.data("months")).split(","),
				    monthNamesShort: ($this.data("shortmonths")).split(","),
				    dayNamesMin: ($this.data("daymin")).split(","),
				};
			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("");
					initGMap(parseFloat(data.lat), parseFloat(data.lng));
				} 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;
		});
		
		if ($frmUpdateListing.length > 0 && validate) {
			var validator = $frmUpdateListing.submit(function() {
				// update underlying textarea before submit validation
				tinymce.activeEditor.editorManager.triggerSave();
			}).validate({
				rules: {
					"listing_refid": {
						required: true,
						remote: "index.php?controller=pjAdminListings&action=pjActionCheckRefId&id=" + $frmUpdateListing.find("input[name='id']").val()
					}
				},
				messages: {
					"listing_refid": {
						remote: myLabel.vr_duplicate_ref_id
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				onkeyup: false,
				ignore: "", //Will validate hidden tabs (not active)
				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");
				    	}
				    }
				}
			});
	
			$("a.fancybox").fancybox();
			
			if (spinner) {
				$("input[name='listing_bedrooms'], input[name='listing_bathrooms'], input[name='listing_adults'], input[name='listing_children']").spinner({
					min: 0
				});
				$(".field-int").spinner({
					min: 0,
					stop: function (event, ui) {
						var $this = $(this),
							name = $this.attr("name");
						if (name == "o_min_booking_lenght") {
							$("input[name='o_max_booking_lenght']").spinner("option", "min", $this.val());
						} else if (name == "o_max_booking_lenght") {
							$("input[name='o_min_booking_lenght']").spinner("option", "max", $this.val());
						}
					}
				});
				$("input[name='o_deposit_payment']").spinner("option", {
					min: 0,
					max: 100,
					step: 0.01,
					numberFormat: "n"
				});
				$("input[name='o_tax_payment']").spinner("option", {
					step: 0.01,
					numberFormat: "n"
				});
				$("input[name='o_min_booking_lenght'], input[name='o_max_booking_lenght']").spinner("option", "min", 1);
			}
			
			if (chosen) {
				$("#owner_id").chosen();
				$("#country_id").chosen();
			}
		}
		
		if (tipsy) {
			$(".listing-tip").tipsy({
				offset: 1,
				opacity: 1,
				html: true,
				gravity: "nw",
				className: "tipsy-listing"
			});
		}
		
		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=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&foreign_id=" + myGallery.foreign_id,
				watermarkUrl: "index.php?controller=pjGallery&action=pjActionWatermarkGallery&foreign_id=" + myGallery.foreign_id
			});
		}
		
		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 ($("#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 _formatStatus(val, obj) 
			{
				if(obj.status == 'F')
				{
					return '<span class="pj-table-cell-label pj-status pj-status-F">'+myLabel.hidden+'</span>';
				}else if(obj.status == 'E'){
					if(obj.is_expired == 1)
					{
						return '<span class="pj-table-cell-label pj-status b5 pj-status-E">'+myLabel.exp_date+'</span><span class="red">'+obj.expire+'</span>';
					}else{
						return '<span class="pj-table-cell-label pj-status b5 pj-status-E">'+myLabel.exp_date+'</span><span>'+obj.expire+'</span>';
					}
				}else{
					return '<span class="pj-table-cell-label pj-status b10 pj-status-T">'+myLabel.active+'</span>';
				}
			}
			var gridOpts = {
				buttons: [{type: "edit", url: "index.php?controller=pjAdminListings&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminListings&action=pjActionDeleteListing&id={:id}"},
				          {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},
				              {text: myLabel.view_reservations, url: "index.php?controller=pjAdminReservations&action=pjActionIndex&listing_id={:id}"}
				           ]}],
				columns: [{text: myLabel.image, type: "text", sortable: false, editable: false, renderer: formatImage, width: 100},
				          {text: myLabel.ref_id, type: "text", sortable: true, editable: false, renderer: formatRefid, width: 140},
				          {text: myLabel.latest_reservation, type: "text", sortable: false, editable: false, width: 200},
				          {text: myLabel.publish, type: "text", sortable: true, editable: false, renderer: _formatStatus, width: 120}
				          ],
				dataUrl: "index.php?controller=pjAdminListings&action=pjActionGetListing" + pjGrid.queryString,
				dataType: "json",
				fields: ['image', 'listing_refid', 'latest', 'status'],
				paginator: {
					actions: [
						{text: myLabel.delete_selected, url: "index.php?controller=pjAdminListings&action=pjActionDeleteListingBulk", 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", 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) {
					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}"}
				];
				gridOpts.columns = [
				    {text: myLabel.image, type: "text", sortable: false, editable: false, renderer: formatImage, width: 100},
				    {text: myLabel.ref_id, type: "text", sortable: true, editable: false, width: 110},
				    {text: myLabel.latest_reservation, type: "text", sortable: false, editable: false},
					{text: myLabel.expire, type: "text", sortable: true, editable: false, width: 70},
					{text: "", type: "text", sortable: false, editable: false, renderer: formatExtend, width: 165}
				];
				gridOpts.fields = ['image', 'listing_refid', 'latest', '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: "",
					listing_refid: "",
					country_id: "",
					type_id: "",
					user_id: "",
					adults_from: "",
					adults_to: "",
					children_from: "",
					children_to: "",
					bedrooms_from: "",
					bedrooms_to: "",
					bathrooms_from: "",
					bathrooms_to: "",
					floor_area_from: "",
					floor_area_to: ""
				});
				$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, {
					q: $(".frm-filter").find("input[name='q']").val()
				});
				$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) {
				$(".pj-button-detailed").trigger("click");
				if (chosen) {
					$("#user_id").val('').trigger("liszt:updated");
				}
			}).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: "",
					adults_from: "",
					adults_to: "",
					children_from: "",
					children_to: "",
					type_id: "",
					bedrooms_from: "",
					bedrooms_to: "",
					bathrooms_from: "",
					bathrooms_to: "",
					floor_area_from: "",
					floor_area_to: ""
				});
				$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("change", "#status", function (e) {
			if($(this).val() == 'E')
			{
				$('#expiration_container').show();
			}else{
				$('#expiration_container').hide();
			}
		}).on("click", ".pjVrBtnCopyBookings", function (e) {
			if ($dialogCopyBookings.length > 0 && dialog) {
				var to_id = $(this).attr('data-id'),
					from_id = $('select[name="from_booking_id"]').val();
				$dialogCopyBookings.data('from', from_id).data('to', to_id).dialog("open");
			}
		}).on("click", ".pjVrBtnCopyTerms", function (e) {
			if ($dialogCopyTerms.length > 0 && dialog) {
				var to_id = $(this).attr('data-id'),
					from_id = $('select[name="from_term_id"]').val();
				$dialogCopyTerms.data('from', from_id).data('to', to_id).dialog("open");
			}
		}).on("click", ".pjVrBtnCopyEmails", function (e) {
			if ($dialogCopyEmails.length > 0 && dialog) {
				var to_id = $(this).attr('data-id'),
					from_id = $('select[name="from_email_id"]').val();
				$dialogCopyEmails.data('from', from_id).data('to', to_id).dialog("open");
			}
		});
		
		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()));
		    }
		}
		
		if ($dialogCopyBookings.length > 0 && dialog) 
		{
			$dialogCopyBookings.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[vrApp.locale.button.yes] = function () {
						var from_id = $dialogCopyBookings.data('from'),
							to_id = $dialogCopyBookings.data('to');
						$.ajax({
							type: "GET",
							dataType: "json",
							url: "index.php?controller=pjAdminListings&action=pjActionCopy&tab_id=tabs-8&from_id="+from_id+"&to_id="+to_id,
							success: function (res) {
								window.location.href="index.php?controller=pjAdminListings&action=pjActionUpdate&id="+to_id+"&tab_id=tabs-8&err=AL11";
							}
						});
						$dialogCopyBookings.dialog("close");
					};
					buttons[vrApp.locale.button.no] = function () {
						$dialogCopyBookings.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		
		if ($dialogCopyTerms.length > 0 && dialog) 
		{
			$dialogCopyTerms.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[vrApp.locale.button.yes] = function () {
						var from_id = $dialogCopyTerms.data('from'),
							to_id = $dialogCopyTerms.data('to');
						$.ajax({
							type: "GET",
							dataType: "json",
							url: "index.php?controller=pjAdminListings&action=pjActionCopy&tab_id=tabs-9&from_id="+from_id+"&to_id="+to_id,
							success: function (res) {
								window.location.href="index.php?controller=pjAdminListings&action=pjActionUpdate&id="+to_id+"&tab_id=tabs-9&err=AL12";
							}
						});
						$dialogCopyTerms.dialog("close");
					};
					buttons[vrApp.locale.button.no] = function () {
						$dialogCopyTerms.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		
		if ($dialogCopyEmails.length > 0 && dialog) 
		{
			$dialogCopyEmails.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[vrApp.locale.button.yes] = function () {
						var from_id = $dialogCopyEmails.data('from'),
							to_id = $dialogCopyEmails.data('to');
						$.ajax({
							type: "GET",
							dataType: "json",
							url: "index.php?controller=pjAdminListings&action=pjActionCopy&tab_id=tabs-10&from_id="+from_id+"&to_id="+to_id,
							success: function (res) {
								window.location.href="index.php?controller=pjAdminListings&action=pjActionUpdate&id="+to_id+"&tab_id=tabs-10&err=AL13";
							}
						});
						$dialogCopyEmails.dialog("close");
					};
					buttons[vrApp.locale.button.no] = function () {
						$dialogCopyEmails.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
	});
})(jQuery_1_8_2);