var map;
var markerArea;
var geocoder = new GClientGeocoder();
var mainMap = true;
geocoder.setBaseCountryCode('pl');
var markersLoaded = new Array();

function addMarker(point,title,description,mapIcon,hide) {
    if (!mapIcon) {
        mapIcon = createIcon('inne');
    }
    var marker = new GMarker(point,{title:title,description:description,icon:mapIcon});
    marker.txt = '<div class="mapsInfo">'+description+'</div>';
    map.addOverlay(marker);
    GEvent.addListener(marker,"click",function() {
        marker.openInfoWindowHtml(marker.txt);
    });
    if (hide) {
        marker.hide();
    }
    else {
//        markerArea.extend(point);
//        zoomFit();
    }
    return marker;
}

function loadMarkers (xml) {
    var url = xml;
    // jeśli markery dla tej kategorii były załadowane, to wyjdź
    for (i in markersLoaded) {
        if (markersLoaded[i] == url)
            return;
    }
    
    // znajdź div zawierający mapę i dodaj preloader
    var mapContainer = $('#'+map.getContainer().getAttribute('id'));
    mapContainer.mapPreloader(true);

    GDownloadUrl(xml, function(data, responseCode) {
      if (responseCode==200) {
        var xml = GXml.parse(data);
        $(xml).find("marker").each(function() {
          var marker = $(this);
          var lat = parseFloat(marker.attr("lat"));
          var lng = parseFloat(marker.attr("lng"));
          var title = $(this).find('title').text();
          var description = $(this).find('description').text();
          var type = $(this).find('type').text();
          var address = $(this).find('address').text();
          var hide = false;
          if (typeof( markerGroups[type] ) != "undefined") {
              if (lat>0 && lng>0) {
                  var m = addMarker(new GLatLng(lat,lng),title,description,markerGroups[type][1],hide);
                  markerGroups[type][0].push(m);
              }
              else {
                  geocoder.getLatLng(address,function(latlng) { 
                      if (latlng) {
                          var m = addMarker(latlng,title,description,markerGroups[type][1],hide);
                          markerGroups[type][0].push(m);
                      }
                  });
              }
          }
        });
        // załadowano, zapamiętaj jaki plik xml i usuń preloader
        markersLoaded.push(url);
        mapContainer.mapPreloader(false);
    }
  });
}

function toggleGroup(type,show) {
    for (var i = 0; i < markerGroups[type][0].length; i++) {
        var marker = markerGroups[type][0][i];
        if (show==1) { marker.show(); }
        else if (show==0) { marker.hide(); }
        else {
            if (marker.isHidden()) { marker.show(); } 
            else { marker.hide(); }
        }
    }
}

function toggleGroupArray(type,show) {
    for (x=0;x<type.length;x++)
    {
        for (var i = 0; i < markerGroups[type[x]][0].length; i++) {
            var marker = markerGroups[type[x]][0][i];
            if (show==1) { marker.show(); }
            else if (show==0) { marker.hide(); }
            else {
                if (marker.isHidden()) { marker.show(); }
                else { marker.hide(); }
            }
        }
    }
}

function toggleMainGroup(type,show) {
    $.each( markerGroups, function() {
        for (var i = 0; i < this[0].length; i++) {
            if (this[2]==type) {
                var marker = this[0][i];
                if (show==1) { marker.show(); }
                else if (show==0) { marker.hide(); }
                else {
                    if (marker.isHidden()) { marker.show(); }
                    else { marker.hide(); }
                }
            }
        }
    } );
}

function zoomFit() {
    newzoom = map.getBoundsZoomLevel (markerArea);
    newcenter = markerArea.getCenter();
    map.setCenter (newcenter,newzoom);
}

function createIcon (url) {
    var icon = new GIcon();
    icon.image =  '/images/markers/' + url + '.gif';
    icon.iconSize = new GSize(33, 38);
    icon.iconAnchor = new GPoint(15, 38);
    icon.shadow = '/images/markers/cien.png';
    icon.shadowSize = new GSize(56, 38);
    icon.infoWindowAnchor = new GPoint(15,12);
    return icon;
}

// funkcje JQuery
$.fn.mapNavigation = function() {
    $nav=$(this);

    // zaznacz wszystkie checkboxy
    $nav.find('div input').attr("checked",true);

    // akcje
    // tabs - pokaz markery z aktywnej zakladki, ukryj markery z nieaktywnych
    $nav.find('ul:first li a').click( function() {
        $nav.find('div ul li:not(.first) input').each( function() {
            toggleGroup($(this).val(),0);
        });
        $($(this).attr('href')).find('li:not(.first) input').each( function() {
            if ( $(this).is(":checked") ) {
                toggleGroup($(this).val(),1);
            }
        });
    });
    // po kliknieciu na pierwszy checkbox - zaznacz/odznacz cala grupe
    $nav.find("li.first input").click( function() {
        if ( $(this).is(":checked") ) {
            $(this).parents('ul:first').find("input").attr("checked",true);
            toggleMainGroup($(this).val(),1);
        }
        else {
            $(this).parents('ul:first').find("input").attr("checked",false);
            toggleMainGroup($(this).val(),0);
        }
    });
    // zwykle markery pokazuja/ukrywaja cala grupe
    $nav.find("li:not(.first) input").click(function(){
        var group=$(this).val().split(",");
        toggleGroup(group);
    });
    // obrazki symuluja klikniecie w checkbox
    $nav.find("img").click(function(){
        $(this).parents('li:first').find('input').trigger("click");
    });
};

$.fn.mapCities = function() {
    var boxCitiesTimeout;
    $box=$(this);
    $box.find('p').click(function(){ $box.find('ul').toggle(); });
    $box.mouseover(function(){ clearTimeout(boxCitiesTimeout); });
    $box.mouseout(function(){ boxCitiesTimeout = setTimeout ( function(){ $box.find('ul').hide(); }, 2000); });
    $box.find('a').click(function(){
        $box.find('a').removeClass('current');
        $(this).addClass('current');
        $box.find('p').html($(this).text());
        $box.find('ul').hide();
        var city=$(this).attr("class").split(":");
        map.setCenter(new GLatLng(city[0],city[1]),parseInt(city[2]));
        return false;
    });
};

$.fn.mapNavigationBox = function() {
    $nav=$(this).find('form fieldset ul');

    // zaznacz pierwsze dwa checkboxy
    $nav.find('li input:not(:last)').each(function(){
        toggleMainGroup($(this).val(),1);
        $(this).attr("checked",true);
    });

    // odznacz ostatniego checkboxa
    $nav.find('li input:last').each(function(){
        toggleMainGroup($(this).val(),0);
        $(this).attr("checked",false);
    });

    // akcje
    $nav.find('li input').click(function(){
        toggleMainGroup($(this).val());
    });
};

$.fn.mapPreloader = function(show) {
    if (show == true) {
        $mapContainer = $(this);
        $mapContainer.append("<div id=\"mapPreloader\"></div>");
        $mapPreloader = $(this).find('#mapPreloader');

        // dodaj preloader pośrodku mapy
        var preloaderImageSize = 66;
        var w = parseInt($mapContainer.css("width"));
        var x = w/2 - preloaderImageSize/2;
        var y = w/2 - preloaderImageSize/2;

        $mapContainer.css({'position' : 'relative'});
        $mapPreloader.css({'position' : 'absolute', 'left' : x+'px', 'top' : y+'px'});
        $mapPreloader.html("<img src=\"/images/preloader_maps.gif\" width=\""+preloaderImageSize+"\" height=\""+preloaderImageSize+"\" alt=\"loading map\" />");
    } else {
        // usuń preloader
        $(this).find('#mapPreloader').remove();
    }
};