(function($) {
    "use strict";
	$(document).ready(function() {
		function initialize_map_new() {

				var latitude = jQuery('.location_lon').val();
				var longitude = jQuery('.location_lat').val()
				var latlng = jQuery("#cordinats2").val();
				if(latlng != undefined && latlng.length > 10) {
					var re = /\s*,\s*/;
					var arr = latlng.split(re);
					var myLatLng = {
						lat: parseFloat(arr[0]),
						lng: parseFloat(arr[1])
					};
					latitude = parseFloat(arr[0]);
					longitude = parseFloat(arr[1]);
				}
				var mapOptions = {
					center: new google.maps.LatLng(latitude, longitude),
					zoom: 17
				};
				var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
				if(latlng != undefined && latlng.length > 10) {
					var marker2 = new google.maps.Marker({
						position: myLatLng,
						map: map,
						draggable: true,
						title: ''
					});
					google.maps.event.addListener(marker2, "drag", function() {
						jQuery.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + marker2.getPosition().lat() + "," + marker2.getPosition().lng() + "&sensor=true_or_false", function(data, textStatus) {
							var adress1 = data.results[0].formatted_address;
							infowindow.setContent("<div><strong>" + adress1 + "</strong><br>" + data.results[1].formatted_address);
							jQuery("#formatted_address").val(adress1);
							jQuery("#location_lon").val(marker2.getPosition().lng());
							jQuery("#location_lat").val(marker2.getPosition().lat());
							jQuery("#cordinats2").val(marker2.getPosition().lat() + "," + marker2.getPosition().lng());
						});
						infowindow.open(map, marker);
					});
				}
				var input = (document.getElementById("pac-input"));
				var types = document.getElementById("type-selector");
				// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
				//map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
				var autocomplete = new google.maps.places.Autocomplete(input);
				autocomplete.bindTo("bounds", map);
				var infowindow = new google.maps.InfoWindow();
				var marker = new google.maps.Marker({
					map: map,
					draggable: true,
					anchorPoint: new google.maps.Point(0, -29)
				});
				google.maps.event.addListener(autocomplete, "place_changed", function() {
					infowindow.close();
					marker.setVisible(false);
					var place = autocomplete.getPlace();
					if(!place.geometry) {
						return;
					}
					if(place.geometry.viewport) {
						map.fitBounds(place.geometry.viewport);
					} else {
						map.setCenter(place.geometry.location);
						map.setZoom(17);
					}
					marker.setIcon(({
						url: place.icon,
						size: new google.maps.Size(71, 71),
						origin: new google.maps.Point(0, 0),
						anchor: new google.maps.Point(17, 34),
						scaledSize: new google.maps.Size(35, 35)
					}));
					marker.setPosition(place.geometry.location);
					marker.setVisible(true);
					jQuery("#location_lon").val(place.geometry.location.lng());
					jQuery("#location_lat").val(place.geometry.location.lat());
					var crtt = place.geometry.location.lat() + "," + place.geometry.location.lng();
					var foradre = place.formatted_address;
					jQuery("#cordinats2").val(crtt);
					jQuery("#cordinats2").trigger("change");
					jQuery("#formatted_address").val(foradre);
					var address = "";
					if(place.address_components) {
						address = [(place.address_components[0] && place.address_components[0].short_name || ""), (place.address_components[1] && place.address_components[1].short_name || ""), (place.address_components[2] && place.address_components[2].short_name || "")].join(" ");
					}
					infowindow.setContent("<div><strong>" + place.name + "</strong><br>" + address);
					infowindow.open(map, marker);
				});
				/*************************/
				google.maps.event.addListener(marker, "drag", function() {
					jQuery.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + marker.getPosition().lat() + "," + marker.getPosition().lng() + "&sensor=true_or_false", function(data, textStatus) {
						var adress1 = data.results[0].formatted_address;
						infowindow.setContent("<div><strong>" + adress1 + "</strong><br>" + data.results[1].formatted_address);
						jQuery("#formatted_address").val(adress1);
						jQuery("#location_lon").val(marker.getPosition().lng());
						jQuery("#location_lat").val(marker.getPosition().lat());
						jQuery("#cordinats2").val(marker.getPosition().lat() + "," + marker.getPosition().lng());
					});
					infowindow.open(map, marker);
				});

				function setupClickListener(id, types) {
					var radioButton = document.getElementById(id);
					google.maps.event.addDomListener(radioButton, "click", function() {
						autocomplete.setTypes(types);
					});
				}
		
		}
		initialize_map_new();

		function save_user_settings() {
			if(typeof user_avatar_loaded !== 'undefined') {
				userFiles = user_avatar_loaded;
				$('.file_attachments_avatar').val(userFiles);
			}
			if(typeof user_banner_loaded !== 'undefined') {
				userFiles = user_banner_loaded;
				$('.file_attachments_banner').val(userFiles);
			}
			/** Add Images **/
			var userFiles = [];
			if(typeof jwsUserFilesLoaded !== 'undefined') {
				userFiles = jwsUserFilesLoaded;
				jQuery('.file_attachments').val(jwsUserFilesLoaded);
			}
			var jwsFeaturedID = 0;
			var orderChanged = false;
			var jws_timeout;
			$('.jws_add_car_form input[type="file"]').on('change', function() {
				var jwsDontChangeFeatured = false;
				$('.jws-image-preview, .jws-placeholder-generated').not('.jws-placeholder-generated-php, .jws-placeholder-generated-php .jws-image-preview, .jws-placeholder-generated-php').remove();
				var files = $(this)[0].files;
				for(var key in files) {
					if(typeof(files[key]) === 'object') {
						userFiles.push(files[key]);
					}
				}
				var jwsFeaturedSet = 0;
				if(userFiles) {
					[].forEach.call(userFiles, readAndPreview);
				}

				function readAndPreview(file, index) {
					if(typeof(userFiles[0]) === 'number') {
						jwsDontChangeFeatured = true;
					}
					var currentFiles = index;
					// Make sure `file.name` matches our extensions criteria
					if(/\.(jpe?g|png)$/i.test(file.name)) {
						var reader = new FileReader();
						reader.addEventListener("load", function() {
							jwsFeaturedSet++;
							if(userFiles[currentFiles]) {
								var $jws_append_placeholder_start = '<div class="jws-placeholder jws-placeholder-generated"><div class="inner">';
								var $jws_append_placeholder_end = '</div></div>';
								var jwsDelete = '<i class="remove jws-icon-icon_close" data-id="' + currentFiles + '"></i>'
								if(jwsFeaturedSet == 1 && !jwsDontChangeFeatured) {
									jwsFeaturedID = currentFiles;
									$('.jws-media-car-main-input').append('<div class="jws-image-preview" data-id="' + currentFiles + '" style="background:url(' + this.result + ')"></div>');
								}
								$('.jws-placeholder-native').remove();
								$('.jws-media-car-gallery').append($jws_append_placeholder_start + '<div class="jws-image-preview" data-media = "' + file.name + '" data-id="' + currentFiles + '" style="background-image:url(' + this.result + ')">' + jwsDelete + '</div>' + $jws_append_placeholder_end);
							}
							/*Enable droppadble on new elements again*/
							$('.jws-media-car-gallery .jws-placeholder').droppable({
								drop: jwsDroppableEvent
							});
						}, false);
						reader.readAsDataURL(file);
					}
				}
				jws_resort_array();
			});
			$(document).on('mouseenter', '.jws-media-car-gallery .jws-placeholder .inner .jws-image-preview .remove', function() {
				$(this).closest('.inner').addClass('deleting');
			});
			$(document).on('mouseleave', '.jws-media-car-gallery .jws-placeholder .inner .jws-image-preview .remove', function() {
				$(this).closest('.inner').removeClass('deleting');
			});
			$(document).on('click', '.jws-media-car-gallery .jws-placeholder .inner .jws-image-preview .remove', function() {
				var jws_id = $(this).attr('data-id');
				var jws_length = 0;
				delete userFiles[jws_id];
				$('.jws-placeholder .inner').removeClass('deleting');
				$(this).closest('.jws-placeholder').remove();
				$(userFiles).each(function(i, e) {
					if(typeof(e) !== 'undefined') {
						jws_length++;
					}
				});
				if(jws_length == 0) {
					$('.jws-media-car-main-input .jws-image-preview').remove();
					$('.jws-add-media-car').removeClass('hasImages');
					var defaultPlaceholders = '';
					for(var i = 0; i < 4; i++) {
						defaultPlaceholders += '<div class="jws-placeholder jws-placeholder-native"><div class="inner"><i class="jws-icon-add"></i></div></div>';
					}
					$('.jws-media-car-gallery').append(defaultPlaceholders);
				}
				if(jwsFeaturedID == jws_id) {
					var changeFeatured = $('.jws-media-car-gallery .jws-placeholder:nth-child(1)');
					jwsFeaturedID = changeFeatured.find('.jws-image-preview').attr('data-id');
					$('.jws-media-car-main-input .jws-image-preview').remove();
					$(changeFeatured).find('.jws-image-preview').clone().appendTo('.jws-media-car-main-input');
				}
				jws_resort_array();
			});
			/*Droppable*/
			$(document).on("mouseenter", '.jws-media-car-gallery .jws-placeholder .inner .jws-image-preview', function(e) {
				var item = $(this);
				item.draggable({
					revert: 'invalid',
					helper: "clone"
				})
			});
			$('.jws-media-car-gallery .jws-placeholder').droppable({
				drop: jwsDroppableEvent
			});

			function jwsDroppableEvent(event, ui) {
				var dragFromPreview = ui.draggable;
				var dragFrom = dragFromPreview.closest('.inner');
				var dragTo = $(this).find('.inner');
				var dragToPreview = dragTo.find('.jws-image-preview');
				if(dragFromPreview.length > 0 && dragToPreview.length > 0 && dragTo.length > 0 && dragFrom.length > 0) {
					if(dragFrom[0] != dragTo[0]) {
						var dragFromId = dragFromPreview.data('id');
						var dragToId = dragToPreview.data('id');
						dragFromPreview.clone().appendTo(dragTo);
						dragToPreview.clone().appendTo(dragFrom);
						var droppingInIndex = dragTo.closest('.jws-placeholder').index();
						var draggingIndex = dragFromPreview.closest('.jws-placeholder').index();
						/*If placed in first pos*/
						if(droppingInIndex === 0) {
							$('.jws-media-car-main-input .jws-image-preview').remove();
							dragFromPreview.clone().appendTo('.jws-media-car-main-input');
							jwsFeaturedID = dragFromPreview.data('id');
						}
						/*If moving from first place*/
						if(draggingIndex === 0) {
							$('.jws-media-car-main-input .jws-image-preview').remove();
							dragToPreview.clone().appendTo('.jws-media-car-main-input');
							jwsFeaturedID = dragToPreview.data('id');
						}
						orderChanged = true;
						dragFromPreview.remove();
						dragToPreview.remove();
						jws_resort_array();
						orderChanged = true;
					}
				}
			}

			function jws_resort_array() {
				jws_timeout = setTimeout(function() {
					var tmpArr = [];
					var value = [];
					$('.jws-placeholder.jws-placeholder-generated').each(function(i, e) {
						/*Get old id*/
						var oldId = $(this).find('.jws-image-preview').attr('data-id');
						var media = $(this).find('.jws-image-preview').attr('data-media');
						/*Set new ids to preview and to delete icon*/
						$(this).find('.jws-image-preview').attr('data-id', i);
						$(this).find('.jws-image-preview .remove').attr('data-id', i);
						value[i] = media;
						if(typeof(userFiles[oldId]) !== 'undefined') {
							tmpArr[i] = userFiles[oldId];
						}
					});
					jQuery('.file_attachments').val(value);
					jwsFeaturedID = 0;
					userFiles = tmpArr;
				}, 100);
			}
			$('.edit-account .user_picked_files').on('change', function() {
				var jwsDontChangeFeatured = false;
				var media = $(this).find('.jws-item').attr('data-media');
				var parents = $(this).parents('.form-row');
				parents.find('.jws_uploaded_files .jws-item').remove();
				parents.find('input[type="hidden"]').val(media);
				var files = $(this)[0].files;
				var jwsFeaturedSet = 0;
				if(files) {
					[].forEach.call(files, readAndPreview);
				}

				function readAndPreview(file, index) {
					if(typeof(files[0]) === 'number') {
						jwsDontChangeFeatured = true;
					}
					var currentFiles = index;
					// Make sure `file.name` matches our extensions criteria
					if(/\.(jpe?g|png)$/i.test(file.name)) {
						var reader = new FileReader();
						reader.addEventListener("load", function() {
							jwsFeaturedSet++;
							if(files[currentFiles]) {
								var $jws_append_placeholder_start = '<div class="jws-placeholder jws-placeholder-generated"><div class="inner">';
								var $jws_append_placeholder_end = '</div></div>';
								var jwsDelete = '<i class="remove jws-icon-icon_close" data-media = "' + file.name + '" data-id="' + currentFiles + '"></i>'
								if(jwsFeaturedSet == 1 && !jwsDontChangeFeatured) {
									jwsFeaturedID = currentFiles;
									parents.find('.jws_uploaded_files').append('<div class="jws-item" data-media = "' + file.name + '" style="background-image: url(' + this.result + ')">' + jwsDelete + '</div>');
								}
							}
						}, false);
						reader.readAsDataURL(file);
					}
				}
			});
			$(document).on('click', '.jws_uploaded_files .remove', function() {
				$(this).closest('.jws_uploaded_files').prev(".upload-file").find('input[type="hidden"]').val('');
				$(this).closest('.jws_uploaded_files .jws-item').remove();
			});
			$('.jws-edit-account-form.edit-account').submit(function(e) {
				e.preventDefault();
				jws_resort_array();
				var formData = new FormData();
				jQuery('.jws-submit-car').addClass('form-loader');
				/*Add image*/
				formData.append('profile_img', $('input[name="profile_img"]')[0].files[0]);
				formData.append('profile_banner', $('input[name="profile_banner"]')[0].files[0]);
				jQuery.each(userFiles, function(key, value) {
					formData.append('dealer_images[' + key + ']', value);
				});
				/*Add text fields*/
				var formInputs = $(this).serializeArray();
				for(var key in formInputs) {
					if(formInputs.hasOwnProperty(key)) {
						formData.append(formInputs[key]['name'], formInputs[key]['value']);
					}
				}
				formData.append('action', 'update_account_details');
				$.ajax({
					type: "POST",
					url: jws_script.ajax_url,
					dataType: 'json',
					context: this,
					data: formData,
					contentType: false,
					processData: false,
					beforeSend: function() {
						jQuery('.jws-notes').slideUp();
					},
					success: function(data) {
						if(data.status === true) {
							var html = '<ul class="jws-dealer-note red"><li>' + data.error_msg + '</li></ul>';
							jQuery('.jws-notes').html(html).slideDown();
						} else {
							var html = '<ul class="jws-dealer-note green"><li>' + data.error_msg + '</li></ul>';
							jQuery('.jws-notes').html(html).slideDown();
							window.location.href = data.redirect;
						}
						jQuery('.jws-submit-car').removeClass('form-loader');
					}
				});
			});
		};
		save_user_settings();
	});
})(jQuery);