﻿(function($) {
    // ******** global variables *********	
    //ścieżka do katalogu z plikami na macierzy
  
    var debugmode = 0;
    var xmlPath;
    var youtubeURL;
    //tablica z zawartością plików xml z playlistami
    var gmFiles = [];
    var markers = [];
    var $gmBox;
    var map;
    var opts;


    // ****** END global variables *******

    jQuery.fn.jMapsPrsa = function(options) {
        opts = jQuery.extend({}, jQuery.fn.jMapsPrsa.defaults, options);
        $gmBox = jQuery(this);
        var gmFilesPaths = opts.gmFilesPaths;

        xmlPath = opts.xmlPath;

       

      
      
      //  debug("gmFilesPaths", gmFilesPaths);
      //  debug("xmlPath", xmlPath);

        //ramy html'a wewnątrz kontenera z mapą
        if (opts.header) {
            $gmBox.append('<div class="gmHeader"></div>');
        };
        $gmBox.append('<div id="gmMap" style="width:' + opts.width + 'px; height:' + opts.height + 'px"></div>');
        map = new GMap2(document.getElementById("gmMap"));
        
        if (!gmFilesPaths.length) {  
			map.setCenter(new GLatLng(52, 21), 4);
			return this;
        }
       
        if (opts.navigation) {
            $gmBox.append('<div class="gmSidebar"><ul></ul></div>')
        };

        loadMaps(gmFilesPaths);

    };


    // ******* private functions *********
    function makeMarkers(mapId) {
        var currentMap = $(gmFiles[mapId]);
        var $gmSideBar = $gmBox.find('.gmSidebar ul');
        var currentFilePath = opts.gmFilesPaths[mapId];
        var start = currentFilePath.lastIndexOf("/") + 1;
        var documentId = currentFilePath.substring(start, currentFilePath.lastIndexOf("."));        
       
        
        $('marker', currentMap).each(function() {
            var $markerNode = $(this);
            var lat = parseFloat($markerNode.find('lat').text());
            var lng = parseFloat($markerNode.find('lng').text());
            var point = new GLatLng(lat, lng);
            var id = parseInt($markerNode.find('id').text());
            var html = $markerNode.find('description').text();
            var title = $markerNode.find('title').text();
            var date = $markerNode.find('date').text();

            var marker = new GMarker(point);
            markers[id] = marker;
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml('<span class="gmMarkerTitle">' + title + '</span><span class="gmMarkerDate">' + date + '</span><div class="gmMarkerHtml">' + html + '</div><div class="gmArticleLink"><a href="http://www.polskieradio.pl/trojka/motocykle/relacje/artykul'+documentId+'.html">więcej</a></div>');
            });

            map.addOverlay(marker);

            //pasek nawigacyjny vel. sidebar
          //  if ($gmSideBar.length) {
          //      var $li = $('<li><a href="#" rel=' + mapId + '_' + id + '>' + title + '</a></li>');
          //      $('a', $li).click(function() {
          //          GEvent.trigger(markers[$(this).attr('rel')], "click");
          //          return false;
          //      });
           //     $gmSideBar.append($li);
          //  };
        }); //end each	
    }


    function initMap() {
      
        var mapsCount = gmFiles.length;
        var lastDate;
        var DateNow = 0;

        for (var i = 0; i < mapsCount; i++) {
            var currentMap = $(gmFiles[i]);
            var CurrentMapOpts = $("Markers", currentMap);
            var zoom, lat, lng, title;

            var $lastMarker = $("marker:last", currentMap)

            //szukam daty najmłodszego markera i na nim centruję mapę
            var lastdate = $("date", $lastMarker).text();
            if (lastdate.split("/").length != 3) {                        
                        lastDate = new Date();
                        }
                        else{
                        lastDate = new Date(lastdate);
                        }

          
          if($lastMarker.length>0){
            lat = parseFloat($('lat', $lastMarker).text());
            lng = parseFloat($('lng', $lastMarker).text());
            zoom = parseInt(CurrentMapOpts.attr('zoom'));
          //  title = CurrentMapOpts.attr('title');

                    //    lat = parseFloat(CurrentMapOpts.attr('lat'));
                    //    lng = parseFloat(CurrentMapOpts.attr('lng'));
                    //    zoom = parseInt(CurrentMapOpts.attr('zoom'));
            //            title = CurrentMapOpts.attr('title');

            if (lastDate > DateNow) {
                map.setCenter(new GLatLng(lat, lng), zoom);
               //  map.setCenter(new GLatLng(21, 55), 7);
                DateNow = lastDate;
            }
            map.setMapType(G_PHYSICAL_MAP);

            //$gmBox.find('.gmHeader').html(title);

            makeMarkers(i);
            addMapControls();
            }
        }
    }


    function addMapControls() {
        if (opts.zoom) map.addControl(new GLargeMapControl());
        if (opts.changeView) {
            map.addMapType(G_PHYSICAL_MAP);
            var hierarchy = new GHierarchicalMapTypeControl();
            hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP, null, true);
            map.addControl(hierarchy);
        }
    };

    //ładuje listę map z xml'i
    function loadMaps(_gmFilesPaths) {
        var filesRead = 0;
        jQuery.each(_gmFilesPaths, function() {
            var currentFile = this;
            debug("File url", xmlPath + currentFile);
            jQuery.ajax({
                type: "GET",
                url: "/_controls/xml/getxml.aspx",
                data: { 'link': xmlPath + currentFile },
                dataType: "xml",
                success: function(xml) {
                    gmFiles.push(xml);
                },
                error: function() {
                    debug("ajax error", this.msg);
                },
                complete: function() {
                    //po zaczytaniu ostatniego pliku generuje mapy                    
                    filesRead++;
                    if (filesRead == _gmFilesPaths.length) {
                        initMap();
                    }
                }
            }); //end ajax	
        });  //end each		
    }; //end function




    function debug(msg, jQueryobj) {
        if (debugmode) {
            if (window.console && window.console.log) {
                window.console.log('# ' + msg + ' : ' + jQueryobj);
            }
            else { alert('# ' + msg + ' : ' + jQueryobj); }
        }
    };

    function debugs(msg) {
        if (debugmode) {
            if (window.console && window.console.log) {
                window.console.log('# ' + msg);
            }
            else { alert('# ' + msg); }
        }
    };

    // ******* END private functions *********


    // ******** default settings *********** 
    jQuery.fn.jMapsPrsa.defaults = {
        xmlPath: "http://www.polskieradio.pl/_cms/googlemaps/",
        width: 400,
        height: 400,
        navigation: true,
        zoom: true,
        changeView: true
    };
})(jQuery);
