// mapmeta - contains a list of types + onmaploaded
// mapdata - raw loaded json data

function gmaps_failure()
{
//      alert("Het is niet gelukt Google Maps in te laden. Meestal betekend dit dat er geen internet verbinding is.");
//      return;

        var errordialog = product.openWindow(
                                                { name:                 'cityselection'
                                                , title:                'Error'
                                                , className:    'mappopup pointpopup' //'frmSelectCity'
                                                , canclose:             true
                                                , candrag:              true
                                                //, content:            dummy
                                                , center:               true
                                                , visible:              false

                                                , preferredWidth:       300

                                                //, anchoredge: 'topright'
                                                //, anchorishorcentre:  false
                                                //, anchorisvercentre:  true
                                                });
        errordialog.body.innerHTML = 'Google Maps kon niet ingeladen worden. Controleer uw internet verbinding.';
        errordialog.show();
}

/* callback for Google Maps to indicate it being ready for usage */
function initializeGMaps()
{
        state.gmaps_loaded = true;

        removeClass(document.getElementById('googleMap'), "mapuninitialized");
        //product.state.gmaps_initialized
        product.initMapUsage_GMap();
}

productC.prototype.initMapUsage_GMap = function product_initMapUsage_GMap()
{
        var self = this;

        mapmeta.icon_notpublished = { filename: 'notpublished.png'
									, width: 23
									, height: 23
									};

        console.log("MapVIZ / creating Google Maps V3 map");

        mygmap = new spcGMap();
        mygmap.settypes(mapmeta.types);
        mygmap.createBaseIcons();

        console.log("MapVIZ / setting up events");

        mygmap.onitemselect = function(itemid, itemclass)
        {
                console.log('Item #'+itemid+' is selected');

                // don't show anything when clicking on a track
                if (itemclass == "track")
                        return;

                if (mapmeta.iscityselect)
                {
                        if (mygmap.editmode)
                                return;

                        self.selectCity(mapmeta.getItemById(itemid).name);
                }
                else
                {
                        var mapitem = mapmeta.getItemById(itemid);

                        // if we aren't a developer and there's no media, give a warning
                        if (!product.state.devmode && (!mapitem.media || mapitem.media.length==0))
                        {
                                alert("Er zijn geen foto's of filmmateriaal voor dit punt.");
                                return;
                        }

                        showPointGallery(itemid);
                }
        }

        mapmeta.onMapLoaded = function(forcereload)
        {
                // load info about all videos
                medialist.load('', forcereload);

                product.state.map = mapmeta.mapname; // make obsolete
                product.map = mapmeta.mapname; // OBSOLETE??

                //var mapcontentpath = this.getMapContentPath();

                self.applyLoadedMap();
        }

        // was a map already loaded before the Google Maps instance was created?
        if (mapmeta.maploaded && !mapmeta.appliedtomap)
        {
                this.applyLoadedMap();
        }
}

productC.prototype.applyLoadedMap = function()
{
        console.log("Map / apply loaded map");

        console.log(mapmeta);
        if (mapmeta.mapname != 'nederland') // FIXME: check if it's a cityselect map
                this.switchSection('map');
        //else
        //      this.switchSection('mainmenu');

        mygmap.applyNewSettings();

        if (this.sidebar)
                this.sidebar.updatesize();

        if (mapmeta.mapname == 'nederland') // FIXME: check if it's a cityselect map
        {
                // FIXME: oh nasty to do this here :P
                if (!this.citiessidebar)
                {
                        this.citiessidebar = new mapselectionsidebar();
                        this.citiessidebar.container.style.width = "280px"; // FIXME
                }

                //console.error("no sidebar yet to generate citylist for");
                this.citiessidebar.generateCityList(); // FIXME
        }

        if (this.citiessidebar)
                this.citiessidebar.updatesize();

        this.resizeHeaderBar();

        document.getElementById('sectionTitle').innerHTML = initialCap(mapmeta.mapname);

        //alert(mapmeta.mapdataraw.introurl);
        if (mapmeta.mapdataraw.introurl)
        {
                // Als de melding dialoog al open is, breng deze naar voren
                var wnd = product.getWindowByName('mapintro')
                if (wnd)
                {
                        wnd.toFront();
                        return;
                }

                // fixme: embedcontent instead of height
                var wndMapIntro = this.openInWindow(
                                        { title: 'Melding'
                                        , name: 'mapintro'
                                        , className: ''
                                        , url: mapmeta.mapdataraw.introurl
                                        , height: 200
                                        //, embedcontent: true
                                        });

                //var viewport = getViewPortDimensions();
                //wndMapIntro.setOuterSize(800,viewport.height);
        }
}

/*
productC.prototype.getMapContentPath = function()
{
        return 'content/mapspecific/'+product.map+'/';
}
*/

productC.prototype.gotoMap = function productC_gotoMap(mapname)
{
    console.warn('gotoMap %s', mapname);

        if (mapname == this.state.map)
                return;

        mapmeta.load(mapname);
}

productC.prototype.showCitySelection = function product_showCitySelection()
{
        if (product.getWindowByName('cityselection'))
                return;

        requestdoc(
                { url:          product.url.selcitywelcome
                , callback:     function()
                                        {
                                                var dummy = document.createElement('div');
                                                dummy.innerHTML = this.req.responseText;

                                                var wndSelectCity = product.openWindow(
                                                                                                { name:                 'cityselection'
                                                                                                , title:                'Kies een plaats'
                                                                                                , className:    'mappopup pointpopup' //'frmSelectCity'
                                                                                                , canclose:             false
                                                                                                , content:              dummy
                                                                                                , center:               false
                                                                                                });

                                                wndSelectCity.setPosition(340,140);

                                                //wndSelectCity.body.innerHTML = this.req.responseText;
                                                //wndSelectCity.centeronscreen();
                                        }
                });
}

productC.prototype.showTrackSpecs = function(trackid)
{
        var trackinfo = document.createDocumentFragment();

        var tracktypedescription = ['nog niet berekend', 'naar school', 'naar huis', 'onbekend'];

        var track = mapmeta.getTrackDataById(trackid);              // get track raw data from the server
        var trackitem = mygmap.getItemByTrackId(trackid); // get track's entry as added to the mapitems

        var tbl = document.createElement('table');
        var tbody = document.createElement('tbody');
        tbody.appendChild(createTableRow('Richting:', tracktypedescription[track.type]));
        //tbody.appendChild(createTableRow('Aantal stops:', '?'/*track.stops*/));
        tbody.appendChild(createTableRow('Gereden op:', track.timedescription));//track.dtstart+' - '+track.dtend+' ('+track.duration+' minuten)'));
        tbody.appendChild(createTableRow('Totale reistijd:', track.duration+' minuten'));
        tbody.appendChild(createTableRow('Afstand hemelsbreed:', track.dist_starttoend+' Km'));
        tbody.appendChild(createTableRow('Afstand gereden:', track.dist_travelled+' Km'));

        tbody.appendChild(createTableRow('Snelheden:', ''));
        tbody.appendChild(createTableRow('maximaal:', track.speed_max+' Km/h'));
        tbody.appendChild(createTableRow('gemiddelde (geheel):', track.speed_avg+' Km/h'));
        tbody.appendChild(createTableRow('gemiddelde:', track.speed_moved_avg+' Km/h'));

        if (product.config.debug)
        {
			tbody.appendChild(createTableRowDivider());
			tbody.appendChild(createTableRow('trackid:', '#'+trackid));
			tbody.appendChild(createTableRow('beginpunt:', '#'+track.dev.startpoint));
			tbody.appendChild(createTableRow('eindpunt:', '#'+track.dev.endpoint));
			tbody.appendChild(createTableRow('logid:', '#'+track.dev.logid));
			tbody.appendChild(createTableRow('logfile:', track.dev.logfilename));
        }

        tbl.appendChild(tbody);
        trackinfo.appendChild(tbl);

        if (trackid != window.trackhoverid)
        {
			if (window.trackhoverid > 0)
			{
//              alert("disabling previous track "+window.trackhoverid);
					var prevtrack = mygmap.getItemByTrackId(window.trackhoverid);
					if (prevtrack && prevtrack.instance)
							prevtrack.instance.setHover(false);
			}

			window.trackhoverid = trackid;

			if (trackitem && trackitem.instance)
			{
				trackitem.instance.setHover(true);
			}
        }

        //trackinfo.appendChild(document.createTextNode('(dit is nog een test)'));

        product.sidebar.popup.replaceDOMContent(trackinfo);
        product.sidebar.popup.show();

/*
        // position/center the popup to the left of the active row
        var rowpos = getOffsetToViewport(oArgs.target); //getBoundingClientRect(oArgs.target);
        var posx = rowpos.left;// - 25; // + oArgs.target.clientWidth/2;
        var posy = rowpos.top + oArgs.target.clientHeight/2 - product.sidebar.popup.wnd.getOuterSize().height/2;
        product.sidebar.popup.position(posx, posy);
*/
}



function createTableRow(title, value)
{
        var trow = document.createElement('tr');

        var th  = document.createElement('th');
        th.appendChild(document.createTextNode(title));
        th.style.whiteSpace = 'nowrap';

        var td  = document.createElement('td');
        td.appendChild(document.createTextNode(value));
        td.style.whiteSpace = 'nowrap';

        trow.appendChild(th);
        trow.appendChild(td);

        return trow;
}

function createTableRowDivider(title)
{
        var trow = document.createElement('tr');

        var td  = document.createElement('th');
        td.setAttribute("colspan", "2");

        var hr = document.createElement('hr');
        td.appendChild(hr);

        trow.appendChild(td);

        return trow;
}
