/*
 * imaptools-demo.js
 * $Id: $
 *
 * Some additional utilities used by the iMaptools.com Demo Application.
 *
 * Copyright 2006, Stephen Woodbridge, All Rights Reserved.
 * info@imaptools.com
 * http://imaptools.com/
 *
 */

    var mapObj = null;
    var rgeoToggle = false;
    // Create a Info-window icon object...
    var myInfoSkin = new msInfoSkin(
        '/img/angolo_a.png', '/img/angolo_b.png',
        '/img/angolo_c.png', '/img/angolo_d.png',
        '/img/report_t.png', '/img/report_d.png',
        '/img/report_l.png', '/img/report_r.png',
        '/img/report_x.png', '/img/close.png',
        '/img/report_arrow.png' );
    var redIcon = new msIcon( null, null );
    var blueIcon = new msIcon( '/img/mm_20_blue.png',
                               '/img/mm_20_shadow.png',
                               6, 19 );
    var geopois = null;
    var rgeopoi = null;
    var dxy = 0.004;
    $(document).ready(function(){
        function update_pois () {
            mapObj.removeOverlayPoints();
            if (rgeopoi && rgeopoi.length)
                mapObj.setOverlayPoints(rgeopoi, blueIcon, myInfoSkin);
            if (geopois && geopois.length)
                mapObj.setOverlayPoints(geopois, redIcon, myInfoSkin);
        }
        if ( browser.isIE ) {
            window.onbeforeprint = function(){
                $("#rgeo").hide();
                $("#rgeo2").show();
                $("#help").show();
            };
            window.onafterprint = function(){
                $("#help").hide();
                if (!rgeoToggle) {
                    $("#rgeo2").hide();
                    $("#rgeo").show();
                }
            };
        }
        // hide elements until we need them
        $("#errormsg").hide();
        $("#geolist").hide();
        $("a.umn").attr("target", "_umn");
        $("#showxml").attr("target", "_xml");
        $("p.center").attr("align", "center");

        // initialize the map
        myMap1 = new msMap( document.getElementById("map_tag"), 'standardRight' );
        myMap1.setCgi( "/cgi-bin/mapserv" );
        myMap1.setFullExtent( -160.0, -60.0, 15.0, 75.0 );
        myMap1.setLocation("location");
        var a = getget("xmin");
        var b = getget("xmax");
        var c = getget("ymin");
        if (a.length && b.length && c.length)
            myMap1.setExtent(parseFloat(a), parseFloat(b), parseFloat(c));

        a = getget("ll");
        if (a.length) {
            var loc = a.split(",");
            myMap1.reCenter(parseFloat(loc[1]), parseFloat(loc[0]), dxy);
        }
        var map = getget("map");
        if (map.length) {
            for(i=0; i<document.mf.mapfile.length; i++)
                if (map == document.mf.mapfile.options[i].value) {
                    document.mf.mapfile.selectedIndex = i;
                    break;
                }
            updateMap(map, "myMap1");
        }
        else
            updateMap("google-aa2", "myMap1");

        mapObj = myMap1;

        $("#address").bind("submit", function(e){
            e.preventDefault();
            if(mapObj) mapObj.show_loading_image(true); // show it
            // setup functions to handle geocoding
            var query = {};
            query['FULL'] = $("#address").find("input[@name='address']").val();
            query['XML']  = "1";
            query['FUZZY'] = 'on';
            $.post("/cgi-bin/geo", query, function(xml){
                var code = parseInt($("response", xml).get(0).getAttribute("code"), 10);
                // no results, so show an error
                if (code == 0) {
                    alert("Sorry, that address could not be found.\n" +
                          "Try leaving off the zip, or house number\n" +
                          "Make sure you have a comma after the street.");
                }
                // post result(s) to the div 
                else {
                    $("#geolist").show();
                    $("#geolist").find("a,br").remove();
                    var pois = Array();
                    pois[0] = Array();
                    pois[1] = Array();
                    pois[2] = Array();
                    pois[3] = Array();
                    $("item", xml).each(function(){
                        var name = Array();
                        
                        var gtype = $("type", this).text();
                        if (gtype == 'RANGE') {
                            var lfr = $("lfr", this).text();
                            var lto = $("lto", this).text();
                            var rfr = $("rfr", this).text();
                            var rto = $("rto", this).text();
                            name[name.length] = lfr + '-' + lto + ':' + rfr + '-' + rto;
                            name[name.length] = $("stdaddr",   this).text();
                            name[name.length] = $("place",     this).text();
                            name[name.length] = $("state",     this).text();
                            name[name.length] = $("zip",       this).text();
                        } else if (gtype == 'ADDRESS' || gtype == 'CLOSEST') {
                            name[name.length] = $("stdaddr",   this).text();
                            name[name.length] = $("place",     this).text();
                            name[name.length] = $("state",     this).text();
                            name[name.length] = $("zip",       this).text();
                        } else if (gtype == 'PLACE') {
                            name[name.length] = $("place",     this).text();
                            name[name.length] = $("state",     this).text();
                        } else if (gtype == 'ZIP') {
                            name[name.length] = $("place",     this).text();
                            name[name.length] = $("state",     this).text();
                            name[name.length] = $("zip",       this).text();
                        }
                        var lat   = $("latitude",  this).text();
                        var lon   = $("longitude", this).text();
                        var container = $("#geolist");
                        container
                            .append("<a href='#" + lat + "," + lon + "'>" + 
                                    name.join(', ') + "</a><br />");
                        $("a:last", container)
                            .click(function(e){
                                e.preventDefault();
                                var href = $(this).get(0).getAttribute("href");
                                var loc = href.substring(href.indexOf("#",0)+1,href.length-1).split(",");
                                var myMap = eval("myMap1");
                                myMap.reCenter(parseFloat(loc[1]), parseFloat(loc[0]), dxy);
                                myMap.redraw();
                                //myMap.dump("errormsg");
                            });
                        pois[0].push( lon );
                        pois[1].push( lat );
                        pois[2].push( [''] );
                        pois[3].push( [name.join(', ')] );
                    });
                    geopois = pois;
                    update_pois();
                }
                // got a single result, so reposition map
                if (code == 1) {
                    var href = $("#geolist").find("a").get(0).getAttribute("href");
                    var loc = href.substring(href.indexOf("#",0)+1,href.length-1).split(",");
                    var myMap = eval("myMap1");
                    myMap.reCenter(parseFloat(loc[1]), parseFloat(loc[0]), dxy);
                    myMap.redraw();
                    //myMap.dump("errormsg");
                }
            });
            if(mapObj) mapObj.show_loading_image(false); // show it
            //return false;
        });
        
        var schema = {
            country:  {property: ['NAME']},
            states:   {property: ['NAME']},
            county:   {property: ['NAME', 'SSCCC']},
            cousub:   {property: ['NAME', 'FIPS']},
            place:    {property: ['NAME', 'FIPS']},
            landmark: {property: ['NAME', 'CFCC', 'LAND', 'DISTANCE_TO_POINT']},
            water:    {property: ['NAME', 'CFCC', 'LAND', 'DISTANCE_TO_POINT']},
            landpt:   {property: ['NAME', 'CFCC', 'LAND', 'DISTANCE_TO_POINT']},
            streets:  {property: ['TLID', 'NAME', 'CFCC', 'FRADDL', 'TOADDL',
                                  'FRADDR', 'TOADDR', 'ZIPL', 'ZIPR', 'RTE_NUM',
                                  'DISTANCE_TO_POINT'],
                       streetAddress: ['interpolated'],
                       crossStreets:  ['A', 'B']},
            highways: {property: ['TLID', 'NAME', 'CFCC', 'FRADDL', 'TOADDL',
                                  'FRADDR', 'TOADDR', 'ZIPL', 'ZIPR', 'RTE_NUM',
                                  'DISTANCE_TO_POINT'],
                       streetAddress: ['interpolated'],
                       crossStreets:  ['A', 'B']},
            z5ta:     {property: ['NAME']},
            timezone: {property: ['TIMEZONE', 'GMT_DST_OF', 'GMT_OFFSET']},
            nws_zones:{property: ['NAME', 'STATE_ZONE', 'CWA', 'TIME_ZONE',
                                  'FE_AREA']}
        };

        //$("#errormsg").show().append("<pre>" + dumpObj(schema, "schema", "", 0) + "</pre>");
            
        $("#map_tag").bind('dblclick', function (e) {
            var loc = mapObj.getLocation();
            var query = {};
            query['x'] = loc[0];
            query['y'] = loc[1];
            rgeopoi = Array();
            rgeopoi[0] = Array();
            rgeopoi[1] = Array();
            rgeopoi[2] = Array();
            rgeopoi[3] = Array();
            rgeopoi[0].push(loc[0]);
            rgeopoi[1].push(loc[1]);
            rgeopoi[2].push(['lat','lon']);
            rgeopoi[3].push([''+loc[1],''+loc[0]]);
            $("#showxml").attr({href: "/rgeo/?x="+loc[0]+"&y="+loc[1]});
            $.post("/rgeo/", query, function(xml) {
                $("#rgeo").show();
                $("#rgeo2").hide();
                rgeoToggle = false;
                $("#rgeoxml").each(function(){
                    if (xml.xml == undefined) {
                        var XS = new XMLSerializer();
                        this.value = XS.serializeToString(xml);
                    } else {
                        this.value = xml.xml;
                    }
                });
    if (browser.isIE) {
        alert("If this is fixed you should get another alert");
        alert($("feature[@typename]", xml).text());
    }
                var str = '<p>Here is the processed Reverse Geocoder results for the double click location. <span class="click" onclick=toggle()>Toggle</span></p>'; 
                //if(0)
                for (var feature in schema) {
                    if (feature == "objRef") continue;
                    var description = $("feature[@typeName='"+feature+"']/description", xml).text();
                    if (description.length == 0) continue;
                    str += "<h2>"+description+"</h2>\n";
                    str += "<table border=\"1\" cellspacing=\"0\">\n";
                    for (var prop in schema[feature]) {
                        if (prop == "objRef") continue;
                        var arr = schema[feature][prop];
                        for (var i=0; i<arr.length; i++) {
                            var pname = '';
                            var pvalue = '';
                            if (prop == 'property') {
                                pname = arr[i];
                                pvalue = $("feature[@typeName='"+feature+"']/property[@typeName='"+pname+"']", xml).text();
                            } else {
                                pname = prop;
                                pvalue = $("feature[@typeName='"+feature+"']/"+prop+"[@typeName='"+arr[i]+"']", xml).text();
                            }
                            str += "<tr><td class=\"xml\" align=\"right\">" + pname + "</td><td class=\"xml\">" + pvalue.replace(/^\s+|\s+$/g, '') + "</td></tr>\n";
                        }
                    }
                    str += "</table>\n";
                }
                $("#rgeo2").html(str);
            });
            update_pois();
        });

    });

    function toggle() {
        if (rgeoToggle) {
            $("#rgeo2").hide();
            $("#rgeo").show();
        } else {
            $("#rgeo").hide();
            $("#rgeo2").show();
        }
        rgeoToggle = ! rgeoToggle;
        return false;
    }

    function hidehelp() {
        $("#help").hide();
        if (browser.isIE)
            $("#options").show();
        $("#mapstyle").show();
        return false;
    }
        
    function showhelp() {
        $("#mapstyle").hide();
        $("#help").show();
        if (browser.isIE)
            $("#options").hide();
        return false;
    }

    function doprint() {
        $("#rgeo").hide();
        $("#rgeo2").show();
        $("#help").show();
        window.print();
        /*
        $("#help").hide();
        if (!rgeoToggle) {
            $("#rgeo2").hide();
            $("#rgeo").show();
        }
        */
        return false;
    }
