<div id="geocoder">
    <h1 class="side">Add a Property</h1>
    <input type='text' oninput='geocodeThis()' id='search' placeholder="Enter Address Here" >
    <ul id='results' style="background-color:transparent;padding: unset;">
        
    </ul>
    <div id='categories'>
    {% for category in categories %}
    <img src="{{ category.pin_icon.icon.url }}" height="40" class="categoryIcon" onclick="changeMarkerIcon('{{ category.pin_icon.icon.url }}', {{ category.id }})" class="markercat"/>
    {% endfor %}
    <form method="post" action="webmap/addpoint/">
        {% csrf_token %}
        <!-- display category with alias -->
        <p>
            <label for="id_category">Category:</label> 
            <select name="category" id="id_category" required>
                {% for category in categories %}
                    <option value = "{{ category.id }}">{{ category.name }}</option>
                {% endfor %}
            </select>
            <a href='admin/webmap/category/' title="Customize" style="margin-left: 16px;"><img src="/media/icons/customize1.svg" class="customizeCategoryLabelBtn" /></a>
        </p>
        {{ form.as_p }}
        <p>
        <label for="id_saveToFolder">Folder:</label>
        <select name = "saveToFolder" id="id_saveToFolder">
            <option value = "">Unsorted</option>
            {% for folder in folders %}
                <option value = "{{ folder.id }}">{{ folder.name }}</option>
            {% endfor %}
        </select>
        <a href='admin/webmap/folder/add/' title="Add new folder" style="margin-left: 16px;"><img src="/media/icons/add_folder1.svg" class="addFolderBtn" /></a>
        <P>
        <button class="buttonloc" type="submit" id="saveLocationButton">Save Property</button>
    </form>
    </div>
</div>

<script>

$( document ).ready(function() {
    var foption = $('#id_category').find("option");
    for(var i = 0; i< foption.length; i++){
        if(!foption.eq(i).val()){
            foption.eq(i).remove();
        }
    }
    
    $('#id_category').change(function(){
        catID = $(this).val();
        {% for category in categories %}
            if (catID == {{ category.id }}) {
                url = '{{ category.pin_icon.icon.url }}';
                changeMarkerIcon(url, catID);
            }
        {% endfor %}
    });
    if(Cookies.get('location') != undefined  && Cookies.get('latlon') != undefined){
        $("#id_location").attr('disabled',false);
        let latlon = JSON.parse(Cookies.get('latlon'))
        let location = Cookies.get('location')
        document.getElementById("id_location").value=location;
        document.getElementById("id_latitude").value=latlon[0];
        document.getElementById("id_longitude").value=latlon[1];
        if(location.substring(location.length - 15) == ', United States'){
            document.getElementById("id_address").value = location.substring(0, location.length - 15)
        } else {
            document.getElementById("id_address").value = location
        }
    }
    $("#saveLocationButton").click(function(){
        removeSavedLocationCookies()
    })
})

function geocodeThis() {
    removeSavedLocationCookies()
    var theUrl = "https://api.mapbox.com/geocoding/v5/mapbox.places/"+search.value+".json?language=en&country=US&access_token={{ token }}";
    httpGetAsync(theUrl, updateResults);
    if(search.value != ''){
        $("#id_location").attr('disabled',false);
    }else{
        $("#id_location").attr('disabled',true);
    }
}

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest({mozSystem: true});
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function panto(latlon) {
    map.setView(latlon,13)
}

var marker;

function addMarker(latlon){
    // Add marker to map at click location; add popup window
    if (!!marker) {
        map.removeLayer(marker);
    }
    var myIcon = L.icon({
                    iconUrl: "https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/images/marker-icon.png",
                    iconSize: [25,41],
                    iconAnchor: [13,41],
                    popupAnchor:  [0, -30]
                });
    marker = new L.marker(latlon, {icon: myIcon}).addTo(map);
}

function changeMarkerIcon(url, catvalue) {
    var myIcon = L.icon({
        iconUrl: url,
        iconSize: [25,41],
        iconAnchor: [13,41],
        popupAnchor:  [0, -30]
    });
    if (!!marker) {
        marker.setIcon(myIcon);
    }
    document.getElementById("id_category").value=catvalue;
    Cookies.set("icon_url",url)
    Cookies.set("catvalue",catvalue)
}

function updateResults(json) {
    var myNode = document.getElementById("results");
    while (myNode.firstChild) {
        myNode.removeChild(myNode.firstChild);
        //myNode.removeChild(myNode.remove);
    }
    data = JSON.parse(json).features.slice(0,4);
    for (feature in data) {
        f = data[feature];
        var lon = f.geometry.coordinates[0];
        var lat = f.geometry.coordinates[1];
        var entry = document.createElement('li');
        entry.setAttribute('id', 'feature');
        placename = document.createElement('div');
        placename.appendChild(document.createTextNode(f.place_name));
        placename.setAttribute('id', 'place_name');
        entry.appendChild(placename);
        
        coords = document.createElement('div');
        coords.appendChild(document.createTextNode(lat+","+lon));
        coords.setAttribute('id', 'coords');
        coords.setAttribute('style', "display: none;");
        entry.appendChild(coords);
        
        entry.onclick = function() {
            latlon = (this).childNodes[1].innerHTML.split(',').map(Number);
            let locationString = (this).childNodes[0].innerHTML;
            panto(latlon);
            addMarker(latlon);
            Cookies.set('location',locationString)
            Cookies.set('latlon',JSON.stringify(latlon))
            while (myNode.firstChild) {
                myNode.removeChild(myNode.firstChild);
                //myNode.removeChild(myNode.remove);
            }
            if(locationString.substring(locationString.length - 15) == ', United States'){
                document.getElementById("id_address").value = locationString.substring(0, locationString.length - 15)
            } else {
                document.getElementById("id_address").value = locationString
            }
            document.getElementById("id_location").value=locationString;
            document.getElementById("id_latitude").value=latlon[0];
            document.getElementById("id_longitude").value=latlon[1];
        }
        myNode.appendChild(entry);
    }
}
var streetViewPrintErrorToast;
function printPDF() {
    if ($('.pano-canvas').is(":visible")) {
        if(!streetViewPrintErrorToast) {
            streetViewPrintErrorToast = $.toast({
                text: "Uable to print in street view mode", // Text that is to be shown in the toast
                icon: 'warning', // Type of toast icon
                showHideTransition: 'fade', // fade, slide or plain
                allowToastClose: true, // Boolean value true or false
                hideAfter: 3000, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                position: 'bottom-center', // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
                textAlign: 'left',  // Text alignment i.e. left, right or center
                loader: true,  // Whether to show loader or not. True by default
                loaderBg: '#9EC600',
                bgColor: '#a94442',
                afterHidden: function () {
                    streetViewPrintErrorToast = null;
                }
            });
        }
    } else {
        const cloneDoc = document.documentElement.cloneNode(true)
        const body = cloneDoc.getElementsByTagName("body")[0]
        const map = cloneDoc.getElementsByClassName("map")[0]
        const map_script = cloneDoc.getElementsByClassName("map_script")[0];
        if(map_script){
            $( map_script ).remove();
        }
        // remove delete dialog
        const del_Dialog_script = cloneDoc.getElementsByClassName("del_Dialog_script")[0];
        if(del_Dialog_script){
            $( del_Dialog_script ).remove();
        }
        const deleteNoticeDialog = cloneDoc.getElementsByClassName("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable")[0]
        if( deleteNoticeDialog ){
            deleteNoticeDialog.style.display = 'none'
        }
        const logo = document.createElement('div')
        logo.setAttribute("style", "position:absolute;top:20px;left:20px;z-index:9999;");
        logo.innerHTML = '<img src="/media/images/logo1_original.png" align="left" height="50" alt="REIndicator">'
        body.prepend(logo)
        const topbar = cloneDoc.getElementsByClassName("topbar")[0]
        body.removeChild(topbar)
        const dropdown = cloneDoc.getElementsByClassName("dropdown")[0]
        body.removeChild(dropdown)
        const drawer = cloneDoc.getElementsByClassName("drawer")[0]
        body.removeChild(drawer)
        const leaflet_control_zoom = cloneDoc.getElementsByClassName("leaflet-control-zoom")[0]
        leaflet_control_zoom.style.display = 'none'
        const jq_toast_wrap = cloneDoc.getElementsByClassName("jq-toast-wrap")[0]
        if (jq_toast_wrap) {
            jq_toast_wrap.style.display = 'none'
        }
        const pegman_contorl = cloneDoc.getElementsByClassName("leaflet-pegman")[0]
        if (pegman_contorl) {
            pegman_contorl.style.display = 'none'
        }
        const legendBox = cloneDoc.getElementsByClassName("legend")[0]
        if (legendBox) {
            legendBox.style.display = 'block'
        }
        const leaflet_control_attribution = cloneDoc.getElementsByClassName("leaflet-control-attribution")[0]
        leaflet_control_attribution.style.display = 'none'
        map.style.height = '100%'
        const width = $( document ).width() * 0.2645833333
        const height = $( document ).height() * 0.2645833333 
        var csrftoken = Cookies.get('csrftoken');
        let data = cloneDoc.outerHTML
        
        data = data.replace(/\/media\//g, window.location.origin + '/media/')
        data = data.replace(/\/static\//g, window.location.origin + '/static/')
        $.ajax({
            method: "POST",
            headers: { "X-CSRFToken": csrftoken },
            url: "webmap/converttopdf/",
            data: { data, width, height},
            success: function( msg ) {
                window.open(window.location.origin+msg,'_blank');
            }
        });
    }
}
</script>
