﻿/**
 * FG Forrest a.s.
 * @param options : object - like params as defaultConfig variable in this function
 * @param callerName : string - name of variable called this function
 */

var cezGoogleMap = function(options, callerName) {
    var defaultConfig = {
        replaceId: "map",
        prefixUrl: "/edee/",
        defaultZoom : 7,
        defaultLat: 49.793785,
        defaultLng: 15.459565,
        maxSearchingZoom : 13,
        checkBoxAllId: "togleShowAllCategories",
        checkBoxCategoryClass: "toggleShowCategory",
        searchSubmitId: "mapSearchForm",
        searchClearId: "mapSearchClear",
        searchResolutionId: "sidebar",
        gpsTracking: false, //mapa umi na zaklade dvou adres najit mezi nimi nejkratsi cestu (napr v kontaktnich mistech
        infoWindow : {
            categoryDesription: "",
            moreLinkTitle: "Více informací"
        }

    };

    //zmargování výchozího nastavení a nastavení z parametru options
    var mapConfig =  jQuery.extend( {}, defaultConfig, options);

    //pro rizeni jake kategorie maji byt na mape zobrazeny pomoci get parametru "cat" v url
    var getParams = getUrlVars(); //parametry v URL do pole
    if(getParams['cat']) {
         mapConfig.categoriesShowArray = getParams['cat'].split(',');
    }

    //vytvoreni pole vsech kategorii a kategorií, které nemají být aktivní
    var categoriesArray = []; // pole všech dostupných kategorií
    var categoriesHiddenArray = []; //pole skrytých kategorií
    //naplnění pole categoriesArray všemi kategoriemi, které jsou definovány v mapConfig, tedy i v parametru options 
    jQuery.each(mapConfig.categories, function(i, item) {
        categoriesArray.push(i);
    });
    //naplnění pole categoriesHiddenArray všemi kategoriemi, které mají být skryté
    //testuje se, které kategorie z pole categoriesShowArray nejsou obsaženy v  categoriesArray 
    jQuery.map(categoriesArray, function(i) {
        if (jQuery.inArray(i, mapConfig.categoriesShowArray) == -1) categoriesHiddenArray.push(i);
    });

    var map;
    var gdir; //pro gps tracking
    var gpsInfo;
    var geocoder;

    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        var gmarkers = [];
        var gicons = [];

        /* Definice rozmeru a typu ikon + stinu */
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.iconAnchor = new GPoint(17, 39);
        baseIcon.iconSize = new GSize(30, 40);
        baseIcon.shadow = "/edee/content/sysutf/www/img/google-mapy/shadow.png";
        baseIcon.shadowSize = new GSize(53, 39);
//        baseIcon.infoWindowAnchor = new GPoint(30, 30);
      baseIcon.infoWindowAnchor = new GPoint(180, 32);
        baseIcon.infoShadowAnchor = new GPoint(18, 25);
        baseIcon.printImage = '/edee/content/sysutf/www/img/google-mapy/printImage.gif';
        baseIcon.mozPrintImage = '/edee/content/sysutf/www/img/google-mapy/mozPrintImage.gif';
        baseIcon.transparent = '/edee/content/sysutf/www/img/google-mapy/transparent.png';
        baseIcon.printShadow = '/edee/content/sysutf/www/img/google-mapy/printShadow.gif';
        baseIcon.imageMap = [29,0,29,1,29,2,29,3,29,4,29,5,29,6,29,7,29,8,29,9,29,10,29,11,29,12,29,13,29,14,29,15,29,16,29,17,29,18,29,19,29,20,29,21,29,22,29,23,29,24,29,25,29,26,29,27,29,28,29,29,17,30,17,31,18,32,18,33,18,34,18,35,18,36,18,37,18,38,18,39,17,39,17,38,16,37,16,36,15,35,15,34,14,33,14,32,13,31,13,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,0,0];

        //Nacteni gicons z objektu konfigurace
        jQuery.each(mapConfig.categories, function(i, item) {
            gicons[i] = new GIcon(baseIcon, item.gicon);
        });
        var map = new GMap2(document.getElementById(mapConfig.replaceId));
        document.getElementById(mapConfig.replaceId).style.backgroundImage = "url(/edee/content/sysutf/www/img/google-mapy/loader_white_big_1.gif)";
        map.addControl(new GLargeMapControl3D());

        // Inicializace a nastaveni zakl. parametru mapy
        map.addMapType(G_PHYSICAL_MAP);
        var hierarchy = new GHierarchicalMapTypeControl();
        hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, null, true);
        map.addControl(hierarchy);

        map.setCenter(new GLatLng(mapConfig.defaultLat, mapConfig.defaultLng), mapConfig.defaultZoom);
        map.addControl(new GOverviewMapControl());
        map.addControl(new GScaleControl());

//pokud ma mapa gps tracking, inicializuj prislune objekty
if(mapConfig.gpsTracking == true){
        gdir = new GDirections(map); //druhy parametr pro vypis popisu cesty, document.getElementById("directions")
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
}
        /* *********************** */

        // Read the data

        var process_it = function(data) {
            var jsonData = eval("(" + data + ")");
            jQuery.each(jsonData.markers, function(i, item) {
                var marker = createMarker(item);
                // zobrazení jednotlivych markeru (bodu) na mape
                map.addOverlay(marker);
            });
             
            hideCategoryArray(categoriesHiddenArray);
            showCategoryArray(mapConfig.categoriesShowArray);
        }
        GDownloadUrl(mapConfig.downloadUrl, function(data){process_it(data);});

    }
    else {
        alert("Omlouváme se, ale Google Mapy nejsou s tímto internetovým prohlížečem kompatibilní.");
    }

    //Odchyt změn formulářů výběru kategorií a vyhledávání
    jQuery("#" + mapConfig.checkBoxAllId).click(function() {
        togleShowAllCategories(categoriesArray);
    });

    jQuery("." + mapConfig.checkBoxCategoryClass).click(function() {
        var togleCategory = [jQuery(this).attr("id").substring(0, jQuery(this).attr("id").length - 3)];
        if (jQuery(this).is(":checked")) {
            showCategoryArray(togleCategory);
        }
        else {
            hideCategoryArray(togleCategory);
        }
    });

    jQuery("#" + mapConfig.searchSubmitId).submit(function() {
        searchLocations();
        return false;
    });

    jQuery("#" + mapConfig.searchClearId).click(function() {
        clearMapsSearchResult();
    });



    function strip_tags(html){ 
        if (arguments.length < 3) { 
            html = html.replace(/<\/?(?!\!)[^>]*>/gi, ', '); 
        } else { 
            allowed = arguments[1]; 
            specified = eval("["+arguments[2]+"]"); 
            if (allowed) { 
                regex='<!--?(?!(' + specified.join('|') + '))\b[^-->]*>'; 
                html = html.replace(new RegExp(regex, 'gi'), ''); 
            } else { 
                regex = '<!--?(' + specified.join('|') + ')\b[^-->]*>'; 
                html=html.replace(new RegExp(regex, 'gi'), ''); 
            } 
        } 
        return html; 
    } 



    // A function to create the marker and set up the event window
    function createMarker(item) {
        var point = new GLatLng(item.lat, item.lng);

         if (item.category == 'smluvnipartnerimista')  { 

              item.mycategory = "Smluvní partner";
              var marker = new GMarker(point, {icon:gicons[item.category],title:(strip_tags(item.mycategory))+' - '+(strip_tags(item.name))+', '+(strip_tags(item.address))});

         } else if (item.category == 'zakaznickacentramista') {

              item.mycategory = "Zákaznické centrum";
              var marker = new GMarker(point, {icon:gicons[item.category],title:(strip_tags(item.mycategory))+' - '+(strip_tags(item.name))});

         } else {

              item.mycategory = item.category;
              var marker = new GMarker(point, {icon:gicons[item.category],title:(strip_tags(item.name))+', '+(strip_tags(item.address))});

         }


//        var marker = new GMarker(point, {icon:gicons[item.category],title:(strip_tags(item.mycategory))+' - '+(strip_tags(item.name))+', '+(strip_tags(item.address))});

//        var marker = new GMarker(point, {icon:gicons[item.category],title:(strip_tags(item.name))+', '+(strip_tags(item.address))});

        // === Store the category and name info as a marker properties ===
        marker.mycategory = item.category;
        marker.myname = item.name;
        marker.myaddress = item.address;
        marker.myurl = getValidUrl(item.url);

        var html = "<h3>"+item.name+"<\/h3><p>"+item.address+"</p>";

        GEvent.addListener(marker, 'click', function() {
            map.setCenter(point, mapConfig.defaultZoom);
            marker.openExtInfoWindow(map, "simple_example_window", getInfoWindowHtml(item),{beakOffset: 0, paddingX: 50, paddingY: 40});
		// pro slide napovedu z oranzoveho pole
		jQuery(".calc-help-title", jQuery(".moreinfo")).tooltip({ 
			effect: 'slide',
			position: 'bottom right',
			delay: 100,
                        relative: false,
                        offset: [10,-5],
			tipClass: 'calc-help-title-content'
		});

        });

        gmarkers.push(marker);
        return marker;

        GEvent.addListener(map, 'extinfowindowclose', function() {
            GLog.write("extinfowindowclose found");
        });


    }

    function searchLocations() {
                vyhledavani = jQuery('input[name=address]').val();
                if (! /, Česká republika$/.test(vyhledavani)) {
                    jQuery("input[name=address]").val(vyhledavani + ", Česká republika")
                }

        var address = document.getElementById('addressInput').value;
        geocoder.getLatLng(address, function(latlng) {
            if (!latlng) {
                alert('Adresa ' + address + ' nebyla nalezena.');
            } else {
                searchLocationsNear(latlng);

                showSidebar();
                map.closeExtInfoWindow();

            }
        });
    }

    function searchLocationsNear(center) {
        var radius = document.getElementById('radiusSelect').value;
        var category = mapConfig.searchingCategory;
        var searchUrl = '/edee/content/sysutf/bsh/cez/search_gen.html?center_lat=' + center.lat() + '&center_lng=' + center.lng() + '&radius=' + radius + '&category=' + escape(category);
        GDownloadUrl(searchUrl, function(data) {
            var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName('marker');
            map.clearOverlays();

            /*skrytí všech categorií na mapě*/
            hideCategoryArray(categoriesArray);

            var sidebar = document.getElementById(mapConfig.searchResolutionId);
            sidebar.innerHTML = '';
            if (markers.length == 0) {
                sidebar.innerHTML = '<p class="align-center"><br /><strong>Nebyly nalezeny žádné výsledky. Zkuste zvětšit hodnotu kilometrů v hledaném okolí a hledání opakujte.</strong></p>';
                map.setCenter(new GLatLng(mapConfig.defaultLat, mapConfig.defaultLng), mapConfig.defaultZoom);
                return;
            }
            jQuery('div#closeSidebar').css('display', 'block');

            var bounds = new GLatLngBounds();
            jQuery.each(markers, function(i, item) {
                var itemMarker = new Object();
                itemMarker.lng = item.getAttribute('lng');
                itemMarker.lat = item.getAttribute('lat');
                itemMarker.name = item.getAttribute('name');
                itemMarker.address = item.getAttribute('address');
                itemMarker.url = item.getAttribute('urlmarker');
                itemMarker.info = item.getAttribute('infomarker');
                itemMarker.openPo = item.getAttribute('openpo');
                itemMarker.endPo = item.getAttribute('endpo');
                itemMarker.openUt = item.getAttribute('openut');
                itemMarker.endUt = item.getAttribute('endut');
                itemMarker.openSt = item.getAttribute('openst');
                itemMarker.endSt = item.getAttribute('endst');
                itemMarker.openCt = item.getAttribute('openct');
                itemMarker.endCt = item.getAttribute('endct');
                itemMarker.openPa = item.getAttribute('openpa');
                itemMarker.endPa = item.getAttribute('endpa');
                itemMarker.openSo = item.getAttribute('openso');
                itemMarker.endSo = item.getAttribute('endso');
                itemMarker.openNe = item.getAttribute('openne');
                itemMarker.endNe = item.getAttribute('endne');
                itemMarker.category = item.getAttribute('category');
                itemMarker.distance = parseFloat(item.getAttribute('distance'));

                var point = new GLatLng(parseFloat(item.getAttribute('lat')), parseFloat(item.getAttribute('lng')));


                var marker = new GMarker(point, gicons[itemMarker.category]);
                map.addOverlay(marker);

                var sidebarEntry = createSidebarEntry(marker, itemMarker);
                sidebar.appendChild(sidebarEntry);

                //pokud gps tracking, zobraz u kazdeho vysledku odkaz
	        if(mapConfig.gpsTracking == true){ 
                     var gpsInfo = document.createElement('p');
                     gpsInfo.className = 'gpsInfoTrigger';
                     gpsInfo.innerHTML = '<b class="gMapsGPSshowDirections" onclick="cezMap.setDirections(\'' + itemMarker.address + '\');">Zobrazit trasu autem do tohoto místa</b>';
                     sidebar.appendChild(gpsInfo);
	        }
                bounds.extend(point);
            });

            map.setCenter(bounds.getCenter(), (map.getBoundsZoomLevel(bounds) >= mapConfig.maxSearchingZoom) ? mapConfig.maxSearchingZoom : map.getBoundsZoomLevel(bounds));

        });
    }

    function createSidebarEntry(marker, item) {
        var div = document.createElement('div');
        div.innerHTML = getSidebarHtml(item);
        div.className = 'sidebarItemWrapper';
        div.setAttribute('title', 'Zobrazit místo na mapě');
        //div.style.width = '175px';

        GEvent.addDomListener(div, 'click', function() {
            GEvent.trigger(marker, 'click');
        });
        GEvent.addDomListener(marker, 'click', function() {
            marker.openExtInfoWindow(map, "simple_example_window_search", getInfoWindowHtml(item), {beakOffset: 0});
		// pro slide napovedu z oranzoveho pole
		jQuery(".calc-help-title", jQuery(".sidebarItemWrapper")).tooltip({ 
			effect: 'slide',
			position: 'bottom right',
			delay: 100,
                        relative: false,
                        offset: [-10,10],
			tipClass: 'calc-help-title-content'
		});
		// pro slide napovedu z oranzoveho pole
		jQuery(".calc-help-title", jQuery(".moreinfo")).tooltip({ 
			effect: 'slide',
			position: 'bottom right',
			delay: 100,
                        relative: false,
                        offset: [10,-5],
			tipClass: 'calc-help-title-content'
		});
        });

        GEvent.addDomListener(div, 'mouseover', function() {
            div.style.backgroundColor = '#fff';
        });
        GEvent.addDomListener(div, 'mouseout', function() {
            div.style.backgroundColor = '#F5F5F5';
        });
        return div;

    }

    /**
     * zobrazi pole kategorii na mape
     * @param category : array - pole kategorií pro zobrazení
     */
    function showCategoryArray(category) {
        jQuery.map(category, function(i) {
            for (var j = 0; j < gmarkers.length; j++) {
                if (gmarkers[j].mycategory == i) {
                    map.addOverlay(gmarkers[j]);
                    gmarkers[j].show();
                }
            }
            jQuery("#" + i + "box").attr("checked", "checked");
        });

        if (jQuery("." + mapConfig.checkBoxCategoryClass + ":checked").length == categoriesArray.length) {
            jQuery("#" + mapConfig.checkBoxAllId).attr("checked", "checked");
        } else {
            jQuery("#" + mapConfig.checkBoxAllId).removeAttr("checked");
        }
    }

    /**
     * skryje pole kategorii na mape
     * @param category : array - pole kategorií pro skrytí
     */
    function hideCategoryArray(category) {
        jQuery.map(category, function(i) {
            for (var j = 0; j < gmarkers.length; j++) {
                if (gmarkers[j].mycategory == i) {
                    gmarkers[j].hide();
                }
                jQuery("#" + i + "box, #" + mapConfig.checkBoxAllId).removeAttr("checked");
            }
            map.closeInfoWindow();
        });
    }

    /**
     * zobrazení nebo skrytí požadovaných kategorií
     * @param categories - array
     */
    function togleShowAllCategories(categories) {
        if (jQuery("#" + mapConfig.checkBoxAllId).is(":checked")) {
            showCategoryArray(categories);
        } else {
            hideCategoryArray(categories);
            map.closeExtInfoWindow();
        }
    }

    /**
     * Funkce pro vztvoření validní url na preview nebo na ostrý provoz
     * @param url : string - nekompletní url požadované cesty
     */
    function getValidUrl(url){
        return (url.indexOf("http://") == 0 || url.indexOf("https://") == 0 || url == null || url == '' || url == 'null') ? url : mapConfig.prefixUrl + "content/pubutf/www" + url;
    }

    /**
     * Funkce vrací HTML Info Window yobrayující se v mapě
     * @param contents : Object
     */
    function getInfoWindowHtml(contents){
        contents.validUrl = getValidUrl(contents.url);
        contents.moreLinkTitle = (mapConfig.categories[contents.category].moreLinkTitle == undefined) ? mapConfig.infoWindow.moreLinkTitle : mapConfig.categories[contents.category].moreLinkTitle;
        contents.categoryDescriptionHtml = (mapConfig.categories[contents.category].categoryDesription == undefined) ? mapConfig.infoWindow.categoryDesription : mapConfig.categories[contents.category].categoryDesription;
        contents.categoryDescriptionHtml = (contents.categoryDescriptionHtml != "") ? "<strong>" + contents.categoryDescriptionHtml + "<\/strong>" : "";
        var html = "";
        html += '<div class="close">';
        html +=     "<a onclick='" + callerName + ".closeInfoWindow();' href='javascript:;'><span>X</span></a>";
        html += "</div>";
        html +=     "<div class='moreinfo'>" + contents.categoryDescriptionHtml + "<h3>" + contents.name + "</h3><p>" + contents.address + "</p>" + ((contents.openPo != 'null' && contents.openPo != '') ? "<table class='no-border'><tr><th>Po</th><td>" + contents.openPo + " - " + contents.endPo + "</td></tr><tr><th>Út</th><td>" + contents.openUt + " - " + contents.endUt + "</td></tr><tr><th>St</th><td>" + contents.openSt + " - " + contents.endSt + "</td></tr><tr><th>Čt</th><td>" + contents.openCt + " - " + contents.endCt + "</td></tr><tr><th>Pá</th><td>" + contents.openPa + " - " + contents.endPa + "</td></tr></table>" : "") + "" + ((contents.info != 'null' && contents.info != '') ? "<p>" + contents.info + "</p>" : "") + ((contents.validUrl != 'null' && contents.validUrl != '') ? "<a href='" + contents.validUrl + "'>" + contents.moreLinkTitle + "</a>" : "") + "</div>";
        html += "<div class='zoom'>";
        html += "<a class='zoomIn' href='javascript:" + callerName + ".zoomIn();'>Přiblížit</a><span class='oddelovac'>|</span><a class='zoomOut' href='javascript:" + callerName + ".zoomOut();'>Oddálit</a><span class='oddelovac'>|</span><a class='center' href='javascript:" + callerName + ".showCompleteMap();'>Celá ČR</a></div>";
        return html;
    }


    function getAltWindowHtml(contents){

        contents.categoryDescriptionHtml = (mapConfig.categories[contents.category].categoryDesription == undefined) ? 

mapConfig.infoWindow.categoryDesription : mapConfig.categories[contents.category].categoryDesription;

        contents.categoryDescriptionHtml = (contents.categoryDescriptionHtml != "") ? "<b>" + contents.categoryDescriptionHtml + "<\/b>" : "";
        var html = "";
        html +=     "<span>" + contents.categoryDescriptionHtml + ", " + contents.name + "<br/>" + contents.address + "</span>";
        return html;
    }

    /**
     * Funkce vrací HTML položky zobrazující se ve výsledku hledání
     * @param contents : Object
     */
    function getSidebarHtml(contents){
        //&nbsp;(' + contents.distance.toFixed(1) + '&nbsp;km vzdušnou čarou) ---uz se nepouziva
        contents.validUrl = getValidUrl(contents.url);
        contents.moreLinkTitle = (mapConfig.categories[contents.category].moreLinkTitle == undefined) ? mapConfig.infoWindow.moreLinkTitle : mapConfig.categories[contents.category].moreLinkTitle;
        contents.categoryDescriptionHtml = (mapConfig.categories[contents.category].categoryDesription == undefined) ? mapConfig.infoWindow.categoryDesription : mapConfig.categories[contents.category].categoryDesription;
        contents.categoryDescriptionHtml = (contents.categoryDescriptionHtml != "") ? "<strong>" + contents.categoryDescriptionHtml + "<\/strong>" : "";		
        var html = '<div class="sidebarItem"><h3 style="display: inline; bottom:5px;">' + contents.name + '</h3><p>' + contents.address + '<br />' + ((contents.validUrl != "null" && contents.validUrl != "") ? '<br /><a href="' + contents.validUrl + '">'+ contents.moreLinkTitle +'</a><br />' : '') + '<br />' + ((contents.info != "null" && contents.info != "") ? contents.info : '') + '</p></div><div class="sidebarItemRight"><table class="no-border">' + ((contents.openPo != "null" && contents.openPo != "") ?'<tr><th>Po</th><td>' + contents.openPo + ' - ' + contents.endPo + '</td></tr>' : '') + '' + ((contents.openUt != "null" && contents.openUt != "") ?'<tr><th>Út</th><td>' + contents.openUt + ' - ' + contents.endUt + '</td></tr>' : '') + '' + ((contents.openSt != "null" && contents.openSt != "") ?'<tr><th>St</th><td>' + contents.openSt + ' - ' + contents.endSt + '</td></tr>' : '') + '' + ((contents.openCt != "null" && contents.openCt != "") ?'<tr><th>Čt</th><td>' + contents.openCt + ' - ' + contents.endCt + '</td></tr>' : '') + '' + ((contents.openPa != "null" && contents.openPa != "") ?'<tr><th>Pá</th><td>' + contents.openPa + ' - ' + contents.endPa + '</td></tr>' : '') + '</table></div><span class="clear"></span>';
		
        return html;
    }

    function clearMapsSearchResult() {
        map.closeExtInfoWindow();
        map.clearOverlays();
        jQuery('div#' + mapConfig.searchResolutionId).css('display', 'none');
        jQuery('div#closeSidebar').css('display', 'none');
        showCategoryArray(mapConfig.categoriesShowArray);
        map.setCenter(new GLatLng(mapConfig.defaultLat, mapConfig.defaultLng), mapConfig.defaultZoom);
    }

    function showSidebar() {
        jQuery("div#" + mapConfig.searchResolutionId).css("display", "block");
        setTimeout('jQuery("#stin-end").hide();jQuery("#stin-end").show();', 1000);
    }
    /* *********** Fce z info okna *********** */

    this.zoomIn = function() {                /* funkce pro zoomovani a defaultni zobrazeni */
        map.setCenter();
        map.zoomIn(null,null,true);
    };
    this.zoomOut = function() {
        map.setCenter();
        map.zoomOut();
    };

    this.zoomInSearch = function() {         /* funkce pro zoomovani a defaultni zobrazeni */
        map.setCenter();
        map.zoomIn();
    };
    this.zoomOutSearch = function() {
        map.setCenter();
        map.zoomOut();
    };
    this.closeInfoWindow = function(){
        map.closeExtInfoWindow();
    };
    this.showCompleteMap = function(){
        map.setCenter(new GLatLng(mapConfig.defaultLat, mapConfig.defaultLng), mapConfig.defaultZoom);
        map.closeExtInfoWindow();
    };


/* *********** Fce pro GPS Tracking *********** */

    this.setDirections = function(toAddress) {
         map.closeExtInfoWindow();
         var fromAddress = jQuery("#addressInput").val();
         var rel1 = /(.*)\(([A-Za-z]{0,2})\)/;
         toAddress = toAddress.replace(rel1, "$1");
         toAddress = toAddress.replace('<br />', ',');
         toAddress = toAddress.replace('<br />', ',');
         toAddress = toAddress.replace('<br/>', ',');
         toAddress = toAddress.replace('<br/>', ',');
         //toAddress = strip_tags(toAddress);
         toAddress += ",Česká Republika";
         gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "cs_CS"});
         //jQuery("#print").html(toAddress);
     };

    /**
     * Funkce pro chybová hlaseni gps trackingu
     * 
     */
    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     //alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
		 alert('Bohužel jedna ze zadaných adres nebyla nalezena. Zkuste ji více specifikovat.');
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     //alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	     alert('Bohužel služba není v tuto chvíli dostupná, zkuste to později.');
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     //alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
		 alert('Zadejte prosím adresu.');
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     //alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
		 alert('Klíč není pro tuto doménu správný.');
	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     //alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	     alert("Cesta nebyla nalezena.");
	   else alert("Nastala neočekávaná chyba/An unknown error occurred.");
	   
	}

    /**
     * Funkce volana pro provedeni trackingu (vypis ruznych hodnot: vzdalenosti, doby trvani)
     * 
     */
	function onGDirectionsLoad(){ 

		jQuery("#placeHolderForGPSInfo").html('Přibližně <b>' + gdir.getDistance().html + "</b> po silnici (" + gdir.getDuration().html + ')');
                jQuery.scrollTo('#google-maps', 400 );
                setTimeout(function() {
                    jQuery("#placeHolderForGPSInfo").animate({ backgroundColor: "#F24F00", color: "#fff" }, 500).animate({ backgroundColor: "#F6F6F6", color: "#000" }, 1000);
                }, 600);

	}


};
