var bmCurrentPage = "";
var map = null;
var mapLocation = null;
var currentLat = 45.813082685527796;
var currentLong = 15.976266860961914;
var currentRoute = -1;
var currentLeg = -1;
var currentStep = -1;
var lastLat = 0;
var lastLong = 0;
var currentHeading = 0;
var currentSpeed = "0.00";
var pointLat = 0;
var pointLng = 0;
var dataToShow = new Array();
var mobileIcons = new Array();
var mobileImages = new Array();
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var directionDisplayLocation;
var directionsServiceLocation = new google.maps.DirectionsService();
var markerHome = null;
var markerHomePOI = null;
var markerSelected = null;
var driveType = 1;
var followLocation = 1;
var markerCurrent = null;
var mapPOIs = new Array();
var loadingLocationPOIs = false;
var locationRefreshDistance = new Array();
var locationDirResponse = null;
var POITypes = new Array();
var selectedPOIType = "";
var overrideLocation = false;

function initData()
{
  POITypes[0] = "atm";
  POITypes[1] = "biljeznik";
  POITypes[2] = "odvjetnik";
  POITypes[3] = "ljekarna";
  POITypes[4] = "domzdr";
  POITypes[5] = "train";
  POITypes[6] = "plane";
  POITypes[7] = "bus";
  POITypes[8] = "police";
  POITypes[9] = "lutrija";
  POITypes[10] = "kerum";
  POITypes[11] = "trajekt";
  POITypes[12] = "tcom";

  for (i=0; i<POITypes.length; i++) {
    dataToShow[POITypes[i]] = 0;
  }
  driveType = 1;
  followLocation = 1;

  mobileIcons["atm"] = "icons/atm.png";
  mobileIcons["biljeznik"] = "../icons/biljeznik.png";
  mobileIcons["ljekarna"] = "icons/ljekarna.png";
  mobileIcons["gowalla"] = "../icons/gowalla.png";
  mobileIcons["odvjetnik"] = "../icons/odvjetnik.png";
  mobileIcons["foursquare"] = "../icons/foursquare.png";
  mobileIcons["domzdr"] = "icons/domzdr.png";
  mobileIcons["train"] = "icons/train.png";
  mobileIcons["plane"] = "icons/plane.png";
  mobileIcons["bus"] = "icons/bus.png";
  mobileIcons["police"] = "icons/police.png";
  mobileIcons["lutrija"] = "icons/lutrija.png";
  mobileIcons["kerum"] = "icons/store.png";
  mobileIcons["trajekt"] = "icons/trajekt.png";
  mobileIcons["tcom"] = "icons/tcom.png";

  iconSize = new google.maps.Size(32, 32);
  iconSizeSmall = new google.maps.Size(20, 20);
  iconOrigin = new google.maps.Point(0,0);
  mobileImages["home"] = new google.maps.MarkerImage( "../icons/citydot.png", new google.maps.Size(19, 20), iconOrigin, new google.maps.Point(10, 10), new google.maps.Size(19, 20) );
  for (i=0; i<POITypes.length; i++) {
    mobileImages[POITypes[i]] = new google.maps.MarkerImage( mobileIcons[POITypes[i]], iconSize, iconOrigin, new google.maps.Point(16, 16), iconSize );
    mobileImages[POITypes[i]+"small"] = new google.maps.MarkerImage( mobileIcons[POITypes[i]], iconSizeSmall, iconOrigin, new google.maps.Point(16, 16), iconSizeSmall );
  }

  locationRefreshDistance[0] = 0.500;
  locationRefreshDistance[1] = 1.000;
  locationRefreshDistance[2] = 2.500;

  if (window.navigator.standalone) {
    obj = document.getElementById("addToHomeScreen");
    if (obj!=null) {
      obj.style.visibility = "hidden";
      obj.style.height = "0px";
    }
  }
  //initializeMap();
}

function requestObject()
{
  var xmlhttp=false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
   }
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
  }
  if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
  }

  return xmlhttp;
}


function initializeMap() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var latlng = new google.maps.LatLng(currentLat, currentLong);
  var myOptions = {
    zoom: 15,
    center: latlng,
    mapTypeControl: false,
    disableDoubleClickZoom: false,
    scaleControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  //window.scrollTo(0,60);
}

function initializeMapLocation() {
  directionsDisplayLocation = new google.maps.DirectionsRenderer();
  var loclatlng = new google.maps.LatLng(currentLat, currentLong);
  var myLocOptions = {
    zoom: 14,
    center: loclatlng,
    mapTypeControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  mapLocation = new google.maps.Map(document.getElementById("map_canvas_location"), myLocOptions);
  directionsDisplayLocation.setMap(mapLocation);
  directionsDisplayLocation.setPanel(document.getElementById("directionsPanelPOI"));

}


function showError(error)
{
  obj = document.getElementById( "locationData" );
  obj.innerHTML = "<span class='msgError'>Greška! Ne mogu<br>odrediti lokaciju :(</span>";
}

function writeSpeed(where)
{
  /*
  obj = document.getElementById( where );
  obj.innerHTML = currentSpeed;
  if (currentSpeed < 50) {
    obj.style.backgroundImage = "url( images/speedlow.png )";
  } else if (currentSpeed < 80) {
    obj.style.backgroundImage = "url( images/speedmed.png )";
  } else {
    obj.style.backgroundImage = "url( images/speedhigh.png )";
  }
  */
  //alert( currentSpeed );
}

function showLocation(position)
{
  //alert( currentLat );
  if (!overrideLocation) {
    currentLat = position.coords.latitude;
    currentLong = position.coords.longitude;
    currentSpeed = position.coords.speed;
    currentHeading = position.coords.heading;
    //snapToAddress();
  }
  if (currentSpeed==null) {
    currentSpeed = 0;
  } else {
    currentSpeed = currentSpeed*3.6;
  }
  currentSpeed = currentSpeed.toFixed(1);// + " km/h";

  if (bmCurrentPage=="opcije") {
    obj = document.getElementById( "locationData" );
    var strLat = currentLat + " ";
    var strLng = currentLong + " ";
    obj.innerHTML = "<span class='msgNormal'>Lat: " + strLat.substring(0,12) + "<br>" + "Lng: " + strLng.substring(0,12) + "</span>";
    if (!overrideLocation) {
      img2 = document.getElementById("lokacija");
      img2.src = "images/on.png";
    } else {
      //img2 = document.getElementById("newLocationOO");
      //img2.src = "images/off.png";
    }
  }

  if (bmCurrentPage=="mapa" && followLocation) {
    writeSpeed( "speed" );
    p1 = new google.maps.LatLng( currentLat, currentLong );
    var currentOptions = {
      map: map,
      position: p1,
      icon: mobileImages["home"],
      zIndex: 5,
      title: getLangTxt("0001")
    };
    if (markerHomePOI==null) {
      markerHomePOI = new google.maps.Marker( currentOptions );
    } else {
      markerHomePOI.setMap(map);
      markerHomePOI.setPosition( p1 );
    }
    setTimeout( delayedCenter, 333, map, p1 );
  }

  if (bmCurrentPage=="mapaLokacija" && followLocation) {
    writeSpeed( "speedLokacija" );
    p1 = new google.maps.LatLng( currentLat, currentLong );
    var currentOptions = {
      map: mapLocation,
      position: p1,
      icon: mobileImages["home"],
      zIndex: 5,
      title: getLangTxt("0001")
    };
    if (markerHome==null) {
      markerHome = new google.maps.Marker( currentOptions );
    } else {
      markerHome.setIcon( mobileImages["home"] );
      markerHome.setMap( mapLocation );
      markerHome.setPosition( p1 );
    }
    setTimeout( delayedCenter, 333, mapLocation, p1 );

    dst = distance( currentLat, currentLong, lastLat, lastLong, "K" );
    dst = dst.toFixed(3);
    useRD = 0;
    if (currentSpeed>50 && currentSpeed<80) {
      useRD = 1;
    } else if (currentSpeed>80) {
      useRD = 2;
    }

    doRefresh = (locationRefreshDistance[useRD] - dst) * 1000;
    if (doRefresh<0) doRefresh = 0;
    document.getElementById("autoRefreshDistance").innerHTML = refreshIn + doRefresh.toFixed(0) + " m";

    if (dst>=locationRefreshDistance[useRD]) {
      lastLat = currentLat;
      lastLong = currentLong;
      setTimeout( getMapPOI, 100 );
    }

    //to next turn
    refreshNavigation();
  }

}

function refreshNavigation()
{
  if (currentRoute>=0 && currentLeg>=0 && currentStep>=0 && locationDirResponse!=null) {
    if (currentStep<locationDirResponse.routes[0].legs[0].steps.length) {
      useStep = locationDirResponse.routes[0].legs[0].steps[currentStep];
      useBearing = bearing( currentLat, currentLong, useStep.end_point.lat(), useStep.end_point.lng() );
      if (currentHeading>=0 && currentHeading<=360) {
        useBearing = useBearing - currentHeading;
        if (useBearing<0) {
          useBearing += 360;
        }
      }
      if (currentHeading==null) {
        currentHeading = 0;
      }
      /*
      useDist = distance( currentLat, currentLong, useStep.end_point.lat(), useStep.end_point.lng(), "K" )*1000;
      document.getElementById("lokacijaNavigation").innerHTML = useDist.toFixed(0) + " m" +
                                                                "<br>" +
                                                                "B: " + useBearing.toFixed(0) + "°" +
                                                                "<br>" +
                                                                "H: " + currentHeading + "°";
                                                                //"<br>" +
                                                                //currentStep + " / " + (locationDirResponse.routes[0].legs[0].steps.length-1);
      /*
      if (useDist>80) {
        //document.getElementById("naviTurn").style.visibility = "hidden";
      }
      if (useDist<80 ) {

        document.getElementById("naviTurn").style.visibility = "visible";
        document.getElementById("naviText").innerHTML = useDist.toFixed(0) + " m";
        if (useBearing>=0 && useBearing<180) {
          useImg = "empty.png";
        } else {
          useImg = "empty.png";
        }
        document.getElementById("naviTurn").style.backgroundImage = "url(navi/" + useImg + ")";

      }
      if (useDist<20) {
        document.getElementById("naviTurn").style.visibility = "hidden";
        currentStep++;
        if (currentStep>=locationDirResponse.routes[0].legs[0].steps.length) {
          currentStep = locationDirResponse.routes[0].legs[0].steps.length-1;
        }
      }
      if (currentStep>=locationDirResponse.routes[0].legs[0].steps.length-1) {
        if (useDist<50) {
          document.getElementById("naviTurn").style.visibility = "visible";
          document.getElementById("naviText").innerHTML = useDist.toFixed(0) + " m";
          document.getElementById("naviTurn").style.backgroundImage = "url(navi/empty.png)";
        }
        if (useDist<20) {
          document.getElementById("naviTurn").style.visibility = "hidden";
        }
      }
      */

    } else {
      document.getElementById("lokacijaNavigation").innerHTML = "";
    }
  } else {
    document.getElementById("lokacijaNavigation").innerHTML = "";
  }
}

function getCloseData()
{
  document.getElementById("blizu").innerHTML = "<h1 class=\"rrh1\">"+getLangTxt("0002")+"</h1>";
  var address = "../actions.php?a=confirmLocationGPSMobile&lat=" + currentLat + "&long=" + currentLong + "&type=" + selectedPOIType;
  //alert( address );
  ajaxObjectGPS = requestObject();
  ajaxObjectGPS.open("GET", address, true);
  ajaxObjectGPS.onreadystatechange=function() {
    if (ajaxObjectGPS.readyState==4) {
      document.getElementById("blizu").innerHTML = ajaxObjectGPS.responseText;
    }
  }
  ajaxObjectGPS.send(null)
}

function writeTestData()
{
  obj = document.getElementById("blizu");
  obj.innerHTML = '<h1 class="rrh1">Promjena</h1>';
}

function doLoadDataForId( id )
{
  //writeTestData();
}

function switchDataToShow(id, reloadPOIs)
{
  ext = new Array();
  onoff = new Array();
  ext[0] = "_off.png";
  ext[1] = ".png";
  onoff[0] = "off.png";
  onoff[1] = "on.png";
  //img = document.getElementById("i"+id);
  //img2 = document.getElementById(id);
  //img3 = document.getElementById("ml"+id);
  //if (img==null) {
    //return;
  //}
  for (i=0; i<POITypes.length; i++) {
    dataToShow[POITypes[i]] = 0;
    //document.getElementById("i"+POITypes[i]).src = "../icons/" + POITypes[i] + ext[dataToShow[POITypes[i]]];
    //document.getElementById("FLi"+POITypes[i]).src = "../icons/" + POITypes[i] + ext[dataToShow[POITypes[i]]];

    //document.getElementById(POITypes[i]).src = "images/" + onoff[dataToShow[POITypes[i]]];
    //document.getElementById("FL" + POITypes[i]).src = "images/" + onoff[dataToShow[POITypes[i]]];

    //document.getElementById("ml"+POITypes[i]).src = "../icons/" + POITypes[i] + ext[dataToShow[POITypes[i]]];
  }

  if (dataToShow[id]==0) {
    dataToShow[id] = 1;
  } else {
    dataToShow[id] = 0;
  }

  selectedPOIType = id;
  
  /*
  img.src = "../icons/" + id + ext[dataToShow[id]];
  img2.src = "images/" + onoff[dataToShow[id]];
  img3.src = "../icons/" + id + ext[dataToShow[id]];

  /*

  createCookie( id, dataToShow[id], 30 );

  img.src = "../icons/" + id + ext[dataToShow[id]];
  img2.src = "images/" + onoff[dataToShow[id]];
  img3.src = "../icons/" + id + ext[dataToShow[id]];

  setVisibleTypes(reloadPOIs);
  */

  if (reloadPOIs) {
    getMapPOI();
  }
}

function setVisibleTypes(reloadPOIs)
{
  /*
  var data = "";
  data += "&atm=" + dataToShow["atm"];
  data += "&biljeznik=" + dataToShow["biljeznik"];
  data += "&odvjetnik=" + dataToShow["odvjetnik"];
  data += "&ljekarna=" + dataToShow["ljekarna"];
  data += "&gowalla=" + dataToShow["gowalla"];
  data += "&foursquare=" + dataToShow["foursquare"];
  ajaxTypes = requestObject();
  var address = "../actions.php?a=setVisibleTypes" + data;
  ajaxTypes.open("GET", address, true);
  //alert(address);
  ajaxTypes.onreadystatechange=function() {
    if (ajaxTypes.readyState==4) {
      if (reloadPOIs) {
        getMapPOI();
      }
      //confirmLocationGPS( markerHome.getPoint().lat(), markerHome.getPoint().lng() );
      //alert("bbb");
      //document.getElementById("popisGradova").innerHTML = ajaxTypes.responseText;
    }
  }
  ajaxTypes.send(null)
  */
}

function showLocationOnMap( lat, lng, pv_type, desc )
{
  if (map==null) {
    initializeMap();
  }

  pointLat = lat;
  pointLng = lng;
  //document.getElementById( "pointTitle" ).innerHTML = "<h1 class=\"rrh1\">"+desc+"</h1>";
  document.getElementById( "pointTitle" ).innerHTML = desc;

  p1 = new google.maps.LatLng( currentLat, currentLong );
  p2 = new google.maps.LatLng( lat, lng );

  var currentOptions = {
    map: map,
    position: p1,
    icon: mobileImages["home"],
    zIndex: 5,
    title: getLangTxt("0001")
  };
  if (markerHomePOI==null) {
    markerHomePOI = new google.maps.Marker( currentOptions );
  } else {
    markerHomePOI.setMap( map );
    markerHomePOI.setPosition( p1 );
  }

  var selectedOptions = {
    map: map,
    position: p2,
    icon: mobileImages[pv_type],
    zIndex: 0,
    title: "Odabrana lokacija"
  };
  if (markerSelected==null) {
    markerSelected = new google.maps.Marker( selectedOptions );
  } else {
    markerSelected.setIcon( mobileImages[pv_type] );
    markerSelected.setPosition( p2 );
  }

  //map.setCenter( p1 );

  refreshDirections();

  /*
  locationFrom = "(" + p1.lat() + ", " + p1.lng() + ")";
  locationTo = "(" + p2.lat() + ", " + p2.lng() + ")";

  if (driveType==0) {
    travelMode = google.maps.DirectionsTravelMode.DRIVING;
  } else {
    travelMode = google.maps.DirectionsTravelMode.WALKING;
  }
  var request = {
        origin: locationFrom,
        destination: locationTo,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC,
        travelMode: travelMode

  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      }
  });
  */
}

function switchDriveType(id)
{
  ext = new Array();
  ext[1] = "_off.png";
  ext[0] = ".png";
  onoff = new Array();
  onoff[0] = "off.png";
  onoff[1] = "on.png";
  //img = document.getElementById("mlcar");
  img2 = document.getElementById(id);

  if (img2==null) {
    return;
  }
  if (driveType==0) {
    driveType = 1;
  } else {
    driveType = 0;
  }
  createCookie( id, driveType, 30 );
  //img.src = "../icons/car" + ext[driveType];
  img2.src = "images/" + onoff[driveType];
}

function followCurrentLocation(id)
{
  onoff = new Array();
  onoff[0] = "off.png";
  onoff[1] = "on.png";
  img2 = document.getElementById(id);
  if (img2==null) {
    return;
  }
  if (followLocation==0) {
    followLocation = 1;
  } else {
    followLocation = 0;
  }
  createCookie( id, followLocation, 30 );
  img2.src = "images/" + onoff[followLocation];
}


function showMapPage()
{
  page = document.getElementById( "mapa" );
  points = document.getElementById( "blizu" );

  //showPage( page, points );
}

function refreshLocation()
{
  overrideLocation = false;
  if (navigator.geolocation) {
    img2 = document.getElementById("lokacija");
    img2.src = "images/off.png";
    //alert("a");
    navigator.geolocation.getCurrentPosition(showLocation, showError, {enableHighAccuracy:true});
    //alert("b");
  }
}

function showCurrentPosition()
{
  if (mapLocation==null) {
    initializeMapLocation();
  } else {
    //mapLocation.panBy( 140, 128 );
  }

  //document.getElementById("directionsPanelPOI").innerHTML = "";
  //directionsDisplayLocation.setMap(null);

  var p1 = new google.maps.LatLng( currentLat, currentLong );

  var currentOptions = {
    map: mapLocation,
    position: p1,
    icon: mobileImages["home"],
    zIndex: 5,
    title: getLangTxt("0001")
  };
  if (markerHome==null) {
    markerHome = new google.maps.Marker( currentOptions );
  } else {
    markerHome.setMap(null);
    markerHome = new google.maps.Marker( currentOptions );
    markerHome.setMap( mapLocation );
    markerHome.setPosition( p1 );
  }
  //mapLocation.setZoom( 15 );

  setTimeout( delayedCenter, 333, mapLocation, p1 );
  setTimeout( getMapPOI, 1000 );
  //getMapPOI();

  /*
  document.getElementById( "pointTitleLocation" ).innerHTML = "<b>"+getLangTxt("0001")+"</b><br>Lat: " + currentLat +
                                                              "<br>Lng: " + currentLong + "<br>";
                                                              //"Center Lat: " + mapLocation.getCenter().lat() + "<br>" +
                                                              //"Center Lng: " + mapLocation.getCenter().lng() + "<br>";
  */
}

function delayedCenter( useMap, point )
{
  useMap.setCenter( point );
  useMap.setZoom( useMap.getZoom() );
}

function refreshDirections()
{
  locationFrom = "(" + currentLat + ", " + currentLong + ")";
  locationTo = "(" + pointLat + ", " + pointLng + ")";

  if (driveType==0) {
    travelMode = google.maps.DirectionsTravelMode.DRIVING;
  } else {
    travelMode = google.maps.DirectionsTravelMode.WALKING;
  }
  var request = {
        origin: locationFrom,
        destination: locationTo,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC,
        travelMode: travelMode

  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

function refreshDirectionsLocation( lat, lng, desc )
{
  document.getElementById( "directionsPanelPOITitle" ).innerHTML = desc + "<br>";
  locationFrom = "(" + currentLat + ", " + currentLong + ")";
  locationTo = "(" + lat + ", " + lng + ")";

  if (driveType==0) {
    travelMode = google.maps.DirectionsTravelMode.DRIVING;
  } else {
    travelMode = google.maps.DirectionsTravelMode.WALKING;
  }
  var request = {
        origin: locationFrom,
        destination: locationTo,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC,
        travelMode: travelMode

  };
  directionsDisplayLocation.setMap(mapLocation);


  directionsServiceLocation.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      locationDirResponse = response;
      directionsDisplayLocation.setDirections(response);
      if (response.routes.length>0) {
        currentRoute = 0;
        if (response.routes[0].legs.length>0) {
          currentLeg = 0;
          if (response.routes[0].legs[0].steps.length>0) {
            currentStep = 0;
            refreshNavigation();
          }
        }
      }
      /*
      console.log( "Ruta: " + response.routes.length );
      console.log( "Tocaka: " + response.routes[0].overview_path.length );
      console.log( "Legs: " + response.routes[0].legs.length );
      for (i=0; i<response.routes[0].legs.length; i++) {
        //console.log( "Leg " + i + " steps: " + response.routes[0].legs[i].steps.length );

        for (j=0; j<response.routes[0].legs[i].steps.length; j++) {
          console.log( "Leg " + i + " step " + j + " distance: " +
                       response.routes[0].legs[i].steps[j].distance.value );
        }

      }
      */
    }
  });
}


function readCookie(name)
{
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) {
      res = c.substring(nameEQ.length,c.length)
      //alert( name + " = " + res );
      if (name!="language") {
        if (res=="undefined") { res = "1"; }
      }
      return res;
    }
  }
  return "0";
}

function createCookie(name,value,days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  } else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function changeLanguage( lang )
{
  createCookie( "language", lang, 100 );
  document.location = "indexGO.php";
}

function getLangTxt( code )
{
  if (readCookie("language")=="hr") {
    if (code=="0001") {
      return "Moja lokacija";
    } else if (code=="0002") {
      return "Preuzimam podatke...";
    } else if (code=="0003") {
      return "Nazad";
    } else if (code=="0004") {
      return "Osvježi podatke";
    }


  } else if (readCookie("language")=="en") {
    if (code=="0001") {
      return "My location";
    } else if (code=="0002") {
      return "Downloading data...";
    } else if (code=="0003") {
      return "Back";
    } else if (code=="0004") {
      return "Refresh data";
    }
  }
}

function getMapPOI()
{
  if (loadingLocationPOIs) {
    return;
  }
  loadingLocationPOIs = true;
  ajaxMapPOIs = requestObject();
  var address = "../actions.php?a=getMapPOI&lat="+currentLat+"&long="+currentLong+"&list=mapPOIs&map=mapLocation" +
                "&type=" + selectedPOIType + "&device=mobile";
  ajaxMapPOIs.open("GET", address, true);
  //alert(address);
  ajaxMapPOIs.onreadystatechange=function() {
    if (ajaxMapPOIs.readyState==4) {
      loadingLocationPOIs = false;
      deleteMarkersLocation();
      eval( ajaxMapPOIs.responseText );
    }
  }
  ajaxMapPOIs.send(null)
}

function deleteMarkersLocation()
{
  for (i=0; i<mapPOIs.length; i++) {
    mapPOIs[i].setMap(null);
    mapPOIs[i].setVisible(false);
    mapPOIs[i] = null;
  }
  mapPOIs.length = 0;
}

function updateOrientation()
{
  var orientation = window.orientation;
  switch (orientation) {
    // If we're horizontal
    case 90:
    case -90:
      document.body.setAttribute("orient", "landscape");
      break;
    default:
      document.body.setAttribute("orient", "portrait");
      break;
  }
}

function distance(lat1, lon1, lat2, lon2, unit) {
	var radlat1 = Math.PI * lat1/180
	var radlat2 = Math.PI * lat2/180
	var radlon1 = Math.PI * lon1/180
	var radlon2 = Math.PI * lon2/180
	var theta = lon1-lon2
	var radtheta = Math.PI * theta/180
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist)
	dist = dist * 180/Math.PI
	dist = dist * 60 * 1.1515
	if (unit=="K") { dist = dist * 1.609344 }
	if (unit=="N") { dist = dist * 0.8684 }
	return dist
}

function playAudio()
{
  aud = document.getElementById("testAudio");
  aud.play();
  //window.location = "voice/test1.mp3";
}

function bearing(lat1, lon1, lat2, lon2)
{
  lat1 = lat1.toRad(); lat2 = lat2.toRad();
  var dLon = (lon2-lon1).toRad();

  var y = Math.sin(dLon) * Math.cos(lat2);
  var x = Math.cos(lat1)*Math.sin(lat2) -
          Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
  return Math.atan2(y, x).toBrng();
}

Number.prototype.toRad = function() {  // convert degrees to radians
  return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
  return this * 180 / Math.PI;
}

Number.prototype.toBrng = function() {  // convert radians to degrees (as bearing: 0...360)
  return (this.toDeg()+360) % 360;
}

function setNewLocation()
{
  obj = document.getElementById("newLocation");
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( {address: obj.value}, geocoderResults );
}

function geocoderResults( results, status )
{
  if (!results) {
    alert( "Došlo je do greške" );
  } else {
    overrideLocation = true;
    res = results[0].geometry.location;
    currentLat = res.lat();
    currentLong = res.lng();
    document.getElementById("newLocationOO").src = "images/on.png";
    document.getElementById("lokacija").src = "images/off.png";
    obj = document.getElementById("newLocation");
    document.getElementById("noNavi").innerHTML = "<center><span class='msgError biggerText'>"+obj.value+"</span></center>";
    showLocation(null);
  }
}

function snapToAddress()
{
  obj = new google.maps.LatLng( currentLat, currentLong );
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( {latLng: obj}, snapResults );

}

function snapResults( results, status )
{
  if (!results) {
    //alert( "Došlo je do greške" );
  } else {
    //obj = document.getElementById("newLocation");
    //obj.value = results[0].address_components.long_name;
  }
}

