/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var gMap;
var gMapRadius;
var defaultGMapValues;
var gmapHomeLat;
var gmapHomeLng;
var gmapGeoLat;
var gmapGeoLng;
var gMarkers = new Array;
var geoTimeout;
var gDirectionsDisplay;

/**
 * nastaveni icon pro markery
 */
 var iconTypes = new Array();
 iconTypes['home'] = 'images/gmap/home2.png';
 iconTypes['absolvent'] = 'images/gmap/absolvent.png';
 iconTypes['obchod'] = 'images/gmap/obchod.png';
 iconTypes['eshop'] = 'images/gmap/eshop.png';
 iconTypes['konzultant'] = 'images/gmap/konzultant.png';

/** nastaveni kraju
 *
 *  Legenda (id poli nize => nazev kraje):
 *   1 => Jihočeský kraj
 *   2 => Jihomoravský kraj
 *   3 => Karlovarský kraj
 *   4 => Královohradecký kraj
 *   5 => Liberecký kraj
 *   6 => Moravskoslezský kraj
 *   7 => Olomoucký kraj
 *   8 => Pardubický kraj
 *   9 => Plzeňský kraj
 *  10 => Středočeský kraj
 *  11 => Praha
 *  12 => Ústecký kraj
 *  13 => Vysočina
 *  14 => Zlínský kraj
 *  15 => Brno
 *  16 => Ostrava
 *  17 => Celá Česká republika
 */
var krajex = new Array();
var krajey = new Array();
var krajezoom = new Array();

krajex[1] = 49.1026;
krajey[1] = 14.4635;
krajex[2] = 49.099;
krajey[2] = 16.5646;
krajex[3] = 50.1452;
krajey[3] = 12.7716
krajex[4] = 50.4313;
krajey[4] = 15.9384;
krajex[5] = 50.7121;
krajey[5] = 15.076;
krajex[6] = 49.799;
krajey[6] = 17.8802;
krajex[7] = 49.6818;
krajey[7] = 17.2787;
krajex[8] = 49.9176;
krajey[8] = 16.1334;
krajex[9] = 49.6018;
krajey[9] = 13.2275;
krajex[10] = 50.0386;
krajey[10] = 14.3646;
krajex[11] = 50.0818;
krajey[11] = 14.4196;
krajex[12] = 50.4872;
krajey[12] = 13.7933;
krajex[13] = 49.3931;
krajey[13] = 15.6473;
krajex[14] = 49.1781;
krajey[14] = 17.6056;
krajex[15] = 49.1898;
krajey[15] = 16.6144;
krajex[16] = 49.824;
krajey[16] = 18.2692;
krajex[17] = 49.8462914122132;
krajey[17] = 15.44677734375;
krajex[18] = 48.836882; // střed sk
krajey[18] = 19.538269; // střed sk
krajex[19] = 48.294706;
krajey[19] = 17.275543;
krajex[20] = 48.398756;
krajey[20] = 17.725983;
krajex[21] = 48.23437;
krajey[21] = 18.319244;
krajex[22] = 48.814641;
krajey[22] = 18.236847;
krajex[23] = 48.536886;
krajey[23] = 19.383774;
krajex[24] = 49.216341;
krajey[24] = 19.244842;
krajex[25] = 48.642528;
krajey[25] = 21.079559;
krajex[26] = 49.173265;
krajey[26] = 21.378937;

krajezoom[1] = 8;
krajezoom[2] = 8;
krajezoom[3] = 8;
krajezoom[4] = 8;
krajezoom[5] = 8;
krajezoom[6] = 8;
krajezoom[7] = 8;
krajezoom[8] = 8;
krajezoom[9] = 8;
krajezoom[10] = 8;
krajezoom[11] = 11;
krajezoom[12] = 8;
krajezoom[13] = 8;
krajezoom[14] = 8;
krajezoom[15] = 11;
krajezoom[16] = 11;
krajezoom[17] = 7;
krajezoom[18] = 7;
krajezoom[19] = 8;
krajezoom[20] = 8;
krajezoom[21] = 8;
krajezoom[22] = 8;
krajezoom[23] = 8;
krajezoom[24] = 8;
krajezoom[25] = 8;
krajezoom[26] = 8;



function gmapInitialize(defaultGMapValues, callback)
{
  //Vychozi nastaveni map
 if(!defaultGMapValues) {
    var defaultGMapValues = {
      radius: {
        enabled : false,
        defaultRadius: 15000,
        minRadius: 1000,
        maxRadius: 120000
      },
      defaultZoom: 8,
      defaultLat: 49.9695849,
      defaultLng: 14.3733875,
      mapElementId: 'gmap'

    };
  }

  var centerLatLng = new google.maps.LatLng(defaultGMapValues.defaultLat, defaultGMapValues.defaultLng);
  var bubbleString;
  var mapOptions = {
    zoom: defaultGMapValues.defaultZoom,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  var map = new google.maps.Map(document.getElementById(defaultGMapValues.mapElementId), mapOptions);


  if(defaultGMapValues.radius.enabled){
    gMapRadius = drawRadius(defaultGMapValues.radius.defaultRadius, map);

    var alertView = false;
    $("#gSlider").slider({
      animate: true,
      max: 120000,
      min: 0,
      value: 0,
      slide: function(event, ui) {
          if(getHomeLat() > 0 && getHomeLng() > 0) {
            $("#sliderInfo").html(parseInt($("#gSlider").slider("option","value")/1000));
            gMapRadius.setRadius($("#gSlider").slider("option","value"));
          }
          else {
              if(alertView != true) {
                alert("Pro použití této funkce musíte zvolit výchozí bod.\nZadejte prosím svou adresu a poté použijte posuvník rozsahu znovu.");
                alertView = true;
                return false;
              }
          }
      },
      stop: function(event, ui){
          // volani funkce pro callback
          if(getHomeLat() > 0 && getHomeLng() > 0) {
            GMapSliderCallback(defaultGMapValues, parseInt($("#gSlider").slider("option","value")/1000));
          }
          else {
            alert("Pro použití této funkce musíte zvolit výchozí bod.\nZadejte prosím svou adresu a poté použijte posuvník rozsahu znovu.");
          }
      }
    });

  }

  return map;
}

function drawRadius(distance, map) {
    var gMapRadius = new google.maps.Circle({
      center: new google.maps.LatLng(map.getCenter().lat(),map.getCenter().lng()),
      fillColor: '#cccccc',
      fillOpacity: 0.5,
      strokeWeight: 1,
      radius: distance,
      zIndex: 0,
      map: map
    });
    return gMapRadius;
}

function redrawRadius(distance) {
    gMapRadius.setCenter(new google.maps.LatLng(getHomeLat(),getHomeLng()));
}

function drawMarker(iconType, lat, lng, title, windowString, map) {

  if(iconType != 'default') {
      var icon = webDir() +'/'+iconTypes[iconType];

      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat,lng),
        map: map,
        clickable: true,
        icon: icon,
        title: title
      });
  }
  else {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat,lng),
        map: map,
        clickable: true,
        title: title
      });
  }

  var infowindow = new google.maps.InfoWindow({
    content: windowString
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });


  gMarkers[gMarkers.length] = marker;
}

function deleteOverlays() {
  if (gMarkers) {
    for (i in gMarkers) {
      gMarkers[i].setMap(null);
    }
    gMarkers.length = 0;
  }

}

function deleteRoutes(){
    if(gDirectionsDisplay)
    {
        gDirectionsDisplay.setMap(null);
    }
}

/**
 * Funkce k nastaveni centrovani google map
 */
function set_map_center(id)
{
    gMap.setCenter(new google.maps.LatLng(krajex[id],krajey[id]));
    gMap.setZoom(krajezoom[id]);
    
    deleteOverlays();
}

function redrawMarkersFromJSON(json){

    if(typeof json != "undefined"){
        deleteOverlays();
        drawMarkersFromJSON(json);
    }

}

/**
 * Funkce vykresluje markery z JSON
 */
function drawMarkersFromJSON(json) {
  if(typeof json != "undefined") {
    var json = jQuery.parseJSON(json);
    
    for (var i = 0; i < json.length; i++) {
      drawMarker(json[i].markerType, json[i].lat, json[i].lng, json[i].name, json[i].bubble, gMap);
    }
  }
}

function getActualLat() {
    return gMap.getCenter().lat();
}

function getActualLng() {
    return gMap.getCenter().lng();
}

function getHomeLat() {
    return gmapHomeLat;
}

function getHomeLng() {
    return gmapHomeLng;
}

function routeFromTo(to, from, travelMode) {
    var dirReq, directionsService;

    if(getHomeLat() > 0 && getHomeLng() > 0) {
        travelMode = travelMode || google.maps.DirectionsTravelMode.DRIVING;
        from = from || new google.maps.LatLng(getHomeLat(),getHomeLng());

        to = jQuery.parseJSON(to);

        dirReq = {
            origin: from,
            destination: new google.maps.LatLng(to['lat'],to['lng']),
            travelMode: travelMode
        };
        gDirectionsDisplay = new google.maps.DirectionsRenderer();
        directionsService = new google.maps.DirectionsService();
        gDirectionsDisplay.setMap(gMap);
        directionsService.route(dirReq, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                gDirectionsDisplay.setDirections(result);
                createSteps(result);
            } else {}

        });
    }
    else {
        alert("Pro použití této funkce musíte zvolit výchozí bod.\nZadejte prosím svou adresu a poté klikněte znovu na odkaz pro navigaci k obchodu.");
    }
}

function setHomeLocation(lat, lng) {
    gmapHomeLat = lat;
    gmapHomeLng = lng;
}

function createSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  var stepIndex;
  
  deleteOverlays();
  var myRoute = directionResult.routes[0].legs[0];

  showDuration(myRoute.steps[0].duration);
  showDistance(myRoute.steps[0].distance);

  for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = new google.maps.Marker({
        position: myRoute.steps[i].start_point,
        map: gMap
      });
      stepIndex = 'step-'+i;
      attachInstructionText(marker, stepIndex, myRoute.steps[i].instructions);
      gMarkers[i] = marker;
  }
  showSteps();
}

function attachInstructionText(marker, index, text) {
  addToStepDisplay(index, text);
  google.maps.event.addListener(marker, 'click', function() {
      highlightStep(index);
  });
}

function findMyPosition() {
    if (navigator.geolocation) {
       alert("Pro dokončení operace prosím potvrďte, že si přejete poskytnout Vaši aktuální polohu a poté vyčkejte.\nZaměření Vaší polohy může chvíli trvat.")
       geoTimeout = setTimeout('geolocationError()', 5000);
       navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
    } else {
       alert("Bohužel nastala chyba.\nVáš prohlížeč nepodporuje Geolocation API!");
    }
}

function geolocationSuccess(position) {
    clearTimeout(geoTimeout);

    gmapGeoLat = position.coords.latitude;
    gmapGeoLng = position.coords.longitude;
    
    setMyPosition(position);
}

function geolocationError() {
    if(gmapGeoLat > 0 && gmapGeoLng > 0) {
        var fakeGeolocation;
        fakeGeolocation.coords.latitude = gmapGeoLat;
        fakeGeolocation.coords.longitude = gmapGeoLng;
    }
    else {
        alert("Vaši aktuální polohu se bohužel nepodařilo zjistit.\nZkuste prosím vyplnit Vaši adresu ručně do pole pro adresu.");
    }
}

function findMyPositionByAddress(id) {
    var address = document.getElementById(id).value;

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        gMap.setCenter(results[0].geometry.location);
        gMap.setZoom(12);
        setHomeLocation(results[0].geometry.location.lat(), results[0].geometry.location.lng());
        redrawRadius(gMapRadius);
        setMyPositionByAddress(results[0]);
      } 
      else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
        alert("Pro Vaši adresu nebyly nalezeny žádné výsledky.");
      }
      else if (status == google.maps.GeocoderStatus.INVALID_REQUEST) {
        alert("Server vrátil informaci, že zadaná adresa neexistuje.\nZkuste to prosím znovu.");
      }
    });
}

function getAddressByLatlng(lat, lng) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {'location': new google.maps.LatLng(lat, lng)}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        return results[0].formatted_address;
      }
    });
}

function getLatLngByAddress(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if(callback != "undefined") {
            callback(results[0].geometry.location);
        }
      }
      else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
        alert("Pro Vaši adresu nebyly nalezeny žádné výsledky.");
      }
      else if (status == google.maps.GeocoderStatus.INVALID_REQUEST) {
        alert("Server vrátil informaci, že zadaná adresa neexistuje.\nZkuste to prosím znovu.");
      }
    });
}
