var mapbig;
var geocoder;
var markerbig;
var LatLng;
var mapOptions;
var latitude;
var longitude;
var is_mobile_map=false;
var userAddress = "";
var address_changed = 0;
var service;
var cityBoundries = {
"Ahmedabad" : "23.022505,72.571365",
"Aurangabad" : "19.876165,75.343315",
"Bangalore" : "12.971599,77.594566",
"Chennai" : "13.082881,80.276002",
"Gurgaon" : "28.477743,77.067818",
"Hyderabad" : "17.413399,78.460046",
"Kakinada" : "16.9891,82.2475",
"Kharghar" : "19.0473,73.0699",
"Mumbai" : "19.076,72.8777",
"Nagpur" : "21.1458,79.0882",
"Nashik" : "19.9975,73.7898",
"Navi Mumbai" : "19.033,73.0297",
"Navsari" : "20.9467,72.952",
"Powai" : "19.1197,72.9052",
"Pune" : "18.5204,73.8567",
"Rajkot" : "22.3039,70.8022",
"Surat" : "21.17024,72.8311",
"Thane" : "19.2183,72.9781",
"Vadodara" : "22.3072,73.1812",
"Valsad" : "20.5992,72.9342",
"Vapi" : "20.3893,72.9106",
"Vijayawada" : "16.5062,80.648",
"Vishakapatnam" : "17.6868,83.2185",
"AHMEDABAD" : "23.022505,72.571365",
"AURANGABAD" : "19.876165,75.343315",
"BANGALORE" : "12.971599,77.594566",
"CHENNAI" : "13.082881,80.276002",
"GURGAON" : "28.477743,77.067818",
"HYDERABAD" : "17.413399,78.460046",
"KAKINADA" : "16.9891,82.2475",
"KHARGHAR" : "19.0473,73.0699",
"MUMBAI" : "19.076,72.8777",
"NAGPUR" : "21.1458,79.0882",
"NASHIK" : "19.9975,73.7898",
"NAVI MUMBAI" : "19.033,73.0297",
"NAVSARI" : "20.9467,72.952",
"POWAI" : "19.1197,72.9052",
"PUNE" : "18.5204,73.8567",
"RAJKOT" : "22.3039,70.8022",
"SURAT" : "21.17024,72.8311",
"THANE" : "19.2183,72.9781",
"VADODARA" : "22.3072,73.1812",
"VALSAD" : "20.5992,72.9342",
"VAPI" : "20.3893,72.9106",
"VIJAYAWADA" : "16.5062,80.648",
"VISHAKAPATNAM" : "17.6868,83.2185",
};

function selectCityByName (cityName) {
	console.log("selectCityByName called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=selectCityByName_called","");
	var fname = getFormName();
	var cityEle = document.forms[fname].cityid;
	for (var i = 0 ; i < cityEle.length ; i++) {
		if ("" != cityName && cityName == cityEle[i].label) {
			cityEle[i].selected=true;
			break;
		}
	}
}

function geocodeCity(/*geocoder, resultMap*/) {
	//navigator.sendBeacon("/log.php?apply_for_new_connection=geocodeCity_called","");
	console.log("geocodeCity called");
	var cityName = document.getElementById('city').value;
	if ("" !== cityName) {
		var latlongarr = cityBoundries[cityName].split(',');
		console.log("latlongarr " + latlongarr);
		var geolocation = {
			lat: parseFloat(latlongarr[0]),
			lng: parseFloat(latlongarr[1])
		};
		var circle = new google.maps.Circle({
			center : geolocation,
			radius : 50000/*position.coords.accuracy*/
		});
	}
}

$("#address").change(function(){
	console.log("$(\"#address\").change called");
	address_changed = 1;
	console.log("address_changed " + address_changed);
	//navigator.sendBeacon("/log.php?apply_for_new_connection=address.change_called","");
	if (is_mobile_map) {
		var formname = document.getElementById("customer_location_sm").form.id; //document.forms[$('#customer_location_sm').attr("data-form")].id;
	}
});

/*
$("#address").blur(function() {
	console.log("$(\"#address\").blur called");
	console.log("address_changed " + address_changed);
	userAddress = $("#address").val();
	var fullAddress = userAddress;
	if ("" != $("#area1").val()) {
		fullAddress = fullAddress + ", " + $("#area1").val() 
	}
	if ("" != $("#city").val()) {
		fullAddress = fullAddress + ", " + $("#city").val() 
	}
	if (address_changed == 1) {
		addressGeocode(fullAddress);
	}
	navigator.sendBeacon("/log.php?apply_for_new_connection=address_on_blur_called","");
});
*/

function addressGeocode (userAddress) {
	console.log("addressGeocode called");
	if ("" != $("#address").val()) {
		if(!geocoder) {
			return;
		}
		geocoder.geocode({
			'address' : userAddress
		}, function(results, status) {
			if (status === 'OK') {
				//mapbig.setCenter(results[0].geometry.location);
				//markerbig.setPosition(results[0].geometry.location);
				$("#latitude").val(markerbig.getPosition().lat());
				$("#longitude").val(markerbig.getPosition().lng());
			} else {
			}
		});
		//navigator.sendBeacon("/log.php?apply_for_new_connection=addressGeocode_called_geocode","");
	}
}

function search_address() {
	console.log("search_address called");
	navigator.sendBeacon("/log.php?apply_for_new_connection=search_address_called","");
	var input = document.getElementById("address");
	geocoder = new google.maps.Geocoder;
	
	/*map initializing code - starts*/
	var mapElement;
	if ($("#mapbig").is(":visible")) {
		mapElement=document.getElementById("mapbig");
	} else {
		mapElement=document.getElementById("mapsmall");
		is_mobile_map=true;
	}
	latitude = 22.828828;
	longitude = 79.609303;
	LatLng = new google.maps.LatLng(latitude, longitude);
	mapOptions = {
		center : LatLng,
		zoom : 4
	};
	mapbig = new google.maps.Map(mapElement,mapOptions);
	markerbig = new google.maps.Marker({
		position : LatLng,
		map : mapbig,
		draggable : true
	});
	google.maps.event.addListener(markerbig, 'dragend', function(e) {
		$("#latitude").val(this.getPosition().lat());
		$("#longitude").val(this.getPosition().lng());
		getFormattesdMapAddressByLatLong (this.getPosition().lat(), this.getPosition().lng());
		_ga_send_(["apply_for_new_connection", "map_marker_location changed", "dragged"]);
		navigator.sendBeacon("/log.php?map_marler_location_change=dragged","");
	});
    google.maps.event.addListener(mapbig, "click", function (evt) {
        markerbig.setPosition(evt.latLng);
		$("#latitude").val(markerbig.getPosition().lat());
		$("#longitude").val(markerbig.getPosition().lng());
		getFormattesdMapAddressByLatLong (markerbig.getPosition().lat(), markerbig.getPosition().lng());
		_ga_send_(["apply_for_new_connection", "map_marker_location changed", "clicked"]);
		navigator.sendBeacon("/log.php?map_marler_location_change=clicked","");
    });
    var controlDivBig = document.createElement('div');
    //var controlDivSmall = document.createElement('div');
    addYourLocationButton(controlDivBig);
    controlDivBig.index = 1;
    //addYourLocationButton(controlDivSmall);
    //controlDivSmall.index = 2;
    mapbig.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDivBig);
    //mapsmall.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDivSmall);
	/*map initializing code - ends*/
	if (is_mobile_map) {
	    var centerControlDiv = document.getElementById('closemap');
	    centerControlDiv.index = 3;
	    mapbig.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(centerControlDiv);
	}
	geocodeCity();
}
function openMap () {
	console.log("openMap called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=search_address_called","");
	if (is_mobile_map && "Show Map" === $("#customer_location_sm").val()) {
		return;
	} else {
		getCurrentLocation ();
	}
}
function getCurrentLocation () {
	console.log("getCurrentLocation called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=getCurrentLocation_called","");
	var startPos;
	var geoSuccess = function(position) {
		startPos = position;
		latitude = startPos.coords.latitude;
		longitude = startPos.coords.longitude;
		//alert(latitude+","+longitude);
		var city = document.getElementById("city").value;
		var dataTbP = '{"accountNo":"410624","securityKey":"b095f2869549ec9b7736f1d7d3242d6c","input":{"latitude":"'+latitude+'","longitude":"'+longitude+'"}}';
		console.log(dataTbP);
		$.ajax({
			url : "https://mapp.youbroadband.in/youbb/stage/execute/raw/getBuildingDetailsFromLatLong",
			contentType : "application/json; charset=utf-8",
			dataType : "json",
			type : "POST",
			data : dataTbP,
			success : function(response) {
				//console.log(JSON.stringify(response));
				var data = response["data"];
				var response = data["response"];
				var building_array = response;
				var results_html = [];
				var autocomplete_results = document.querySelector('.autocomplete-results');
				var autocomplete_input = document.getElementById('address');
				if(response.length>0){
					$("#place_details").val(JSON.stringify(response));
					$("#search_keyword").val('');
					$("#landmark").val(response[0]["landmark"]);
					$("#building_name").val(response[0]["building_name"]);
					$("#city").val(response[0]["city"]);
					$("#latitude").val(latitude);
					$("#longitude").val(longitude);
					$("#browser_latitude").val(latitude);
					$("#browser_longitude").val(longitude);
					$("#address").val(response[0]["address"]);
					$("#address").focus();
				}else{
					getFormattesdAddressByLatLong (latitude, longitude);
				}
			}
		});
	}
	var geoError = function(err) { 
		console.error("Error [code:'"+err.code+"', message:'"+err.message+"']");
		if (err.code == 1) {
			alert("We could not auto detect your location, please select your location manually. \n \nGPS access was denied please check device and browser location settings.");
		} else {
			//alert("Sorry, "+err.message);
		}
	}
	var locationOptions = {};
	//if(deviceInfo.raw.browser.isIE && parseInt(deviceInfo.browser_version) == 11 &&  deviceInfo.os.isWindows10) {
	            locationOptions = {
	                enableHighAccuracy: false,
	                  maximumAge: 50000
	            }
	//    }
	navigator.geolocation.getCurrentPosition(geoSuccess,geoError,locationOptions);
	_ga_send_(["apply_for_new_connection", "current_locaiton_clicked", ""]);
	//navigator.sendBeacon("/log.php?apply_for_new_connection=current_locaiton_clicked_geocode","");
	
}

function getFormattesdAddressByPlace (place) {
	console.log("getFormattesdAddressByPlace called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=getFormattesdAddressByPlace_called","");
	$("#latitude").val(place.geometry.location.lat());
	$("#longitude").val(place.geometry.location.lng());
	$("#address").val(place.formatted_address);
	$("#address").focus();
	$("#address").change();
	address_changed = 0;
	console.log("address_changed " + address_changed);
    address = parseAddressComponent(place);
	if ($('#city').val() != address.city) {
		var fname = getFormName();
        selectCityByName(address.city);
		//selectcity(document.getElementById("cityid"),document.getElementById(fname));
	}
	var centerLatLng=new google.maps.LatLng(latitude, longitude);
	markerbig.setPosition(centerLatLng);
	mapbig.panTo(centerLatLng);
	mapbig.setZoom(17);
}

function getFormattesdAddressByLatLong (latitude, longitude) {
	console.log("getFormattesdAddressByLatLong called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=getFormattesdAddressByLatLong_called","");
	$("#latitude").val(latitude);
	$("#longitude").val(longitude);
	$("#browser_latitude").val(latitude);
	$("#browser_longitude").val(longitude);
	var centerLatLng=new google.maps.LatLng(latitude, longitude);
	markerbig.setPosition(centerLatLng);
	mapbig.panTo(centerLatLng);
	mapbig.setZoom(17);
	if(!geocoder) {
		return;
	}
	geocoder.geocode({ 'location': centerLatLng }, function (results, status) {
		if (status === 'OK') {
			console.log("calling geocode");
	        address = parseAddressComponent(results[0]);
	        console.log("logsssssssssss:"+address+results[0].formatted_address);
	        $("#building_name").val(results[0].address_components[0]["long_name"]);
	  	   	$("#landmark").val(results[0].address_components[1]["long_name"]);
	  	    $("#place_details").val(JSON.stringify(results));
	        if ($('#city').val() != address.city) {
	        	var fname = getFormName();
	        	selectCityByName(address.city);
	        }
	        $("#address").val(results[0].formatted_address);
	        $("#address").focus();
	        $("#address").change();
	        address_changed = 0;
	        $("#map_address").val(results[0].formatted_address);
	        updateCurrentLatLong($("#address").val(),$("#cityid option:selected").text(),"googleapiwebsite");
		}
	});  
}

function getFormName() {
	console.log("getFormName called");
	var formName = document.getElementById("address").form.id;
	return formName;
}

function getFormattesdMapAddressByLatLong (latitude, longitude) { 
	console.log("getFormattesdMapAddressByLatLong called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=getFormattesdMapAddressByLatLong_called","");
	$("#latitude").val(latitude);
	$("#longitude").val(longitude);
	$("#browser_latitude").val(latitude);
	$("#browser_longitude").val(longitude);
	//alert($("#latitude").val()+","+$("#latitude").val());
	var centerLatLng=new google.maps.LatLng(latitude, longitude);
	if(!geocoder) {
		return;
	}
    geocoder.geocode({ 'location': centerLatLng }, function (results, status) {
        if (status === 'OK') {
            address = parseAddressComponent(results[0]);
        	$("#address").val(results[0].formatted_address);
        	$("#address").focus();
        	$("#address").change();
        	address_changed = 0;
        	if ($('#city').val() != address.city) {
				var fname = getFormName();
                selectCityByName(address.city);
				//selectcity(document.getElementById("cityid"),document.getElementById(fname));
        	}
        	updateCurrentLatLong(results[0].formatted_address,$("#cityid option:selected").text(),"googleapiwebsite");
        } else {
        }
    });
}

function addYourLocationButton(controlDiv) 
{
	console.log("addYourLocationButton called");
    var firstChild = document.createElement('button');
    firstChild.style.backgroundColor = '#fff';
    firstChild.style.border = 'none';
    firstChild.style.outline = 'none';
    firstChild.style.width = '28px';
    firstChild.style.height = '28px';
    firstChild.style.borderRadius = '2px';
    firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    firstChild.style.cursor = 'pointer';
    firstChild.style.marginRight = '10px';
    firstChild.style.padding = '0px';
    firstChild.title = 'Your Location';
    controlDiv.appendChild(firstChild);

    var secondChild = document.createElement('div');
    secondChild.style.margin = '5px';
    secondChild.style.width = '18px';
    secondChild.style.height = '18px';
    secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
    secondChild.style.backgroundSize = '180px 18px';
    secondChild.style.backgroundPosition = '0px 0px';
    secondChild.style.backgroundRepeat = 'no-repeat';
    secondChild.id = 'you_location_img';
    firstChild.appendChild(secondChild);
    firstChild.addEventListener('click', function() {
        var imgX = '0';
        var animationInterval = setInterval(function(){
            if(imgX == '-18') imgX = '0';
            else imgX = '-18';
            $('#you_location_img').css('background-position', imgX+'px 0px');
        }, 500);
        getCurrentLocation();
    });
}
$('#address').keypress(function(event) {
	console.log("$('#address').keypress called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=address.keypress_called","");
	if (event.keyCode === 10 || event.keyCode === 13)
		event.preventDefault();
});

$('#exampleModal').on('shown.bs.modal', function() {
	console.log("$('#exampleModal').on called");
	//navigator.sendBeacon("/log.php?apply_for_new_connection=exampleMode.on_called","");
	$('#exampleModal').trigger('focus');
	mapbig.setCenter(centerLatLng);
	google.maps.event.trigger(mapbig, 'resize');
	var centerLatLng=new google.maps.LatLng(latitude, longitude);
	mapbig.panTo(centerLatLng);
});
var _ga_send_=function(a){a instanceof Array&&"function"===typeof ga&&ga&&ga("send",{hitType:"event",eventCategory:a[0],eventAction:a[1],eventLabel:3===a.length&&a[2]})};
window.onerror = function (a, c, b, d, e) {
    a = { message: a, fileName: c, line: b, lineNumber: b, Qja: d, error: e };
    (new Image).src = "https://youbroadband.in/log.php?log=PPC53CUR3&type=gif&t=" + JSON.stringify(a);
    //navigator.sendBeacon("https://youbroadband.in/log.php?log=PPC53CUR3&type=beacon&t=", JSON.stringify(a));
};
let displayPlacesSuggestions = function(predictions, status) {
	let geocoder = new google.maps.Geocoder();
	geocodeCity();
	/*if (status != google.maps.places.PlacesServiceStatus.OK) {
		alert(status);
	   	return;
	}*/
	let inputContainer = document.querySelector('autocomplete-input-container');
	let autocomplete_results = document.querySelector('.autocomplete-results');
	let autocomplete_input = document.getElementById('address');
	autocomplete_results.classList.add("google");
	let results_html = [];
	predictions.forEach(function(prediction) {
		results_html.push('<li class="autocomplete-item" data-type="place" data-place-id='+prediction.place_id+'><i class="fa fa-map-marker" aria-hidden="true" style="font-size:17px"></i>      			    <span class="autocomplete-text">'+prediction.description+'</span></li>');
	});
	autocomplete_results.innerHTML = results_html.join("");
	autocomplete_results.style.display = 'block';
	let autocomplete_items = autocomplete_results.querySelectorAll('.autocomplete-item');
	for (let autocomplete_item of autocomplete_items) {
		autocomplete_item.addEventListener('click', function() {
	   	let prediction = {};
	  	const selected_text = this.querySelector('.autocomplete-text').textContent;
	  	service = new google.maps.places.PlacesService(mapbig);
	  	var request = {
	  		    placeId: autocomplete_item.getAttribute("data-place-id"),
	  		    fields: ["name", "address_components","formatted_address", "place_id", "geometry","vicinity"]
	  	};
	  	service.getDetails(request, function(place, status) {
	  	    if (status === google.maps.places.PlacesServiceStatus.OK) {
	  	    	console.log(place);
	  	    	address = parseAddressComponent(place);
	  	    	$("#building_name").val(place.name);
	  	    	$("#landmark").val(place.vicinity);
	  	    	$("#place_details").val(JSON.stringify(place));
	  	    	$("#place_id").val(autocomplete_item.getAttribute("data-place-id"));
	  	    	//alert(place.geometry.location.lat());
	  	    	$("#latitude").val(place.geometry.location.lat());
	  	    	$("#longitude").val(place.geometry.location.lng());
	  	    	$("#browser_latitude").val(place.geometry.location.lat());
	  	    	$("#browser_longitude").val(place.geometry.location.lng());
	  	    	/*var bounds = new google.maps.LatLngBounds();
	            markerbig.setPosition(place.geometry.location);
	            if (place.geometry.viewport) {
	          		bounds.union(place.geometry.viewport);
	            } else {
	           		bounds.extend(place.geometry.location);
	            }
	            mapbig.fitBounds(bounds);*/
	  	    	console.log("address_component:"+place.address_components+","+place.address_components[2]["short_name"]);
	  	    	updateCurrentLatLong(place.formatted_address,$("#cityid option:selected").text(),"googleapiwebsite");
	  	      }
	  	});
	  	_ga_send_(["apply_for_new_connection", "google_api", "google_Api_caled"]);
	  	if(autocomplete_input.value.length>50){
	  		$("#search_keyword").val(autocomplete_input.value.substring(0, 50));
	  	}else{
	  		$("#search_keyword").val(autocomplete_input.value);
	  	}
	  	
	  	$("#building_data").val("NO");
	  	_ga_send_(["apply_for_new_connection", "google_api_keyword", autocomplete_input.value]);
        autocomplete_input.value = selected_text;
        autocomplete_results.style.display = 'none';
		});
	}
};

