var map, cluster, eventListeners=[], markersArray=[], icon, respfile, sgamarker;
var markerGroups = { "Square": [], "Circle": [], "Cross": [], "Triangle": [], "Star": []};
var maxShow = 10; 
var tilePrediction, lyrPrediction, mapPrediction;

function myOnLoad() {
    if (GBrowserIsCompatible()) {
        map=new GMap2(document.getElementById('map'));
        //map.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);
        
        map.setCenter(new GLatLng(-25.734,134.489),4);
        map.savePosition();        
        map.addControl(new GMapTypeControl()  ); // , new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7))
        map.addControl(new GLargeMapControl()  ); // , new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 28))

		initMapLoading();
		showMapLoading();
		
		initLegend();
        
        
        //	add an HtmlControl containing a couple of form elements
        //var html='<div id="divopt"><div class="htmlControl" style="padding:0px 3px 3px 3px">Enable clustering: <input type="checkbox" checked="checked" onclick="toggleClustering()" /></div></div>';
        //var control=new HtmlControl(html);
        //map.addControl(control, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,32)));
        
        function myClusterClick(args) {
            cluster.defaultClickAction=function(){
                map.setCenter(args.clusterMarker.getLatLng(), map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds))
                delete cluster.defaultClickAction;
            }
            var html='<div><h4>'+args.clusteredMarkers.length+' Locations:</h4>'; 
            var iwi = 0; 
            var countCurr = 0; 
            for (i=0; i<args.clusteredMarkers.length; i++) {
                if (countCurr == maxShow) {
                    if (iwi==1) {
                        html+='<br /><a href="javascript:toggleList('+iwi+','+(iwi+1)+')">next</a>';
                    } else {
                        html+='<br /><a href="javascript:toggleList('+iwi+','+(iwi-1)+')">prev</a> | <a href="javascript:toggleList('+iwi+','+(iwi+1)+')">next</a>';
                    }
                    html+='</div>'; 
                    countCurr = 0; 
                }
                if (countCurr == 0) {
                    iwi++
                    if (iwi==1) {
                        html+='<div id="iw_' + iwi + '" class="show">'; 
                    } else {
                        html+='<div id="iw_' + iwi + '" class="hide">'; 
                    }
                }
                html+='<a href="javascript:cluster.triggerClick('+args.clusteredMarkers[i].index+')">'+args.clusteredMarkers[i].getTitle()+'</a><br />';
                countCurr++; 
            }
            html+='<br /><a href="javascript:toggleList('+iwi+','+(iwi-1)+')">prev</a>';
            html+='</div>'; 
    
            html+='<br /><a href="javascript:void(0)" onclick="cluster.defaultClickAction()">Zoom</a> in to show these locations</div>';
            args.clusterMarker.openInfoWindowHtml(html);
        }

        //	create a ClusterMarker
        cluster=new ClusterMarker(map, {clusterMarkerTitle:'Click to see info about %count locations' , clusterMarkerClick:myClusterClick });

        //        icon=new GIcon();
        //        icon.shadow='images/gmt/shadow50.png';
        //        icon.shadowSize=new GSize(37, 34);
        //        icon.iconSize=new GSize(20, 34);
        //        icon.iconAnchor=new GPoint(10, 30);
        //        icon.infoWindowAnchor=new GPoint(10, 8);
        icon=new GIcon();
        icon.iconSize=new GSize(16, 16);
        icon.iconAnchor=new GPoint(8, 8);
        icon.infoWindowAnchor=new GPoint(8, 1);

        loadMapData();

		hideMapLoading(); 

        //GEvent.addListener(map, "moveend", function() {refreshMarkers();});
    }
}

var nscontrol;
function loadSGA(sid) {
    //loadPrediction("New Sites", "addedSiteLayer", sid);
    
    var nsdisplay = '<div class="htmlControl" style="padding:0px 3px 3px 3px; text-align:left">';
    nsdisplay += '<div id="nsdisplay">New site: ' + nslo + ', ' + nsla + '</div>'; 
    nsdisplay += '<input type="button" name="rerunsga" id="rerunsga" value="Generate new site" onclick="nsaction=\'addsite\';doSubmit(glastform,gwiz)" />'; 
    nsdisplay += '<br /> <br />'; 
    nsdisplay += '<input type="button" name="downloadns" id="downloadns" value="Download new sites" onclick="downloadNewSites()" />'; 
    nsdisplay += '<br /> <br />';
    nsdisplay += '<img src="images/legend_sga.png" />';
    nsdisplay += '</div>'; 
    //nsdisplay += '<input type="button" name="deletens" id="deletens" value="Delete site and regenerate" onclick="nsaction=\'delsite\';doSubmit(glastform,gwiz)" />'; 
    
    if (sgamarker) map.removeOverlay(sgamarker);
    sgamarker = new GMarker(new GLatLng(nsla, nslo), {draggable: true});
    GEvent.addListener(sgamarker, "dragend", function() {
        nsla = sgamarker.getLatLng().lat();
        nslo = sgamarker.getLatLng().lng();
    });    
    map.addOverlay(sgamarker);
    
    nscontrol = new HtmlControl(nsdisplay);
    map.addControl(nscontrol, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,72)));
    
    
}

var mecontrol;
function loadMaxent(sid) {
    var medisplay = '<div class="htmlControl" style="padding:0px 3px 3px 3px; text-align:left; font-size: 14px">';
    medisplay += 'Maxent results: <a target="_blank" href="output/maxent/' + sid + '/species.html">Overview</a>';
    medisplay += '<br /> <br />';
    medisplay += '<img src="images/legend_maxent.png" />';
    medisplay += '</div>';

    mecontrol = new HtmlControl(medisplay);
    map.addControl(mecontrol, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,72)));
}

function loadPrediction(name, layerid, sid) {
    if (mapPrediction != null) map.removeMapType(mapPrediction);
    // Create tile layers
    tilePrediction = new GTileLayer(new GCopyrightCollection(""), 1, 17);
    tilePrediction.myLayers = layerid;
    tilePrediction.myFormat = 'image/png';
	tilePrediction.myBaseURL = 'http://www.biomaps.net.au/biomaps.asp?sessionid='+sid+'&'; 
    //tilePrediction.myBaseURL = 'http://t1.maps.biomaps.net.au/biomaps.asp?sessionid='+sid+'&'; 
    //tilePrediction.myBaseURL = 'http://localhost/cgi-bin/mapserv.exe?map=c:/projects/mapfiles/biomaps2group.map&'+sid+'&'; //'http://t1.maps.biomaps.net.au/biomaps.asp?sessionid='+sid+'&'; 
    tilePrediction.getTileUrl = CustomGetTileUrl;
    tilePrediction.getOpacity = function() {return 0.9;}
    
    lyrPrediction = [G_NORMAL_MAP.getTileLayers()[0],tilePrediction];
    mapPrediction = new GMapType(lyrPrediction, G_SATELLITE_MAP.getProjection(), name, G_SATELLITE_MAP);
    map.addMapType(mapPrediction);
    map.setMapType(mapPrediction);
}

var mlcontrol;
function initLegend() {
    var mldisplay = '<div class="htmlControl" style="padding:0px 3px 3px 3px; text-align:left; font-size: 14px;">';
    mldisplay += 'BioClim/Domain legend <br /> <img src="images/legend_bioclim_domain.png" />';
    mldisplay += '</div>';
    mlcontrol = new HtmlControl(mldisplay);
}
function showLegend() {
    map.addControl(mlcontrol, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,72)));
}
function hideLegend() {
    map.removeControl(mlcontrol);
}

var mplcontrol;
function initMapLoading() {
    var mpldisplay = '<div class="htmlControl" style="padding:10px; text-align:left;font-size: 12px;">';
    mpldisplay += '<div class="loading-indicator" style="font-size: 18px; color: red; letter-spacing: 2px; font-weight: bold"><img src="images/default/grid/loading.gif" style="width:16px;height:16px;" align="absmiddle">&#160;Loading...</div>';
    mpldisplay += '</div>';
    mplcontrol = new HtmlControl(mpldisplay);
}
function showMapLoading() {
    map.addControl(mplcontrol, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(500,100)));
}
function hideMapLoading() {
    map.removeControl(mplcontrol);
}

function hideLegendControls() {
	map.removeControl(nscontrol); 
	map.removeControl(mecontrol);
	map.removeControl(mlcontrol);
}

function newMarker(markerLocation, title, markerIcon, details, cn, ic) {
    var marker=new GMarker(markerLocation, {title:title, icon:markerIcon});
    eventListeners.push(GEvent.addListener(marker, 'click', function() {
        //marker.openInfoWindowHtml('<p>'+details+'</p>');
        //marker.openInfoWindowHtml('<iframe src="sinfo.jsp?lat='+markerLocation.lat()+'&lon='+markerLocation.lng()+'" frameborder="0" scrolling="yes" width="650px" height="250px"></iframe>');
        if (location.href.indexOf("mapam.jsp") > -1) {
            marker.openInfoWindowHtml('<iframe src="sinfo.jsp?cn='+cn+'&ic='+ic+'" frameborder="0" scrolling="yes" width="500px" height="300px"></iframe>');
        } else {
            marker.openInfoWindowHtml('<iframe src="sinfo.jsp?lat='+markerLocation.lat()+'&lon='+markerLocation.lng()+'" frameborder="0" scrolling="yes" width="500px" height="300px"></iframe>');
        }
    }));
    return marker;
}

function toggleClustering() {
    cluster.clusteringEnabled=!cluster.clusteringEnabled;
    cluster.refresh(true);
}

function toggleList(c,n) {
    if (n==0) return; 
    $('iw_'+n).className = 'show';
    $('iw_'+c).className = 'hide';
}

function loadMapData(){
    var initialLoad = true; 
    processIt=function(file, code){
        respfile = file;
        if(code===200){
            markersArray=[];
            for(i=eventListeners.length-1; i>=0; i--){
                GEvent.removeListener(eventListeners[i]);
            }
            eventListeners=[];
            //eval(file);
            eval("tjs = " + file); 
            var json = tjs.slresults; 
            var marker, newIcon, j=1, title, details;
            for (var i=0; i<json.length; i++) {
                //newIcon=new GIcon(icon, 'images/icon_'+j+'.png');
                title='id: '+i+', ('+json[i].x+', '+json[i].y+')';
                newIcon=new GIcon(icon, 'images/maptools/'+json[i].t+'.gif');
                //title=json[i].s+' ('+json[i].n+')';
				title=json[i].s+' ('+json[i].i+')';
                details = "species: " + json[i].s;
                details += "<br />common name: " + json[i].n;
                details += "<br />institution: " + json[i].c;
                details += "<br />catalog number: " + json[i].i;
                marker=newMarker(new GLatLng(json[i].x, json[i].y), title, newIcon, details, json[i].i, json[i].c);
                //markersArray.push(marker);
                var mtype = json[i].t;
                markerGroups[mtype].push(marker); 
                
                j++;
                if (j>26) {
                    j=1;
                }
            }
            cluster.removeMarkers();
            //	add an HtmlControl containing a couple of form elements
            var infohtml='<div class="htmlControl" style="padding:0px 3px 3px 3px; text-align:left"><input type="checkbox" checked="checked" onclick="toggleClustering()" /> Enable clustering';
            
            //cluster.addMarkers(markersArray);
            if (markerGroups["Square"].length > 0) {
                if ($('chkSquare') == null || ($('chkSquare') != null && $('chkSquare').checked)) {
                    cluster.addMarkers(markerGroups["Square"]);
                }
                //infohtml += '<br /><input id="chkSquare" type="checkbox" checked="checked" onclick="toggleGroup(\'Square\')" /> Square';
            }
            if (markerGroups["Circle"].length > 0) {
                if ($('chkCircle') == null || ($('chkCircle') != null && $('chkCircle').checked)) {
                    cluster.addMarkers(markerGroups["Circle"]);
                }
                //infohtml += '<br /><input id="chkCircle" type="checkbox" checked="checked" onclick="toggleGroup(\'Circle\')" /> Circle';
            }
            if (markerGroups["Cross"].length > 0) {
                if ($('chkCross') == null || ($('chkCross') != null && $('chkCross').checked)) {
                    cluster.addMarkers(markerGroups["Cross"]);
                }
                //infohtml += '<br /><input id="chkCross" type="checkbox" checked="checked" onclick="toggleGroup(\'Cross\')" /> Cross';
            }
            if (markerGroups["Triangle"].length > 0) {
                if ($('chkTriangle') == null || ($('chkTriangle') != null && $('chkTriangle').checked)) {
                    cluster.addMarkers(markerGroups["Triangle"]);
                }
                //infohtml += '<br /><input id="chkTriangle" type="checkbox" checked="checked" onclick="toggleGroup(\'Triangle\')" /> Triangle';
            }
            if (markerGroups["Star"].length > 0) {
                if ($('chkStar') == null || ($('chkStar') != null && $('chkStar').checked)) {
                    cluster.addMarkers(markerGroups["Star"]);
                }
                //infohtml += '<br /><input id="chkStar" type="checkbox" checked="checked" onclick="toggleGroup(\'Star\')" /> Star';
            }
            if (initialLoad) {
                var control=new HtmlControl(infohtml);
                map.addControl(control, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,32)));
            }
            cluster.fitMapToMarkers();
            map.savePosition();
            //document.title='ClusterMarker: Demo Map '+json.length+' markers';
            json=[];
        } else {
            GLog.write('Marker data retrieval failed. Error code: '+code);
        }
        initialLoad = false; 
    };
    //var url="getdata.jsp";
    if (sessionid != "null") {
        var url="GetData?sid=" + sessionid; 
        GDownloadUrl(url, processIt);
    } else if (location.href.indexOf("mapam.jsp") > -1 || location.href.indexOf("mapam2.jsp") > -1) {
        var url="GetData?dest=ext"; 


        // Build an empty URL structure in which we will store
        // the individual query values by key.
        var objURL = new Object();
 
 
        // Use the String::replace method to iterate over each
        // name-value pair in the query string. Location.search
        // gives us the query string (if it exists).
        window.location.search.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
 
        // For each matched query string pair, add that
        // pair to the URL struct using the pre-equals
        // value as the key.
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
        }
    );

        // Loop over the URL values that we collected.
        for (var strKey in objURL){
                            
            if (strKey == "cqn") {
                url += "&cqn=" + objURL[ strKey ]; 
            } else if (strKey == "cql") {
                url += "&cql=" + objURL[ strKey ]; 
            } else if (strKey == "csy") {
                url += "&csy=" + objURL[ strKey ]; 
            } 
        }

        GDownloadUrl(url, processIt);
		loadBiomapsPowered(); 
    } else {
        map.setCenter(new GLatLng(-25.734,134.489),4);
        map.savePosition();
    }

}

function toggleGroup(type) {
    cluster.removeMarkers();
    processIt(respfile, 200); 
    /*
    var status = $('chk' + type).checked; 
    for (var i = 0; i < markerGroups[type].length; i++) {
    var marker = markerGroups[type][i];
    
    if (status) { // marker.isHidden()
    marker.show();
    } else {
    marker.hide();
    }
    }
     */
}

function refreshMarkers() {
    if (markerGroups["Square"].length > 0) {
        toggleGroup("Square");
    }
    if (markerGroups["Circle"].length > 0) {
        toggleGroup("Circle");
    }
    if (markerGroups["Cross"].length > 0) {
        toggleGroup("Cross");
    }
    if (markerGroups["Triangle"].length > 0) {
        toggleGroup("Triangle");
    }
    if (markerGroups["Star"].length > 0) {
        toggleGroup("Star");
    }
    
}


