/**
 * @author florian
 */

$(document).observe('dom:loaded', function(event) {

    Element.fire( document, 'app:resize');

    var host = "http://carto.aprona.net"
    var mapfile = "/data/html/a/aprona/svn/carto/mapserver/aprona.map"
    //var mapurl = host+"/cgi-bin/mapserv?map="+mapfile+"&"
    window.map = new OpenLayers.Map( 'map', {
        controls: [
            new OpenLayers.Control.CustomNavToolbar({id: 'navtoolbar', div: OpenLayers.Util.getElement('h-toolbar') })
            ,new OpenLayers.Control.ScaleLine()
            ,new OpenLayers.Control.Scale()
            ,new OpenLayers.Control.MousePosition()
            ,new OpenLayers.Control.OverviewMap()
            ,new OpenLayers.Control.KeyboardDefaults()
        ],
        numZoomLevels: 7
    });
    
    map.addLayer( new OpenLayers.Layer.WMS(
            'Alsace',
        host+"/cgi-bin/tilecache.cgi?",
            {
                layers: 'aprona2',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'alsace',
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                current_query: false,
                controllable: false,
                projection:'EPSG:27572',
                /*maxResolution: 299.47916666666669,*/
                maxResolution: 449.21875,
                isBaseLayer: true,
                opacity: 0.5,
                units: 'm'
            }
    ));
    map.addLayer( new OpenLayers.Layer.WMS( 
            'Profondeur nappe', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'profondeur',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'profondeur',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                transparent: true,
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Profondeur nappe ME', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'profondeur2',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'profondeur2',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                transparent: true,
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Alluvions', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'alluvions',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'alluvions',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                transparent: true,
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'R&eacute;seau Pi&eacute;zo Internet', 
                host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'piezo',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'piezo',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                transparent: true,
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Nitrate', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'nitrate',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'nitrate',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Chlorures', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'chlorure',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'chlorure',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Solvants Chlor&eacute;s', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'solvant_chlore',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'solvant_chlore',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Produits phytosanitaires', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'phytosanitaire',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'phytosanitaire',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));

    map.addLayer( new OpenLayers.Layer.WMS( 
            'Reseau Qualit&eacute;', 
            host+'/cgi-bin/mapserv?map='+mapfile+'&', 
            {
                layers: 'qualite',
                srs: 'EPSG:27572',
                format: 'image/png'
            }, {
                name: 'qualite',
                current_query: false,
                controllable: true,
                gutter: 5,
                maxExtent: new OpenLayers.Bounds(930000, 2270000, 1050000,2500000 ),
                maxResolution: 299.47916666666669,
                projection:'EPSG:27572',
                units: 'm',
                isBaseLayer: false,
                opacity: 0.5
            }
    ));
    
    map.setCenter(new OpenLayers.LonLat(970000, 2370000), 0);
    
    map.addControl(new OpenLayers.Control.CustomLayerSwitcher());
    
    map.addControl(new OpenLayers.Control.CustomQueryLayerSwitcher({
        id: 'query-layer-switcher'
    }));

    map.getControl('query-layer-box').panel_div.observe('queryLayerBox:deactivate', function (e) {
        $('infoBulle').hide();
    });
    
    map.events.register('move', map, function (e) {
        $('infoBulle').hide();
    });

    map.events.register('click', map, function (e) {
        var layer =  map.getControl('query-layer-switcher').getCurrentQueryLayer();
        if(layer && layer.getVisibility()) {
            var url = layer.getFullRequestString({
                REQUEST: 'GetFeatureInfo',
                EXCEPTIONS: 'application/vnd.ogc.se_xml',
                BBOX: map.getExtent().toBBOX(),
                X: e.xy.x,
                Y: e.xy.y,
                INFO_FORMAT: 'text/html',
                QUERY_LAYERS: layer.params.LAYERS,
                WIDTH: map.size.w,
                HEIGHT: map.size.h,
                VERSION: '1.3.0'
            });
            $(document.body).setStyle({cursor: 'wait'});
            OpenLayers.Request.issue({
                url: url
                ,scope: this
                ,success: function(ajax) {
                    $(document.body).setStyle({cursor:'auto'});
                    if( ! ajax.responseText) {
                            $('infoBulle').hide();
                            return;
                    }
                    $('infoBulleContent').update(ajax.responseText);
                    handleInfoBulleContent($('infoBulleContent'));
                    $('infoBulle').setStyle({
                        left: e.xy.x - 35 +'px',
                        top: e.xy.y + 90 +'px'
                    }).show();
                }
                ,failure: function() {
                    $(document.body).setStyle({cursor:'auto'}); 
                }
            });
        }
        OpenLayers.Event.stop(e);
    });

    // GESTION VILLE
    new Ajax.Autocompleter('ville-autocomplete', 'ville-autocomplete-div', 'communes.php', {
        afterUpdateElement: function(input, element) {
            json = decodeURIComponent(element.readAttribute('rel')).evalJSON();
            map.setCenter(new OpenLayers.LonLat(json.x,json.y), 5);
        }
    });
    Event.observe('set-center-form', 'submit', function(event) {
        event.stop();
    });
    
    new Draggable('global-layer-legend', {
        handle: 'move'
    });
    
    $('global-layer-legend-reduce').observe('click', function(event) {
        $('global-layer-legend-content').toggle();
    });
    
    $('global-layer-legend-close').observe('click', function(event) {
        $('global-layer-legend').hide();
    });
});

function handleInfoBulleContent(contentDiv) {
    contentDiv.select('.unescape').each(function(el) {
        el.update(unescape(el.firstChild.nodeValue.replace(/\+/g, ' ')));
    });
    contentDiv.select('.date').each(function(el) {
        if(el.firstChild) {
           var dt = [ el.firstChild.nodeValue.substring(6, 8), el.firstChild.nodeValue.substring(4, 6), el.firstChild.nodeValue.substring(0, 4) ].join('/');
           el.update(dt); //new Date(dt).toLocaleDateString());
        }
    });
    contentDiv.select('.float').each(function(el) {
        if(el.firstChild) {
            el.update(new Number(el.firstChild.nodeValue).toFixed(2));
        }
    });
    contentDiv.select('.replace_htmlentities').each(function(el) {
        if(el.firstChild) {
            el.update(el.firstChild.nodeValue.replace(/&micro;/g, 'µ').replace(/&eacute;/g, 'é').replace(/&egrave;/g, 'è'));
        }
    });
}

Event.observe(document.onresize ? document : window, 'resize', function(event) {
    Element.fire( document, 'app:resize');
});

Event.observe( document, 'app:resize', function(event) {
    $('infoBulle').hide();
    var w = 0, h = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        w = window.innerWidth;
        h = window.innerHeight;
        //FireFox
        if (document.body && document.body.offsetWidth)
            w=document.body.offsetWidth;
    } else if( document.documentElement &&
            ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    // attention a changer ces tailles si on touche au css
    // les tailles sont mis en dur pour eviter tout probleme de compatibilitÃ© de navigateur
    if (w<950) w=950;
    //bug id mantis 001389 en 100x768 on ne veut plus d'ascenseur
    //if (h<630) h=630;
    if (h<600) h=600;
    if (h!=0 && w!=0) {
        var mh=(h - 110)+'px';
        var mih=(h - 70)+'px';
        var mw=(w - 335)+'px';
        var il=(w - 305)+'px';
        var tw=(w - 10)+'px';
        var tbw=(w - 315)+'px';
        document.getElementById('zone_titre').style.width = tw;
        document.getElementById('zone_edito').style.width = tbw;
        document.getElementById('zone_principale').style.height = mh;
        document.getElementById('zone_principale').style.width = mw;
        //document.getElementById('zone_ihm').style.height = mih;
        document.getElementById('zone_ihm').style.left = il;
        document.getElementById('global-layer-legend').style.right = il;
    }
});


