
/*
* Constants for given map
* TODO: read it from tilemapresource.xml
*/

var mapBounds = new GLatLngBounds(new GLatLng(37.417236796, -122.187278), new GLatLng(37.440548, -122.149363551));
var mapMinZoom = 14;
var mapMaxZoom = 17;
var opacity = 1.00;
var map;

/*
* Full-screen Window Resize
*/

function getWindowHeight() {
    if (self.innerHeight) return self.innerHeight;
    if (document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;
    if (document.body) return document.body.clientHeight;
    return 0;
}

function getWindowWidth() {
    if (self.innerWidth) return self.innerWidth;
    if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth;
    if (document.body) return document.body.clientWidth;
    return 0;
}

function resize() {
    var map = document.getElementById("map");
    var header = document.getElementById("header");
    var footer = document.getElementById("footer");
    map.style.height = (getWindowHeight() - 250) + "px";
    map.style.width = (getWindowWidth()) + "px";
    header.style.width = (getWindowWidth() - 20) + "px";
    footer.style.width = (getWindowWidth() - 20) + "px";
    // map.checkResize();
}

function doSearch() {
    var query = document.getElementById('q').value;
    if (query == '') {
        return;
    }
    //    map.clearOverlays();
    //document.getElementById("throbber").style.display = 'block';
    document.getElementById("search").value = 'Searching...';
    document.getElementById("search").disabled = true;
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
        // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                req = false;
            }
        }
    }
    if (req) {
        req.onreadystatechange = processReqChange;
        req.open("GET", "http://ucomm.stanford.edu/cgi-bin/map/stanford_search.pl?q=" + query + "&sf=" + document.getElementById('sf').value, true);
        req.send("");
        document.getElementById("query_link").setAttribute("href", "?q=" + escape(query) + "&sf=" + document.getElementById('sf').value);
    }
    return false;
}

function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            var results = req.responseText;
            var r = /<result>/;
            var matches = 0;
            var first = true;

            var bounds = new GLatLngBounds();

            while (r.exec(results)) {
                matches++;

                var reg = /id>([^<]*)</;
                var ar = reg.exec(results);
                var id = ar[1];
                results = results.substring(ar.index + id.length);

                var reg = /lat>([^<]*)</i;
                var ar = reg.exec(results);
                var lat = ar[1];
                results = results.substring(ar.index + lat.length);

                var reg = /lng>([^<]*)</i;
                var ar = reg.exec(results);
                var lng = ar[1];
                results = results.substring(ar.index + lng.length);

                lat = (lat - .0003);
                lng = (lng - 0 + .0003);

                var center = new GLatLng(lat, lng);
                var marker = createMarker(map, center, id);
                map.addOverlay(marker);
                bounds.extend(center);

                if (first) {
                    var listener = GEvent.addListener(map, "moveend", function () {
                        var infoWindow = document.createElement("div");
                        var iframe = document.createElement("iframe");
                        iframe.style.width = "215";
                        iframe.style.height = "220";
                        iframe.scrolling = "auto";
                        iframe.style.border = 0;
                        iframe.style.padding = 0;
                        iframe.src = "http://campus-map.stanford.edu/bldg-report.cfm?id=" + id;
                        infoWindow.appendChild(iframe);
                        marker.openInfoWindow(infoWindow);
                        GEvent.removeListener(listener);
                    });
                    map.panTo(center);
                    first = false;
                }

            }

            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());

            if (matches == 0) {
                alert("No results were found");
            }

        } else {
            alert("There was a problem retrieving the XML data");
        }
        document.getElementById("search").value = 'Search';
        document.getElementById("search").disabled = false;
    }
}

function createMarker(map, point, id) {
    var marker = new GMarker(point);
    var infoWindow = document.createElement("div");
    var iframe = document.createElement("iframe");
    iframe.style.width = "215";
    iframe.style.height = "197";
    iframe.scrolling = "auto";
    iframe.style.border = 0;
    iframe.style.padding = 0;
    iframe.src = "http://campus-map.stanford.edu/bldg-report.cfm?id=" + id;
    infoWindow.appendChild(iframe);

    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindow(infoWindow);
    });

    return marker;
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) return "";
    else return results[1];
}

/*
* Main load function:
*/

function load() {

    if (GBrowserIsCompatible()) {

        // Bug in the Google Maps: Copyright for Overlay is not correctly displayed
        var gcr = GMapType.prototype.getCopyrights;
        GMapType.prototype.getCopyrights = function (bounds, zoom) {
            return["&copy;"].concat(gcr.call(this, bounds, zoom));
        }

        map = new GMap2(document.getElementById("map"), { backgroundColor: '#fff' });
        map.setCenter(mapBounds.getCenter(), map.getBoundsZoomLevel(mapBounds));

        var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
        var mercator = new GMercatorProjection(mapMaxZoom + 1);
        tilelayer.getTileUrl = function (tile, zoom) {
            if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
                return "http://www.maptiler.org/img/none.png";
            }
            var ymax = 1 << zoom;
            var y = ymax - tile.y - 1;
            var tileBounds = new GLatLngBounds(
            mercator.fromPixelToLatLng(new GPoint((tile.x) * 256, (tile.y + 1) * 256), zoom), mercator.fromPixelToLatLng(new GPoint((tile.x + 1) * 256, (tile.y) * 256), zoom));
            if (mapBounds.intersects(tileBounds)) {
                return zoom + "/" + tile.x + "/" + y + ".png";
            } else {
                return "http://www.maptiler.org/img/none.png";
            }
        }

        // IE 7-: support for PNG alpha channel
        // Unfortunately, the opacity for whole overlay is then not changeable, either or...
        tilelayer.isPng = function () {
            return true;
        };
        tilelayer.getOpacity = function () {
            return opacity;
        }

        var customMap = new GMapType([G_NORMAL_MAP.getTileLayers()[0], tilelayer], G_NORMAL_MAP.getProjection(), 'Stanford', {
            errorMessage: "Out of bounds"
        });

        map.addMapType(customMap);
        map.setMapType(customMap);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableContinuousZoom();
        map.enableScrollWheelZoom();
        map.setMapType(customMap);
    }
    resize();
    document.getElementById('q').value = gup('q');
    document.getElementById('sf').value = gup('sf');
    doSearch();

}

onresize = function () {
    resize();
};

function openWindow(url, windowname, width, height, toolbar){
        var sizestring = 'width=' + width + ',height=' + height;
	SmallWin = window.open(url,windowname,'scrollbars,resizable,' 
	           + sizestring +',toolbar='+toolbar
                   +',location=0,status=0,directories=0,menubar='+toolbar);
	SmallWin.focus();	
}
