{% load static %}
<script type="text/javascript">
function flyto(lat, lon) {
  removeSavedLocationCookies()
  map.setView([lat,lon],13)
}
function toggleMarker(i,ptpk) {
  if (map.hasLayer(markers[i])) {
    markerShow(i,false,ptpk)
  } else {
    markerShow(i,true,ptpk)
  }
}

function markerShow(i,visible,ptpk) {
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/markerShow/",
    data: { visible, ptpk },
    success: function( msg ) {
      if(msg == 'success'){
        if(visible == true){
          map.addLayer(markers[i]);
          for (var mile_index = 0; mile_index < 3; mile_index++){
            if(markerCircles[i]["_"+mile_index])
              map.addLayer(markerCircles[i][mile_index]);
          }
          $(".showIcon"+i).attr('src', '/media/icons/show2.png');
          if(allPoints[i].folderID != ''){
            setFolderMarkerShowIconAndCookie(allPoints[i].folderID, 'show')
          } else {
            setUnsortedFolderMarkerShowIconAndCookie('show');
          }
          setAllMarkerShowIconAndCookie('show')
        } else {
          map.removeLayer(markers[i]);
          clearLabelOfOnePoint(i)
          $(".labelDropdownBtn"+i).attr('src', '/media/icons/name.png');
          for (var mile_index = 0; mile_index < 3; mile_index++){
            map.removeLayer(markerCircles[i][mile_index]);
            map.removeLayer(circle_label_group[i][mile_index]);
          }
          $(".showIcon"+i).attr('src', '/media/icons/show1.png');
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function toggleAllMarker() {
  var visible
  if(Cookies.get('showAllIcon') == undefined) {
    visible = false
  } else {
    if(Cookies.get('showAllIcon') == 'show') {
      visible = false
    } else {
      visible = true
    }
  }
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/markerAllShow/",
    data: { visible },
    success: function( msg ) {
      if(msg == 'success'){
        var markerCount = Object.keys(markers).length
        if(visible == true){
          for (var i = 1; i <= markerCount; i++)
            if (!map.hasLayer(markers[i])){
              map.addLayer(markers[i]);
              $(".showIcon"+i).attr('src', '/media/icons/show2.png');
              for (var mile_index = 0; mile_index < 3; mile_index++){
                if(markerCircles[i]["_"+mile_index])
                  map.addLayer(markerCircles[i][mile_index]);
              }
            }
          for(var folderID of getAllFolderIDs()) {
            setFolderMarkerShowIconAndCookie(folderID, 'show')
          }
          setUnsortedFolderMarkerShowIconAndCookie('show')
          setAllMarkerShowIconAndCookie('show')
        } else {
          for (var i = 1; i <= markerCount; i++)
            if (map.hasLayer(markers[i])) {
              map.removeLayer(markers[i]);
              $(".showIcon"+i).attr('src', '/media/icons/show1.png');
              clearLabelOfOnePoint(i);
              $(".labelDropdownBtn"+i).attr('src', '/media/icons/name.png');
              for (var mile_index = 0; mile_index < 3; mile_index++){
                map.removeLayer(markerCircles[i][mile_index]);
                map.removeLayer(circle_label_group[i][mile_index]);
              }
            }
          for(var folderID of getAllFolderIDs()) {
            setFolderMarkerShowIconAndCookie(folderID, 'hide')
          }
          setUnsortedFolderMarkerShowIconAndCookie('hide')
          setAllMarkerShowIconAndCookie('hide')
          setShowAllCircleLabelsIconAndCookie('hide')
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function getAllFolderIDs() {
  var result = []
  for(var index in allPoints) {
    if(!result.includes(allPoints[index].folderID) && allPoints[index].folderID != '')
      result.push(allPoints[index].folderID)
  }
  return result
}

function togglefolderMarkers(folderID) {
  var visible
  if(Cookies.get('sAMIF'+folderID) == undefined) {
    visible = false
  } else {
    if(Cookies.get('sAMIF'+folderID) == 'show') {
      visible = false
    } else {
      visible = true
    }
  }
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/showMarkersByFolder/",
    data: { visible, folderID },
    success: function( response ) {
      if(response != 'Failed'){
        var markerCount = Object.keys(response).length
        if(visible == true){
          for (var i = 0; i < markerCount; i++)
            if (!map.hasLayer(markers[response[i] + 1])){
              map.addLayer(markers[response[i] + 1]);
              $(".showIcon"+(response[i] + 1)).attr('src', '/media/icons/show2.png');
              for (var mile_index = 0; mile_index < 3; mile_index++){
                if(markerCircles[response[i] + 1]["_"+mile_index])
                  map.addLayer(markerCircles[response[i] + 1][mile_index]);
              }
            }
          setFolderMarkerShowIconAndCookie(folderID, 'show')
          setAllMarkerShowIconAndCookie('show')
        } else {
          for (var i = 0; i < markerCount; i++)
            if (map.hasLayer(markers[response[i] + 1])) {
              map.removeLayer(markers[response[i] + 1]);
              $(".showIcon"+(response[i] + 1)).attr('src', '/media/icons/show1.png');
              clearLabelOfOnePoint(response[i] + 1);
              $(".labelDropdownBtn"+(response[i] + 1)).attr('src', '/media/icons/name.png');
              for (var mile_index = 0; mile_index < 3; mile_index++){
                map.removeLayer(markerCircles[response[i] + 1][mile_index]);
                map.removeLayer(circle_label_group[response[i] + 1][mile_index]);
              }
            }
          setFolderMarkerShowIconAndCookie(folderID, 'hide')
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function toggleMarkersNotInFolder() {
  var visible
  if(Cookies.get('showAllMarkersNotInFolder') == undefined) {
    visible = false
  } else {
    if(Cookies.get('showAllMarkersNotInFolder') == 'show') {
      visible = false
    } else {
      visible = true
    }
  }
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/showMarkersNotInFolder/",
    data: { visible },
    success: function( response ) {
      if(response != 'Failed'){
        var markerCount = Object.keys(response).length
        if(visible == true){
          for (var i = 0; i < markerCount; i++)
            if (!map.hasLayer(markers[response[i] + 1])){
              map.addLayer(markers[response[i] + 1]);
              $(".showIcon"+(response[i] + 1)).attr('src', '/media/icons/show2.png');
              for (var mile_index = 0; mile_index < 3; mile_index++){
                if(markerCircles[response[i] + 1]["_"+mile_index])
                  map.addLayer(markerCircles[response[i] + 1][mile_index]);
              }
            }
          setUnsortedFolderMarkerShowIconAndCookie('show');
          setAllMarkerShowIconAndCookie('show')
        } else {
          for (var i = 0; i < markerCount; i++)
            if (map.hasLayer(markers[response[i] + 1])) {
              map.removeLayer(markers[response[i] + 1]);
              $(".showIcon"+(response[i] + 1)).attr('src', '/media/icons/show1.png');
              clearLabelOfOnePoint(response[i] + 1);
              for (var mile_index = 0; mile_index < 3; mile_index++){
                map.removeLayer(markerCircles[response[i] + 1][mile_index]);
                map.removeLayer(circle_label_group[response[i] + 1][mile_index]);
              }
            }
          setUnsortedFolderMarkerShowIconAndCookie('hide');
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function setAllMarkerShowIconAndCookie(isShow) {
  if (isShow == 'show'){
    Cookies.set('showAllIcon','show');
    $("#showAllIcon").attr('src', '/media/icons/show2.png');
  } else {
    Cookies.set('showAllIcon','hide')
    $("#showAllIcon").attr('src', '/media/icons/show1.png');
  }
}
function setFolderMarkerShowIconAndCookie(folderID, isShow) {
  if (isShow == 'show'){
    Cookies.set('sAMIF'+folderID,'show')
    $(".folderShow_"+folderID).attr('src', '/media/icons/show2.png');
  } else {
    Cookies.set('sAMIF'+folderID,'hide')
    $(".folderShow_"+folderID).attr('src', '/media/icons/show1.png');
  }
}
function setUnsortedFolderMarkerShowIconAndCookie(isShow) {
  if (isShow == 'show'){
    Cookies.set('showAllMarkersNotInFolder','show')
    $(".folderShow_undefined").attr('src', '/media/icons/show2.png');
  } else {
    Cookies.set('showAllMarkersNotInFolder','hide')
    $(".folderShow_undefined").attr('src', '/media/icons/show1.png');
  }
}
function setShowAllCirclesIconAndCookie(isShow) {
  if (isShow == 'show'){
    Cookies.set('showAllCircles','show')
    $("#showAllCircles").attr('src', '/media/icons/circle2.png');
  } else {
    Cookies.set('showAllCircles','hide')
    $("#showAllCircles").attr('src', '/media/icons/circle1.png');
  }
}
function setShowAllCircleLabelsIconAndCookie(isShow) {
  if (isShow == 'show'){
    Cookies.set('showAllCircleLabels','show')
    $("#showAllCircleLabels").attr('src', '/media/icons/circle_label2.png');
  } else {
    Cookies.set('showAllCircleLabels','hide')
    $("#showAllCircleLabels").attr('src', '/media/icons/circle_label1.png');
  }
}

var direction_string = ['left','right','bottom'];
function toggleAllMarkerLabels() {
  var markerCount = Object.keys(markers).length
  if(isMarkerLabelShowing == false) {
    for (var i = 1; i <= markerCount; i++){
      if(map.hasLayer(markers[i])){
        if(!isLocationLabelShown(i)) {
          markerLabels[i][2] = new L.tooltip({ // 2: default : bottom
                                  permanent: true,
                                  direction: direction_string[2],
                                  className: 'location_name_label',
                                  opacity: 0.9,
                          })
                          .setContent(allPoints[i].name.replace(/\s*,\s*|\s+,/g, '<br>'))
                          .setLatLng([
                              allPoints[i].lat,
                              allPoints[i].lon
                          ])
                          .addTo(map);
          $(".name_btn_li_"+i+"_2").css('color','green')
          $(".labelDropdownBtn"+i).attr('src', '/media/icons/name_hover.png');
        }
      }
    }
    isMarkerLabelShowing = true
    $("#toggleAllMarkerLabels").attr('src', '/media/icons/name_hover.png');
  } else {
    for (var i = 1; i <= markerCount; i++){
      clearLabelOfOnePoint(i);
      $(".labelDropdownBtn"+i).attr('src', '/media/icons/name.png');
    }
    isMarkerLabelShowing = false
    $("#toggleAllMarkerLabels").attr('src', '/media/icons/name.png');
  }
}

function clearLabelOfOnePoint(i){
  for(var di_index = 0; di_index <= 2; di_index++) {
    if(markerLabels[i][di_index] != undefined && map.hasLayer(markerLabels[i][di_index])) {
      map.removeLayer(markerLabels[i][di_index])
    }
    $(".name_btn_li_"+i+"_"+di_index).css('color','red')
  }
}
function isLocationLabelShown(i) {
  for(var di_index = 0; di_index <= 2; di_index++) {
    if(markerLabels[i][di_index] != undefined && map.hasLayer(markerLabels[i][di_index]))
      return true
  }
  return false
}
function toggleLabel(i,direction_index) {
  if(markerLabels[i][direction_index] == undefined || !map.hasLayer(markerLabels[i][direction_index])) {
    if(map.hasLayer(markers[i])){
      clearLabelOfOnePoint(i)
      markerLabels[i][direction_index] = new L.tooltip({ // 2: default : bottom
                                permanent: true,
                                direction: direction_string[direction_index],
                                className: 'location_name_label',
                                opacity: 0.9,
                        })
                        .setContent(allPoints[i].name.replace(/\s*,\s*|\s+,/g, '<br>'))
                        .setLatLng([
                            allPoints[i].lat,
                            allPoints[i].lon
                        ])
                        .addTo(map);
      $(".name_btn_li_"+i+"_"+direction_index).css('color','green')
      $(".labelDropdownBtn"+i).attr('src', '/media/icons/name_hover.png');
    }
  } else {
    map.removeLayer(markerLabels[i][direction_index])
    $(".name_btn_li_"+i+"_"+direction_index).css('color','red')
    $(".labelDropdownBtn"+i).attr('src', '/media/icons/name.png');
  }
}

function toggleCircle(i,ptpk,mile_index) {
  if (map.hasLayer(markerCircles[i][mile_index])) {
    markerCircleShow(i,false,ptpk,mile_index)
  } else {
    markerCircleShow(i,true,ptpk,mile_index)
  }
}

function markerCircleShow(i,visible,ptpk,mile_index) {
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/markerCircleShow/",
    data: { visible, ptpk, mile_index },
    success: function( msg ) {
      if(msg == 'success'){
        if(visible == true){
          if(map.hasLayer(markers[i])){
            map.addLayer(markerCircles[i][mile_index]);
            markerCircles[i]["_"+mile_index] = true;
            $(".circle_btn_li_"+i+"_"+mile_index).css('color','green')
            setShowAllCirclesIconAndCookie('show')
            if($(".circleDropdownBtn"+i).attr('src').includes("circle1")) // if red circle
              $(".circleDropdownBtn"+i).attr('src', '/media/icons/circle2.png');
          }
          else
            alert("Circle can't be shown because this location is hidden.")
        } else {
          map.removeLayer(markerCircles[i][mile_index]);
          markerCircles[i]["_"+mile_index] = false;
          map.removeLayer(circle_label_group[i][mile_index]);
          $(".circle_btn_li_"+i+"_"+mile_index).css('color','red')
          if(markerCircles[i]["_0"] == false && markerCircles[i]["_1"] == false && markerCircles[i]["_2"] == false && $(".circleDropdownBtn"+i).attr('src').includes("circle2")) {
            $(".circleDropdownBtn"+i).attr('src', '/media/icons/circle1.png');
          }
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function toggleAllCircles() {
  var visible
  if(Cookies.get('showAllCircles') == undefined) {
    visible = false
  } else {
    if(Cookies.get('showAllCircles') == 'show') {
      visible = false
    } else {
      visible = true
    }
  }
  var csrftoken = Cookies.get('csrftoken');
  $.ajax({
    method: "POST",
    headers: { "X-CSRFToken": csrftoken },
    url: "webmap/markerCirclesAllShow/",
    data: { visible },
    success: function( msg ) {
      if(msg == 'success'){
        var markerCount = Object.keys(markerCircles).length
        if(visible == true){
          for (var i = 1; i <= markerCount; i++)
            for (var mile_index = 0; mile_index < 3; mile_index++)
              if (!map.hasLayer(markerCircles[i][mile_index]) && map.hasLayer(markers[i])){
                map.addLayer(markerCircles[i][mile_index]);
                markerCircles[i]["_"+mile_index] = true;
                $(".circle_btn_li_"+i+"_"+mile_index).css('color','green')
              }
          setShowAllCirclesIconAndCookie('show')
          $(".circleDropdownBtn").attr('src', '/media/icons/circle2.png');
        } else {
          for (var i = 1; i <= markerCount; i++)
            for (var mile_index = 0; mile_index < 3; mile_index++)
              if (map.hasLayer(markerCircles[i][mile_index])){
                map.removeLayer(markerCircles[i][mile_index]);
                markerCircles[i]["_"+mile_index] = false;
                map.removeLayer(circle_label_group[i][mile_index]);
                $(".circle_btn_li_"+i+"_"+mile_index).css('color','red')
              }
          setShowAllCirclesIconAndCookie('hide')
          setShowAllCircleLabelsIconAndCookie('hide')
          $(".circleDropdownBtn").attr('src', '/media/icons/circle1.png');
        }
      } else {
        alert("Show changing failed!")
      }
    }
  });
}

function toggleAllCircleLabels() {
  var visible
  if(Cookies.get('showAllCircleLabels') == undefined) {
    visible = true
  } else {
    if(Cookies.get('showAllCircleLabels') == 'show') {
      visible = false
    } else {
      visible = true
    }
  }
  var circleGroupCount = Object.keys(circle_label_group).length
  if(visible == true){
    for (var i = 1; i <= circleGroupCount; i++)
      for (var mile_index = 0; mile_index < 3; mile_index++)
        if (!map.hasLayer(circle_label_group[i][mile_index]) && map.hasLayer(markerCircles[i][mile_index])) {
          map.addLayer(circle_label_group[i][mile_index]);
          circle_label_group[i][mile_index].setLatLng([
                                markerCircles[i][mile_index].getLatLng().lat,
                                markerCircles[i][mile_index].getBounds().getEast()
                            ])
        }
    setShowAllCircleLabelsIconAndCookie('show')
  } else {
    for (var i = 1; i <= circleGroupCount; i++)
      for (var mile_index = 0; mile_index < 3; mile_index++)
        if (map.hasLayer(circle_label_group[i][mile_index])) 
          map.removeLayer(circle_label_group[i][mile_index]);
    setShowAllCircleLabelsIconAndCookie('hide')
  }
}

function toggleAllMFPPoints30() {
  if(layers['MFPPoints30'].isVisible()){
    layers['MFPPoints30'].hide()
    $('#showMFPPoints30').attr('src', '/media/icons/MFP.png');
  } else {
    layers['MFPPoints30'].show()
    $('#showMFPPoints30').attr('src', '/media/icons/MFP_hover.png');
  }
}

function toggleEmergingNeighborhoods() {
  if(isENSymbolShowing == false) {
    if (isColorBlind == false) {
      styles['MicroNeighborhoods'].setContent(layer_css.MicroNeighborhoods.normal + layer_css.MicroNeighborhoods.EN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showEN').attr('src', '/media/icons/EN_plus_hover.png');
          isENSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['MicroNeighborhoods'].setContent(layer_css.MicroNeighborhoods.colorBlindFriendly + layer_css.MicroNeighborhoods.EN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showEN').attr('src', '/media/icons/EN_plus_hover.png');
          isENSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  } else {
    if (isColorBlind == false) {
      styles['MicroNeighborhoods'].setContent(layer_css.MicroNeighborhoods.normal)
        .then(() => {
          enLegendVisible(false);
          $('#showEN').attr('src', '/media/icons/EN_plus.png');
          isENSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['MicroNeighborhoods'].setContent(layer_css.MicroNeighborhoods.colorBlindFriendly)
        .then(() => {
          enLegendVisible(false);
          $('#showEN').attr('src', '/media/icons/EN_plus.png');
          isENSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  }
}

function toggleEDNeighborhoods() {
  if(isEDNSymbolShowing == false) {
    if (isColorBlind == false) {
      styles['DCTestNew'].setContent(layer_css.DCTestNew.normal + layer_css.DCTestNew.EDN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showEDN').attr('src', '/media/icons/ed_on.png');
          isEDNSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['DCTestNew'].setContent(layer_css.DCTestNew.colorBlindFriendly + layer_css.DCTestNew.EDN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showEDN').attr('src', '/media/icons/ed_on.png');
          isEDNSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  } else {
    if (isColorBlind == false) {
      styles['DCTestNew'].setContent(layer_css.DCTestNew.normal)
        .then(() => {
          enLegendVisible(false);
          $('#showEDN').attr('src', '/media/icons/ed_off.png');
          isEDNSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['DCTestNew'].setContent(layer_css.DCTestNew.colorBlindFriendly)
        .then(() => {
          enLegendVisible(false);
          $('#showEDN').attr('src', '/media/icons/ed_off.png');
          isEDNSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  }
}

function toggleEmergingNeighborhoodsSingleFamily() {
  if(isSFENSymbolShowing == false) {
    if (isColorBlind == false) {
      styles['MicroNeighborhoodsSingleFamily'].setContent(layer_css.MicroNeighborhoodsSingleFamily.normal + layer_css.MicroNeighborhoodsSingleFamily.EN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showSingleEN').attr('src', '/media/icons/EN_plus_hover.png');
          isSFENSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['MicroNeighborhoodsSingleFamily'].setContent(layer_css.MicroNeighborhoodsSingleFamily.colorBlindFriendly + layer_css.MicroNeighborhoodsSingleFamily.EN_symbol)
        .then(() => {
          enLegendVisible(true);
          $('#showSingleEN').attr('src', '/media/icons/EN_plus_hover.png');
          isSFENSymbolShowing = true
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  } else {
    if (isColorBlind == false) {
      styles['MicroNeighborhoodsSingleFamily'].setContent(layer_css.MicroNeighborhoodsSingleFamily.normal)
        .then(() => {
          enLegendVisible(false);
          $('#showSingleEN').attr('src', '/media/icons/EN_plus.png');
          isSFENSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    } else {
      styles['MicroNeighborhoodsSingleFamily'].setContent(layer_css.MicroNeighborhoodsSingleFamily.colorBlindFriendly)
        .then(() => {
          enLegendVisible(false);
          $('#showSingleEN').attr('src', '/media/icons/EN_plus.png');
          isSFENSymbolShowing = false
        })
        .catch(() => {
          console.error('Error updating the cartoCSS for the layer');
        });
    }
  }
}

function onDeleteHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" .deleteIcon"+x).attr('src', '/media/icons/bin2.png');
}

function offDeleteHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" .deleteIcon"+x).attr('src', '/media/icons/bin1.png');
}
function onShowHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" .showIcon"+x).attr('src', '/media/icons/show2.png');
}

function offShowHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" .showIcon"+x).attr('src', '/media/icons/show1.png');
}
/* New */
function onCatHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" #catchange"+x).attr('src', '/media/icons/pin2.png');
}

function offCatHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" #catchange"+x).attr('src', '/media/icons/pin1.png');
}
function onFolderHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" #folderchange"+x).attr('src', '/media/icons/folder2.png');
}

function offFolderHover(table_num, x)
{
  $("#location_folder_group_"+table_num+" #folderchange"+x).attr('src', '/media/icons/folder1.png');
}

function formToggle(table_num, x)
{
  $("#location_folder_group_"+table_num+" #form"+x).toggle('slow');
}

function folderToggle(table_num, x)
{
  $(document).ready(function() {
    $("#location_folder_group_"+table_num+" #foldermenu"+x).toggle('slow');
  });
}

function folderPointsToggle(x)
{
  trs = jQuery("[id=folderpoints"+x+"]");
  l = trs.length;
  for (i = 0; i < l; i++) {
    $(trs[i]).toggle();
  }
}
function otherPointsToggle(x)
{
  trs = jQuery("[id=otherpoint]");
  l = trs.length;
  for (i = 0; i < l; i++) {
    $(trs[i]).toggle();
  }
}

function folderClick(x,y)
{
  $(".folder"+x+"_"+y).click();
}

function circleDropdownToggle(table_num, x)
{
  $(document).ready(function() {
    $("#location_folder_group_"+table_num+" #circleDropdown"+x).toggle('slow');
  });
}

function labelDropdownToggle(table_num, x)
{
  $(document).ready(function() {
    $("#location_folder_group_"+table_num+" #labelDropdown"+x).toggle('slow');
  });
}

/*   End new */
</script>
<script language="javascript">
  $(document).ready(function(e) {
    try {
      $("#catchange").msDropDown();
    } catch(e) {
      alert(e.message);
    }
    // Initial folder showing(name asc)
    for(var i = 1; i < 5 ; i++) {
      if (i == 1) {
        $('#location_folder_group_'+i).show()
      } else {    
        $('#location_folder_group_'+i).hide()
      }
    }
    $('#orderBySelector').change(function(){
      for(var i = 1; i < 5 ; i++) {
        if (i == $(this).val()) {
          $('#location_folder_group_'+i).show()
        } else {    
          $('#location_folder_group_'+i).hide()
        }
      }
    })
  });
</script>
<div>
  <h1 class="side">My Saved Properties</h1>
  <div style="margin-left:12px;">
    <label>Sort by: </label>
    <select id='orderBySelector'>
      <option value=1>Name A -> Z</option>
      <option value=2>Name Z -> A</option>
      <option value=3>Oldest created</option>
      <option value=4>Latest created</option>
    </select>
    <div style="cursor:pointer;vertical-align:top;display:inline-block;">
      <input id="showAllIcon" type="image"
        value="show/hide"
        onclick="toggleAllMarker();"
        alt="Show/Hide All Points" title="Show/Hide All Points"
        style="width:25px; float:left"/>
      <input id="toggleAllMarkerLabels" type="image"
        value="show/hide"
        onclick="toggleAllMarkerLabels();"
        alt="Show/Hide All Property Names" title="Show/Hide All Property Names"
        style="width:25px; float:left"/>
      <input id="showAllCircles" type="image"
        value="show/hide"
        onclick="toggleAllCircles();"
        alt="Show/Hide All Circles" title="Show/Hide All Circles"
        style="width:25px; float:left"/>
      <input id="showAllCircleLabels" type="image"
        value="show/hide"
        onclick="toggleAllCircleLabels();"
        alt="Show/Hide All Circle Labels" title="Show/Hide All Circle Labels"
        style="width:25px; float:left"/>
      {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Anticipator' or userLevel == 'Multi_Analyzer' or userLevel == 'MDM1' %}
      <input id="showMFPPoints30" type="image"
        src='/media/icons/MFP.png' value="show/hide"
        onclick="toggleAllMFPPoints30();"
        alt="Show/Hide Multifamily Properties" title="Show/Hide Multifamily Properties"
        style="width:25px; float:left"/>
      <i id="warningPopupIconForMFPPoints30" class="fa fa-info-circle" style="color:#e41515; float:left;" aria-hidden="true" onclick="mfpWarningPopup();"></i>
      {% endif %}
      {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'MDM1' %}
      <input id="showEN" type="image"
        src='/media/icons/EN_plus.png' value="show/hide"
        onclick="toggleEmergingNeighborhoods();"
        alt="Show/Hide Emerging Neighborhoods" title="Show/Hide Emerging Neighborhoods"
        style="width:25px; float:left"/>
      <input id="showEDN" type="image"
        src='/media/icons/ed_off.png' value="show/hide"
        onclick="toggleEDNeighborhoods();"
        alt="Show/Hide Emerging & Declining Neighborhoods" title="Show/Hide Emerging & Declining Neighborhoods"
        style="width:25px; float:left"/>
      {% endif %}
      {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Single_Anticipator' %}
      <input id="showSingleEN" type="image"
        src='/media/icons/EN_plus.png' value="show/hide"
        onclick="toggleEmergingNeighborhoodsSingleFamily();"
        alt="Show/Hide Emerging Neighborhoods" title="Show/Hide Emerging Neighborhoods"
        style="width:25px; float:left"/>
      {% endif %}
    </div>
  </div>
  {% if points %}
  {% for folder_group in folders_groups %}
    <table id = "location_folder_group_{{ forloop.counter }}">
    {% for folder in folder_group %}
      <tr class = "folderParent">
        <td id="folder_icon" style="cursor:pointer;vertical-align:top;">
          <img class="val" src='/media/icons/folder.svg' 
           height="40" onclick="folderPointsToggle({{ folder.id }});"
           onmouseover="this.src='/media/icons/folder_hover.svg';"
           onmouseout="this.src='/media/icons/folder.svg';"/>
        </td>
        <td id="folder_name">{{ folder.name }}</td>
        <td style="cursor:pointer;vertical-align:middle;">
          <input type="image" class="folderShow_{{ folder.id }}"
            src='/media/icons/show1.png' value="show/hide"
            onclick="togglefolderMarkers({{ folder.id }});"
            alt="Show/Hide Points in Folder" title="Show/Hide Points in Folder"
            style="width:25px; float:left"/>
        </td>
      </tr>
      {% for point in points %}
        {% if point.folder.name == folder.name %}
        <tr id="folderpoints{{ folder.id }}" style="display:none">
          <td id="location_icon" style="cursor:pointer;vertical-align:top;">
            {% if  point.category.pin_icon.icon.url == None %}
              <img class="val" src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/images/marker-icon.png" height="40" />
            {% else %}
              <img class="val" src="{{ point.category.pin_icon.icon.url }}" height="40" />
            {% endif %}
          </td>
          <td style="cursor:pointer;vertical-align:top;padding:0;width:125px;"
           onclick="flyto( {{ point.latitude }}, {{ point.longitude }} )">
            {{ point.location|cut:", United States" }}
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="showIcon{{ forloop.counter }}" type="image"
            {% if  point.visible %}
             src='/media/icons/show2.png' value="show/hide"
            {% else %}
             src='/media/icons/show1.png' value="show/hide"
            {% endif %}
             onclick="toggleMarker({{ forloop.counter }},{{ point.pk }});"
             alt="Show/Hide Points" title="Show/Hide Points"
             style="width:25px; float:left"/>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="labelDropdownBtn{{ forloop.counter }}" type="image"
              src='/media/icons/name.png' alt="Show/Hide Property Name"
              title="Show/Hide Property Name" style="max-height:25px;width:auto;float:left"
              onclick="labelDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="labelDropdown{{ forloop.counter }}" style="display:none;width:49px;margin:0;overflow:hidden">
              <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_0' onclick="labelDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'0');">Left</li>
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_1' onclick="labelDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'1');">Right</li>
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_2' onclick="labelDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'2');">Bottom</li>
              </ul>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="circleDropdownBtn circleDropdownBtn{{ forloop.counter }}" type="image"
              {% if point.circleVisible or point.circleVisible1 or point.circleVisible2%}src='/media/icons/circle2.png'{% else %}src='/media/icons/circle1.png'{% endif %}
              alt="Show/Hide Circle"
              title="Show/Hide Circle" style="max-height:25px;width:auto;float:left"
              onclick="circleDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="circleDropdown{{ forloop.counter }}" style="display:none;width:40px;margin:0;overflow:hidden">              
              <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_0' onclick="circleDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},0);" style="color: {% if point.circleVisible %}green{% else %}red{% endif %}">1 mi</li>
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_1' onclick="circleDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},1);" style="color: {% if point.circleVisible1 %}green{% else %}red{% endif %}">3 mi</li>
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_2' onclick="circleDropdownToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},2);" style="color: {% if point.circleVisible2 %}green{% else %}red{% endif %}">5 mi</li>
              </ul>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input id="catchange{{ forloop.counter }}" type="image"
             src='/media/icons/pin1.png' alt="Change Category"
             title = "Change Category" style="max-height:25px;width:auto;float:left"
             onmouseover="onCatHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"
             onmouseout="offCatHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"
             onclick="formToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="form{{ forloop.counter }}"
             style="display:none;width:40px;margin:0;overflow:hidden">
              <form method="post" action="webmap/changepoint/">
              {% csrf_token %}
                <input type="hidden" name="ptpk" value="{{ point.pk }}"  />
                <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                {% for category in categories %}
                  <li>
                    <input name="catpk_{{ category.id }}" type="image"
                     value="{{ category.id }}" src="{{ category.pin_icon.icon.url }}"
                     style="width:25px;height:41px;"
                     title="{{ category.name }}">
                  </li>
                {% endfor %}
                </ul>
              </form>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input id="folderchange{{ forloop.counter }}" type="image"
             src='/media/icons/folder1.png' alt="Change Folder"
             title="Change Folder" style="max-height:25px;width:auto;float:left"
             onmouseover="onFolderHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"
             onmouseout="offFolderHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"
             onclick="folderToggle({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="foldermenu{{ forloop.counter }}" style="display:none;width:70px;margin:0;overflow:hidden">
              <form method="post" action="webmap/changepointfolder/">
              {% csrf_token %}
                <input type="hidden" name="ptpk" value="{{ point.pk }}"  />
                <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                {% for folder in folders %}
                  <li>
                    <input name="folderpk_{{ folder.id }}" type="image"
                     class="folder{{ folder.id }}_{{ point.pk }}"
                     value="{{ folder.id }}" src='/media/icons/folder1.png'
                     style="width:15px"
                     title="{{ folder.name }}">
                     <div onclick="folderClick({{ folder.id }}, {{ point.pk }})">
                      {{ folder.name }}
                     </div>
                  </li>
                {% endfor %}
                </ul>
              </form>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <form method="post" action="webmap/deletepoint/"
             onsubmit="return confirm('Do you really want to delete {{ point.location|cut:", United States" }}?');">
            {% csrf_token %}
              <input type="hidden" name="pk" value="{{ point.pk }}"/>
              <input class="deleteIcon{{ forloop.counter }}" type="image"
               src='/media/icons/bin1.png' alt="Delete Point"
               title="Delete Point" style="width:25px; float:left"
               onmouseover="onDeleteHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"
               onmouseout="offDeleteHover({{ forloop.parentloop.parentloop.counter }},{{ forloop.counter }});"/>
            </form>
          </td>
        </tr>
        {% endif %}
      {% endfor %}      
    {% endfor %}
    <tr class = "unsortedParent unsortFolder">
      <td id="folder_icon" style="cursor:pointer;vertical-align:top;">
        <img class="val" src='/media/icons/folder.svg'
         height="40" onclick="otherPointsToggle();"
         onmouseover="this.src='/media/icons/folder_hover.svg';"
         onmouseout="this.src='/media/icons/folder.svg';"/>
        </td>
        <td id="folder_name">Unsorted</td>
        <td style="cursor:pointer;vertical-align:middle;">
          <input type="image" class="folderShow_undefined"
            src='/media/icons/show1.png' value="show/hide"
            onclick="toggleMarkersNotInFolder();"
            alt="Show/Hide Points in Folder" title="Show/Hide Points in Folder"
            style="width:25px; float:left"/>
        </td>
    </tr>
    {% for point in points %}
      {% if not point.folder.name %}
        <tr id="otherpoint" class = "unsortFolder" style="display:none">
          <td id="location_icon" style="cursor:pointer;vertical-align:top;">
            {% if  point.category.pin_icon.icon.url == None %}
              <img class="val" src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/images/marker-icon.png" height="40" />
            {% else %}
              <img class="val" src="{{ point.category.pin_icon.icon.url }}" height="40" />
            {% endif %}
          </td>
          <td style="cursor:pointer;vertical-align:top;padding:0;width:125px;"
           onclick="flyto( {{ point.latitude }}, {{ point.longitude }} )">
            {{ point.location|cut:", United States" }}
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="showIcon{{ forloop.counter }}" type="image"
            {% if  point.visible %}
             src='/media/icons/show2.png' value="show/hide"
            {% else %}
             src='/media/icons/show1.png' value="show/hide"
            {% endif %}
             onclick="toggleMarker({{ forloop.counter }},{{ point.pk }});"
             alt="Show/Hide Points" title="Show/Hide Points"
             style="width:25px; float:left"/>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="labelDropdownBtn{{ forloop.counter }}" type="image"
              src='/media/icons/name.png' alt="Show/Hide Property Name"
              title="Show/Hide Property Name" style="max-height:25px;width:auto;float:left"
              onclick="labelDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="labelDropdown{{ forloop.counter }}" style="display:none;width:49px;margin:0;overflow:hidden">
              <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_0' onclick="labelDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'0');">Left</li>
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_1' onclick="labelDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'1');">Right</li>
                <li class = 'name_btn_li name_btn_li_{{ forloop.counter }}_2' onclick="labelDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleLabel({{ forloop.counter }},'2');">Bottom</li>
              </ul>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input class="circleDropdownBtn circleDropdownBtn{{ forloop.counter }}" type="image"
              {% if point.circleVisible or point.circleVisible1 or point.circleVisible2%}src='/media/icons/circle2.png'{% else %}src='/media/icons/circle1.png'{% endif %}
              alt="Show/Hide Circle"
              title="Show/Hide Circle" style="max-height:25px;width:auto;float:left"
              onclick="circleDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="circleDropdown{{ forloop.counter }}" style="display:none;width:40px;margin:0;overflow:hidden">              
              <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_0' onclick="circleDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},0);" style="color: {% if point.circleVisible %}green{% else %}red{% endif %}">1 mi</li>
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_1' onclick="circleDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},1);" style="color: {% if point.circleVisible1 %}green{% else %}red{% endif %}">3 mi</li>
                <li class = 'circle_btn_li circle_btn_li_{{ forloop.counter }}_2' onclick="circleDropdownToggle({{ forloop.parentloop.counter }},{{ forloop.counter }}); toggleCircle({{ forloop.counter }},{{ point.pk }},2);" style="color: {% if point.circleVisible2 %}green{% else %}red{% endif %}">5 mi</li>
              </ul>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input id="catchange{{ forloop.counter }}" type="image"
             src='/media/icons/pin1.png' alt="Change Category"
             title = "Change Category" style="max-height:25px;width:auto;float:left"
             onmouseover="onCatHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"
             onmouseout="offCatHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"
             onclick="formToggle({{ forloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="form{{ forloop.counter }}" style="display:none;width:40px;margin:0;overflow:hidden">
              <form method="post" action="webmap/changepoint/">
              {% csrf_token %}
                <input type="hidden" name="ptpk" value="{{ point.pk }}"  />
                <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                {% for category in categories %}
                  <li>
                    <input name="catpk_{{ category.id }}" type="image"
                     value="{{ category.id }}" src="{{ category.pin_icon.icon.url }}"
                     style="width:25px;height:41px;"
                     title="{{ category.name }}">
                  </li>
                {% endfor %}
                </ul>
              </form>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <input id="folderchange{{ forloop.counter }}" type="image"
             src='/media/icons/folder1.png' alt="Change Folder"
             title="Change Folder" style="max-height:25px;width:auto;float:left"
             onmouseover="onFolderHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"
             onmouseout="offFolderHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"
             onclick="folderToggle({{ forloop.parentloop.counter }},{{ forloop.counter }});"/>
            <div id="foldermenu{{ forloop.counter }}" style="display:none;width:70px;margin:0;overflow:hidden">
              <form method="post" action="webmap/changepointfolder/">
              {% csrf_token %}
                <input type="hidden" name="ptpk" value="{{ point.pk }}"  />
                <ul style="list-style-type:none;margin:0;padding:0;vertical-align:top;">
                {% for folder in folders %}
                  <li>
                    <input name="folderpk_{{ folder.id }}" type="image"
                     class="folder{{ folder.id }}_{{ point.pk }}"
                     value="{{ folder.id }}" src='/media/icons/folder1.png'
                     style="width:15px"
                     title="{{ folder.name }}">
                     <div onclick="folderClick({{ folder.id }}, {{ point.pk }})">
                      {{ folder.name }}
                     </div>
                  </li>
                {% endfor %}
                </ul>
              </form>
            </div>
          </td>
          <td style="cursor:pointer;vertical-align:top;">
            <form method="post" action="webmap/deletepoint/"
             onsubmit="return confirm('Do you really want to delete {{ point.location|cut:", United States" }}?');">
            {% csrf_token %}
              <input type="hidden" name="pk" value="{{ point.pk }}"/>
              <input class="deleteIcon{{ forloop.counter }}" type="image"
               src='/media/icons/bin1.png' alt="Delete Point"
               title="Delete Point" style="width:25px; float:left"
               onmouseover="onDeleteHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"
               onmouseout="offDeleteHover({{ forloop.parentloop.counter }},{{ forloop.counter }});"/>
            </form>
          </td>
        </tr>
      {% endif %}
    {% endfor %}
    </table>
  {% endfor %}
  {% else %}
    <p>You do not have any saved properties</p>
  {% endif %}
</div>
