var dirn = new GDirections();
var gdir = new GDirections();
var step = 1; // metres
var tick = 40; // milliseconds
var poly;
var poly2;
var lastVertex = 0;
var eol;
var marker;
var homeMarker;
var k=0;
var stepnum=0;
var speed = "";
var animationPlaying = false;

var img = new Image();
var img270 = new Image();
var angle;
var canvas;
var zoom4In = 17;
var zoom4Med = 16;
var zoom4Out = 15;
var tick4In = 40;
var tick4Med = 35;
var tick4Out = 30;
var routeStartId = "0";
var routeEndId = "-1";
var latestActionInterval = -1;
var wallet = 0;
var consumating = false;
var creatingPresent = false;
var creatingPackage = false;

var markerPerson;

var suggestionsActive = false;

var allowedBounds;
var mainMapShown = true;

var currentLat = 0;
var currentLong = 0;

var iconRed = new GIcon();
var iconCity = new GIcon();
var iconBiljeznik = new GIcon();
var iconOdvjetnik = new GIcon();
var iconCurrent = new GIcon();
var iconLjekarna = new GIcon();
var iconGowalla = new GIcon();
var iconFourSquare = new GIcon();
var iconDomzdr = new GIcon();
var iconTrain = new GIcon();
var iconPlane = new GIcon();
var iconBus = new GIcon();
var iconPolice = new GIcon();
var iconLutrija = new GIcon();
var iconKerum = new GIcon();
var iconTrajekt = new GIcon();
var iconTcom = new GIcon();

var marker = null;
var markerHome = null;
var customIcons = [];
var currentDesc = "";

var dataToShow = new Array();

var pointIsCity = false;

var pointFromURL = "";

var win = null;

var isZoomToCity = false;

var POITypes = new Array();


function loadIcons()
{
  iconRed.image = 'mobile/icons/atm.png';
  iconRed.iconSize = new GSize(32, 32);
  iconRed.iconAnchor = new GPoint(16, 16);
  iconRed.infoWindowAnchor = new GPoint(16, 16);

  iconCurrent.image = 'icons/current.png';
  iconCurrent.iconSize = new GSize(32, 32);
  iconCurrent.iconAnchor = new GPoint(16, 16);
  iconCurrent.infoWindowAnchor = new GPoint(16, 16);


  iconBiljeznik.image = 'icons/biljeznik.png';
  iconBiljeznik.iconSize = new GSize(32, 32);
  iconBiljeznik.iconAnchor = new GPoint(16, 16);
  iconBiljeznik.infoWindowAnchor = new GPoint(16, 16);

  iconOdvjetnik.image = 'icons/odvjetnik.png';
  iconOdvjetnik.iconSize = new GSize(32, 32);
  iconOdvjetnik.iconAnchor = new GPoint(16, 16);
  iconOdvjetnik.infoWindowAnchor = new GPoint(16, 16);

  iconLjekarna.image = 'mobile/icons/ljekarna.png';
  iconLjekarna.iconSize = new GSize(32, 32);
  iconLjekarna.iconAnchor = new GPoint(16, 16);
  iconLjekarna.infoWindowAnchor = new GPoint(16, 16);

  iconGowalla.image = 'icons/gowalla.png';
  iconGowalla.iconSize = new GSize(32, 32);
  iconGowalla.iconAnchor = new GPoint(16, 16);
  iconGowalla.infoWindowAnchor = new GPoint(16, 16);

  iconFourSquare.image = 'icons/foursquare.png';
  iconFourSquare.iconSize = new GSize(32, 32);
  iconFourSquare.iconAnchor = new GPoint(16, 16);
  iconFourSquare.infoWindowAnchor = new GPoint(16, 16);


  iconCity.image = 'icons/citydot.png';
  iconCity.iconSize = new GSize(19, 20);
  iconCity.iconAnchor = new GPoint(7, 12);
  iconCity.infoWindowAnchor = new GPoint(7, 12);

  iconDomzdr.image = 'mobile/icons/domzdr.png';
  iconDomzdr.iconSize = new GSize(32, 32);
  iconDomzdr.iconAnchor = new GPoint(16, 16);
  iconDomzdr.infoWindowAnchor = new GPoint(16, 16);

  iconTrain.image = 'mobile/icons/train.png';
  iconTrain.iconSize = new GSize(32, 32);
  iconTrain.iconAnchor = new GPoint(16, 16);
  iconTrain.infoWindowAnchor = new GPoint(16, 16);

  iconPlane.image = 'mobile/icons/plane.png';
  iconPlane.iconSize = new GSize(32, 32);
  iconPlane.iconAnchor = new GPoint(16, 16);
  iconPlane.infoWindowAnchor = new GPoint(16, 16);

  iconBus.image = 'mobile/icons/bus.png';
  iconBus.iconSize = new GSize(32, 32);
  iconBus.iconAnchor = new GPoint(16, 16);
  iconBus.infoWindowAnchor = new GPoint(16, 16);

  iconPolice.image = 'mobile/icons/police.png';
  iconPolice.iconSize = new GSize(32, 32);
  iconPolice.iconAnchor = new GPoint(16, 16);
  iconPolice.infoWindowAnchor = new GPoint(16, 16);

  iconLutrija.image = 'mobile/icons/lutrija.png';
  iconLutrija.iconSize = new GSize(32, 32);
  iconLutrija.iconAnchor = new GPoint(16, 16);
  iconLutrija.infoWindowAnchor = new GPoint(16, 16);

  iconKerum.image = 'mobile/icons/store.png';
  iconKerum.iconSize = new GSize(32, 32);
  iconKerum.iconAnchor = new GPoint(16, 16);
  iconKerum.infoWindowAnchor = new GPoint(16, 16);

  iconTrajekt.image = 'mobile/icons/trajekt.png';
  iconTrajekt.iconSize = new GSize(32, 32);
  iconTrajekt.iconAnchor = new GPoint(16, 16);
  iconTrajekt.infoWindowAnchor = new GPoint(16, 16);

  iconTcom.image = 'mobile/icons/tcom.png';
  iconTcom.iconSize = new GSize(32, 32);
  iconTcom.iconAnchor = new GPoint(16, 16);
  iconTcom.infoWindowAnchor = new GPoint(16, 16);

  customIcons["atm"] = iconRed;
  customIcons["city"] = iconCity;
  customIcons["biljeznik"] = iconBiljeznik;
  customIcons["current"] = iconCurrent;
  customIcons["odvjetnik"] = iconOdvjetnik;
  customIcons["ljekarna"] = iconLjekarna;
  customIcons["gowalla"] = iconGowalla;
  customIcons["foursquare"] = iconFourSquare;
  customIcons["domzdr"] = iconDomzdr;
  customIcons["train"] = iconTrain;
  customIcons["plane"] = iconPlane;
  customIcons["bus"] = iconBus;
  customIcons["police"] = iconPolice;
  customIcons["lutrija"] = iconLutrija;
  customIcons["kerum"] = iconKerum;
  customIcons["trajekt"] = iconTrajekt;
  customIcons["tcom"] = iconTcom;

}

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 bearing( from, to ) {
  // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
  // Convert to radians.
  var lat1 = from.latRadians();
  var lon1 = from.lngRadians();
  var lat2 = to.latRadians();
  var lon2 = to.lngRadians();
  // Compute the angle.
  var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
  if ( angle < 0.0 )
    angle  += Math.PI * 2.0;
  if (angle == 0) {angle = 0.01;}
  return angle;
}

function plotcar() {
  var cosa = Math.cos(angle);
  var sina = Math.sin(angle);
  canvas.clearRect(0,0,50,50);
  canvas.save();
  canvas.rotate(angle);
  canvas.translate(24*sina+24*cosa,24*cosa-24*sina);
  if (angle>3.9 && angle<5.6) {
    canvas.drawImage(img270, -24, -24);
  } else {
    canvas.drawImage(img,-24,-24);
  }
  canvas.restore();
}

function setMinMaxZoom(useMap, mapMin, mapMax)
{
  var mapTypes = useMap.getMapTypes();
  for (var i=0; i<mapTypes.length; i++) {
    mapTypes[i].getMinimumResolution = function() {return mapMin;}
    mapTypes[i].getMaximumResolution = function() {return mapMax;}
  }
}

function createMap()
{
  map.addControl(new GSmallZoomControl3D());
  map.addControl(new GScaleControl());
  map.setCenter(new GLatLng(45.813082685527796, 15.976266860961914), 8, G_NORMAL_MAP);
  map.enableContinuousZoom();
  map.enableDoubleClickZoom();
  map.enableScrollWheelZoom();
  var minMapScale = 6;
  var maxMapScale = 17;
  setMinMaxZoom( map, minMapScale, maxMapScale );

  mapBig.addControl(new GSmallZoomControl3D());
  mapBig.addControl(new GScaleControl());
  mapBig.setCenter(new GLatLng(45.813082685527796, 15.976266860961914), 6, G_NORMAL_MAP);
  mapBig.enableContinuousZoom();
  mapBig.enableDoubleClickZoom();
  mapBig.enableScrollWheelZoom();
  var minMapScale = 6;
  var maxMapScale = 17;
  setMinMaxZoom( mapBig, minMapScale, maxMapScale );
}

function createMarker(point, desc, type, id)
{
  myMarker = new GMarker(point, customIcons[type]);
  // Show this markers index in the info window when it is clicked
  var html = "";
  if (id!=null && id!="-1" && id!="0") {
    html = "<span class='infoLocation'>";
    if (pointIsCity) {
      //tockeOpisCities[id] = desc;
      html = "";
      html += desc;
    } else {
      //tockeOpis[id] = desc;
      html = desc;
    }
    html += "</span>";
  } else if (id=="-1") {
    html = "<b>" + desc + "</b>";
  } else {
    html = "<span class='infoLocation'>" + desc +"</span>";
  }

  if (pointIsCity) {
    GEvent.addListener(myMarker, "click", function() {zoomToCity( point.y, point.x );});
    GEvent.addListener(myMarker, "mouseover", function() {writeCityName(html, point.y, point.x);});
  } else {
    if (id!="0") {
      GEvent.addListener(myMarker, "click", function() {myMarker.openInfoWindowHtml(html);});
      GEvent.addListener(myMarker, "mouseover", function() {myMarker.openInfoWindowHtml(html);});
      currentDesc = html;
    }
  }


  if (id!=null) {
  }
  return myMarker;
};

function updatePoly(d)
{
  // Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
  if (poly2.getVertexCount() > 10) {
    poly2=new GPolyline([poly.getVertex(lastVertex-1)]);
    map.addOverlay(poly2)
  }

  if (poly.GetIndexAtDistance(d) < lastVertex+2) {
     if (poly2.getVertexCount()>1) {
       poly2.deleteVertex(poly2.getVertexCount()-1)
     }
     poly2.insertVertex(poly2.getVertexCount(),poly.GetPointAtDistance(d));
  } else {
    poly2.insertVertex(poly2.getVertexCount(),poly.getVertex(lastVertex++));
  }
}

GEvent.addListener(dirn,"load", function() {
  //document.getElementById("controls").style.display="none";
  poly=dirn.getPolyline();
  eol=poly.Distance();
  map.setCenter(poly.getVertex(0),16);
  //map.addOverlay(new GMarker(poly.getVertex(0),G_START_ICON));
  //map.addOverlay(new GMarker(poly.getVertex(poly.getVertexCount()-1),G_END_ICON));
  if (supportsCanvas) {
    marker = new ELabel(poly.getVertex(0), '<canvas id="carcanvas" width="48" height="48"><\/canvas>',null,new GSize(-24,24));
    map.addOverlay(marker);
    canvas = document.getElementById("carcanvas").getContext('2d');
    var p0 = poly.getVertex(0);
    var p1 = poly.getVertex(1);
    angle = bearing(p0,p1);
    plotcar();
  } else {
    marker = new GMarker(poly.getVertex(0),{icon:car});
    map.addOverlay(marker);
  }
  //marker = new GMarker(poly.getVertex(0),{icon:car});
  //map.addOverlay(marker);
  var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
  //document.getElementById("step").innerHTML = steptext;
  drawStep( steptext );
  poly2 = new GPolyline([poly.getVertex(0)]);
  map.addOverlay(poly2);
  //map.setZoom( 16 );
  animationPlaying = true;
  setTimeout("animate(0)",500);  // Allow time for the initial map display
});

GEvent.addListener(dirn,"error", function() {
  alert("Location(s) not recognised. Code: "+dirn.getStatus().code);
});

function start() {
  if (animationPlaying) {
    return;
  }
  vratiMapu();
  stepnum = 0;

  var startpoint = "";
  var endpoint = "";

  canStartRoute = false;
  if (routeStartId >= "0" && routeEndId >= "0" ) {
    if (routeStartId!=routeEndId) {
      startpoint = tocke[routeStartId].getPoint().toString();
      endpoint = tocke[routeEndId].getPoint().toString();
      canStartRoute = true;
    } else {
      markerPerson.openInfoWindow( "<span class='infoLocation'>"+lang["0004"]+" <b>" + tockeOpis[routeStartId] + "</b>!<br>"+lang["0005"]+"</span>" );
    }
  } else {
    alert( lang["0006"] );
  }
  lastVertex = 0;
  if (canStartRoute) {
    document.getElementById( "suggestionsActive" ).innerHTML = "";
    map.removeOverlay( markerPerson );
    dirn.loadFromWaypoints([startpoint,endpoint],{getPolyline:true,getSteps:true});
    //document.getElementById("step").style.visibility = "visible";
    //document.getElementById("step").style.height = "50px";
    //document.getElementById("latestAction").style.visibility = "hidden";
    //document.getElementById("latestAction").style.height = "0px";

  }
}

function cameToLocation()
{
    startLoader();
    ajaxObject = requestObject();
    var address = "actions.php?a=checkIn&p=" + routeEndId + "&u="+user_id + "&d=" + (eol/1000).toFixed(2);
    //alert( address );
    ajaxObject.open("GET", address,true);
    ajaxObject.onreadystatechange=function() {
      if (ajaxObject.readyState==4) {
        var str4InfoWindow = "<span class='infoLocation'>"+fb_first_name+" "+lang["0007"]+" <b>" + tockeOpis[routeStartId] + "</b>.";
        //alert( str4InfoWindow );
        //alert( ajaxObject.responseText );
        if (ajaxObject.responseText=="1") {
          str4InfoWindow += "<br>"+lang["0008"]+"";
          str4InfoWindow += "<br><label onClick=\"brisiMapu(true);\" class=\"routeLink\">"+lang["0009"]+"</label>";
          //str4InfoWindow += "<br><img src='icons/menu/drink.png' onClick='showDrinks()' class='routeLink' width=32 height=32>";
        }
        str4InfoWindow += "</span>";
        markerPerson = createMarker(marker.getPoint(), str4InfoWindow, "person");
        map.addOverlay( markerPerson );
        markerPerson.openInfoWindow( str4InfoWindow );
        document.getElementById( "percentCompleted" ).style.width = "0px";
        document.getElementById( "percentCompleted" ).innerHTML = "";
        document.getElementById( "interiorView" ).innerHTML = "";
        endLoader();
      }
    }
    ajaxObject.send(null)

    //document.getElementById("step").innerHTML = "";
    drawStep( "" );
    //document.getElementById("routeDescription").innerHTML = "";// tockeOpis[routeStartId] + " => " + tockeOpis[routeEndId] + ", pređena udaljenost " + (d/1000).toFixed(2) + " km";
    drawRouteDescription( "" );
    map.removeOverlay(marker);
    map.removeOverlay(poly2);
    animationPlaying = false;
    routeStartId = routeEndId;
    writeCurrentPosition();
    map.setCenter( marker.getPoint() );
    //document.getElementById("step").style.visibility = "hidden";
    //document.getElementById("step").style.height = "0px";
    //document.getElementById("latestAction").style.visibility = "visible";
    //document.getElementById("latestAction").style.height = "100px";
    drawRouteDescription( "suggestLocation" );
    //brisiMapu();

}

function drawRoutePercent(d)
{
  postoPuta = (d/eol)*100;
  if (postoPuta<10 || postoPuta>90) {
    if (map.getZoom()!=zoom4In) {
      map.setZoom( zoom4In );
      map.setCenter( marker.getPoint() );
      tick = tick4In;
    }
  } else if (postoPuta<20 || postoPuta>80) {
    if (map.getZoom()!=zoom4Med) {
      map.setZoom( zoom4Med );
      map.setCenter( marker.getPoint() );
      tick = tick4Med;
    }
  } else {
    if (map.getZoom()!=zoom4Out) {
      map.setZoom( zoom4Out );
      map.setCenter( marker.getPoint() );
      tick = tick4Out;
    }
  }
  document.getElementById( "percentCompleted" ).style.width = Math.round( (postoPuta/100)*670 ) + "px";
}

function drawRouteDescription(d)
{
  var strDesc = ""+lang["0010"]+" <b>" + tockeOpis[routeStartId] + "</b> "+lang["0011"]+" <b>" + tockeOpis[routeEndId] + "</b>. ";
  strDesc += ""+lang["0012"]+" " + (d/1000).toFixed(2) + " km";
  if (routeStartId==routeEndId) {
    strDesc = "";
  }
  if (d=="suggestLocation") {
    suggestLocationMenu();
  } else {
    document.getElementById("routeDescription").innerHTML = strDesc;
  }
}

function drawVehicle(p, d)
{
  marker.setPoint(p);
  if (supportsCanvas) {
    if (poly.GetIndexAtDistance(d)>lastVertex) {
      lastVertex = poly.GetIndexAtDistance(d);
      if (lastVertex == poly.getVertexCount()) {
        lastVertex -= 1;
      }
      while (poly.getVertex(lastVertex-1).equals(poly.getVertex(lastVertex))) {
        lastVertex-=1;
      }

      angle = bearing(poly.getVertex(lastVertex-1),poly.getVertex(lastVertex) );
      plotcar();
    }
  }
}

function animate(d)
{
  if (d>eol) {
    cameToLocation();
    return;
  }

  drawRoutePercent(d);
  drawRouteDescription(d);

  var p = poly.GetPointAtDistance(d);

  if (!map.getBounds().containsLatLng(p)) {
    map.panTo(p);
  }

  //stepnum += 3;
  if (stepnum+1 < dirn.getRoute(0).getNumSteps()) {
    if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d)) {
      stepnum++;
      var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
      //document.getElementById("step").innerHTML = steptext;
      drawStep( steptext );
      var stepdist = dirn.getRoute(0).getStep(stepnum-1).getDistance().meters;
      var steptime = dirn.getRoute(0).getStep(stepnum-1).getDuration().seconds;
      var stepspeed = ((stepdist/steptime) * 2.24).toFixed(0);
      step = stepspeed/2.5;
      speed = ""; //<br>Current speed: " + stepspeed +" mph";
    }
  } else {
    if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d)) {
      //document.getElementById("step").innerHTML = "<b>Dolazak na odredište<\/b>";
      drawStep( "<b>"+lang["0013"]+"<\/b>" );
    }
  }

  drawVehicle(p, d);

  setTimeout("animate("+(d+step)+")", tick);
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function drawStep( txt )
{
  //document.getElementById("step").innerHTML = txt;
}

function loadJS(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function getLocation()
{
  document.getElementById("chooseLocation").innerHTML = "<span class='msgError'>Mogućnost određivanja lokacije je pronađena, moraš mi dopustiti određivanje tvoje lokacije.</span>";
  navigator.geolocation.getCurrentPosition(showLocation, showError, {enableHighAccuracy:true,maximumAge:60000});
}

function showError(error)
{
  document.getElementById("chooseLocation").innerHTML = "<span class='msgError'>Greška prilikom određivanja lokacije :(</span>";
}

function showLocation(position)
{
  //alert( position.coords.latitude );
  //map.setCenter(new GLatLng(position.coords.latitude, position.coords.longitude), 15, G_NORMAL_MAP);
  lat = position.coords.latitude;
  lng = position.coords.longitude;
  currentLat = lat;
  currentLong = lng;
  ajaxObjectCD = requestObject();
  var address = "actions.php?a=getNearbyLocation&lat=" + lat + "&long=" + lng;
  ajaxObjectCD.open("GET", address, true);
  ajaxObjectCD.onreadystatechange=function() {
    if (ajaxObjectCD.readyState==4) {
      //document.getElementById("location").innerHTML = ajaxObjectCD.responseText;
      document.getElementById("chooseLocation").innerHTML = "Lokacija pročitana uspješno";
      document.getElementById("location").innerHTML = "<label onClick='zoomToCity(" + lat + ", " + lng + "); writeNearbyCity(" + lat + ", " + lng + ");'><span class='msgGood'>Lokacija je (uspješno) određena.</span></label>";
      if (pointFromURL!="") {
        document.getElementById("location").innerHTML += " <label onClick=\"" + pointFromURL + "\"><span class='msgGood'>Prikaži predloženu adresu.</span></label>";
        eval(pointFromURL);
      } else {
        writeNearbyCity( lat, lng );
        zoomToCity( currentLat, currentLong );
      }
      citiesList();
    }
  }
  ajaxObjectCD.send(null)
}

function writeNearbyCity(lat, lng)
{
  ajaxObjectCity = requestObject();
  var address = "actions.php?a=getNearbyCity&lat=" + lat + "&long=" + lng;
  //alert( address );
  ajaxObjectCity.open("GET", address, true);
  ajaxObjectCity.onreadystatechange=function() {
    if (ajaxObjectCity.readyState==4) {
      //document.getElementById("location").innerHTML = ajaxObjectCD.responseText;
      document.getElementById("chooseLocation").innerHTML = "<b>" + ajaxObjectCity.responseText + "</b>";
    }
  }
  ajaxObjectCity.send(null)
}


function showChooseLocation()
{
  document.getElementById("location").innerHTML = "<span class='msgError'>Automatsko određivanje lokacije nije moguće.</span>";
  citiesList();
  //setLocation();
}

function setLocation()
{
  if (currentLat!=0 && currentLong!=0) {
    ajaxObjectCD = requestObject();
    var address = "actions.php?a=chooseFromLocation&lat=" + currentLat + "&long=" + currentLong;
    ajaxObjectCD.open("GET", address, true);
    ajaxObjectCD.onreadystatechange=function() {
      if (ajaxObjectCD.readyState==4) {
        //document.getElementById("chooseLocation").innerHTML = ajaxObjectCD.responseText;
      }
    }
    ajaxObjectCD.send(null)
  } else { //nema navigaciju
    ajaxObjectCD = requestObject();
    var address = "actions.php?a=getCities";
    ajaxObjectCD.open("GET", address, true);
    ajaxObjectCD.onreadystatechange=function() {
      if (ajaxObjectCD.readyState==4) {
        //document.getElementById("chooseLocation").innerHTML = ajaxObjectCD.responseText;
      }
    }
    ajaxObjectCD.send(null)
  }
}

function getStreet()
{
  ajaxObjectCD = requestObject();
  cc = document.getElementById("chooseCity");
  var address = "actions.php?a=getStreet&city=" + cc.options[cc.selectedIndex].value;
  ajaxObjectCD.open("GET", address, true);
  ajaxObjectCD.onreadystatechange=function() {
    if (ajaxObjectCD.readyState==4) {
      //document.getElementById("chooseLocation").innerHTML = ajaxObjectCD.responseText;
    }
  }
  ajaxObjectCD.send(null)
}

function confirmLocation()
{
  cc = document.getElementById("chooseCity");
  cs = document.getElementById("chooseStreet");
  var address = "actions.php?a=getData&city=" + cc.options[cc.selectedIndex].value + "&street=" + cs.options[cs.selectedIndex].value;
  //alert( address );
  ajaxObjectCD = requestObject();
  ajaxObjectCD.open("GET", address, true);
  ajaxObjectCD.onreadystatechange=function() {
    if (ajaxObjectCD.readyState==4) {
      document.getElementById("textData").innerHTML = ajaxObjectCD.responseText;
      mapCreation();
      zoomOnLocation();
      if (document.getElementById('leftSide')!=null) {
        document.getElementById('leftSide').tabber.tabShow(1);
      }
      //map.setCenter(new GLatLng(currentLat, currentLong), 15, G_NORMAL_MAP);
    }
  }
  ajaxObjectCD.send(null)
}

function zoomOnLocation()
{
  cc = document.getElementById("chooseCity");
  cs = document.getElementById("chooseStreet");
  var address = "actions.php?a=setZoom&city=" + cc.options[cc.selectedIndex].value + "&street=" + cs.options[cs.selectedIndex].value;
  ajaxObjectCD = requestObject();
  ajaxObjectCD.open("GET", address, true);
  ajaxObjectCD.onreadystatechange=function() {
    if (ajaxObjectCD.readyState==4) {
      eval( ajaxObjectCD.responseText );
      map.setCenter(new GLatLng(currentLat, currentLong), 16, G_NORMAL_MAP);
      map.clearOverlays();
      marker = createMarker(new GLatLng(currentLat, currentLong), pointDesc, "bar", "-1");
      map.addOverlay( marker );
      marker.openInfoWindowHtml(currentDesc);
    }
  }
  ajaxObjectCD.send(null)
}

function confirmLocationGPS( lat, lng)
{
  //cc = document.getElementById("chooseCity");
  //cs = document.getElementById("chooseStreet");
  var address = "actions.php?a=confirmLocationGPS&lat=" + lat + "&long=" + lng;
  //alert( address );
  ajaxObjectGPS = requestObject();
  ajaxObjectGPS.open("GET", address, true);
  ajaxObjectGPS.onreadystatechange=function() {
    if (ajaxObjectGPS.readyState==4) {
      document.getElementById("textData").innerHTML = ajaxObjectGPS.responseText;
      mapCreation();
      zoom = map.getZoom();
      if (isZoomToCity) {
        zoom = 16;
      }
      isZoomToCity = false;
      map.setCenter(new GLatLng(lat, lng), zoom, G_NORMAL_MAP);
      map.clearOverlays();
      markerHome = createMarker(new GLatLng(lat, lng), "Odabrana lokacija", "current", "0");
      map.addOverlay( markerHome );
      //markerHome.openInfoWindowHtml(currentDesc);
      document.getElementById('leftSide').tabber.tabShow(1);
    }
  }
  ajaxObjectGPS.send(null)
}

function mapCreation()
{
  if (map==null) {
    map = new GMap2(document.getElementById("map"));
    mapBig = new GMap2(document.getElementById("mapInText"));
    createMap();
    loadIcons();
    GEvent.addListener(map,"click",function(overlay, point){
      if (!overlay) {
        selectFromPoint(point);
      }
    });
    GEvent.addListener(mapBig,"click",function(overlay, point){
      if (!overlay) {
        selectFromPoint(point);
      }
    });
    directionsPanel = document.getElementById("routeHelp");
    gdir = new GDirections(map, directionsPanel);
    GEvent.addListener(gdir, "load", function() {
      if (poly) map.removeOverlay(poly);
      poly = gdir.getPolyline();
      map.addOverlay(poly);
    });
    GEvent.addListener(gdir, "addoverlay", hideDirMarkers);
  }
}

function hideDirMarkers(){
  var numMarkers = gdir.getNumGeocodes()
  for (var i = 0; i < numMarkers; i++) {
    var dirMarker = gdir.getMarker(i);
    if (dirMarker != null) {
      dirMarker.hide();
    } else {
      //alert("Marker is null");
    }
  }
}

function selectFromPoint(point)
{
  confirmLocationGPS( point.y, point.x );
}

function selectCityFromPoint(point)
{
  zoomToCity( point.y, point.x );
}

function zoomToCity( lat, lng )
{
  isZoomToCity = true;
  confirmLocationGPS( lat, lng );
  mapBig.setCenter(new GLatLng(lat, lng), 9, G_NORMAL_MAP);
}

function showOnMap( lat, lng, desc, pv_type, rowid )
{
  /*
  alert( lat );
  alert( lng );
  alert( desc );
  alert( pv_type );
  alert( rowid );
  */
  if (marker!=null) {
    map.removeOverlay( marker );
  }
  //map.clearOverlays();
  p = markerHome.getPoint();
  map.setCenter(new GLatLng(lat, lng), 18, G_NORMAL_MAP);
  while (!map.getBounds().containsLatLng(p)) {
    zoomLevel = map.getZoom();
    zoomLevel--;
    map.setZoom( zoomLevel );
  }
  marker = createMarker(new GLatLng(lat, lng), desc, pv_type, "-1");
  map.addOverlay( marker );
  //marker.openInfoWindowHtml(currentDesc);
  objrow = document.getElementById( rowid );
  for (i=0; i<20; i++) {
    objrow = document.getElementById( "datarow" + i );
    if (objrow!=null) {
      objrow.style.backgroundImage = "";
    }
  }
  objrow = document.getElementById( rowid );
  objrow.style.backgroundImage = "url(img/selectedrow.png)";
  drawRoute( markerHome.getPoint(), marker.getPoint() );
}

function drawRoute( fromPoint, toPoint )
{
  var route = "from: (" + fromPoint.lat() + ", " + fromPoint.lng() +") " +
              "to: (" + toPoint.lat() + ", " + toPoint.lng() +") ";
  gdir.load(route, {getPolyline:true,preserveViewport:true});
}

function writeCityName(city, lat, lng)
{
  document.getElementById("chooseLocation").innerHTML = city;
  //mapBig.setCenter(new GLatLng(lat, lng), mapBig.getZoom(), G_NORMAL_MAP);
}

function citiesList()
{
  ajaxObjectAllC = requestObject();
  var address = "actions.php?a=citiesList";
  ajaxObjectAllC.open("GET", address, true);
  //alert("aaa");
  ajaxObjectAllC.onreadystatechange=function() {
    if (ajaxObjectAllC.readyState==4) {
      //alert("bbb");
      document.getElementById("popisGradova").innerHTML = ajaxObjectAllC.responseText;
    }
  }
  ajaxObjectAllC.send(null)
}

function switchDataToShow(id)
{
  ext = new Array();
  ext[0] = "_off.png";
  ext[1] = ".png";
  img = document.getElementById(id);
  if (img==null) {
    return;
  }
  if (dataToShow[id]==0) {
    dataToShow[id] = 1;
  } else {
    dataToShow[id] = 0;
  }
  img.src = "mobile/icons/" + id + ext[dataToShow[id]];

  setVisibleTypes();
}

function setVisibleTypes()
{
  var data = "";
  for (i=0; i<POITypes.length; i++) {
    data += "&" + POITypes[i] + "=" + dataToShow[POITypes[i]];
  }
  /*
  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) {
      confirmLocationGPS( markerHome.getPoint().lat(), markerHome.getPoint().lng() );
      //alert("bbb");
      //document.getElementById("popisGradova").innerHTML = ajaxTypes.responseText;
    }
  }
  ajaxTypes.send(null)
}

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]] = 1;
  }
  /*
  dataToShow["atm"] = 1;
  dataToShow["biljeznik"] = 1;
  dataToShow["odvjetnik"] = 1;
  dataToShow["ljekarna"] = 1;
  dataToShow["gowalla"] = 1;
  dataToShow["foursquare"] = 1;
  */

  ajaxInfoCount = requestObject();
  var address = "actions.php?a=infoCount";
  ajaxInfoCount.open("GET", address, true);
  //alert(address);
  ajaxInfoCount.onreadystatechange=function() {
    if (ajaxInfoCount.readyState==4) {
      document.getElementById("infoCount").innerHTML = ajaxInfoCount.responseText;
    }
  }
  ajaxInfoCount.send(null)
}

function sendLinkToFriend()
{
  linkToSend = "http://blizumene.com/?lat=" + map.getCenter().lat() + "&lng=" + map.getCenter().lng();
  win = new Window({ className: "alphacube", title: "", width:590, height:170, destroyOnClose: true, recenterAuto:false, resizable: false,
                     closable: true, minimizable: false, maximizable: false, draggable: false, showModal: true});
  sendLinkForm = $("sendLink").innerHTML;
  win.getContent().update("Link: " + linkToSend + "<br>" + sendLinkForm);
  win.showCenter(true);
  $("ime").focus();

  //document.getElementById("rightTop").innerHTML = linkToSend;
}

function winCancel()
{
  win.closeAll();
}

function sendLink()
{
  lat = map.getCenter().lat();
  lng = map.getCenter().lng();
  fromIme = $("ime").value;
  fromMail = $("from").value;
  to = $("to").value;
  address = "actions.php?a=sendLink&fromIme=" + fromIme + "&fromMail=" + fromMail + "&to=" + to + "&lat=" + lat + "&long=" + lng;
  ajaxInfoCount = requestObject();
  ajaxInfoCount.open("GET", address, true);
  ajaxInfoCount.onreadystatechange=function() {
    if (ajaxInfoCount.readyState==4) {
      msg = "";
      if (ajaxInfoCount.responseText=="1") {
        msg = "<span class='msgGood'>Pozicija je poslana ;)</span>";
        //msg += ajaxInfoCount.responseText;
      } else {
        msg = "<span class='msgError'>Došlo je do greške prilikom slanja pozicije :(</span>";
        //msg += ajaxInfoCount.responseText;
      }
      win.getContent().update(msg);
      t=setTimeout( closeWin(), 5000 );
    }
  }
  ajaxInfoCount.send(null)

  //alert( address );
}

function closeWin()
{
  if (win!=null) {
    win.hide();
  }
}
