//google.load("maps", "2");
//google.load("search", "1");

var container;
var containerSW
var map;
var mypano;
var trafficOvl;
var log = 0;
var traffic = false;
var gdir;
var olat, olng;

function initMap() {

    if (!GBrowserIsCompatible()) {
        alert('Sorry. Your browser is not Google Maps compatible.');
    }
    else {
        if (!map) {

            container = document.getElementById("mymap");
            log ++;
            map = new GMap2(container);

            map.addControl(new GScaleControl());
            map.addControl(new GLargeMapControl());
            map.setCenter(new GLatLng(37.69631767236258, -122.33070373535156), 11);
            map.addMapType(G_PHYSICAL_MAP);
            // map.addMapType(G_SATELLITE_3D_MAP);
            //    traffic button does not work with expandable info windo (zIndex too high)
            // map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
            var hierarchy = new GHierarchicalMapTypeControl();
            hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, " Show labels", true);
            map.addControl(hierarchy);
            map.enableScrollWheelZoom();
            moveListener();
            resizeMap();

            GEvent.addListener(map.getInfoWindow(), "maximizeend", function() {
                setTimeout('loadContent();', 50);
            });
        }
    }
    //google.setOnLoadCallback(init);  // this is timed too early
    //YAHOO.setOnRenderCallback(init()); // after render() we can call initMap() successful
    initp();
}

/**
 * Private function that handles performing an ajax request to the server.  The response
 * information is assumed to be HTML and is placed inside this extInfoWindow's contents region.
 * Last, check to see if the height has changed, and resize the extInfoWindow accordingly.
 * @private
 * @param {String} url The Url of where to make the ajax request on the server
 */
function ajaxRequest(url) {
    var thisMap = map;
    var thisCallback = this.callback_;
    GDownloadUrl(url, function(response, statusCode) {
        var infoWindow = document.getElementById('detailContent');
        if (response == null || statusCode == -1) {
            infoWindow.innerHTML = '<span class="error">ERROR: The Ajax request failed to get HTML content from "' + url + '"</span>';
        } else {
            infoWindow.innerHTML = response;
        }
        if (thisCallback != null) {
            thisCallback();
        }
        //thisMap.getExtInfoWindow().resize();
        GEvent.trigger(thisMap, 'extinfowindowupdate');
    });
}

function resizeMap() {
    // alert ("resize");
    container.style.width = YAHOO.widget.LayoutUnit.getLayoutUnitById("center1").body.clientWidth + 'px';
    container.style.height = YAHOO.widget.LayoutUnit.getLayoutUnitById("center1").body.clientHeight + 'px';

    if (map) {
        //  alert("resize map " + container.style.width + " h: " + container.style.height  );
        map.checkResize();
    }
    if (mypano) {
        containerSW.style.width = YAHOO.widget.LayoutUnit.getLayoutUnitById("center1").body.clientWidth + 'px';
        containerSW.style.height = 250;
        //YAHOO.widget.LayoutUnit.getLayoutUnitById("center1").body.clientHeight + 'px';
        //   alert("resize mypano " +containerSW.style.width + " h: " + containerSW.style.height );
        //GLog.writeHtml("resize mypano " +containerSW.style.width + " h: " + containerSW.style.height );
        mypano.checkResize();
    }
}

function toggleMap() {
    container.style.display = container.style.display == '' ? 'none' : '';
    map.checkResize();
}
//@todo view webcast: [  http://www.infoq.com/presentations/vanderburg-power-of-javascript  ]
function toggleTraffic() {
    if (trafficOvl) {
        if (traffic) {
            map.removeOverlay(trafficOvl);
            traffic = false;
        }
        else {
            map.addOverlay(trafficOvl);
            traffic = true;
        }

    }
    else {
        trafficOvl = new GTrafficOverlay();
        map.addOverlay(trafficOvl);
        traffic = true;
    }

}

// ------------ Highlight circle
_mSvgEnabled = true;
// @todo browser handles drawing of cirlce, if set to false a png file will be loaded from google's server
var circleLine2;
var circlePoints;
var radius;
var thickness;
function drawFilledCircle(centerMarker, color) {
    //var oStatusDiv = document.getElementById("status");
    var zoom = map.getZoom();
    var normalProj = G_NORMAL_MAP.getProjection();
    var centerPt = normalProj.fromLatLngToPixel(centerMarker.getPoint(), zoom);
    var radiusMarker = centerMarker.getPoint();

    var radiusPt = normalProj.fromLatLngToPixel(radiusMarker, zoom);
    var _color = '#2257D6';

    if (color) {
        _color = color;
    }

    circlePoints = Array();
    centerMarker.hiliteOvl[zoom] = Array();
    with (Math) {
        radius = 25;
        //floor(sqrt(pow((centerPt.x-radiusPt.x),2) + pow((centerPt.y-radiusPt.y),2)));
        thickness = min(255, radius);
        var n;
        for (n = 1; n < floor(2 * radius / thickness) + 1; n++) {
            radiusB = radius - (thickness / 2) * n;

            for (var a = 0; a < 361; a += 10) {
                var aRad = a * (PI / 180);
                y = centerPt.y + radiusB * sin(aRad)
                x = centerPt.x + radiusB * cos(aRad)
                var p = new GPoint(x, y);
                circlePoints.push(normalProj.fromPixelToLatLng(p, zoom));
            }

            var radOnEarth = (centerMarker.getPoint().distanceFrom(radiusMarker) / 1000).toFixed(3);

            // map.removeOverlay(circleLine2);
            circleLine2 = new GPolyline(circlePoints, _color, thickness, 0.5);
            map.addOverlay(circleLine2);
            // @todo when saveing hilite overlay to marker. the saved overlay is only valid for the current zoom level
            // if user hilites and zooms / in out no new circle is drawn! exixting circle is displayed which can look misplaced ...
            centerMarker.hiliteOvl[zoom][n] = circleLine2;

            /* oStatusDiv.innerHTML += 'Radius on Earth: ' + radOnEarth + ' km<br>\n';
             oStatusDiv.innerHTML += 'Circumference on Earth: ' + (PI*radOnEarth*2).toFixed(3) + ' km<br>\n';
             oStatusDiv.innerHTML += 'Areal on Earth: ' + (PI*pow(radOnEarth,2)).toFixed(3) + ' km<br>\n';
             oStatusDiv.innerHTML += '<hr>';
             oStatusDiv.innerHTML += 'Radius on screen at zoom ' + zoom + ' : ' + radius.toFixed(0) + ' px<br>';
            */

        }
    }
}
// --- directions
function directionsInit() {
    setDLinks();
    // === create a GDirections Object ===
    gdir = new GDirections(map, document.getElementById("directions"));

    // === Array for decoding the failure codes ===
    var reasons = [];
    reasons[G_GEO_SUCCESS] = "Success";
    reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST] = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY] = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

    // === catch Directions errors ===
    GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason = "Code " + code;
        if (reasons[code]) {
            reason = reasons[code]
        }

        alert("Failed to obtain directions, " + reason);
    });
}

function getDirections() {
    if (!gdir) {
        directionsInit();
    }
    var saddr;
    var daddr;
    var dirs = document.getElementById("directions").innerHTML;
    var bizaddr = document.getElementById("bizaddr").value;
    document.getElementById("cbreverse").checked = false;
    toggleDirectionHeaderNFooter();

    if (document.getElementById("dirFrom").style.display == '') {
        saddr = bizaddr;
        daddr = document.getElementById("otheraddr1").value;
    }
    else {
        saddr = document.getElementById("otheraddr").value;
        daddr = bizaddr;
    }
    loadDirections(saddr, daddr, false);
}

function clearDirections() {
    if (gdir) {
        gdir.clear();
    }

    YAHOO.widget.LayoutUnit.getLayoutUnitById('right1').expand();
    document.getElementById("directions").innerHTML = "";
}

function closeDirections() {
    if (gdir) {
        gdir.clear();
    }
    YAHOO.widget.LayoutUnit.getLayoutUnitById('right1').collapse();
    document.getElementById("directions").innerHTML = "";
}

function setDLinks() {

    document.getElementById("dirclosetop").innerHTML = '<a href="#" id="closeDirections" onclick="javascript:closeDirections();" id="cDir">Close Directions</a></br>';
    document.getElementById("gsrfooter").innerHTML = '<a href="#" id="clearDirections" onclick="javascript:closeDirections();" id="cDir">Close Directions</a>';
}

function getDirectionsSFICG() {
    var saddr, daddr;

    if (!gdir) {
        directionsInit();
    }
    var dirs = document.getElementById("directions").innerHTML;
    saddr = document.getElementById("otheraddr1ak").value;
    daddr = document.getElementById("otheraddr2ak").value;


    var spoi = cache['sficg'].getAt(saddr);
    if (spoi) {
        saddr = spoi.gstitle + "@" + spoi.getPoint().lat() + ',' + spoi.getPoint().lng()

        var dpoi = cache['sficg'].getAt(daddr);
        if (dpoi) {
            var da2 = ', ' + dpoi.gsaddr2;
            if (da2 == 'null') {
                da2 = '';
            }
            daddr = dpoi.gstitle + "@" + dpoi.getPoint().lat() + ',' + dpoi.getPoint().lng()
            loadDirections(saddr, daddr, false);

        }
    }
}

function loadDirections(saddr, daddr, reverseDEL) {
    var source = saddr;
    var dest = daddr;
    var reverse = document.getElementById("cbreverse").checked;

    if (reverse) {
        source = daddr;
        dest = saddr;
    }
    map.closeInfoWindow();
    if (YAHOO.widget.LayoutUnit.getLayoutUnitById('right1').getStyle("display") == "block") {
        gdir.load("from: " + source + " to: " + dest);
    }
    else {
        YAHOO.widget.LayoutUnit.getLayoutUnitById('right1').expand();
        //alert("from: " + saddr + " to: " + daddr);
        YAHOO.widget.LayoutUnit.getLayoutUnitById('right1').on('expand', function() {
            gdir.load("from: " + source + " to: " + dest);
        });
    }
    track('directions/' + source + '/' + dest);
}

function toggleDirectionHeaderNFooter(reverse) {
    var n1 = 'From:'
    var n2 = 'To:';
    if (reverse) {
        document.getElementById('dirhd').innerHTML = '<br />' + n2 + '<br />';
        document.getElementById('dirft').innerHTML = n1 + '<br>';
    } else {
        document.getElementById('dirhd').innerHTML = '<br />' + n1 + '<br />';
        document.getElementById('dirft').innerHTML = n2 + '<br>';
    }
}

function moveListener() {
    GEvent.addListener(map, "drag", function() {
        var centerDec = map.getCenter();
        olat = centerDec;
        //  var center = centerDec.toString();
        // var sub = center.substring(1, center.length - 1);
        var sub = map.getCenter().lat() + ',' + map.getCenter().lng()
        map.closeInfoWindow();
        document.getElementById('mapwhere').value = sub;
        document.getElementById('where').value = 'search on map';

    });

    GEvent.addListener(map, "zoomend", function() {
        if (curTmp) {
            // munhilite(curTmp);
            munhiliteCurrent();
        }
    });

}

function saveOrigin(lat, lng) {
    olat = lat;
    olng = lng;
}

var removedMarkers = 0;
function hideMarkers(ovl) {
    if (cache[ovl]) {
        for (var i = 0; i < cache[ovl].getLength(); i++) {
            cache[ovl].getAt(i).hide();
            mgr.removeMarker(cache[ovl].getAt(i));
            removedMarkers++;
        }
    }
}

function unhideMarkers(ovl) {
    if (lastAddedMarker > 0) {
        if (cache[ovl]) {
            for (var i = 0; i < lastAddedMarker; i++) {
                mgr.addMarker(cache[ovl].getAt(i), 0);
            }
        }
        document.getElementById("cbhidesrmarkers").checked = false;
    }
}


function createOriginMarker() {

    // var myMapwhere = document.getElementById('where').value;
    var customIcon = new GIcon();
    customIcon.image = "images/star_red.png";
    customIcon.iconSize = new GSize(24, 24);
    customIcon.iconAnchor = new GPoint(12, 12);
    customIcon.infoWindowAnchor = new GPoint(12, 12);

    // var point = new GLatLng(olat, olng);
    //bounds.extend(point);
    var marker = new GMarker(olat, customIcon);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml("<small><b>search origin</b></small><br>" + myMapwhere);
    });
    map.addOverlay(marker);
}

// ------------ Street View related code
function initsw() {
    containerSW = document.getElementById("sview");
    mypano = new GStreetviewPanorama(containerSW);
    fenwayPark = new GLatLng(42.345573, -71.098326);
    myPOV = {yaw:370.64659986187695,pitch:-20};
    mypano.setLocationAndPOV(fenwayPark, myPOV);
    GEvent.addListener(mypano, "error", handleNoFlash);
    toggleStreetView();

}

function toggleStreetView() {
    containerSW.style.display = containerSW.style.display == '' ? 'none' : '';
    containerSW.style.width = layout.getUnitByPosition("center").body.clientWidth + 'px';
    containerSW.style.height = "200px";
    mypano.checkResize();
}

function handleNoFlash(errorCode) {
    if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
}  