/*****
*
* Tasmania Demo Map library
*
* $Id: tasmania.js 91 2008-08-13 16:42:59Z klaus $
*
* draw a simple basemap of tasmania with power-stations on top
* data is queried from SQLite database tasmania.sqlite
*
* seamless mapping data set at 1:5 million scale has been downloaded from
* Geoscience Australia (GEODATA TOPO 5M) and is used under licence.
* http://www.ga.gov.au/nmd/products/digidat/5m.jsp
*
*****/

window.onload = function() {
    // initialize SQLite database service, assume SQLite-db in same directory
    var db = openDatabase("Tasmania", "1.0", "Tasmania Demo Map", 1048576);
    var wp = new WKTParser();

    var canvasMap = document.getElementById("mapCanvas");
    var canvasAnno = document.getElementById("annoCanvas");

    createSVGNode = function(ntype,ncoords) {
        var elem;
        if (ntype == 'annotation') {
            elem = document.createElementNS('http://www.w3.org/2000/svg','text');
            elem.appendChild(document.createTextNode(" "));
            elem.setAttributeNS(null,"x",ncoords.x);
            elem.setAttributeNS(null,"y",ncoords.y);
        }
        else if (ntype.search(/point$/) != -1) {
            elem = document.createElementNS('http://www.w3.org/2000/svg','circle');
            elem.setAttributeNS(null,"cx",ncoords.x);
            elem.setAttributeNS(null,"cy",ncoords.y);
        }
        else if (ntype.search(/linestring$/) != -1 || ntype.search(/polygon$/) != -1) {
            elem = document.createElementNS('http://www.w3.org/2000/svg','path');
            elem.setAttributeNS(null,"d",ncoords);
        }
        else {
            // create element with name ntype
            elem = document.createElementNS('http://www.w3.org/2000/svg',ntype);
        }
        return elem;
    };

    addLayer = function(canvas,layerId,sql) {
        var canvasId = canvas.getAttributeNS(null,"id");
        var g = createSVGNode("g");   // wrap layer into a group
        g.setAttributeNS(null,"id",layerId);

        db.transaction(function(tx) {
            tx.executeSql(sql, [], function(tx, rs) {
                for(var i=0; i<rs.rows.length; i++) {
                    var row = rs.rows.item(i); // create short-cut
                    var geom = wp.parse(row.geom)
                    var elem = null;

                    if (canvasId == 'mapCanvas') {
                        elem = createSVGNode(wp.getType(),geom);
                        if (row.radius) {
                            elem.setAttributeNS(null,"r",row.radius);
                        }
                        elem.setAttributeNS(null,"class",row.style);
                        elem.setAttributeNS(null,"title",row.name);
                        elem.setAttributeNS("http://svg.cc/2008/tas","tas:id",row.id)
                        elem.setAttributeNS("http://svg.cc/2008/tas","tas:name",row.name)
                    }
                    else if (canvasId == 'annoCanvas') {
                        elem = createSVGNode('annotation',geom);
                        elem.firstChild.nodeValue = row.name;
                        elem.setAttributeNS(null,"class",row.style);
                        elem.setAttributeNS("http://svg.cc/2008/tas","tas:id",row.id);
                        elem.setAttributeNS("http://svg.cc/2008/tas","tas:name",row.name);
                        elem.setAttributeNS("http://svg.cc/2008/tas","tas:anchor",row.anchor);

                        setAnnoPosition(elem,row.anchor);
                    }
                    g.appendChild(elem);
                    //alert(printNode(g))
                }
                canvas.appendChild(g);
            });
        });
        return g;
    };

    setAnnoPosition = function(elem,position) {
        var p = (position != null) ? position.toString() : '7';
        // set horizontal position
        if (p.match(/^[258]$/)) {
            elem.setAttributeNS(null,"text-anchor","middle")
        }
        else if (p.match(/^[369]$/)) {
            elem.setAttributeNS(null,"text-anchor","end")
        }
        else {
            elem.setAttributeNS(null,"text-anchor","start")
        }
        // set vertical position
        if (p.match(/^[123]$/)) {
            elem.setAttributeNS(null,"baseline-shift","-0.7em")
        }
        else if (p.match(/^[456]$/)) {
            elem.setAttributeNS(null,"baseline-shift","-0.35em")
        }
        else {
            elem.setAttributeNS(null,"baseline-shift","0em")
        }
    };

    // add geometry layers
    addLayer(canvasMap,"layerTerritory","SELECT ogc_fid AS id,name,feat_code AS style,wkt_geometry AS geom FROM territory --LIMIT 1");
    addLayer(canvasMap,"layerLakes"    ,"SELECT ogc_fid AS id,name,feat_code AS style,wkt_geometry AS geom FROM lakes --LIMIT 1");
    addLayer(canvasMap,"layerRivers"   ,"SELECT ogc_fid AS id,name,feat_code || perennial AS style,wkt_geometry AS geom FROM rivers WHERE feat_code != 'connector' --LIMIT 1");
    addLayer(canvasMap,"layerRailways" ,"SELECT ogc_fid AS id,name,feat_code AS style,wkt_geometry AS geom FROM railways --LIMIT 1");
    addLayer(canvasMap,"layerStations" ,"SELECT ogc_fid AS id,name,feat_code AS style,'0.02' AS radius,wkt_geometry AS geom FROM stations --LIMIT 1");
    addLayer(canvasMap,"layerRoads"    ,"SELECT ogc_fid AS id,name,feat_code || class AS style,wkt_geometry AS geom FROM roads --LIMIT 1");
    addLayer(canvasMap,"layerPlaces"   ,"SELECT ogc_fid AS id,name,feat_code AS style,'0.02' AS radius,wkt_geometry AS geom FROM places WHERE CAST(population AS INTEGER) > 10000 --LIMIT 1");

    // add two more layers and store reference for later use
    var layerEnergy = addLayer(canvasMap,"layerEnergy"   ,"SELECT id,name || ' (' || fuel_type || ')' AS name,class AS style,radius,wkt_geometry AS geom FROM view_energy_tasmania ORDER BY CAST(capacity_kw AS INTEGER) DESC --LIMIT 1");
    var layerLabels = addLayer(canvasAnno,"layerLabels","SELECT ogc_fid AS id,name,feat_code || locality AS style,anchor,wkt_geometry AS geom " +
                                      "FROM places WHERE locality IN (3,1) " +
                                      "UNION " +
                                      "SELECT ogc_fid AS id,name,feat_code || locality AS style,anchor,wkt_geometry AS geom " +
                                      "FROM places WHERE CAST(population AS INTEGER) > 10000 " +
                                      "ORDER BY style DESC --LIMIT 1");
    /* add interactivity */

    // identify power stations on click
    layerEnergy.onclick = function(evt) {
        var id = evt.target.getAttributeNS("http://svg.cc/2008/tas","id");
        db.transaction(function(tx) {
            tx.executeSql('SELECT * FROM view_energy_tasmania WHERE id=?',[id], function(tx, rs) {
                var res = [];
                for(var i=0; i<rs.rows.length; i++) {
                    var dat = []
                    for (var col in rs.rows.item(i)) {
                        dat[dat.length] = col+": "+rs.rows.item(i)[col]
                    }
                    res[res.length] = dat.join("\n");
                }
                alert(res);
            });
        });
    }

    // update position of annotation on click
    layerLabels.onclick = function(evt) {
        var label = evt.target;
        var id = evt.target.getAttributeNS("http://svg.cc/2008/tas","id");
        var tool = document.getElementById("toolAnnoPosition");
        var ctm = tool.getScreenCTM();
        tool.parentNode.setAttributeNS(null,"transform","translate("+(evt.clientX/ctm.a)+","+(evt.clientY/ctm.d)+")");
        tool.parentNode.setAttributeNS(null,"display","inline");
        tool.onmouseover = function(e) {
            setAnnoPosition(label,e.target.getAttributeNS("http://svg.cc/2008/tas","anchor"));
        };
        tool.onclick = function(e) {
            var pos = e.target.getAttributeNS("http://svg.cc/2008/tas","anchor");
            // update database
            db.transaction(function(tx) {
                tx.executeSql('UPDATE places SET anchor=? WHERE ogc_fid=?',[pos,id]);
                alert('UPDATE OK');
            });

            setAnnoPosition(label,pos);
            tool.parentNode.setAttributeNS(null,"display","none");
            tool.onmouseover = null;
            tool.onclick = null;
        }
    }
}

if (! window.printNode) {
    window.printNode = function (node) {
        // for debugging content of nodes ...
        var serializer = new XMLSerializer()
        var xml = serializer.serializeToString(node)
        return xml
    };
}
