/**
 * ---------------------- Subversion Information ------------------------------
 * ****************************************************************************
 * $Date: 2009-07-30 10:59:10 -0700 (Thu, 30 Jul 2009) $
 * $Rev: 692 $
 * $Author: steven $
 *
 * SVN URL of this file
 * $HeadURL: http://hal/svn/cms/trunk/idx/inc/js/streetview.js $
 * ****************************************************************************
 *
 * @copyright Real Estate Webmasters 2004 - 2009
 */

var debug;

var gob = null;
var yaw = null;
var pov = null;


function initStreetView () {

    var container = document.getElementById("streetview-container");

    if (container)  {

        var svp = new GStreetviewPanorama(container);

        var lngv = latlng.lng();
        var latv = latlng.lat();

        var svc = new GStreetviewClient();
        svc.getNearestPanorama(latlng, function (data) {

            if (document.getElementById("streetview-tab")) {
                document.getElementById("streetview-tab").style.display = 'block';
            }

            if (!data.Location) return handleNoFlash(600);

            if (typeof(data.Location.lng) != 'undefined') lngv = data.Location.lng;
            if (typeof(data.Location.lat) != 'undefined') latv = data.Location.lat;

            gob = new GLatLng(latv, lngv);
            yaw = computeAngle(gob, latlng);
            pov = {'yaw': yaw, 'pitch': -10};

            svp.setLocationAndPOV(gob, pov);

        });

        GEvent.addListener(svp, "error", handleNoFlash);

    }

}

function handleNoFlash (errorCode) {
    if (errorCode == 600) {
        if (document.getElementById("streetview-container")) {
            document.getElementById("streetview-container").innerHTML = "<p>Sorry, but Google Streetview data is not available for this property.</p>";
        }
        if (document.getElementById("streetview-tab")) {
            document.getElementById("streetview-tab").style.display = 'none';
        }
        return;
    }
    if (errorCode == 603) {
        if (document.getElementById("streetview-container")) {
            document.getElementById("streetview-container").innerHTML = "<p>Flash doesn't appear to be supported by your browser.</p>";
        }
        if (document.getElementById("streetview-tab")) {
            document.getElementById("streetview-tab").style.display = 'none';
        }
        return;
    }
}

function computeAngle (t, o) {
    var k = o.lat() - t.lat();
    var m = o.lng() - t.lng();
    var yaw = Math.atan2(m * Math.cos(o.lat() * (Math.PI / 180)), k) * (180 / Math.PI);
    return wrapAngle(yaw);
}

function wrapAngle (a) {
    if (a >= 360) {
        a -= 360;
    } else if (a < 0) {
        a += 360;
    }
    return a;
}

$(document).ready(function () {
    initStreetView();
});
//window.onload = initStreetView;
window.onunload = GUnload;