jQuery(document).ready(function() {
    jQuery("#interactiveMap").hide();
    jQuery("#interactiveMapBing").hide();
    jQuery(".naviElementImg").on('click', function() {
        var currentValue = jQuery(this).attr("title");
        console.log(currentValue);
        if (currentValue) {
            updateMap(currentValue);
        } else {
            updateMap(jQuery(this).next().text());
        }
    });
});



var tabID = localStorage.getItem('tabID');

function getBigMap(urlData) {
    if (urlData != "") {
        currentLocation = urlData
    }
    console.log(tabID)
    if (tabID == 0) {
        chrome.tabs.create({
            url: "http://earth3dmap.com/chrome-extension/#?l=" + urlData
        }, function(tab) {
            localStorage.setItem('tabID', tab.id);
        });
    } else {
        tabID = localStorage.getItem('tabID');
        chrome.tabs.update(null, { url: "http://earth3dmap.com/chrome-extension/#?l=" + urlData });
    }
}



var googleURL = "https://www.google.com/maps/embed/v1/view";
var googlePlaceURL = "https://www.google.com/maps/embed/v1/place";
var maxZoomLevel,
    deepLink_coordinatesLat,
    deepLink_coordinatesLong;



function updateMap(urlData) {
    jQuery("#interactiveMap").hide();
    jQuery("#interactiveMapBing").hide();
    var DeepLink = urlData;
    if (DeepLink.charAt(2) == '=') {
        DeepLink = DeepLink.substr(3);
    }
    if (DeepLink.charAt(0) == '/') {
        DeepLink = DeepLink.substr(1);
    }
    if (DeepLink.length > 0) {
        var newDeepLink = new Array();
        newDeepLink = DeepLink.split(",")
        for (a in newDeepLink) {
            if (!isNaN(newDeepLink[a])) {
                newDeepLink[a] = parseFloat(newDeepLink[a]);
            } else {
                newDeepLink[a] = newDeepLink[a];
            }
        }
        console.log(newDeepLink)
        if (newDeepLink.length >= 1 && newDeepLink[0] != "kmark") {
            jQuery(".bigger-button, .fullscreen-link").attr('href', "http://earth3dmap.com/chrome-extension/#?l=" + newDeepLink);
            if (newDeepLink.length == 1) {
                generatePlaceMap("interactiveMap", newDeepLink[0])
            } else {
                deepLink_coordinatesLat = newDeepLink[0];
                deepLink_coordinatesLong = newDeepLink[1];
                maxZoomLevel = newDeepLink[6];
                headingIndex = newDeepLink[7];
                if (maxZoomLevel > 20) {
                    maxZoomLevel = 20;
                }
                generateMap("interactiveMapBing", deepLink_coordinatesLat, deepLink_coordinatesLong, maxZoomLevel,headingIndex)

            }
        }
    }
}


function generatePlaceMap(place) {
    jQuery("#interactiveMap").hide();
    jQuery("#interactiveMapBing").hide();
    jQuery("#interactiveMapBing").show();
    var map = new Microsoft.Maps.Map(document.getElementById("interactiveMapBing"), {
        center: new Microsoft.Maps.Location(0, 0),
        mapTypeId: Microsoft.Maps.MapTypeId.birdseye
    });
    Microsoft.Maps.loadModule('Microsoft.Maps.Search', function() {
        var searchManager = new Microsoft.Maps.Search.SearchManager(map);
        var requestOptions = {
            bounds: map.getBounds(),
            where: place,
            callback: function(answer, userData) {
                console.log(answer.results[0].bestView.center)
                generateMap("interactiveMapBing", answer.results[0].bestView.center.latitude + 0.0005, answer.results[0].bestView.center.longitude, 18)

            }
        };
        searchManager.geocode(requestOptions);
    });


}

function generateMap(mapDivID, coordinatesLat, coordinatesLong, zoomLevel, headingIndex) {
    /*BING*/
    //var map;
    var mapLocation = new Microsoft.Maps.Location(coordinatesLat, coordinatesLong);
    console.log(coordinatesLat + " " + coordinatesLong);
    Microsoft.Maps.getIsBirdseyeAvailable(mapLocation, Microsoft.Maps.Heading.north, onResponse);

    function onResponse(isAvailable) {
        if (isAvailable) {
            /*BING*/
            jQuery("#interactiveMapBing").show();
            if(!headingIndex){
                headingIndex=0;
            }
            map = new Microsoft.Maps.Map(document.getElementById(mapDivID), {
                center: mapLocation,
                zoom:zoomLevel,
                heading: headingIndex,
                //navigationBarMode: Microsoft.Maps.NavigationBarMode.compact,
                mapTypeId: Microsoft.Maps.MapTypeId.birdseye
            });
                 Microsoft.Maps.Events.addHandler(map, 'viewchangeend', function () { 
                    urlData=Math.round(map.getCenter().latitude*10000)/10000+","+ Math.round(map.getCenter().longitude*10000)/10000 +",0,0,1,1,"+map.getZoom()+","+map.getHeading();
                    console.log(urlData);
                    jQuery(".bigger-button, .fullscreen-link").attr('href', "http://earth3dmap.com/chrome-extension/#?l=" + urlData);
                });
        } else {
            /*GOOGLE*/
            jQuery("#interactiveMap").show();
            document.getElementById("interactiveMap").src = googleURL + "?key=AIzaSyBRPzq9CdVJXTTS6HKGUCGtZ96AGbQLvjI&center=" + coordinatesLat + "," + coordinatesLong + "&zoom=" + zoomLevel + "&maptype=" + "satellite";
        }
    }
}


function search (place){
    jQuery("#interactiveMap").hide();
    jQuery("#interactiveMapBing").hide();
    jQuery("#interactiveMapBing").show();
    var map = new Microsoft.Maps.Map(document.getElementById('interactiveMapBing'), {
    center: new Microsoft.Maps.Location(47.624527, -122.355255),
    zoom: 8 });
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
    var searchManager = new Microsoft.Maps.Search.SearchManager(map);
    console.log(map.getBounds());
    var requestOptions = {
        bounds: map.getBounds(),
        mapTypeId: Microsoft.Maps.MapTypeId.birdseye,
        where: place,
        callback: function (answer, userData) {
            generateMap("interactiveMapBing", answer.results[0].bestView.center.latitude, answer.results[0].bestView.center.longitude, 18);
        }
    };
    searchManager.geocode(requestOptions);
});
}


function selectedSuggestion(suggestionResult) {
    jQuery(".as_container_search").hide();
    console.log(suggestionResult.location.latitude+","+ suggestionResult.location.longitude);
    updateMap(suggestionResult.location.latitude+","+ suggestionResult.location.longitude+",0,0,1,1,18");
}

function waitForDeepLink() {
    console.log("waitForDeepLink");
    var DeepLink = window.location.hash.substring(4); 
    if (DeepLink.charAt(2) == '=') {
        DeepLink = DeepLink.substr(3);
    }
    if (DeepLink.charAt(0) == '/') {
        DeepLink = DeepLink.substr(1);
    }
    console.log("DeepLink.length"+DeepLink.length);
    if(DeepLink.length>0){
        var newDeepLink = new Array();
        newDeepLink = DeepLink.split(",")
        for (a in newDeepLink) {
            if (!isNaN(newDeepLink[a])) {
                newDeepLink[a] = parseFloat(newDeepLink[a]);
            } else {
                newDeepLink[a] = newDeepLink[a];
            }
        }
        console.log(newDeepLink)
        if (newDeepLink.length >= 1 && newDeepLink[0]!="kmark") {
            if (newDeepLink.length == 1) {
                  search(newDeepLink[0])
            }else{
                deepLink_coordinatesLat = newDeepLink[0];
                deepLink_coordinatesLong = newDeepLink[1];
                maxZoomLevel = newDeepLink[6];
                if (maxZoomLevel > 20) {
                    maxZoomLevel = 20;
                }
                updateMap(newDeepLink[0]+","+ newDeepLink[1]+",0,0,1,1,"+maxZoomLevel);
            }
        }
        
    }else{
        //Niagara Falls
         console.log("waitForDeepLink generateMap");
        generateMap("interactiveMapBing", startCoordinatesLat, startCoordinatesLong, 18, startHeading);
    }
}


var map;
/*ONLY GOOGLE*/
var startCoordinatesArray =[[47.5583,10.7495,18],[43.8802,-103.459,18],[42.6961, 23.332788,19],[32.711057,-117.174559,18],[32.90031,-117.253029,18],[32.423261,-109.986522,12],[40.6897,-74.044664,18],[55.69288,12.597152,18],[50.080894,14.448625,19],[35.742425,139.756327,20]];
/*BING*/
// var startCoordinatesArray = [[40.715,-74.0123],[41.8909,12.4922],[48.8606,2.2941],[40.6896,-74.0442],[36.1114,-115.1718] ,[37.3357,-122.0083],[43.0838,-79.0701],[42.6961,23.332788],[52.5162,13.3777],[42.8809,-8.5447],[43.7232,10.3956],[38.626,-90.1847],[41.4047,2.1746],[43.8802, -103.459],[48.8885,2.3435],[50.8956,4.3416],[34.1345,-118.3217],[45.4345,12.3388],[51.5013,-0.1247],[47.5583, 10.7495],[28.4194,-81.5811],[41.8991,12.4768]];
var randomNumber = Math.floor(Math.random() * startCoordinatesArray.length);
//var randomNumber =9
var startCoordinatesLat = startCoordinatesArray[randomNumber][0];
var startCoordinatesLong = startCoordinatesArray[randomNumber][1];
var startCoordinatesZoom = startCoordinatesArray[randomNumber][2];
var startHeading = 0;
function debugMap() {
    //generatePlaceMap(""41.8908, 12.4923")
    //generatePlaceMap("atonium";
    //search ('munich');

    /*BING*/
  // waitForDeepLink();

  /*ONLY GOOGLE*/
   jQuery("#interactiveMap").show();
   document.getElementById("interactiveMap").src = googleURL + "?key=AIzaSyBRPzq9CdVJXTTS6HKGUCGtZ96AGbQLvjI&center=" + startCoordinatesLat + "," + startCoordinatesLong + "&zoom=" + startCoordinatesZoom + "&maptype=" + "satellite";
   console.log (startCoordinatesLat+","+startCoordinatesLong+","+startCoordinatesZoom)
   jQuery(".bigger-button, .fullscreen-link").attr('href', "http://earth3dmap.com/chrome-extension/#?l=" + startCoordinatesLat+","+startCoordinatesLong+",0,0,1,1,"+startCoordinatesZoom+",0");

   /*BING*/
   Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () {
    var options = {
        maxResults: 4,
        map: map
    };
    var manager = new Microsoft.Maps.AutosuggestManager(options);
    manager.attachAutosuggest('#searchBox', '#searchBoxContainer', selectedSuggestion);
});
}
