var lintMarkerCount = 0;
var lstrMarkerCounts = 'and <strong>[count]</strong> can be found in the current map view';
var lintMaxX = 0;
var lintMaxY = 0;
var viewportMarkerCount = 0;

function getURLVar(urlVarName) {
    //divide the URL in half at the '?'
    var urlHalves = String(document.location).split('?');
    var urlVarValue = '';
    if(urlHalves[1]){
        //load all the name/value pairs into an array
        var urlVars = urlHalves[1].split('&');
        //loop over the list, and find the specified url variable
        for(i=0; i<=(urlVars.length); i++){
            if(urlVars[i]){
                //load the name/value pair into an array
                var urlVarPair = urlVars[i].split('=');
                if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
                    //I found a variable that matches, load it's value into the return variable
                    urlVarValue = urlVarPair[1];
                }
            }
        }
    }
    return urlVarValue;   
}

function getMarkerIcon() {
    icon = new GIcon();
    icon.image = "images/wba_marker.png";
    icon.iconSize = new GSize(38, 42);
    icon.iconAnchor = new GPoint(19, 42);
    icon.infoWindowAnchor = new GPoint(19, 21);
    return icon;
}

function getClusterIcon() {
    // map is 539 x 400 we have lintMaxX and lintMaxY to tell us the grid size
    // so calculate the size of the marker:
    //alert(lintMaxX+' '+lintMaxY);
    if(lintMaxX==0) {
        lintMaxX=10;
    }
    if(lintMaxY==0) {
        lintMaxY=10;
    }
    var gridWidth = Math.ceil(539/lintMaxX);
    var gridHeight = Math.ceil(400/lintMaxY);
    
    zoomIcon = new GIcon();
    //zoomIcon.image = "images/cluster_marker.png";
    zoomIcon.image = "images/marker.png";
    //zoomIcon.iconSize = new GSize(51,51);
    zoomIcon.iconSize = new GSize(gridWidth,gridHeight);
    zoomIcon.iconAnchor = new GPoint(0,0);
    zoomIcon.infoWindowAnchor = new GPoint(0,0);
    return zoomIcon;
}

function getBadGeoIcon() {
    zoomIcon = new GIcon();
    zoomIcon.image = "images/cluster_marker.png";
    zoomIcon.iconSize = new GSize(100,100);
    zoomIcon.iconAnchor = new GPoint(50, 50);
    zoomIcon.infoWindowAnchor = new GPoint(50, 50);
    return zoomIcon;
}

function createClusterPoly(point,zoomTo) {


    var bounds = myGoogleMap.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    
    polyWidth = (northEast.lng() - southWest.lng())/10;
    polyHeight = (northEast.lat() - southWest.lat())/10;
    //alert(polyHeight);
    
    TRLon = point.lng() + polyWidth;
    BRLon = point.lng() + polyWidth;
    BRLat = point.lat() - polyHeight;
    BLLat = point.lat() - polyHeight;
    
    lat = point.lat();
    lon = point.lng();
    
    poly = new GPolygon([
        new GLatLng(lat,lon),
        new GLatLng(lat,TRLon),
        new GLatLng(BRLat,BRLon),
        new GLatLng(BLLat,lon)
        ],'#ffffff',1,0.4,'#035e97',0.3);
        
        
    GEvent.addListener(poly,"click",function() {
        //rather than zooming in here, we're going to do a proximity search
        //around the marker's location
        myGoogleMap.setCenter(point,zoomTo);
        /*
        if (zoomTo<7) {
        //if (viewportMarkerCount>200) {
            myGoogleMap.setCenter(point,zoomTo);
            //myGoogleMap.zoomIn();
        } else {
            //window.location='search_results.php?local=1&lat='+point.lat()+'&lon='+point.lng()+'&z='+zoomTo;
            window.location='search_results.php?vp=1&ne='+northEast.toUrlValue()+'&sw='+southWest.toUrlValue()+'&z='+zoomTo;
        }
        */
        
    });
    
    return poly;
}

function createClusterMarker(point,icon,zoomTo) {
    var marker = new GMarker(point,icon);
    GEvent.addListener(marker,"click",function() {
        //rather than zooming in here, we're going to do a proximity search
        //around the marker's location
        if (zoomTo<7) {
            myGoogleMap.zoomIn();
        } else {
            window.location='search_results.php?local=1&lat='+point.lat()+'&lon='+point.lng()+'&z='+zoomTo;
        }
        
    });
    return marker;
}

function createClickableMarker(point,icon,site_id,site_name,op_name) {
    var strTitle = site_name + ' - ' + op_name; 
    var markerOptions = {icon: icon, title: strTitle};
    var marker = new GMarker(point,markerOptions);
    GEvent.addListener(marker,"click",function() {
        document.location.href='site_info.php?site_id=' + site_id;
    });
    return marker;
}

function createViewportMarker(point,type,site_id,site_name,op_name) {
    switch(type) {
        case 'c':
            lintCurrentZoom = myGoogleMap.getZoom();
            //var markerTmp = createClusterMarker(point,getClusterIcon(),(lintCurrentZoom + 1));
            var markerTmp = createClusterPoly(point,(lintCurrentZoom+1));
            break;
        case 'g':
            lintCurrentZoom = myGoogleMap.getZoom();
            var markerTmp = createClusterMarker(point,getBadGeoIcon(),(lintCurrentZoom + 1));
            break;
        default:
            var markerTmp = createClickableMarker(point,getMarkerIcon(),site_id,site_name,op_name);
    }
    return markerTmp;
}

function getViewportClusterMarkers() {
    var logRef = getURLVar('logRef');
    var cuid = getURLVar('cuid');
    var bounds = myGoogleMap.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&z=' + myGoogleMap.getZoom();
    //alert(getVars);
    if (logRef!='') {
        getVars += '&logRef';
    }
    
    //retrieve the points
    var request = GXmlHttp.create();
    request.open('GET', 'getViewportLocations.php?'+getVars, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var jscript = request.responseText;
            var points;
            //alert(jscript);
            eval(jscript);
            
            viewportMarkerCount = siteCount;
            
            
            //create each point from the list
            for (i in points) {
                var point = new GLatLng(points[i].lat,points[i].lon);
                var marker = createViewportMarker(point,points[i].type,points[i].uid,points[i].siteName,points[i].operatorName);
                myGoogleMap.addOverlay(marker);
            }
            
            //now update the xxx hotspots text with siteCount var from AJAX:
            var lstrCounts = lstrMarkerCounts.replace('[count]',siteCount);
            var filename = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
            //alert("File: ["+filename+"]");
            if(filename!='site_info.php' && filename!='index.php' && filename!='') {
                document.getElementById('mapCounts').innerHTML=lstrCounts;
            }
            if (viewportMarkerCount>0 && viewportMarkerCount<=100 && cuid!='') {
                //alert("getting results");
                getViewportResults();
            }
        }
    }
    request.send(null);
}

function getViewportResults() {
    var bounds = myGoogleMap.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&z=' + myGoogleMap.getZoom();
    
    var request = GXmlHttp.create();
    request.open('GET','/ajax/getViewportResults.php?'+getVars,true);
    request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var resultsTable = request.responseText;
                //alert(resultsTable);
                document.getElementById('ajaxResults').innerHTML = resultsTable;
            }
    }
    request.send(null);
}

function createDetailMarker(point,icon,site_id, site_name, operator) {
    if (operator==6) {
        var markerOptions = {icon: icon, title: site_name, ZIndexProcess:order_bt};
    } else {
        var markerOptions = {icon: icon, title: site_name, ZIndexProcess:order_partner};
    }
    var marker = new GMarker(point,markerOptions);
        
    GEvent.addListener(marker,"click",function() {
        document.location.href='details.php?site_id=' + site_id;
    });
    return marker;
}

function setupLocalMap() {
    
    moveEndEvent = GEvent.addListener(myGoogleMap,"moveend", function() {
        myGoogleMap.clearOverlays();
        var newCenter = myGoogleMap.getCenter();
        lat = newCenter.lat();
        lon = newCenter.lng();
        zoom = myGoogleMap.getZoom();
        
        document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
        getViewportClusterMarkers();
    });
    
    var newCenter = myGoogleMap.getCenter();
    lat = newCenter.lat();
    lon = newCenter.lng();
    
    document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
    zoom = myGoogleMap.getZoom();
    getViewportClusterMarkers();
}

function setupDetailMap() {
    moveEndEvent = GEvent.addListener(myGoogleMap,"moveend", function() {
        var newCenter = myGoogleMap.getCenter();
        lat = newCenter.lat();
        lon = newCenter.lng();
        
        document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
        //getViewportClusterMarkers();
    });
    
    var newCenter = myGoogleMap.getCenter();
    lat = newCenter.lat();
    lon = newCenter.lng();
    
    document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
    getViewportClusterMarkers();
}

function setupSearchMap() {
    moveEndEvent = GEvent.addListener(myGoogleMap,"moveend", function() {
        zoom = myGoogleMap.getZoom();
        
        bounds = myGoogleMap.getBounds();
        southWest = bounds.getSouthWest();
        northEast = bounds.getNorthEast();
        lonSpan = northEast.lng() - southWest.lng();
        latSpan = northEast.lat() - southWest.lat();
        
        var mapCenter = myGoogleMap.getCenter();
        lat = mapCenter.lat();
        lon = mapCenter.lng();
            
        document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
                
        myGoogleMap.clearOverlays();
        if (zoom==1) {
            addOverlay();
        } else {
            getViewportClusterMarkers();
        }
    });
    
    zoom = myGoogleMap.getZoom();
        
    bounds = myGoogleMap.getBounds();
    southWest = bounds.getSouthWest();
    northEast = bounds.getNorthEast();
    lonSpan = northEast.lng() - southWest.lng();
    latSpan = northEast.lat() - southWest.lat();
    
    var mapCenter = myGoogleMap.getCenter();
    lat = mapCenter.lat();
    lon = mapCenter.lng();
            
    document.getElementById('mapCoords').innerHTML = '<strong>Map Centre:</strong> '+lat.toFixed(4)+' '+lon.toFixed(4);
    
    myGoogleMap.clearOverlays();
    if (zoom==1) {
        addOverlay();
    } else {
        getViewportClusterMarkers();
    }
}

function setupSearchMap2() {
    zoom = myGoogleMap.getZoom();
        
    bounds = myGoogleMap.getBounds();
    southWest = bounds.getSouthWest();
    northEast = bounds.getNorthEast();
    lonSpan = northEast.lng() - southWest.lng();
    latSpan = northEast.lat() - southWest.lat();
    
    //myGoogleMap.clearOverlays();
    //getOrangeDistribution(southWest.lng(),northEast.lng(),southWest.lat(),northEast.lat(),zoom);
    addOverlay();
}
    
function addOverlay() {
      if (GBrowserIsCompatible()) {
      
        // Set up the copyright information
        // Each image used should indicate its copyright permissions
        var copyright = new GCopyright(1,
            new GLatLngBounds(new GLatLng(-90, -180), 
            new GLatLng(90, 180)),
            0,
            "©2008 Connection Services");
        var copyrightCollection = new GCopyrightCollection("Orange");
        copyrightCollection.addCopyright(copyright);
        
        var tileLayerOverlay = new GTileLayerOverlay(  
            new GTileLayer(copyright, 1, 1, {    
                tileUrlTemplate: 'http://www.wbadirectory.com/images/mapOverlay/wba_{Z}_{X}_{Y}.gif',     
                isPng:false,
                opacity:0.5
            })
        );
        myGoogleMap.addOverlay(tileLayerOverlay);
      }
    }
