/*jslint vars: true, indent: 4*/
/*global $, document, google*/
(function () {
    "use strict";
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var image;
    var shadow;
    var home;
    var destination;
    var lastContent = '';
    var viverista = null;
    var infowindow = new google.maps.InfoWindow({
        content: '',
        disableAutoPan: true
    });
    var hiddenMarker = null;
    var homeMarker = null;
    var destMarker = null;
    var calcRoute = function (marker) {
        var start = document.getElementById('mylocation').value;
        var switchHiddenMarker = function (marker) {
            if (hiddenMarker !== null) {
                hiddenMarker.setVisible(true);
                hiddenMarker = null;
            }
            if (marker !== null) {
                hiddenMarker = marker;
                hiddenMarker.setVisible(false);
            }
        };
        if (start === '') {
            switchHiddenMarker(null);
            directionsDisplay.setMap(null);
            if (homeMarker !== null) {
                homeMarker.setMap(null);
            }
            if (destMarker !== null) {
                destMarker.setMap(null);
            }
            return;
        }
        directionsDisplay.setMap(map);
        var request = {
            origin: start,
            destination: viverista,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                switchHiddenMarker(marker);
                directionsDisplay.setDirections(response);
                var leg = response.routes[0].legs[0];
                homeMarker.setMap(map);
                homeMarker.setPosition(leg.start_location);
                destMarker.setMap(map);
                destMarker.setPosition(leg.end_location);
                var startUrl = leg.start_location.toUrlValue();
                var endUrl = leg.end_location.toUrlValue();
                var url = 'http://maps.google.com/maps?saddr=' + startUrl + '&daddr=' + endUrl;
                $('#window-gmap').html('open in google.maps');
            }
        });
    };
    var initialize = function () {
        var markers = [ {
            id: 4,
            latitude: 41.8155581,
            longitude: 3.0498580,
            html: 'ARTIFLORA
Av. Castell d\'Aro, 110
17250 Platja d\'Aro
(Girona)
(+34) 972 82 63 87
artiflora@artiflora.net
www.artiflora.net'
        }, {
            id: 82,
            latitude: 42.0102060,
            longitude: 2.9864270,
            html: 'Vivers PLANAS EXPORT
Masos de Púbol, 11
17120 Púbol
(Girona)
(+34) 972 48 82 13
pubol@viversplanas.com
www.viversplanas.com'
        }, {
            id: 10,
            latitude: 41.6252190,
            longitude: 2.3503310,
            html: 'Vivers de CARDEDEU
Mas Riba Alta, Carretera BV-5105 km.4 #Apartat de correus 215
08440 Cardedeu
(Barcelona)
(+34) 938 461 390
info@viverosdecardedeu.com
www.viverosdecardedeu.com'
        }, {
            id: 11,
            latitude: 41.8767230,
            longitude: 3.1390340,
            html: 'Vivers CARDONA
Roca de Gria, 43 - Ctra C-31 sortida 328
17253 Vall-llobrega
(Girona)
(+34) 972 317 407
info@gardencentercardona.com
www.gardencentercardona.com'
        }, {
            id: 12,
            latitude: 41.9671790,
            longitude: 2.7887340,
            html: 'CENTRE VERD
Avda. de la Pau cantonada Camí del Sitjar
17190 Salt
(Girona)
(+34) 972 22 22 41
info@centre-verd.es
www.centreverd.cat'
        }, {
            id: 61,
            latitude: 41.8797220,
            longitude: 2.5030560,
            html: 'CAN JOVER Cultius
Carretera vella de Vic (Gi541) km 0,1  
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 869 922#M: (+34) 627 590 130
info@canjovercultius.com
www.canjovercultius.com'
        }, {
            id: 16,
            latitude: 42.0442280,
            longitude: 2.9143440,
            html: 'Vivers Casa ESTEVENET
Camí del Pla, 9
17462 Bordils
(Girona)
(+34) 972 49 00 10
estevenet69@gmail.com'
        }, {
            id: 18,
            latitude: 42.2016780,
            longitude: 3.0837970,
            html: 'Vivers Garden SANT PERE
Carretera a Castelló s/n
17470 Sant Pere Pescador
(Girona)
(+34) 972 55 05 35
c.poch@gardensantpere.com
www.gardensantpere.com'
        }, {
            id: 21,
            latitude: 42.0102060,
            longitude: 2.9864270,
            html: 'Vivers PLANAS PÚBOL
Masos de Púbol, 11
17120 Púbol
(Girona)
(+34) 972 48 82 13#(+34) 972 49 22 23
pubol@viversplanas.com
www.viversplanas.com'
        }, {
            id: 72,
            latitude: 41.9850000,
            longitude: 2.6155560,
            html: 'Vivers GONZALEZ
c/ les Brugueres, 17
17166 El Pasteral
Girona
(+34) 660 200 580# (+34) 616 259 507
viversgonzalez@hotmail.com'
        }, {
            id: 25,
            latitude: 41.8735080,
            longitude: 2.6293500,
            html: 'Vivers MASSANEDA
Ctra. Sant Hilari s/n
17430 Santa Coloma de Farners
(Girona)
(+34) 972 840 855
info@viversmassaneda.com
www.viversmassaneda.com'
        }, {
            id: 27,
            latitude: 41.8120020,
            longitude: 2.5197990,
            html: 'MICOFORA
Pont vermell 1
17401 Arbúcies
(Girona)
(+34) 635 61 01 82
ramonespigol@gmail.com'
        }, {
            id: 28,
            latitude: 41.8714390,
            longitude: 2.5163050,
            html: 'Cultius MIRALPEIX
Carrer de Can Villaret, 2 #Apartat de correus 59
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 86 89 26
cultius@miralpeix.com
www.miralpeix.com'
        }, {
            id: 30,
            latitude: 42.1590660,
            longitude: 2.9277410,
            html: 'MONERPLANT
Camí de la Vinya s/n
17483 Calabuig - Bàscara
(Girona)
(+34) 972 560 033#M: (+34) 607 484 646
ea3duy@girona.net
www.monerplant.com'
        }, {
            id: 31,
            latitude: 42.1252920,
            longitude: 3.1192480,
            html: 'Vivers i Garden MONER
Can Tell - Ctra. Orriols, s/n
17130 L\'Escala
Girona
(+34) 972 77 13 26
www.viversgardenmoner.com'
        }, {
            id: 35,
            latitude: 41.9583000,
            longitude: 2.6333950,
            html: 'PALM TER
Can Salleras
17160 Anglès
(Girona)
(+34) 609 780 487
info@palmter.com
www.palmter.com'
        }, {
            id: 36,
            latitude: 42.0345420,
            longitude: 2.8983500,
            html: 'Casa PARAIRE
c/ Molí, 1
17462 Bordils
(Girona)
(+34) 972 490 026
vivers@paraire.com
www.paraire.com'
        }, {
            id: 37,
            latitude: 42.0294700,
            longitude: 2.8793340,
            html: 'Vivers PLANAS CELRÀ
c/ Palamós   99
17460 Celrà
(Girona)
(+34) 972 492 223
viversplanas@viversplanas.com
www.viversplanas.com'
        }, {
            id: 69,
            latitude: 42.1121830,
            longitude: 2.8056000,
            html: 'CAREX
Ctra. Borgonyà-Orriols, km. 1,9 
17844 Cornellà de Terri 
(Girona)
(+34) 972 595 010
info@carex.cat
www.carex.cat'
        }, {
            id: 42,
            latitude: 41.8063890,
            longitude: 3.0325000,
            html: 'Vivers RIU d\'AURA
Ctra. de Castell d\'Aro a s\'Agaró, km. 1
17249 Castell d\'Aro
(Girona)
(+34) 972 81 90 14 #M: (+34) 696 33 56 43
riudauravivers@gmail.com'
        }, {
            id: 43,
            latitude: 41.8034310,
            longitude: 2.7660110,
            html: 'Centre de Jardineria SILS
Cruïlla carretera N-II amb Carretera de Vidreres
17410 Sils
(Girona)
(+34) 972 875 252
info@jardineriasils.com
www.jardineriasils.com'
        }, {
            id: 44,
            latitude: 42.0735340,
            longitude: 3.0110650,
            html: 'SOLJARDÍ
Major, 32
17143 Jafre
(Girona)
(+34) 972 768 024#M: (+34) 606 998 880
info@soljardi.com
www.soljardi.com'
        }, {
            id: 47,
            latitude: 41.8293840,
            longitude: 2.4677730,
            html: 'Vivers TARRÉ
Casa Nova d\'en Dorca #Apartat de correus 70
17401 Arbúcies
(Girona)
(+34) 972 860 976#653 40 37 69
viverstarre@hotmail.com'
        }, {
            id: 50,
            latitude: 41.8930560,
            longitude: 2.4552780,
            html: 'Vivers TORTADÈS
Casa Tortadès, Finca la Vileta, s/n
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 868 730
info@tortades.com
www.tortades.cat'
        }, {
            id: 51,
            latitude: 41.9086110,
            longitude: 3.1669440,
            html: 'Centre de Cultius TRAMUNTANA (CET)
Paratge la Faneia, 1
17200 Palafrugell
(Girona)
(+34) 972 30 56 29#(+34) 659 99 67 75 (Mòbil)
acanyigueral@baixemporda.cat
www.centretramuntana.com'
        }, {
            id: 54,
            latitude: 41.8640830,
            longitude: 2.5240950,
            html: 'Cultius MAS LES PLANES
Mas les Planes#Ctra. de Santa Coloma km 1,5
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 87 21 54
cultiusmaslesplanes@gmail.com
www.facebook.com/maslesplanes'
        }, {
            id: 55,
            latitude: 41.8397380,
            longitude: 2.7086430,
            html: 'Cultius BRUGAT
Can Sureda, Serra magra 
17421 Riudarenes
(Girona)
(+34) 972 85 61 83
info@cultiusbrugat.com'
        }, {
            id: 66,
            latitude: 41.8741670,
            longitude: 2.5136110,
            html: 'Vivers GUILLERIES
Ctra. d\'Arbúcies, s/n
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 872 194#M: (+34) 606 865 399
info@viversguilleries.com
www.viversguilleries.com'
        }, {
            id: 73,
            latitude: 41.8061111,
            longitude: 3.0347222,
            html: 'Garden el TRÈVOL COSTA BRAVA
C/ Remei - Moli de Cuc s/n
17249 Castell d\'Aro
Girona
(+34) 972 826 181
gardentrevol@gmail.com'
        }, {
            id: 75,
            latitude: 41.8692670,
            longitude: 2.5111090,
            html: 'Cultius la PEDRA LLARGA
Ctra. d\'Arbúcies, s/n
17403 Sant Hilari Sacalm
(Girona)
(+34) 972 869 571
lapedrallarga@gmail.com
www.cultiuslapedrallarga.com'
        }, {
            id: 59,
            latitude: 42.0663670,
            longitude: 2.5287280,
            html: 'Jardineria i Vivers SANT ISCLE
Mas Prat s/n
17174 Sant Feliu de Pallerols
(Girona)
(+34) 972 44 43 56
info@viversantiscle.com
www.viversantiscle.com'
        }, {
            id: 60,
            latitude: 42.0444160,
            longitude: 2.8956790,
            html: 'Cultius MAS CUNÍ
c/ Molí, 15
17462 Bordils
(Girona)
(+34) 972.49.06.27#M: (+34) 609.526.124
info@cultiusmascuni.com
www.cultiusmascuni.com'
        }, {
            id: 80,
            latitude: 41.3994000,
            longitude: 2.0582000,
            html: 'IN VITRO SL
Riera de la Salut km2, Hivernacles.
08980 Sant Feliu de Llobregat
(Barcelona)
(+34) 93 685 6790 #(+34) 657 91 4343
invitro@invitro.es
www.invitro.es'
        }, {
            id: 67,
            latitude: 41.7503390,
            longitude: 0.9913000,
            html: 'Vivers BORDA
Mas Xerrill - Carretera de Preixens s/n
25334 Castellserà
Lleida
(+34) 973 61 00 98
viversborda@viversborda.com
www.viversborda.com'
        }, {
            id: 81,
            latitude: 42.4404474,
            longitude: 1.9068321,
            html: 'Jarditec TRILLES
Parcel.la 18-19 de Saneja
17528 Guils de Cerdanya
Girona
(+34) 620 809 519
jardinst.trilles@hotmail.com
www.jarditectrilles.com'
        }, {
            id: 78,
            latitude: 41.6279450,
            longitude: 2.3368440,
            html: 'BELLOCH Forestal
Ctra. C-251, km 5.6
08430 La Roca del Vallès
Barcelona
(+34) 93 861 91 00
mateu.sans@belloch.eu
www.bellochforestal.com'
        }, {
            id: 79,
            latitude: 42.2615004,
            longitude: 3.0393302,
            html: 'Jardineria MARTÍ
Carretera de Roses, km 32,5
17485 Vila-sacra
Girona
(+34) 972 51 04 52
oficina@jardineriamarti.net
www.jardineriamarti.net'
        }, {
    id: -1,
    latitude: 42.02690181356306,
    longitude: 2.875497136153058,
    html: 'ASSOCIACIÓ DE VIVERISTES DE GIRONA
c/ la Fàbrica, 25
17460 Celrà (Girona)
Tel. (+34) 972 494 220 | Fax (+34) 972 494 248
e-mail: info (at) viveristesdegirona.com'
} ];
        var options = { 'mapTypeId': google.maps.MapTypeId.ROADMAP };
        map = new google.maps.Map(document.getElementById("gmapglobal"), options);
        directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
        image = new google.maps.MarkerImage('img/flower2.png',
            new google.maps.Size(32, 37),
            new google.maps.Point(0, 0),
            new google.maps.Point(19, 37));
        shadow = new google.maps.MarkerImage('img/shadow.png',
            new google.maps.Size(51, 37),
            new google.maps.Point(0, 0),
            new google.maps.Point(19, 37));
        home = new google.maps.MarkerImage('img/home.png',
            new google.maps.Size(51, 37),
            new google.maps.Point(0, 0),
            new google.maps.Point(19, 37));
        destination = new google.maps.MarkerImage('img/flower.png',
            new google.maps.Size(51, 37),
            new google.maps.Point(0, 0),
            new google.maps.Point(19, 37));
        homeMarker = new google.maps.Marker({
            icon: home,
            shadow: shadow
        });
        destMarker = new google.maps.Marker({
            icon: destination,
            shadow: shadow
        });
        google.maps.event.addListener(destMarker, 'click', function () {
            infowindow.setContent(lastContent);
            infowindow.open(map, destMarker);
        });
        google.maps.event.addListener(map, 'click', function () {
            infowindow.close();
        });
        (function () {
            // create markers, and search and fit the bounds of the markers
            var i, minLat, maxLat, minLng, maxLng;
            var createMarker = function (latlng, html) {
                var marker = new google.maps.Marker({
                    position: latlng,
                    icon: image,
                    shadow: shadow,
                    map: map
                });
                google.maps.event.addListener(marker, 'click', function () {
                    lastContent = html;
                    viverista = marker.getPosition();
                    infowindow.setContent(html);
                    infowindow.open(map, marker);
                    calcRoute(marker);
                });
                return marker;
            };
            for (i = 0; i < markers.length; i += 1) {
                var marker = markers[i];
                var lat = marker.latitude;
                var lng = marker.longitude;
                if (i === 0) {
                    minLat = lat;
                    maxLat = lat;
                    minLng = lng;
                    maxLng = lng;
                } else {
                    if (lat < minLat) { minLat = lat; }
                    if (lng < minLng) { minLng = lng; }
                    if (lat > maxLat) { maxLat = lat; }
                    if (lng > maxLng) { maxLng = lng; }
                }
                var latLng = new google.maps.LatLng(lat, lng);
                var gmarker = createMarker(latLng, marker.html);
                if (marker.id === -1) { 
                    var celra = new google.maps.MarkerImage('img/celra.png',
                        new google.maps.Size(51, 37),
                        new google.maps.Point(0, 0),
                        new google.maps.Point(19, 37));
                    gmarker.setIcon(celra);
                    gmarker.setZIndex(1000);
                }
            }
            map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(minLat, minLng),
                new google.maps.LatLng(maxLat, maxLng)));
        }());
    };
    $(function () {
        initialize();
        $('#mylocation').change(function () {
            if ($(this).val() === '') {
                $('#window-gmap').text('');
            }
            if (hiddenMarker !== null) {
                calcRoute(hiddenMarker);
            }
        });
    });
}());